text
stringlengths 54
60.6k
|
---|
<commit_before>// \brief Command-line utility to send email messages.
#include <iostream>
#include <cstdlib>
#include "EmailSender.h"
#include "StringUtil.h"
#include "TextUtil.h"
#include "util.h"
namespace {
__attribute__((noreturn)) void Usage() {
std::cerr << "Usage: " << ::progname << " [--sender=sender] [-reply-to=reply_to] --recipients=recipients\n"
<< " [--cc-recipients=cc_recipients] [--bcc-recipients=bcc_recipients] [--expand-newline-escapes]\n"
<< " --subject=subject --message-body=message_body [--priority=priority] [--format=format]\n\n"
<< " \"priority\" has to be one of \"very_low\", \"low\", \"medium\", \"high\", or\n"
<< " \"very_high\". \"format\" has to be one of \"plain_text\" or \"html\" At least one\n"
<< " of \"sender\" or \"reply-to\" has to be specified. If \"--expand-newline-escapes\" has\n"
<< " been specified, all occurrences of \\n in the message body will be replaced by a line feed\n"
<< " and a double backslash by a single backslash. The message body is assumed to be UTF-8!\n\n";
std::exit(EXIT_FAILURE);
}
EmailSender::Priority StringToPriority(const std::string &priority_candidate) {
if (priority_candidate == "very_low")
return EmailSender::VERY_LOW;
if (priority_candidate == "low")
return EmailSender::LOW;
if (priority_candidate == "medium")
return EmailSender::MEDIUM;
if (priority_candidate == "high")
return EmailSender::HIGH;
if (priority_candidate == "very_high")
return EmailSender::VERY_HIGH;
LOG_ERROR("\"" + priority_candidate + "\" is an unknown priority!");
}
EmailSender::Format StringToFormat(const std::string &format_candidate) {
if (format_candidate == "plain_text")
return EmailSender::PLAIN_TEXT;
else if (format_candidate == "html")
return EmailSender::HTML;
LOG_ERROR("\"" + format_candidate + "\" is an unknown format!");
}
bool ExtractArg(const char * const argument, const std::string &arg_name, std::string * const arg_value) {
if (StringUtil::StartsWith(argument, "--" + arg_name + "=")) {
*arg_value = argument + arg_name.length() + 3 /* two dashes and one equal sign */;
if (arg_value->empty())
LOG_ERROR(arg_name + " is missing!");
return true;
}
return false;
}
void ParseCommandLine(char **argv, std::string * const sender, std::string * const reply_to,
std::string * const recipients, std::string * const cc_recipients, std::string * const bcc_recipients,
std::string * const subject, std::string * const message_body, std::string * const priority,
std::string * const format, bool * const expand_newline_escapes)
{
*expand_newline_escapes = false;
while (*argv != nullptr) {
if (std::strcmp(*argv, "--expand-newline-escapes") == 0) {
*expand_newline_escapes = true;
++argv;
} else if (ExtractArg(*argv, "sender", sender) or ExtractArg(*argv, "reply-to", reply_to)
or ExtractArg(*argv, "recipients", recipients) or ExtractArg(*argv, "cc-recipients", cc_recipients)
or ExtractArg(*argv, "bcc-recipients", bcc_recipients) or ExtractArg(*argv, "subject", subject)
or ExtractArg(*argv, "message-body", message_body) or ExtractArg(*argv, "priority", priority)
or ExtractArg(*argv, "format", format))
++argv;
else
LOG_ERROR("unknown argument: " + std::string(*argv));
}
if (sender->empty() and reply_to->empty())
LOG_ERROR("you must specify --sender and/or --reply-to!");
if (recipients->empty() and cc_recipients->empty() and bcc_recipients->empty())
LOG_ERROR("you must specify a recipient!");
if (subject->empty())
LOG_ERROR("you must specify a subject!");
if (message_body->empty())
LOG_ERROR("you must specify a message-body!");
}
std::vector<std::string> SplitRecipients(const std::string &recipients) {
std::vector<std::string> individual_recipients;
StringUtil::Split(recipients, ',', &individual_recipients);
return individual_recipients;
}
// "text" is assumed to be UTF-8 encoded.
std::string ExpandNewlineEscapes(const std::string &text) {
std::wstring escaped_string;
if (unlikely(not TextUtil::UTF8ToWCharString(text, &escaped_string)))
LOG_ERROR("can't convert a supposed UTF-8 string to a wide string!");
std::wstring unescaped_string;
bool backslash_seen(false);
for (auto ch : escaped_string) {
if (backslash_seen) {
if (ch == '\\')
unescaped_string += '\\';
else if (ch == 'n')
unescaped_string += '\n';
else {
std::string utf8_string;
TextUtil::WCharToUTF8String(ch, &utf8_string);
LOG_ERROR("unknown escape: \\" + utf8_string + "!");
}
backslash_seen = false;
} else if (ch == '\\')
backslash_seen = true;
else
unescaped_string += ch;
}
std::string utf8_string;
if (unlikely(not TextUtil::WCharToUTF8String(unescaped_string, &utf8_string)))
LOG_ERROR("can't convert a supposed wide string to a UTF-8 string!");
return utf8_string;
}
} // unnamed namespace
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc == 1)
Usage();
EmailSender::Priority priority(EmailSender::DO_NOT_SET_PRIORITY);
EmailSender::Format format(EmailSender::PLAIN_TEXT);
try {
std::string sender, reply_to, recipients, cc_recipients, bcc_recipients, subject, message_body, priority_as_string,
format_as_string;
bool expand_newline_escapes;
ParseCommandLine(++argv, &sender, &reply_to, &recipients, &cc_recipients, &bcc_recipients, &subject, &message_body,
&priority_as_string, &format_as_string, &expand_newline_escapes);
if (not priority_as_string.empty())
priority = StringToPriority(priority_as_string);
if (not format_as_string.empty())
format = StringToFormat(format_as_string);
if (expand_newline_escapes)
message_body = ExpandNewlineEscapes(message_body);
if (not EmailSender::SendEmail(sender, SplitRecipients(recipients), SplitRecipients(cc_recipients),
SplitRecipients(bcc_recipients), subject, message_body, priority, format, reply_to))
LOG_ERROR("failed to send your email!");
} catch (const std::exception &e) {
LOG_ERROR("Caught exception: " + std::string(e.what()));
}
}
<commit_msg>We now support a default sender.<commit_after>// \brief Command-line utility to send email messages.
#include <iostream>
#include <cstdlib>
#include "IniFile.h"
#include "EmailSender.h"
#include "StringUtil.h"
#include "TextUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--sender=sender] [-reply-to=reply_to] --recipients=recipients\n"
<< " [--cc-recipients=cc_recipients] [--bcc-recipients=bcc_recipients] [--expand-newline-escapes]\n"
<< " --subject=subject --message-body=message_body [--priority=priority] [--format=format]\n\n"
<< " \"priority\" has to be one of \"very_low\", \"low\", \"medium\", \"high\", or\n"
<< " \"very_high\". \"format\" has to be one of \"plain_text\" or \"html\" At least one\n"
<< " of \"sender\" or \"reply-to\" has to be specified. If \"--expand-newline-escapes\" has\n"
<< " been specified, all occurrences of \\n in the message body will be replaced by a line feed\n"
<< " and a double backslash by a single backslash. The message body is assumed to be UTF-8!\n\n";
std::exit(EXIT_FAILURE);
}
EmailSender::Priority StringToPriority(const std::string &priority_candidate) {
if (priority_candidate == "very_low")
return EmailSender::VERY_LOW;
if (priority_candidate == "low")
return EmailSender::LOW;
if (priority_candidate == "medium")
return EmailSender::MEDIUM;
if (priority_candidate == "high")
return EmailSender::HIGH;
if (priority_candidate == "very_high")
return EmailSender::VERY_HIGH;
LOG_ERROR("\"" + priority_candidate + "\" is an unknown priority!");
}
EmailSender::Format StringToFormat(const std::string &format_candidate) {
if (format_candidate == "plain_text")
return EmailSender::PLAIN_TEXT;
else if (format_candidate == "html")
return EmailSender::HTML;
LOG_ERROR("\"" + format_candidate + "\" is an unknown format!");
}
bool ExtractArg(const char * const argument, const std::string &arg_name, std::string * const arg_value) {
if (StringUtil::StartsWith(argument, "--" + arg_name + "=")) {
*arg_value = argument + arg_name.length() + 3 /* two dashes and one equal sign */;
if (arg_value->empty())
LOG_ERROR(arg_name + " is missing!");
return true;
}
return false;
}
void ParseCommandLine(char **argv, std::string * const sender, std::string * const reply_to,
std::string * const recipients, std::string * const cc_recipients, std::string * const bcc_recipients,
std::string * const subject, std::string * const message_body, std::string * const priority,
std::string * const format, bool * const expand_newline_escapes)
{
*expand_newline_escapes = false;
while (*argv != nullptr) {
if (std::strcmp(*argv, "--expand-newline-escapes") == 0) {
*expand_newline_escapes = true;
++argv;
} else if (ExtractArg(*argv, "sender", sender) or ExtractArg(*argv, "reply-to", reply_to)
or ExtractArg(*argv, "recipients", recipients) or ExtractArg(*argv, "cc-recipients", cc_recipients)
or ExtractArg(*argv, "bcc-recipients", bcc_recipients) or ExtractArg(*argv, "subject", subject)
or ExtractArg(*argv, "message-body", message_body) or ExtractArg(*argv, "priority", priority)
or ExtractArg(*argv, "format", format))
++argv;
else
LOG_ERROR("unknown argument: " + std::string(*argv));
}
if (recipients->empty() and cc_recipients->empty() and bcc_recipients->empty())
LOG_ERROR("you must specify a recipient!");
if (subject->empty())
LOG_ERROR("you must specify a subject!");
if (message_body->empty())
LOG_ERROR("you must specify a message-body!");
}
std::vector<std::string> SplitRecipients(const std::string &recipients) {
std::vector<std::string> individual_recipients;
StringUtil::Split(recipients, ',', &individual_recipients);
return individual_recipients;
}
// "text" is assumed to be UTF-8 encoded.
std::string ExpandNewlineEscapes(const std::string &text) {
std::wstring escaped_string;
if (unlikely(not TextUtil::UTF8ToWCharString(text, &escaped_string)))
LOG_ERROR("can't convert a supposed UTF-8 string to a wide string!");
std::wstring unescaped_string;
bool backslash_seen(false);
for (auto ch : escaped_string) {
if (backslash_seen) {
if (ch == '\\')
unescaped_string += '\\';
else if (ch == 'n')
unescaped_string += '\n';
else {
std::string utf8_string;
TextUtil::WCharToUTF8String(ch, &utf8_string);
LOG_ERROR("unknown escape: \\" + utf8_string + "!");
}
backslash_seen = false;
} else if (ch == '\\')
backslash_seen = true;
else
unescaped_string += ch;
}
std::string utf8_string;
if (unlikely(not TextUtil::WCharToUTF8String(unescaped_string, &utf8_string)))
LOG_ERROR("can't convert a supposed wide string to a UTF-8 string!");
return utf8_string;
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc == 1)
Usage();
EmailSender::Priority priority(EmailSender::DO_NOT_SET_PRIORITY);
EmailSender::Format format(EmailSender::PLAIN_TEXT);
std::string sender, reply_to, recipients, cc_recipients, bcc_recipients, subject, message_body, priority_as_string,
format_as_string;
bool expand_newline_escapes;
ParseCommandLine(++argv, &sender, &reply_to, &recipients, &cc_recipients, &bcc_recipients, &subject, &message_body,
&priority_as_string, &format_as_string, &expand_newline_escapes);
if (sender.empty() and reply_to.empty()) {
IniFile ini_file("/usr/local/var/lib/tuelib/cronjobs/smtp_server.conf");
sender = ini_file.getString("SMTPServer", "server_user");
}
if (not priority_as_string.empty())
priority = StringToPriority(priority_as_string);
if (not format_as_string.empty())
format = StringToFormat(format_as_string);
if (expand_newline_escapes)
message_body = ExpandNewlineEscapes(message_body);
if (not EmailSender::SendEmail(sender, SplitRecipients(recipients), SplitRecipients(cc_recipients),
SplitRecipients(bcc_recipients), subject, message_body, priority, format, reply_to))
LOG_ERROR("failed to send your email!");
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2005
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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
*
* "@(#) $Id: testACSThreadSleep.cpp,v 1.3 2006/03/24 12:42:31 vwang Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2005-02-15 created
*/
// Uncomment this if you are using the VLT environment
// #include "vltPort.h"
#include "acsThreadManager.h"
#include <acsErrTypeLifeCycle.h>
#include <ACSErrTypeCommon.h>
static char *rcsId="@(#) $Id: testACSThreadSleep.cpp,v 1.3 2006/03/24 12:42:31 vwang Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
class SleepThreadLoop : public ACS::Thread
{
public:
SleepThreadLoop(const ACE_CString &name,
const ACS::TimeInterval &responseTime = ThreadBase::defaultResponseTime,
const ACS::TimeInterval &sleepTime = ThreadBase::defaultSleepTime,
bool del=false) :
ACS::Thread(name,
responseTime,
sleepTime,
del)
{
ACS_TRACE("SleepThreadLoop::SleepThreadLoop");
}
~SleepThreadLoop()
{
ACS_TRACE("SleepThreadLoop::~SleepThreadLoop");
}
void runLoop();
private:
};
/*
* After every sleep() I check if I have to go back
* This is important to handle properly stopping the thread
*/
void SleepThreadLoop::runLoop()
{
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Will sleep 1 sec."));
sleep(10000000); // 1 s
if(!check()) return;
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Will sleep 2 sec."));
sleep(20000000); // 2 s
if(!check()) return;
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Will sleep 1 sec."));
sleep(10000000); // 1 s
if(!check()) return;
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Done iteration."));
}
/**************************************************************
*
* GCH
*
* Main program
*
* Sleeps have been introduced in the code to make its
* execution more deterministic in terms of producing the same
* messages in as much as possible the same order.
* Without them, the code would work but with sometime different
* results due to concurrency.
*
* About error handling.
* I hake kept the exception/error handling as similar as
* possible to the original code, since the structure was already
* good.
* I have therefore just added an outer layer try/catch block
* a fixed a few details and one important error, probably due
* to a misunderstanding in the interface of the exception
* classes.
**************************************************************/
int main(int argc, char *argv[])
{
LoggingProxy logger_m(0, 0, 31);
LoggingProxy::init(&logger_m);
ACS::ThreadManager tm;
ACS_LOG(LM_SOURCE_INFO,"main",
(LM_INFO, "=============== Creating thread"));
tm.create<SleepThreadLoop>("SleepThread",
ACS::ThreadBase::defaultResponseTime,
10000000, // 1 sec
true);
/*
* GCH
* Wait a while to simulate components lifetime
*/
tm.resume("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(20);
/*
* GCH
* Suspend and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Suspend"));
tm.suspend("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(5);
/*
* GCH
* Resume and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Resume"));
tm.resume("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(5);
/*
* GCH
* Suspend and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Suspend"));
tm.suspend("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(5);
/*
* GCH
* Resume and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Resume"));
tm.resume("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(20);
/*
* GCH
* Cleanup the thread.
*/
ACS_LOG(LM_SOURCE_INFO,"main",
(LM_INFO, "=============== Cleaning up thread"));
tm.stop("SleepThread");
ACS_SHORT_LOG((LM_INFO,"End of cleanup"));
/***********************************************
* GCH
* Wait for everything to cleanup and go home
*/
ACE_OS::sleep(5);
ACS_LOG(LM_SOURCE_INFO,"main",
(LM_INFO, "=============== The end"));
return 0;
}
/* __oOo__ */
<commit_msg>Fixed undeterministic test (Sleep) in acsthreads<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2005
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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
*
* "@(#) $Id: testACSThreadSleep.cpp,v 1.3 2006/03/24 12:42:31 vwang Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2005-02-15 created
*/
// Uncomment this if you are using the VLT environment
// #include "vltPort.h"
#include "acsThreadManager.h"
#include <acsErrTypeLifeCycle.h>
#include <ACSErrTypeCommon.h>
static char *rcsId="@(#) $Id: testACSThreadSleep.cpp,v 1.3 2006/03/24 12:42:31 vwang Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
class SleepThreadLoop : public ACS::Thread
{
public:
SleepThreadLoop(const ACE_CString &name,
const ACS::TimeInterval &responseTime = ThreadBase::defaultResponseTime,
const ACS::TimeInterval &sleepTime = ThreadBase::defaultSleepTime,
bool del=false) :
ACS::Thread(name,
responseTime,
sleepTime,
del)
{
ACS_TRACE("SleepThreadLoop::SleepThreadLoop");
m_doLoop = true;
}
~SleepThreadLoop()
{
ACS_TRACE("SleepThreadLoop::~SleepThreadLoop");
}
void runLoop();
void setDoLoop(bool value)
{
m_doLoop = value;
}
private:
bool m_doLoop;
};
/*
* After every sleep() I check if I have to go back
* This is important to handle properly stopping the thread
*/
void SleepThreadLoop::runLoop()
{
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Will sleep 1 sec."));
sleep(10000000); // 1 s
if(!check()) return;
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Will sleep 2 sec."));
sleep(20000000); // 2 s
if(!check()) return;
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Will sleep 1 sec."));
sleep(10000000); // 1 s
if(!check()) return;
ACS_LOG(LM_SOURCE_INFO,"SleepThreadLoop::runLoop",
(LM_INFO, "Done iteration."));
if(m_doLoop == false)
{
sleep(10000000); // 1 s
}
}
/**************************************************************
*
* GCH
*
* Main program
*
* Sleeps have been introduced in the code to make its
* execution more deterministic in terms of producing the same
* messages in as much as possible the same order.
* Without them, the code would work but with sometime different
* results due to concurrency.
*
* About error handling.
* I hake kept the exception/error handling as similar as
* possible to the original code, since the structure was already
* good.
* I have therefore just added an outer layer try/catch block
* a fixed a few details and one important error, probably due
* to a misunderstanding in the interface of the exception
* classes.
**************************************************************/
int main(int argc, char *argv[])
{
LoggingProxy logger_m(0, 0, 31);
LoggingProxy::init(&logger_m);
ACS::ThreadManager tm;
ACS_LOG(LM_SOURCE_INFO,"main",
(LM_INFO, "=============== Creating thread"));
SleepThreadLoop * th = tm.create<SleepThreadLoop>("SleepThread",
ACS::ThreadBase::defaultResponseTime,
10000000, // 1 sec
true);
/*
* GCH
* Wait a while to simulate components lifetime
*/
th->setDoLoop(true);
tm.resume("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(20);
/*
* GCH
* Suspend and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Suspend"));
tm.suspend("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(5);
/*
* GCH
* Resume and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Resume"));
th->setDoLoop(false);
tm.resume("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(5);
/*
* GCH
* Suspend and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Suspend"));
tm.suspend("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(5);
/*
* GCH
* Resume and wait a while to simulate components lifetime
*/
ACS_SHORT_LOG((LM_INFO,"Resume"));
th->setDoLoop(true);
tm.resume("SleepThread");
ACS_SHORT_LOG((LM_INFO,"Waiting"));
ACE_OS::sleep(20);
/*
* GCH
* Cleanup the thread.
*/
ACS_LOG(LM_SOURCE_INFO,"main",
(LM_INFO, "=============== Cleaning up thread"));
tm.stop("SleepThread");
ACS_SHORT_LOG((LM_INFO,"End of cleanup"));
/***********************************************
* GCH
* Wait for everything to cleanup and go home
*/
ACE_OS::sleep(5);
ACS_LOG(LM_SOURCE_INFO,"main",
(LM_INFO, "=============== The end"));
return 0;
}
/* __oOo__ */
<|endoftext|> |
<commit_before>#ifndef _SWITCHBACK_HPP_
#define _SWITCHBACK_HPP_
#include <vector>
#include <boost/array.hpp>
#include <boost/none.hpp>
#include <boost/optional.hpp>
#include <boost/pool/pool_alloc.hpp>
#include <boost/unordered_map.hpp>
#include "search/BucketPriorityQueue.hpp"
#include "util/PointerOps.hpp"
template <
class Domain,
class Node
>
class Switchback
{
private:
typedef typename Node::Cost Cost;
typedef typename Node::State State;
typedef BucketPriorityQueue<Node> Open;
typedef boost::optional<typename Open::ItemPointer> MaybeItemPointer;
typedef boost::unordered_map<
Node *,
MaybeItemPointer,
PointerHash<Node>,
PointerEq<Node>
, boost::fast_pool_allocator< std::pair<Node * const, MaybeItemPointer> >
> Closed;
typedef typename Closed::iterator ClosedIterator;
typedef typename Closed::const_iterator ClosedConstIterator;
private:
const Node *goal;
bool searched;
const Domain &domain;
const static unsigned hierarchy_height = Domain::num_abstraction_levels + 1;
boost::array<unsigned, hierarchy_height> num_expanded;
boost::array<unsigned, hierarchy_height> num_generated;
boost::array<Open, hierarchy_height> open;
boost::array<Closed, hierarchy_height> closed;
private:
Switchback(const Switchback<Domain, Node> &);
Switchback<Domain, Node> & operator =(const Switchback<Domain, Node> &);
public:
Switchback(const Domain &domain)
: goal(NULL)
, searched(false)
, domain(domain)
{
num_expanded.assign(0);
num_generated.assign(0);
}
~Switchback()
{
}
void search()
{
if (searched)
return;
searched = true;
init_open_and_closed();
goal = resume_search(0, domain.get_goal_state());
}
const Node * get_goal() const
{
std::cerr << "final open/closed sizes:" << std::endl;
dump_open_sizes(std::cerr);
dump_closed_sizes(std::cerr);
return goal;
}
const Domain & get_domain() const
{
return domain;
}
unsigned get_num_generated() const
{
unsigned sum = 0;
for (unsigned i = 0; i < hierarchy_height; i += 1)
sum += num_generated[i];
return sum;
}
unsigned get_num_generated(const unsigned level) const
{
return num_generated[level];
}
unsigned get_num_expanded() const
{
unsigned sum = 0;
for (unsigned i = 0; i < hierarchy_height; i += 1)
sum += num_expanded[i];
return sum;
}
unsigned get_num_expanded(const unsigned level) const
{
return num_expanded[level];
}
private:
Cost heuristic(const unsigned level, const State &goal_state)
{
assert(is_valid_level(level));
if (level == Domain::num_abstraction_levels)
return 0;
// Need to create a dummy goal node to look up in the hash table.
// This smells of bad design!
const unsigned next_level = level + 1;
const State abstract_goal_state = domain.abstract(next_level, goal_state);
Node abstract_goal_node(abstract_goal_state, 0, 0);
ClosedIterator closed_it = closed[next_level].find(&abstract_goal_node);
if (closed_it != closed[next_level].end()) {
return closed_it->first->get_g();
}
Node *result = resume_search(next_level, abstract_goal_state);
if (result == NULL) {
std::cerr << "whoops, infinite heuristic estimate!" << std::endl;
assert(false); // for the domains I am running on, there should
// never be an infinite heuristic estimate.
}
return result->get_g();
}
Node * resume_search(const unsigned level, const State &goal_state)
{
assert(is_valid_level(level));
// std::cerr << "conducting hierarchical search at level " << level
// << " for the following state:" << std::endl
// << goal_state << std::endl;
// dump_open_sizes(std::cerr);
// dump_closed_sizes(std::cerr);
// Dummy goal node, for hash table lookup.
Node goal_node(goal_state, 0, 0);
ClosedIterator closed_it = closed[level].find(&goal_node);
if (closed_it != closed[level].end())
return closed_it->first;
std::vector<Node *> children;
// A*-ish code ahead
while (!open[level].empty()) {
if (get_num_expanded() % 500000 == 0) {
std::cerr << get_num_expanded() << " total nodes expanded" << std::endl
<< get_num_generated() << " total nodes generated" << std::endl;
dump_open_sizes(std::cerr);
dump_closed_sizes(std::cerr);
}
assert(open[level].invariants_satisfied());
Node *n = open[level].top();
assert(closed[level].find(n) != closed[level].end());
assert(closed[level].find(n)->second);
assert(open[level].valid_item_pointer(*closed[level].find(n)->second));
open[level].pop();
assert(open[level].invariants_satisfied());
closed[level][n] = boost::none;
assert(all_closed_item_ptrs_valid(level));
if (level % 2 == 0)
domain.compute_successors(*n, children);
else
domain.compute_predecessors(*n, children);
num_expanded[level] += 1;
num_generated[level] += children.size();
for (unsigned child_idx = 0; child_idx < children.size(); child_idx += 1) {
assert(open[level].invariants_satisfied());
assert(open[level].size() <= closed[level].size());
assert(all_closed_item_ptrs_valid(level));
Node *child = children[child_idx];
child->set_h(heuristic(level, child->get_state()));
// std::cerr << "child's h-value: " << child->get_h() << std::endl;
ClosedIterator closed_it = closed[level].find(child);
if (closed_it == closed[level].end()) {
// The child has not been generated before.
closed[level][child] = open[level].push(child);
}
else if (child->get_f() < closed_it->first->get_f() && closed_it->second) {
// A worse version of the child is in the open list.
open[level].erase(*closed_it->second); // knock out the old
// one from the open
// list
assert(open[level].invariants_satisfied());
domain.free_node(closed_it->first); // free the old,
// worse copy
closed[level].erase(closed_it); // insert better
// version of child
closed[level][child] = open[level].push(child);
assert(open[level].invariants_satisfied());
}
else {
// The child has either already been expanded, or is worse
// than the version in the open list.
domain.free_node(child);
}
assert(open[level].invariants_satisfied());
} /* end for */
if (n->get_state() == goal_state)
return n;
} /* end while */
return NULL;
}
void init_open_and_closed()
{
for (int level = Domain::num_abstraction_levels; level >= 0; level -= 1) {
std::cerr << "initializing level " << level << std::endl;
std::cerr << get_num_expanded() << " total nodes expanded" << std::endl
<< get_num_generated() << " total nodes generated" << std::endl;
dump_open_sizes(std::cerr);
dump_closed_sizes(std::cerr);
State start = level % 2 == 0
? domain.get_start_state()
: domain.get_goal_state();
State goal = level % 2 == 0
? domain.get_goal_state()
: domain.get_start_state();
State abstract_start = domain.abstract(level, start);
Cost h_val = heuristic(level, start);
// I think there is trouble with the heuristic initialization
// here. Should it be called with level + 1 and
// abstract_abstract_start?
Node *start_node = domain.create_node(abstract_start,
0,
h_val,
NULL
);
closed[level][start_node] = open[level].push(start_node);
}
}
bool all_closed_item_ptrs_valid(const unsigned level) const
{
#ifdef CHECK_ALL_CLOSED_ITEM_PTRS_VALID
std::cerr << "checking if item pointers are valid" << std::endl
<< " " << closed.size() << " pointers to check" << std::endl;
for (ClosedConstIterator closed_it = closed[level].begin();
closed_it != closed[level].end();
++closed_it) {
if ( closed_it->second && !open[level].valid_item_pointer(*closed_it->second) )
return false;
}
return true;
#else
return true;
#endif
}
static bool is_valid_level(const unsigned level)
{
return level <= Domain::num_abstraction_levels;
}
void dump_open_sizes(std::ostream &o) const
{
o << "open sizes: " << std::endl;
for (unsigned level = 0; level < hierarchy_height; level += 1)
o << " " << level << ": " << open[level].size() << std::endl;
}
void dump_closed_sizes(std::ostream &o) const
{
o << "closed sizes: " << std::endl;
for (unsigned level = 0; level < hierarchy_height; level += 1)
o << " " << level << ": " << closed[level].size() << std::endl;
}
};
#endif /* !_SWITCHBACK_HPP_ */
<commit_msg>Cleanup; change in init_open_and_closed.<commit_after>#ifndef _SWITCHBACK_HPP_
#define _SWITCHBACK_HPP_
#include <vector>
#include <boost/array.hpp>
#include <boost/none.hpp>
#include <boost/optional.hpp>
#include <boost/pool/pool_alloc.hpp>
#include <boost/unordered_map.hpp>
#include "search/BucketPriorityQueue.hpp"
#include "util/PointerOps.hpp"
template <
class Domain,
class Node
>
class Switchback
{
private:
typedef typename Node::Cost Cost;
typedef typename Node::State State;
typedef BucketPriorityQueue<Node> Open;
typedef boost::optional<typename Open::ItemPointer> MaybeItemPointer;
typedef boost::unordered_map<
Node *,
MaybeItemPointer,
PointerHash<Node>,
PointerEq<Node>
, boost::fast_pool_allocator< std::pair<Node * const, MaybeItemPointer> >
> Closed;
typedef typename Closed::iterator ClosedIterator;
typedef typename Closed::const_iterator ClosedConstIterator;
private:
const Node *goal;
bool searched;
const Domain &domain;
const static unsigned hierarchy_height = Domain::num_abstraction_levels + 1;
boost::array<unsigned, hierarchy_height> num_expanded;
boost::array<unsigned, hierarchy_height> num_generated;
boost::array<Open, hierarchy_height> open;
boost::array<Closed, hierarchy_height> closed;
private:
Switchback(const Switchback<Domain, Node> &);
Switchback<Domain, Node> & operator =(const Switchback<Domain, Node> &);
public:
Switchback(const Domain &domain)
: goal(NULL)
, searched(false)
, domain(domain)
{
num_expanded.assign(0);
num_generated.assign(0);
}
~Switchback()
{
}
void search()
{
if (searched)
return;
searched = true;
init_open_and_closed();
goal = resume_search(0, domain.get_goal_state());
}
const Node * get_goal() const
{
std::cerr << "final open/closed sizes:" << std::endl;
dump_open_sizes(std::cerr);
dump_closed_sizes(std::cerr);
return goal;
}
const Domain & get_domain() const
{
return domain;
}
unsigned get_num_generated() const
{
unsigned sum = 0;
for (unsigned i = 0; i < hierarchy_height; i += 1)
sum += num_generated[i];
return sum;
}
unsigned get_num_generated(const unsigned level) const
{
return num_generated[level];
}
unsigned get_num_expanded() const
{
unsigned sum = 0;
for (unsigned i = 0; i < hierarchy_height; i += 1)
sum += num_expanded[i];
return sum;
}
unsigned get_num_expanded(const unsigned level) const
{
return num_expanded[level];
}
private:
Cost heuristic(const unsigned level, const State &goal_state)
{
assert(is_valid_level(level));
if (level == Domain::num_abstraction_levels)
return 0;
// Need to create a dummy goal node to look up in the hash table.
// This smells of bad design!
const unsigned next_level = level + 1;
const State abstract_goal_state = domain.abstract(next_level, goal_state);
Node abstract_goal_node(abstract_goal_state, 0, 0);
ClosedIterator closed_it = closed[next_level].find(&abstract_goal_node);
if (closed_it != closed[next_level].end()) {
return closed_it->first->get_g();
}
Node *result = resume_search(next_level, abstract_goal_state);
if (result == NULL) {
std::cerr << "whoops, infinite heuristic estimate!" << std::endl;
assert(false); // for the domains I am running on, there should
// never be an infinite heuristic estimate.
}
assert(closed[next_level].find(&abstract_goal_node) != closed[next_level].end());
return result->get_g();
}
Node * resume_search(const unsigned level, const State &goal_state)
{
assert(is_valid_level(level));
// Dummy goal node, for hash table lookup.
Node goal_node(goal_state, 0, 0);
ClosedIterator closed_it = closed[level].find(&goal_node);
if (closed_it != closed[level].end())
return closed_it->first;
std::vector<Node *> children;
// A*-ish code ahead
while (!open[level].empty()) {
if (get_num_expanded() % 500000 == 0) {
std::cerr << get_num_expanded() << " total nodes expanded" << std::endl
<< get_num_generated() << " total nodes generated" << std::endl;
dump_open_sizes(std::cerr);
dump_closed_sizes(std::cerr);
}
Node *n = open[level].top();
assert(closed[level].find(n) != closed[level].end());
assert(closed[level].find(n)->second);
assert(open[level].valid_item_pointer(*closed[level].find(n)->second));
open[level].pop();
closed[level][n] = boost::none;
assert(all_closed_item_ptrs_valid(level));
if (level % 2 == 0)
domain.compute_successors(*n, children);
else
domain.compute_predecessors(*n, children);
num_expanded[level] += 1;
num_generated[level] += children.size();
for (unsigned child_idx = 0; child_idx < children.size(); child_idx += 1) {
process_child(level, children[child_idx]);
}
if (n->get_state() == goal_state)
return n;
} /* end while */
return NULL;
}
void process_child(const unsigned level, Node *child)
{
assert(open[level].invariants_satisfied());
assert(open[level].size() <= closed[level].size());
assert(all_closed_item_ptrs_valid(level));
child->set_h(heuristic(level, child->get_state()));
ClosedIterator closed_it = closed[level].find(child);
if (closed_it == closed[level].end()) {
// The child has not been generated before.
closed[level][child] = open[level].push(child);
}
else if (closed_it->second && child->get_f() < closed_it->first->get_f()) {
// A worse version of the child is in the open list.
open[level].erase(*closed_it->second); // knock out the old
// one from the open
// list
domain.free_node(closed_it->first); // free the old,
// worse copy
closed[level].erase(closed_it);
closed[level][child] = open[level].push(child); // insert better version of child
}
else {
// The child has either already been expanded, or is worse
// than the version in the open list.
domain.free_node(child);
}
assert(all_closed_item_ptrs_valid(level));
assert(open[level].invariants_satisfied());
}
void init_open_and_closed()
{
for (int level = Domain::num_abstraction_levels; level >= 0; level -= 1) {
std::cerr << "initializing level " << level << std::endl;
std::cerr << get_num_expanded() << " total nodes expanded" << std::endl
<< get_num_generated() << " total nodes generated" << std::endl;
dump_open_sizes(std::cerr);
dump_closed_sizes(std::cerr);
State start = level % 2 == 0
? domain.get_start_state()
: domain.get_goal_state();
State abstract_start = domain.abstract(level, start);
// I think there is trouble with the heuristic initialization
// here. Should it be called with level + 1 and
// abstract_abstract_start?
Node *start_node = domain.create_node(abstract_start,
0,
0,
NULL
);
closed[level][start_node] = open[level].push(start_node);
}
}
bool all_closed_item_ptrs_valid(const unsigned level) const
{
#ifdef CHECK_ALL_CLOSED_ITEM_PTRS_VALID
std::cerr << "checking if item pointers are valid" << std::endl
<< " " << closed.size() << " pointers to check" << std::endl;
for (ClosedConstIterator closed_it = closed[level].begin();
closed_it != closed[level].end();
++closed_it) {
if ( closed_it->second && !open[level].valid_item_pointer(*closed_it->second) )
return false;
}
return true;
#else
return true;
#endif
}
static bool is_valid_level(const unsigned level)
{
return level <= Domain::num_abstraction_levels;
}
void dump_open_sizes(std::ostream &o) const
{
o << "open sizes: " << std::endl;
for (unsigned level = 0; level < hierarchy_height; level += 1)
o << " " << level << ": " << open[level].size() << std::endl;
}
void dump_closed_sizes(std::ostream &o) const
{
o << "closed sizes: " << std::endl;
for (unsigned level = 0; level < hierarchy_height; level += 1)
o << " " << level << ": " << closed[level].size() << std::endl;
}
};
#endif /* !_SWITCHBACK_HPP_ */
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "serializer/log/extent_manager.hpp"
#include <queue>
#include "arch/arch.hpp"
#include "logger.hpp"
#include "math.hpp"
#include "perfmon/perfmon.hpp"
#include "serializer/log/log_serializer.hpp"
struct extent_info_t {
public:
enum state_t {
state_unreserved,
state_in_use,
state_free
};
private:
state_t state_;
public:
void set_state(state_t new_state) {
guarantee(state_ != state_in_use || extent_use_refcount == 0);
state_ = new_state;
}
state_t state() const { return state_; }
// Valid and non-zero when state_in_use. There are two ways to own a part of
// this refcount. One is if you believe you're currently "using" the extent (if
// you're the LBA or data_block_manager_t). The other is (at the time of
// writing) for every (extent_transaction_t, block_id) for live extent
// transactions that have set an i_array entry to zero (in the data block
// manager) but have not yet been commmitted. The data_block_manager_t and LBA
// ownership of the refcount also can get passed into the extent_transaction_t
// object.
intptr_t extent_use_refcount;
extent_info_t() : state_(state_unreserved),
extent_use_refcount(0) { }
};
class extent_zone_t {
const size_t extent_size;
size_t offset_to_id(int64_t extent) const {
rassert(divides(extent_size, extent));
return extent / extent_size;
}
/* free-list and extent map. Contains one entry per extent. During the
state_reserving_extents phase, each extent has state state_unreserved or
state state_in_use. When we transition to the state_running phase, we link
all of the state_unreserved entries in each zone together into extent free
queue. The free queue can contain entries that point past the end of
extents, if the file size ever gets shrunk. */
std::vector<extent_info_t> extents;
// We want to remove the minimum element from the free_queue first, leaving
// free extents at the end of the file.
std::priority_queue<size_t,
std::vector<size_t>,
std::greater<size_t> > free_queue;
file_t *const dbfile;
// The number of free extents in the file.
size_t held_extents_;
public:
size_t held_extents() const {
return held_extents_;
}
extent_zone_t(file_t *_dbfile, size_t _extent_size)
: extent_size(_extent_size), dbfile(_dbfile), held_extents_(0) {
// (Avoid a bunch of reallocations by resize calls (avoiding O(n log n)
// work on average).)
extents.reserve(dbfile->get_file_size() / extent_size);
}
extent_reference_t reserve_extent(int64_t extent) {
size_t id = offset_to_id(extent);
if (id >= extents.size()) {
extents.resize(id + 1);
}
rassert(extents[id].state() == extent_info_t::state_unreserved);
extents[id].set_state(extent_info_t::state_in_use);
return make_extent_reference(extent);
}
void reconstruct_free_list() {
for (size_t extent_id = 0; extent_id < extents.size(); ++extent_id) {
if (extents[extent_id].state() == extent_info_t::state_unreserved) {
extents[extent_id].set_state(extent_info_t::state_free);
free_queue.push(extent_id);
++held_extents_;
}
}
}
extent_reference_t gen_extent() {
int64_t extent;
if (free_queue.empty()) {
rassert(held_extents_ == 0);
extent = extents.size() * extent_size;
extents.push_back(extent_info_t());
} else if (free_queue.top() >= extents.size()) {
rassert(held_extents_ == 0);
std::priority_queue<size_t,
std::vector<size_t>,
std::greater<size_t> > tmp;
free_queue = tmp;
extent = extents.size() * extent_size;
extents.push_back(extent_info_t());
} else {
extent = free_queue.top() * extent_size;
free_queue.pop();
--held_extents_;
}
extent_info_t *info = &extents[offset_to_id(extent)];
info->set_state(extent_info_t::state_in_use);
extent_reference_t extent_ref = make_extent_reference(extent);
dbfile->set_file_size_at_least(extent + extent_size);
return extent_ref;
}
extent_reference_t make_extent_reference(const int64_t extent) {
size_t id = offset_to_id(extent);
guarantee(id < extents.size());
extent_info_t *info = &extents[id];
guarantee(info->state() == extent_info_t::state_in_use);
++info->extent_use_refcount;
return extent_reference_t(extent);
}
void try_shrink_file() {
// Now potentially shrink the file.
bool shrink_file = false;
while (!extents.empty() && extents.back().state() == extent_info_t::state_free) {
shrink_file = true;
--held_extents_;
extents.pop_back();
}
if (shrink_file) {
dbfile->set_file_size(extents.size() * extent_size);
// Prevent the existence of a relatively large free queue after the file
// size shrinks.
if (held_extents_ < free_queue.size() / 2) {
std::priority_queue<size_t,
std::vector<size_t>,
std::greater<size_t> > tmp;
for (size_t i = 0; i < held_extents_; ++i) {
tmp.push(free_queue.top());
free_queue.pop();
}
// held_extents_ was and will be the number of entries in the free_queue
// that _didn't_ point off the end of the file. We just moved those
// entries to tmp. The remaining entries must therefore point off the
// end of the file. Check that no remaining entries point within the
// file.
guarantee(free_queue.top() >= extents.size(), "Tried to discard valid held extents.");
free_queue = std::move(tmp);
}
}
}
void release_extent(extent_reference_t &&extent_ref) {
int64_t extent = extent_ref.release();
extent_info_t *info = &extents[offset_to_id(extent)];
guarantee(info->state() == extent_info_t::state_in_use);
guarantee(info->extent_use_refcount > 0);
--info->extent_use_refcount;
if (info->extent_use_refcount == 0) {
info->set_state(extent_info_t::state_free);
free_queue.push(offset_to_id(extent));
++held_extents_;
try_shrink_file();
}
}
};
extent_manager_t::extent_manager_t(file_t *file,
const log_serializer_on_disk_static_config_t *static_config,
log_serializer_stats_t *_stats)
: stats(_stats), extent_size(static_config->extent_size()),
state(state_reserving_extents) {
guarantee(divides(DEVICE_BLOCK_SIZE, extent_size));
zone.init(new extent_zone_t(file, extent_size));
}
extent_manager_t::~extent_manager_t() {
rassert(state == state_reserving_extents || state == state_shut_down);
}
extent_reference_t extent_manager_t::reserve_extent(int64_t extent) {
assert_thread();
rassert(state == state_reserving_extents);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->reserve_extent(extent);
}
void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) {
mb->padding = 0;
}
void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) {
assert_thread();
rassert(state == state_reserving_extents);
current_transaction = NULL;
zone->reconstruct_free_list();
state = state_running;
}
void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert_thread();
rassert(state == state_running);
metablock->padding = 0;
}
void extent_manager_t::shutdown() {
assert_thread();
rassert(state == state_running);
rassert(!current_transaction);
state = state_shut_down;
}
void extent_manager_t::begin_transaction(extent_transaction_t *out) {
assert_thread();
rassert(!current_transaction);
current_transaction = out;
out->init();
}
extent_reference_t extent_manager_t::gen_extent() {
assert_thread();
rassert(state == state_running);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->gen_extent();
}
extent_reference_t
extent_manager_t::copy_extent_reference(const extent_reference_t &extent_ref) {
int64_t offset = extent_ref.offset();
return zone->make_extent_reference(offset);
}
void extent_manager_t::release_extent_into_transaction(extent_reference_t &&extent_ref, extent_transaction_t *txn) {
release_extent_preliminaries();
rassert(current_transaction);
txn->push_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent(extent_reference_t &&extent_ref) {
release_extent_preliminaries();
zone->release_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent_preliminaries() {
assert_thread();
rassert(state == state_running);
--stats->pm_extents_in_use;
stats->pm_bytes_in_use -= extent_size;
}
void extent_manager_t::end_transaction(extent_transaction_t *t) {
assert_thread();
rassert(current_transaction == t);
current_transaction = NULL;
t->mark_end();
}
void extent_manager_t::commit_transaction(extent_transaction_t *t) {
assert_thread();
std::vector<extent_reference_t> extents = t->reset();
for (auto it = extents.begin(); it != extents.end(); ++it) {
zone->release_extent(std::move(*it));
}
}
size_t extent_manager_t::held_extents() {
assert_thread();
return zone->held_extents();
}
<commit_msg>Use 64 bit integer for extent size, even on 32 bit<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "serializer/log/extent_manager.hpp"
#include <queue>
#include "arch/arch.hpp"
#include "logger.hpp"
#include "math.hpp"
#include "perfmon/perfmon.hpp"
#include "serializer/log/log_serializer.hpp"
struct extent_info_t {
public:
enum state_t {
state_unreserved,
state_in_use,
state_free
};
private:
state_t state_;
public:
void set_state(state_t new_state) {
guarantee(state_ != state_in_use || extent_use_refcount == 0);
state_ = new_state;
}
state_t state() const { return state_; }
// Valid and non-zero when state_in_use. There are two ways to own a part of
// this refcount. One is if you believe you're currently "using" the extent (if
// you're the LBA or data_block_manager_t). The other is (at the time of
// writing) for every (extent_transaction_t, block_id) for live extent
// transactions that have set an i_array entry to zero (in the data block
// manager) but have not yet been commmitted. The data_block_manager_t and LBA
// ownership of the refcount also can get passed into the extent_transaction_t
// object.
intptr_t extent_use_refcount;
extent_info_t() : state_(state_unreserved),
extent_use_refcount(0) { }
};
class extent_zone_t {
const uint64_t extent_size;
size_t offset_to_id(int64_t extent) const {
rassert(divides(extent_size, extent));
return extent / extent_size;
}
/* free-list and extent map. Contains one entry per extent. During the
state_reserving_extents phase, each extent has state state_unreserved or
state state_in_use. When we transition to the state_running phase, we link
all of the state_unreserved entries in each zone together into extent free
queue. The free queue can contain entries that point past the end of
extents, if the file size ever gets shrunk. */
std::vector<extent_info_t> extents;
// We want to remove the minimum element from the free_queue first, leaving
// free extents at the end of the file.
std::priority_queue<size_t,
std::vector<size_t>,
std::greater<size_t> > free_queue;
file_t *const dbfile;
// The number of free extents in the file.
size_t held_extents_;
public:
size_t held_extents() const {
return held_extents_;
}
extent_zone_t(file_t *_dbfile, uint64_t _extent_size)
: extent_size(_extent_size), dbfile(_dbfile), held_extents_(0) {
// (Avoid a bunch of reallocations by resize calls (avoiding O(n log n)
// work on average).)
extents.reserve(dbfile->get_file_size() / extent_size);
}
extent_reference_t reserve_extent(int64_t extent) {
size_t id = offset_to_id(extent);
if (id >= extents.size()) {
extents.resize(id + 1);
}
rassert(extents[id].state() == extent_info_t::state_unreserved);
extents[id].set_state(extent_info_t::state_in_use);
return make_extent_reference(extent);
}
void reconstruct_free_list() {
for (size_t extent_id = 0; extent_id < extents.size(); ++extent_id) {
if (extents[extent_id].state() == extent_info_t::state_unreserved) {
extents[extent_id].set_state(extent_info_t::state_free);
free_queue.push(extent_id);
++held_extents_;
}
}
}
extent_reference_t gen_extent() {
int64_t extent;
if (free_queue.empty()) {
rassert(held_extents_ == 0);
extent = extents.size() * extent_size;
extents.push_back(extent_info_t());
} else if (free_queue.top() >= extents.size()) {
rassert(held_extents_ == 0);
std::priority_queue<size_t,
std::vector<size_t>,
std::greater<size_t> > tmp;
free_queue = tmp;
extent = extents.size() * extent_size;
extents.push_back(extent_info_t());
} else {
extent = free_queue.top() * extent_size;
free_queue.pop();
--held_extents_;
}
extent_info_t *info = &extents[offset_to_id(extent)];
info->set_state(extent_info_t::state_in_use);
extent_reference_t extent_ref = make_extent_reference(extent);
dbfile->set_file_size_at_least(extent + extent_size);
return extent_ref;
}
extent_reference_t make_extent_reference(const int64_t extent) {
size_t id = offset_to_id(extent);
guarantee(id < extents.size());
extent_info_t *info = &extents[id];
guarantee(info->state() == extent_info_t::state_in_use);
++info->extent_use_refcount;
return extent_reference_t(extent);
}
void try_shrink_file() {
// Now potentially shrink the file.
bool shrink_file = false;
while (!extents.empty() && extents.back().state() == extent_info_t::state_free) {
shrink_file = true;
--held_extents_;
extents.pop_back();
}
if (shrink_file) {
dbfile->set_file_size(extents.size() * extent_size);
// Prevent the existence of a relatively large free queue after the file
// size shrinks.
if (held_extents_ < free_queue.size() / 2) {
std::priority_queue<size_t,
std::vector<size_t>,
std::greater<size_t> > tmp;
for (size_t i = 0; i < held_extents_; ++i) {
tmp.push(free_queue.top());
free_queue.pop();
}
// held_extents_ was and will be the number of entries in the free_queue
// that _didn't_ point off the end of the file. We just moved those
// entries to tmp. The remaining entries must therefore point off the
// end of the file. Check that no remaining entries point within the
// file.
guarantee(free_queue.top() >= extents.size(), "Tried to discard valid held extents.");
free_queue = std::move(tmp);
}
}
}
void release_extent(extent_reference_t &&extent_ref) {
int64_t extent = extent_ref.release();
extent_info_t *info = &extents[offset_to_id(extent)];
guarantee(info->state() == extent_info_t::state_in_use);
guarantee(info->extent_use_refcount > 0);
--info->extent_use_refcount;
if (info->extent_use_refcount == 0) {
info->set_state(extent_info_t::state_free);
free_queue.push(offset_to_id(extent));
++held_extents_;
try_shrink_file();
}
}
};
extent_manager_t::extent_manager_t(file_t *file,
const log_serializer_on_disk_static_config_t *static_config,
log_serializer_stats_t *_stats)
: stats(_stats), extent_size(static_config->extent_size()),
state(state_reserving_extents) {
guarantee(divides(DEVICE_BLOCK_SIZE, extent_size));
zone.init(new extent_zone_t(file, extent_size));
}
extent_manager_t::~extent_manager_t() {
rassert(state == state_reserving_extents || state == state_shut_down);
}
extent_reference_t extent_manager_t::reserve_extent(int64_t extent) {
assert_thread();
rassert(state == state_reserving_extents);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->reserve_extent(extent);
}
void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) {
mb->padding = 0;
}
void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) {
assert_thread();
rassert(state == state_reserving_extents);
current_transaction = NULL;
zone->reconstruct_free_list();
state = state_running;
}
void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert_thread();
rassert(state == state_running);
metablock->padding = 0;
}
void extent_manager_t::shutdown() {
assert_thread();
rassert(state == state_running);
rassert(!current_transaction);
state = state_shut_down;
}
void extent_manager_t::begin_transaction(extent_transaction_t *out) {
assert_thread();
rassert(!current_transaction);
current_transaction = out;
out->init();
}
extent_reference_t extent_manager_t::gen_extent() {
assert_thread();
rassert(state == state_running);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->gen_extent();
}
extent_reference_t
extent_manager_t::copy_extent_reference(const extent_reference_t &extent_ref) {
int64_t offset = extent_ref.offset();
return zone->make_extent_reference(offset);
}
void extent_manager_t::release_extent_into_transaction(extent_reference_t &&extent_ref, extent_transaction_t *txn) {
release_extent_preliminaries();
rassert(current_transaction);
txn->push_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent(extent_reference_t &&extent_ref) {
release_extent_preliminaries();
zone->release_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent_preliminaries() {
assert_thread();
rassert(state == state_running);
--stats->pm_extents_in_use;
stats->pm_bytes_in_use -= extent_size;
}
void extent_manager_t::end_transaction(extent_transaction_t *t) {
assert_thread();
rassert(current_transaction == t);
current_transaction = NULL;
t->mark_end();
}
void extent_manager_t::commit_transaction(extent_transaction_t *t) {
assert_thread();
std::vector<extent_reference_t> extents = t->reset();
for (auto it = extents.begin(); it != extents.end(); ++it) {
zone->release_extent(std::move(*it));
}
}
size_t extent_manager_t::held_extents() {
assert_thread();
return zone->held_extents();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 by Glenn Hickey ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstdio>
#include "halMafExport.h"
#include "halMafBed.h"
using namespace std;
using namespace hal;
static CLParserPtr initParser()
{
CLParserPtr optionsParser = hdf5CLParserInstance();
optionsParser->addArgument("halFile", "input hal file");
optionsParser->addArgument("mafFile", "output maf file (or \"stdout\" to "
"pipe to standard output)");
optionsParser->addOption("refGenome",
"name of reference genome (root if empty)",
"\"\"");
optionsParser->addOption("refSequence",
"name of reference sequence within reference genome"
" (all sequences if empty)",
"\"\"");
optionsParser->addOption("refTargets",
"bed file coordinates of intervals in the reference "
"genome to export (or \"stdin\" to pipe from "
"standard input)",
"\"\"");
optionsParser->addOption("start",
"coordinate within reference genome (or sequence"
" if specified) to start at",
0);
optionsParser->addOption("length",
"length of the reference genome (or sequence"
" if specified) to convert. If set to 0,"
" the entire thing is converted",
0);
optionsParser->addOption("rootGenome",
"name of root genome (none if empty)",
"\"\"");
optionsParser->addOption("targetGenomes",
"comma-separated (no spaces) list of target genomes "
"(others are excluded) (vist all if empty)",
"\"\"");
optionsParser->addOption("maxRefGap",
"maximum gap length in reference",
0);
optionsParser->addOptionFlag("noDupes",
"ignore paralogy edges",
false);
optionsParser->addOptionFlag("noAncestors",
"don't write ancestral sequences",
false);
optionsParser->addOptionFlag("ucscNames",
"use UCSC convention of Genome.Seqeunce "
"for output names. By default, only sequence "
"names are used",
false);
optionsParser->addOptionFlag("unique",
"only write column whose left-most reference "
"coordinate is in the specified range. this "
"is used to insure that the same column isnt "
"sampled twice (due to ducplications) by mafs "
"generated on distinct ranges.",
false);
optionsParser->addOptionFlag("append",
"append to instead of overwrite output file.",
false);
optionsParser->setDescription("Convert hal database to maf.");
return optionsParser;
}
int main(int argc, char** argv)
{
CLParserPtr optionsParser = initParser();
string halPath;
string mafPath;
string refGenomeName;
string rootGenomeName;
string targetGenomes;
string refSequenceName;
string refTargetsPath;
hal_index_t start;
hal_size_t length;
hal_size_t maxRefGap;
bool noDupes;
bool noAncestors;
bool ucscNames;
bool unique;
bool append;
try
{
optionsParser->parseOptions(argc, argv);
halPath = optionsParser->getArgument<string>("halFile");
mafPath = optionsParser->getArgument<string>("mafFile");
refGenomeName = optionsParser->getOption<string>("refGenome");
rootGenomeName = optionsParser->getOption<string>("rootGenome");
targetGenomes = optionsParser->getOption<string>("targetGenomes");
refSequenceName = optionsParser->getOption<string>("refSequence");
refTargetsPath = optionsParser->getOption<string>("refTargets");
start = optionsParser->getOption<hal_index_t>("start");
length = optionsParser->getOption<hal_size_t>("length");
maxRefGap = optionsParser->getOption<hal_size_t>("maxRefGap");
noDupes = optionsParser->getFlag("noDupes");
noAncestors = optionsParser->getFlag("noAncestors");
ucscNames = optionsParser->getFlag("ucscNames");
unique = optionsParser->getFlag("unique");
append = optionsParser->getFlag("append");
if (rootGenomeName != "\"\"" && targetGenomes != "\"\"")
{
throw hal_exception("--rootGenome and --targetGenomes options are "
"mutually exclusive");
}
}
catch(exception& e)
{
cerr << e.what() << endl;
optionsParser->printUsage(cerr);
exit(1);
}
try
{
AlignmentConstPtr alignment = openHalAlignmentReadOnly(halPath,
optionsParser);
if (alignment->getNumGenomes() == 0)
{
throw hal_exception("hal alignmenet is empty");
}
set<const Genome*> targetSet;
const Genome* rootGenome = NULL;
if (rootGenomeName != "\"\"")
{
rootGenome = alignment->openGenome(rootGenomeName);
if (rootGenome == NULL)
{
throw hal_exception(string("Root genome, ") + rootGenomeName +
", not found in alignment");
}
if (rootGenomeName != alignment->getRootName())
{
getGenomesInSubTree(rootGenome, targetSet);
}
}
if (targetGenomes != "\"\"")
{
vector<string> targetNames = chopString(targetGenomes, ",");
for (size_t i = 0; i < targetNames.size(); ++i)
{
const Genome* tgtGenome = alignment->openGenome(targetNames[i]);
if (tgtGenome == NULL)
{
throw hal_exception(string("Target genome, ") + targetNames[i] +
", not found in alignment");
}
targetSet.insert(tgtGenome);
}
}
const Genome* refGenome = NULL;
if (refGenomeName != "\"\"")
{
refGenome = alignment->openGenome(refGenomeName);
if (refGenome == NULL)
{
throw hal_exception(string("Reference genome, ") + refGenomeName +
", not found in alignment");
}
}
else
{
refGenome = alignment->openGenome(alignment->getRootName());
}
const SegmentedSequence* ref = refGenome;
const Sequence* refSequence = NULL;
if (refSequenceName != "\"\"")
{
refSequence = refGenome->getSequence(refSequenceName);
ref = refSequence;
if (refSequence == NULL)
{
throw hal_exception(string("Reference sequence, ") + refSequenceName +
", not found in reference genome, " +
refGenome->getName());
}
}
ios_base::openmode openFlags = ios_base::out;
if (append == true)
{
openFlags |= ios_base::app;
}
ofstream mafFileStream;
if (mafPath != "stdout")
{
mafFileStream.open(mafPath.c_str(), openFlags);
if (!mafFileStream)
{
throw hal_exception("Error opening " + mafPath);
}
}
ostream& mafStream = mafPath != "stdout" ? mafFileStream : cout;
MafExport mafExport;
mafExport.setMaxRefGap(maxRefGap);
mafExport.setNoDupes(noDupes);
mafExport.setNoAncestors(noAncestors);
mafExport.setUcscNames(ucscNames);
mafExport.setUnique(unique);
mafExport.setAppend(append);
ifstream refTargetsStream;
if (refTargetsPath != "\"\"")
{
ifstream bedFileStream;
if (refTargetsPath != "stdin")
{
bedFileStream.open(refTargetsPath.c_str());
if (!refTargetsStream)
{
throw hal_exception("Error opening " + refTargetsPath);
}
}
istream& bedStream = refTargetsPath != "stdin" ? bedFileStream : cin;
MafBed mafBed(mafStream, alignment, refGenome, refSequence, start,
length, targetSet, mafExport);
mafBed.scan(&bedStream);
}
else
{
if (start == 0 && length == 0 && ref->getSequenceLength() == 0)
{
string refSeqName =
refSequence != NULL ? refSequence->getName() : refGenome->getName();
cerr << "hal2maf: Warning reference sequence " << refSeqName
<< " has zero length. MAF output will be empty" << endl;
}
else
{
mafExport.convertSegmentedSequence(mafStream, alignment, ref,
start, length, targetSet);
}
}
if (mafPath != "stdout")
{
// dont want to leave a size 0 file when there's not ouput because
// it can make some scripts (ie that process a maf for each contig)
// obnoxious (presently the case for halPhlyoPTrain which uses
// hal2mafMP --splitBySequence).
if (mafFileStream.tellp() == (streampos)0)
{
std::remove(mafPath.c_str());
}
}
}
catch(hal_exception& e)
{
cerr << "hal exception caught: " << e.what() << endl;
return 1;
}
catch(exception& e)
{
cerr << "Exception caught: " << e.what() << endl;
return 1;
}
return 0;
}
<commit_msg>add header to empty maf<commit_after>/*
* Copyright (C) 2012 by Glenn Hickey ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstdio>
#include "halMafExport.h"
#include "halMafBed.h"
using namespace std;
using namespace hal;
static CLParserPtr initParser()
{
CLParserPtr optionsParser = hdf5CLParserInstance();
optionsParser->addArgument("halFile", "input hal file");
optionsParser->addArgument("mafFile", "output maf file (or \"stdout\" to "
"pipe to standard output)");
optionsParser->addOption("refGenome",
"name of reference genome (root if empty)",
"\"\"");
optionsParser->addOption("refSequence",
"name of reference sequence within reference genome"
" (all sequences if empty)",
"\"\"");
optionsParser->addOption("refTargets",
"bed file coordinates of intervals in the reference "
"genome to export (or \"stdin\" to pipe from "
"standard input)",
"\"\"");
optionsParser->addOption("start",
"coordinate within reference genome (or sequence"
" if specified) to start at",
0);
optionsParser->addOption("length",
"length of the reference genome (or sequence"
" if specified) to convert. If set to 0,"
" the entire thing is converted",
0);
optionsParser->addOption("rootGenome",
"name of root genome (none if empty)",
"\"\"");
optionsParser->addOption("targetGenomes",
"comma-separated (no spaces) list of target genomes "
"(others are excluded) (vist all if empty)",
"\"\"");
optionsParser->addOption("maxRefGap",
"maximum gap length in reference",
0);
optionsParser->addOptionFlag("noDupes",
"ignore paralogy edges",
false);
optionsParser->addOptionFlag("noAncestors",
"don't write ancestral sequences",
false);
optionsParser->addOptionFlag("ucscNames",
"use UCSC convention of Genome.Seqeunce "
"for output names. By default, only sequence "
"names are used",
false);
optionsParser->addOptionFlag("unique",
"only write column whose left-most reference "
"coordinate is in the specified range. this "
"is used to insure that the same column isnt "
"sampled twice (due to ducplications) by mafs "
"generated on distinct ranges.",
false);
optionsParser->addOptionFlag("append",
"append to instead of overwrite output file.",
false);
optionsParser->setDescription("Convert hal database to maf.");
return optionsParser;
}
int main(int argc, char** argv)
{
CLParserPtr optionsParser = initParser();
string halPath;
string mafPath;
string refGenomeName;
string rootGenomeName;
string targetGenomes;
string refSequenceName;
string refTargetsPath;
hal_index_t start;
hal_size_t length;
hal_size_t maxRefGap;
bool noDupes;
bool noAncestors;
bool ucscNames;
bool unique;
bool append;
try
{
optionsParser->parseOptions(argc, argv);
halPath = optionsParser->getArgument<string>("halFile");
mafPath = optionsParser->getArgument<string>("mafFile");
refGenomeName = optionsParser->getOption<string>("refGenome");
rootGenomeName = optionsParser->getOption<string>("rootGenome");
targetGenomes = optionsParser->getOption<string>("targetGenomes");
refSequenceName = optionsParser->getOption<string>("refSequence");
refTargetsPath = optionsParser->getOption<string>("refTargets");
start = optionsParser->getOption<hal_index_t>("start");
length = optionsParser->getOption<hal_size_t>("length");
maxRefGap = optionsParser->getOption<hal_size_t>("maxRefGap");
noDupes = optionsParser->getFlag("noDupes");
noAncestors = optionsParser->getFlag("noAncestors");
ucscNames = optionsParser->getFlag("ucscNames");
unique = optionsParser->getFlag("unique");
append = optionsParser->getFlag("append");
if (rootGenomeName != "\"\"" && targetGenomes != "\"\"")
{
throw hal_exception("--rootGenome and --targetGenomes options are "
"mutually exclusive");
}
}
catch(exception& e)
{
cerr << e.what() << endl;
optionsParser->printUsage(cerr);
exit(1);
}
try
{
AlignmentConstPtr alignment = openHalAlignmentReadOnly(halPath,
optionsParser);
if (alignment->getNumGenomes() == 0)
{
throw hal_exception("hal alignmenet is empty");
}
set<const Genome*> targetSet;
const Genome* rootGenome = NULL;
if (rootGenomeName != "\"\"")
{
rootGenome = alignment->openGenome(rootGenomeName);
if (rootGenome == NULL)
{
throw hal_exception(string("Root genome, ") + rootGenomeName +
", not found in alignment");
}
if (rootGenomeName != alignment->getRootName())
{
getGenomesInSubTree(rootGenome, targetSet);
}
}
if (targetGenomes != "\"\"")
{
vector<string> targetNames = chopString(targetGenomes, ",");
for (size_t i = 0; i < targetNames.size(); ++i)
{
const Genome* tgtGenome = alignment->openGenome(targetNames[i]);
if (tgtGenome == NULL)
{
throw hal_exception(string("Target genome, ") + targetNames[i] +
", not found in alignment");
}
targetSet.insert(tgtGenome);
}
}
const Genome* refGenome = NULL;
if (refGenomeName != "\"\"")
{
refGenome = alignment->openGenome(refGenomeName);
if (refGenome == NULL)
{
throw hal_exception(string("Reference genome, ") + refGenomeName +
", not found in alignment");
}
}
else
{
refGenome = alignment->openGenome(alignment->getRootName());
}
const SegmentedSequence* ref = refGenome;
const Sequence* refSequence = NULL;
if (refSequenceName != "\"\"")
{
refSequence = refGenome->getSequence(refSequenceName);
ref = refSequence;
if (refSequence == NULL)
{
throw hal_exception(string("Reference sequence, ") + refSequenceName +
", not found in reference genome, " +
refGenome->getName());
}
}
ios_base::openmode openFlags = ios_base::out;
if (append == true)
{
openFlags |= ios_base::app;
}
ofstream mafFileStream;
if (mafPath != "stdout")
{
mafFileStream.open(mafPath.c_str(), openFlags);
if (!mafFileStream)
{
throw hal_exception("Error opening " + mafPath);
}
}
ostream& mafStream = mafPath != "stdout" ? mafFileStream : cout;
MafExport mafExport;
mafExport.setMaxRefGap(maxRefGap);
mafExport.setNoDupes(noDupes);
mafExport.setNoAncestors(noAncestors);
mafExport.setUcscNames(ucscNames);
mafExport.setUnique(unique);
mafExport.setAppend(append);
ifstream refTargetsStream;
if (refTargetsPath != "\"\"")
{
ifstream bedFileStream;
if (refTargetsPath != "stdin")
{
bedFileStream.open(refTargetsPath.c_str());
if (!refTargetsStream)
{
throw hal_exception("Error opening " + refTargetsPath);
}
}
istream& bedStream = refTargetsPath != "stdin" ? bedFileStream : cin;
MafBed mafBed(mafStream, alignment, refGenome, refSequence, start,
length, targetSet, mafExport);
mafBed.scan(&bedStream);
}
else
{
if (start == 0 && length == 0 && ref->getSequenceLength() == 0)
{
string refSeqName =
refSequence != NULL ? refSequence->getName() : refGenome->getName();
cerr << "hal2maf: Warning reference sequence " << refSeqName
<< " has zero length. MAF output will be empty" << endl;
mafStream << "##maf version=1 scoring=N/A\n"
<< "# hal " << alignment->getNewickTree() << endl << endl;
}
else
{
mafExport.convertSegmentedSequence(mafStream, alignment, ref,
start, length, targetSet);
}
}
if (mafPath != "stdout")
{
// dont want to leave a size 0 file when there's not ouput because
// it can make some scripts (ie that process a maf for each contig)
// obnoxious (presently the case for halPhlyoPTrain which uses
// hal2mafMP --splitBySequence).
if (mafFileStream.tellp() == (streampos)0)
{
std::remove(mafPath.c_str());
}
}
}
catch(hal_exception& e)
{
cerr << "hal exception caught: " << e.what() << endl;
return 1;
}
catch(exception& e)
{
cerr << "Exception caught: " << e.what() << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "yaml-cpp/yaml.h" // IWYU pragma: keep
#include "gtest/gtest.h"
namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
Node node = Load("foo");
node = Node();
}
TEST(LoadNodeTest, FallbackValues) {
Node node = Load("foo: bar\nx: 2");
EXPECT_EQ("bar", node["foo"].as<std::string>());
EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
EXPECT_EQ(2, node["x"].as<int>());
EXPECT_EQ(2, node["x"].as<int>(5));
EXPECT_EQ(5, node["y"].as<int>(5));
}
TEST(LoadNodeTest, NumericConversion) {
Node node = Load("[1.5, 1, .nan, .inf, -.inf, 0x15, 015]");
EXPECT_EQ(1.5f, node[0].as<float>());
EXPECT_EQ(1.5, node[0].as<double>());
EXPECT_THROW(node[0].as<int>(), TypedBadConversion<int>);
EXPECT_EQ(1, node[1].as<int>());
EXPECT_EQ(1.0f, node[1].as<float>());
EXPECT_NE(node[2].as<float>(), node[2].as<float>());
EXPECT_EQ(std::numeric_limits<float>::infinity(), node[3].as<float>());
EXPECT_EQ(-std::numeric_limits<float>::infinity(), node[4].as<float>());
EXPECT_EQ(21, node[5].as<int>());
EXPECT_EQ(13, node[6].as<int>());
}
TEST(LoadNodeTest, Binary) {
Node node = Load(
"[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
"\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
"B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
"x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
"B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
"dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
"4K\"]");
EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
node[0].as<Binary>());
EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
"Man is distinguished, not only by his reason, "
"but by this singular passion from other "
"animals, which is a lust of the mind, that by "
"a perseverance of delight in the continued and "
"indefatigable generation of knowledge, exceeds "
"the short vehemence of any carnal pleasure.\n"),
270),
node[1].as<Binary>());
}
TEST(LoadNodeTest, IterateSequence) {
Node node = Load("[1, 3, 5, 7]");
int seq[] = {1, 3, 5, 7};
int i = 0;
for (const_iterator it = node.begin(); it != node.end(); ++it) {
EXPECT_TRUE(i < 4);
int x = seq[i++];
EXPECT_EQ(x, it->as<int>());
}
EXPECT_EQ(4, i);
}
TEST(LoadNodeTest, IterateMap) {
Node node = Load("{a: A, b: B, c: C}");
int i = 0;
for (const_iterator it = node.begin(); it != node.end(); ++it) {
EXPECT_TRUE(i < 3);
i++;
EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
}
EXPECT_EQ(3, i);
}
#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
Node node = Load("[1, 3, 5, 7]");
int seq[] = {1, 3, 5, 7};
int i = 0;
BOOST_FOREACH (const Node& item, node) {
int x = seq[i++];
EXPECT_EQ(x, item.as<int>());
}
}
TEST(LoadNodeTest, ForEachMap) {
Node node = Load("{a: A, b: B, c: C}");
BOOST_FOREACH (const const_iterator::value_type& p, node) {
EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
}
}
#endif
TEST(LoadNodeTest, CloneScalar) {
Node node = Load("!foo monkey");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
EXPECT_EQ(clone.Tag(), node.Tag());
}
TEST(LoadNodeTest, CloneSeq) {
Node node = Load("[1, 3, 5, 7]");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(NodeType::Sequence, clone.Type());
EXPECT_EQ(clone.size(), node.size());
for (std::size_t i = 0; i < node.size(); i++) {
EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
}
}
TEST(LoadNodeTest, CloneMap) {
Node node = Load("{foo: bar}");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(NodeType::Map, clone.Type());
EXPECT_EQ(clone.size(), node.size());
EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}
TEST(LoadNodeTest, CloneAlias) {
Node node = Load("&foo [*foo]");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(NodeType::Sequence, clone.Type());
EXPECT_EQ(clone.size(), node.size());
EXPECT_EQ(clone[0], clone);
}
TEST(LoadNodeTest, ForceInsertIntoMap) {
Node node;
node["a"] = "b";
node.force_insert("x", "y");
node.force_insert("a", 5);
EXPECT_EQ(3, node.size());
EXPECT_EQ(NodeType::Map, node.Type());
bool ab = false;
bool a5 = false;
bool xy = false;
for (const_iterator it = node.begin(); it != node.end(); ++it) {
if (it->first.as<std::string>() == "a") {
if (it->second.as<std::string>() == "b")
ab = true;
else if (it->second.as<std::string>() == "5")
a5 = true;
} else if (it->first.as<std::string>() == "x" &&
it->second.as<std::string>() == "y")
xy = true;
}
EXPECT_TRUE(ab);
EXPECT_TRUE(a5);
EXPECT_TRUE(xy);
}
TEST(LoadNodeTest, ResetNode) {
Node node = Load("[1, 2, 3]");
EXPECT_TRUE(!node.IsNull());
Node other = node;
node.reset();
EXPECT_TRUE(node.IsNull());
EXPECT_TRUE(!other.IsNull());
node.reset(other);
EXPECT_TRUE(!node.IsNull());
EXPECT_EQ(node, other);
}
TEST(LoadNodeTest, EmptyString) {
Node node = Load("\"\"");
EXPECT_TRUE(!node.IsNull());
}
TEST(LoadNodeTest, DereferenceIteratorError) {
Node node = Load("[{a: b}, 1, 2]");
EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
EXPECT_EQ(true, (*node.begin()).IsMap());
EXPECT_EQ(true, node.begin()->IsMap());
EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
}
TEST(NodeTest, EmitEmptyNode) {
Node node;
Emitter emitter;
emitter << node;
EXPECT_EQ("", std::string(emitter.c_str()));
}
TEST(NodeTest, ParseNodeStyle) {
EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}
struct ParserExceptionTestCase {
std::string name;
std::string input;
std::string expected_exception;
};
TEST(NodeTest, IncompleteJson) {
std::vector<ParserExceptionTestCase> tests = {
{"JSON map without value", "{\"access\"", ErrorMsg::END_OF_MAP_FLOW},
{"JSON map with colon but no value", "{\"access\":",
ErrorMsg::END_OF_MAP_FLOW},
{"JSON map with unclosed value quote", "{\"access\":\"",
ErrorMsg::END_OF_MAP_FLOW},
{"JSON map without end brace", "{\"access\":\"abc\"",
ErrorMsg::END_OF_MAP_FLOW},
};
for (const ParserExceptionTestCase test : tests) {
try {
Load(test.input);
FAIL() << "Expected exception " << test.expected_exception << " for "
<< test.name << ", input: " << test.input;
} catch (const ParserException& e) {
EXPECT_EQ(test.expected_exception, e.msg);
}
}
}
} // namespace
} // namespace YAML
<commit_msg>Add test to verify that ~ is loaded as null.<commit_after>#include "yaml-cpp/yaml.h" // IWYU pragma: keep
#include "gtest/gtest.h"
namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
Node node = Load("foo");
node = Node();
}
TEST(LoadNodeTest, FallbackValues) {
Node node = Load("foo: bar\nx: 2");
EXPECT_EQ("bar", node["foo"].as<std::string>());
EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
EXPECT_EQ(2, node["x"].as<int>());
EXPECT_EQ(2, node["x"].as<int>(5));
EXPECT_EQ(5, node["y"].as<int>(5));
}
TEST(LoadNodeTest, NumericConversion) {
Node node = Load("[1.5, 1, .nan, .inf, -.inf, 0x15, 015]");
EXPECT_EQ(1.5f, node[0].as<float>());
EXPECT_EQ(1.5, node[0].as<double>());
EXPECT_THROW(node[0].as<int>(), TypedBadConversion<int>);
EXPECT_EQ(1, node[1].as<int>());
EXPECT_EQ(1.0f, node[1].as<float>());
EXPECT_NE(node[2].as<float>(), node[2].as<float>());
EXPECT_EQ(std::numeric_limits<float>::infinity(), node[3].as<float>());
EXPECT_EQ(-std::numeric_limits<float>::infinity(), node[4].as<float>());
EXPECT_EQ(21, node[5].as<int>());
EXPECT_EQ(13, node[6].as<int>());
}
TEST(LoadNodeTest, Binary) {
Node node = Load(
"[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
"\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
"B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
"x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
"B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
"dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
"4K\"]");
EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
node[0].as<Binary>());
EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
"Man is distinguished, not only by his reason, "
"but by this singular passion from other "
"animals, which is a lust of the mind, that by "
"a perseverance of delight in the continued and "
"indefatigable generation of knowledge, exceeds "
"the short vehemence of any carnal pleasure.\n"),
270),
node[1].as<Binary>());
}
TEST(LoadNodeTest, IterateSequence) {
Node node = Load("[1, 3, 5, 7]");
int seq[] = {1, 3, 5, 7};
int i = 0;
for (const_iterator it = node.begin(); it != node.end(); ++it) {
EXPECT_TRUE(i < 4);
int x = seq[i++];
EXPECT_EQ(x, it->as<int>());
}
EXPECT_EQ(4, i);
}
TEST(LoadNodeTest, IterateMap) {
Node node = Load("{a: A, b: B, c: C}");
int i = 0;
for (const_iterator it = node.begin(); it != node.end(); ++it) {
EXPECT_TRUE(i < 3);
i++;
EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
}
EXPECT_EQ(3, i);
}
#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
Node node = Load("[1, 3, 5, 7]");
int seq[] = {1, 3, 5, 7};
int i = 0;
BOOST_FOREACH (const Node& item, node) {
int x = seq[i++];
EXPECT_EQ(x, item.as<int>());
}
}
TEST(LoadNodeTest, ForEachMap) {
Node node = Load("{a: A, b: B, c: C}");
BOOST_FOREACH (const const_iterator::value_type& p, node) {
EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
}
}
#endif
TEST(LoadNodeTest, CloneScalar) {
Node node = Load("!foo monkey");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
EXPECT_EQ(clone.Tag(), node.Tag());
}
TEST(LoadNodeTest, CloneSeq) {
Node node = Load("[1, 3, 5, 7]");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(NodeType::Sequence, clone.Type());
EXPECT_EQ(clone.size(), node.size());
for (std::size_t i = 0; i < node.size(); i++) {
EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
}
}
TEST(LoadNodeTest, CloneMap) {
Node node = Load("{foo: bar}");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(NodeType::Map, clone.Type());
EXPECT_EQ(clone.size(), node.size());
EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}
TEST(LoadNodeTest, CloneAlias) {
Node node = Load("&foo [*foo]");
Node clone = Clone(node);
EXPECT_FALSE(clone == node);
EXPECT_EQ(NodeType::Sequence, clone.Type());
EXPECT_EQ(clone.size(), node.size());
EXPECT_EQ(clone[0], clone);
}
TEST(LoadNodeTest, ForceInsertIntoMap) {
Node node;
node["a"] = "b";
node.force_insert("x", "y");
node.force_insert("a", 5);
EXPECT_EQ(3, node.size());
EXPECT_EQ(NodeType::Map, node.Type());
bool ab = false;
bool a5 = false;
bool xy = false;
for (const_iterator it = node.begin(); it != node.end(); ++it) {
if (it->first.as<std::string>() == "a") {
if (it->second.as<std::string>() == "b")
ab = true;
else if (it->second.as<std::string>() == "5")
a5 = true;
} else if (it->first.as<std::string>() == "x" &&
it->second.as<std::string>() == "y")
xy = true;
}
EXPECT_TRUE(ab);
EXPECT_TRUE(a5);
EXPECT_TRUE(xy);
}
TEST(LoadNodeTest, ResetNode) {
Node node = Load("[1, 2, 3]");
EXPECT_TRUE(!node.IsNull());
Node other = node;
node.reset();
EXPECT_TRUE(node.IsNull());
EXPECT_TRUE(!other.IsNull());
node.reset(other);
EXPECT_TRUE(!node.IsNull());
EXPECT_EQ(node, other);
}
TEST(LoadNodeTest, EmptyString) {
Node node = Load("\"\"");
EXPECT_TRUE(!node.IsNull());
}
TEST(LoadNodeTest, DereferenceIteratorError) {
Node node = Load("[{a: b}, 1, 2]");
EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
EXPECT_EQ(true, (*node.begin()).IsMap());
EXPECT_EQ(true, node.begin()->IsMap());
EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
}
TEST(NodeTest, EmitEmptyNode) {
Node node;
Emitter emitter;
emitter << node;
EXPECT_EQ("", std::string(emitter.c_str()));
}
TEST(NodeTest, ParseNodeStyle) {
EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}
struct ParserExceptionTestCase {
std::string name;
std::string input;
std::string expected_exception;
};
TEST(NodeTest, IncompleteJson) {
std::vector<ParserExceptionTestCase> tests = {
{"JSON map without value", "{\"access\"", ErrorMsg::END_OF_MAP_FLOW},
{"JSON map with colon but no value", "{\"access\":",
ErrorMsg::END_OF_MAP_FLOW},
{"JSON map with unclosed value quote", "{\"access\":\"",
ErrorMsg::END_OF_MAP_FLOW},
{"JSON map without end brace", "{\"access\":\"abc\"",
ErrorMsg::END_OF_MAP_FLOW},
};
for (const ParserExceptionTestCase test : tests) {
try {
Load(test.input);
FAIL() << "Expected exception " << test.expected_exception << " for "
<< test.name << ", input: " << test.input;
} catch (const ParserException& e) {
EXPECT_EQ(test.expected_exception, e.msg);
}
}
}
TEST(NodeTest, LoadTildeAsNull) {
Node node = Load("~");
ASSERT_TRUE(node.IsNull());
}
} // namespace
} // namespace YAML
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "build/intsafe_workaround.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <initguid.h>
#include <shellapi.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/process/kill.h"
#include "base/strings/string16.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_handle.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/installer/util/browser_distribution.h"
#include "win8/delegate_execute/command_execute_impl.h"
#include "win8/delegate_execute/crash_server_init.h"
#include "win8/delegate_execute/delegate_execute_operation.h"
#include "win8/delegate_execute/resource.h"
using namespace ATL;
// Usually classes derived from CAtlExeModuleT, or other types of ATL
// COM module classes statically define their CLSID at compile time through
// the use of various macros, and ATL internals takes care of creating the
// class objects and registering them. However, we need to register the same
// object with different CLSIDs depending on a runtime setting, so we handle
// that logic here, before the main ATL message loop runs.
class DelegateExecuteModule
: public ATL::CAtlExeModuleT< DelegateExecuteModule > {
public :
typedef ATL::CAtlExeModuleT<DelegateExecuteModule> ParentClass;
typedef CComObject<CommandExecuteImpl> ImplType;
DelegateExecuteModule()
: registration_token_(0) {
}
HRESULT PreMessageLoop(int nShowCmd) {
HRESULT hr = S_OK;
base::string16 clsid_string;
GUID clsid;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!dist->GetCommandExecuteImplClsid(&clsid_string))
return E_FAIL;
hr = ::CLSIDFromString(clsid_string.c_str(), &clsid);
if (FAILED(hr))
return hr;
// We use the same class creation logic as ATL itself. See
// _ATL_OBJMAP_ENTRY::RegisterClassObject() in atlbase.h
hr = ImplType::_ClassFactoryCreatorClass::CreateInstance(
ImplType::_CreatorClass::CreateInstance, IID_IUnknown,
instance_.ReceiveVoid());
if (FAILED(hr))
return hr;
hr = ::CoRegisterClassObject(clsid, instance_, CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED, ®istration_token_);
if (FAILED(hr))
return hr;
return ParentClass::PreMessageLoop(nShowCmd);
}
HRESULT PostMessageLoop() {
if (registration_token_ != 0) {
::CoRevokeClassObject(registration_token_);
registration_token_ = 0;
}
instance_.Release();
return ParentClass::PostMessageLoop();
}
private:
base::win::ScopedComPtr<IUnknown> instance_;
DWORD registration_token_;
};
DelegateExecuteModule _AtlModule;
using delegate_execute::DelegateExecuteOperation;
using base::win::ScopedHandle;
int RelaunchChrome(const DelegateExecuteOperation& operation) {
AtlTrace("Relaunching [%ls] with flags [%s]\n",
operation.mutex().c_str(), operation.relaunch_flags());
ScopedHandle mutex(OpenMutexW(SYNCHRONIZE, FALSE, operation.mutex().c_str()));
if (mutex.IsValid()) {
const int kWaitSeconds = 5;
DWORD result = ::WaitForSingleObject(mutex, kWaitSeconds * 1000);
if (result == WAIT_ABANDONED) {
// This is the normal case. Chrome exits and windows marks the mutex as
// abandoned.
} else if (result == WAIT_OBJECT_0) {
// This is unexpected. Check if somebody is not closing the mutex on
// RelaunchChromehelper, the mutex should not be closed.
AtlTrace("Unexpected release of the relaunch mutex!!\n");
} else if (result == WAIT_TIMEOUT) {
// This could mean that Chrome is hung. Proceed to exterminate.
DWORD pid = operation.GetParentPid();
AtlTrace("%ds timeout. Killing Chrome %d\n", kWaitSeconds, pid);
base::KillProcessById(pid, 0, false);
} else {
AtlTrace("Failed to wait for relaunch mutex, result is 0x%x\n", result);
}
} else {
// It is possible that chrome exits so fast that the mutex is not there.
AtlTrace("No relaunch mutex found\n");
}
base::win::ScopedCOMInitializer com_initializer;
base::string16 relaunch_flags(operation.relaunch_flags());
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.fMask = SEE_MASK_FLAG_LOG_USAGE;
sei.nShow = SW_SHOWNORMAL;
sei.lpFile = operation.shortcut().value().c_str();
sei.lpParameters = relaunch_flags.c_str();
AtlTrace(L"Relaunching Chrome via shortcut [%ls]\n", sei.lpFile);
if (!::ShellExecuteExW(&sei)) {
int error = HRESULT_FROM_WIN32(::GetLastError());
AtlTrace("ShellExecute returned 0x%08X\n", error);
return error;
}
return S_OK;
}
extern "C" int WINAPI _tWinMain(HINSTANCE , HINSTANCE, LPTSTR, int nShowCmd) {
scoped_ptr<google_breakpad::ExceptionHandler> breakpad =
delegate_execute::InitializeCrashReporting();
base::AtExitManager exit_manager;
AtlTrace("delegate_execute enter\n");
CommandLine::Init(0, NULL);
HRESULT ret_code = E_UNEXPECTED;
DelegateExecuteOperation operation;
if (operation.Init(CommandLine::ForCurrentProcess())) {
switch (operation.operation_type()) {
case DelegateExecuteOperation::DELEGATE_EXECUTE:
ret_code = _AtlModule.WinMain(nShowCmd);
break;
case DelegateExecuteOperation::RELAUNCH_CHROME:
ret_code = RelaunchChrome(operation);
break;
default:
NOTREACHED();
}
}
AtlTrace("delegate_execute exit, code = %d\n", ret_code);
return ret_code;
}
<commit_msg>Don't pass a string16 to %s.<commit_after>// Copyright (c) 2012 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 "build/intsafe_workaround.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <initguid.h>
#include <shellapi.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/process/kill.h"
#include "base/strings/string16.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_handle.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/installer/util/browser_distribution.h"
#include "win8/delegate_execute/command_execute_impl.h"
#include "win8/delegate_execute/crash_server_init.h"
#include "win8/delegate_execute/delegate_execute_operation.h"
#include "win8/delegate_execute/resource.h"
using namespace ATL;
// Usually classes derived from CAtlExeModuleT, or other types of ATL
// COM module classes statically define their CLSID at compile time through
// the use of various macros, and ATL internals takes care of creating the
// class objects and registering them. However, we need to register the same
// object with different CLSIDs depending on a runtime setting, so we handle
// that logic here, before the main ATL message loop runs.
class DelegateExecuteModule
: public ATL::CAtlExeModuleT< DelegateExecuteModule > {
public :
typedef ATL::CAtlExeModuleT<DelegateExecuteModule> ParentClass;
typedef CComObject<CommandExecuteImpl> ImplType;
DelegateExecuteModule()
: registration_token_(0) {
}
HRESULT PreMessageLoop(int nShowCmd) {
HRESULT hr = S_OK;
base::string16 clsid_string;
GUID clsid;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!dist->GetCommandExecuteImplClsid(&clsid_string))
return E_FAIL;
hr = ::CLSIDFromString(clsid_string.c_str(), &clsid);
if (FAILED(hr))
return hr;
// We use the same class creation logic as ATL itself. See
// _ATL_OBJMAP_ENTRY::RegisterClassObject() in atlbase.h
hr = ImplType::_ClassFactoryCreatorClass::CreateInstance(
ImplType::_CreatorClass::CreateInstance, IID_IUnknown,
instance_.ReceiveVoid());
if (FAILED(hr))
return hr;
hr = ::CoRegisterClassObject(clsid, instance_, CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED, ®istration_token_);
if (FAILED(hr))
return hr;
return ParentClass::PreMessageLoop(nShowCmd);
}
HRESULT PostMessageLoop() {
if (registration_token_ != 0) {
::CoRevokeClassObject(registration_token_);
registration_token_ = 0;
}
instance_.Release();
return ParentClass::PostMessageLoop();
}
private:
base::win::ScopedComPtr<IUnknown> instance_;
DWORD registration_token_;
};
DelegateExecuteModule _AtlModule;
using delegate_execute::DelegateExecuteOperation;
using base::win::ScopedHandle;
int RelaunchChrome(const DelegateExecuteOperation& operation) {
AtlTrace("Relaunching [%ls] with flags [%ls]\n",
operation.mutex().c_str(), operation.relaunch_flags().c_str());
ScopedHandle mutex(OpenMutexW(SYNCHRONIZE, FALSE, operation.mutex().c_str()));
if (mutex.IsValid()) {
const int kWaitSeconds = 5;
DWORD result = ::WaitForSingleObject(mutex, kWaitSeconds * 1000);
if (result == WAIT_ABANDONED) {
// This is the normal case. Chrome exits and windows marks the mutex as
// abandoned.
} else if (result == WAIT_OBJECT_0) {
// This is unexpected. Check if somebody is not closing the mutex on
// RelaunchChromehelper, the mutex should not be closed.
AtlTrace("Unexpected release of the relaunch mutex!!\n");
} else if (result == WAIT_TIMEOUT) {
// This could mean that Chrome is hung. Proceed to exterminate.
DWORD pid = operation.GetParentPid();
AtlTrace("%ds timeout. Killing Chrome %d\n", kWaitSeconds, pid);
base::KillProcessById(pid, 0, false);
} else {
AtlTrace("Failed to wait for relaunch mutex, result is 0x%x\n", result);
}
} else {
// It is possible that chrome exits so fast that the mutex is not there.
AtlTrace("No relaunch mutex found\n");
}
base::win::ScopedCOMInitializer com_initializer;
base::string16 relaunch_flags(operation.relaunch_flags());
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.fMask = SEE_MASK_FLAG_LOG_USAGE;
sei.nShow = SW_SHOWNORMAL;
sei.lpFile = operation.shortcut().value().c_str();
sei.lpParameters = relaunch_flags.c_str();
AtlTrace(L"Relaunching Chrome via shortcut [%ls]\n", sei.lpFile);
if (!::ShellExecuteExW(&sei)) {
int error = HRESULT_FROM_WIN32(::GetLastError());
AtlTrace("ShellExecute returned 0x%08X\n", error);
return error;
}
return S_OK;
}
extern "C" int WINAPI _tWinMain(HINSTANCE , HINSTANCE, LPTSTR, int nShowCmd) {
scoped_ptr<google_breakpad::ExceptionHandler> breakpad =
delegate_execute::InitializeCrashReporting();
base::AtExitManager exit_manager;
AtlTrace("delegate_execute enter\n");
CommandLine::Init(0, NULL);
HRESULT ret_code = E_UNEXPECTED;
DelegateExecuteOperation operation;
if (operation.Init(CommandLine::ForCurrentProcess())) {
switch (operation.operation_type()) {
case DelegateExecuteOperation::DELEGATE_EXECUTE:
ret_code = _AtlModule.WinMain(nShowCmd);
break;
case DelegateExecuteOperation::RELAUNCH_CHROME:
ret_code = RelaunchChrome(operation);
break;
default:
NOTREACHED();
}
}
AtlTrace("delegate_execute exit, code = %d\n", ret_code);
return ret_code;
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include "script/LuaTestSupportScript.hpp"
#include "World.hpp"
class MockWorld : public World {
public:
MockWorld() {
World::_self = this;
}
};
class weather_bindings : public ::testing::Test {
public:
WeatherStruct weather;
MockWorld world;
};
TEST_F(weather_bindings, test_cloud_density_property) {
weather.cloud_density = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.cloud_density == 23)\n"
"weather.cloud_density = 42\n"
"return weather\n"
"end",
"weather_cloud_density_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.cloud_density);
}
TEST_F(weather_bindings, test_fog_density_property) {
weather.fog_density = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.fog_density == 23)\n"
"weather.fog_density = 42\n"
"return weather\n"
"end",
"weather_fog_density_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.fog_density);
}
TEST_F(weather_bindings, test_win_ddir_property) {
weather.wind_dir = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.wind_dir == 23)\n"
"weather.wind_dir = 42\n"
"return weather\n"
"end",
"weather_wind_dir_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.wind_dir);
}
TEST_F(weather_bindings, test_gust_strength_property) {
weather.gust_strength = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.gust_strength == 23)\n"
"weather.gust_strength = 42\n"
"return weather\n"
"end",
"weather_gust_strength_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.gust_strength);
}
TEST_F(weather_bindings, test_percipitation_strength_property) {
weather.percipitation_strength = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.percipitation_strength == 23)\n"
"weather.percipitation_strength = 42\n"
"return weather\n"
"end",
"weather_percipitation_strength_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.percipitation_strength);
}
TEST_F(weather_bindings, test_percipitation_type_property) {
weather.per_type = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.percipitation_type == 23)\n"
"weather.percipitation_type = 42\n"
"return weather\n"
"end",
"weather_percipitation_type_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.per_type);
}
TEST_F(weather_bindings, test_thunderstorm_property) {
weather.thunderstorm = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.thunderstorm == 23)\n"
"weather.thunderstorm = 42\n"
"return weather\n"
"end",
"weather_thunderstorm_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.thunderstorm);
}
TEST_F(weather_bindings, test_temperature_property) {
weather.temperature = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.temperature == 23)\n"
"weather.temperature = 42\n"
"return weather\n"
"end",
"weather_temperature_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.temperature);
}
TEST_F(weather_bindings, test_constructors) {
{
LuaTestSupportScript script { "function test()\n"
"local foo = WeatherStruct()\n"
"foo.cloud_density = 23\n"
"return foo\n"
"end",
"weather_constructor1_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(23, retval.cloud_density);
}
{
LuaTestSupportScript script { "function test()\n"
"local foo = WeatherStruct(23, 42, 5, 12, 6, 82, 9, 88)\n"
"return foo\n"
"end",
"weather_constructor2_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(23, retval.cloud_density);
}
};
auto main(int argc, char **argv) -> int {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Remove deleted WeatherStruct contructors from test<commit_after>#include <gmock/gmock.h>
#include "script/LuaTestSupportScript.hpp"
#include "World.hpp"
class MockWorld : public World {
public:
MockWorld() {
World::_self = this;
}
};
class weather_bindings : public ::testing::Test {
public:
WeatherStruct weather;
MockWorld world;
};
TEST_F(weather_bindings, test_cloud_density_property) {
weather.cloud_density = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.cloud_density == 23)\n"
"weather.cloud_density = 42\n"
"return weather\n"
"end",
"weather_cloud_density_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.cloud_density);
}
TEST_F(weather_bindings, test_fog_density_property) {
weather.fog_density = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.fog_density == 23)\n"
"weather.fog_density = 42\n"
"return weather\n"
"end",
"weather_fog_density_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.fog_density);
}
TEST_F(weather_bindings, test_win_ddir_property) {
weather.wind_dir = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.wind_dir == 23)\n"
"weather.wind_dir = 42\n"
"return weather\n"
"end",
"weather_wind_dir_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.wind_dir);
}
TEST_F(weather_bindings, test_gust_strength_property) {
weather.gust_strength = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.gust_strength == 23)\n"
"weather.gust_strength = 42\n"
"return weather\n"
"end",
"weather_gust_strength_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.gust_strength);
}
TEST_F(weather_bindings, test_percipitation_strength_property) {
weather.percipitation_strength = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.percipitation_strength == 23)\n"
"weather.percipitation_strength = 42\n"
"return weather\n"
"end",
"weather_percipitation_strength_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.percipitation_strength);
}
TEST_F(weather_bindings, test_percipitation_type_property) {
weather.per_type = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.percipitation_type == 23)\n"
"weather.percipitation_type = 42\n"
"return weather\n"
"end",
"weather_percipitation_type_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.per_type);
}
TEST_F(weather_bindings, test_thunderstorm_property) {
weather.thunderstorm = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.thunderstorm == 23)\n"
"weather.thunderstorm = 42\n"
"return weather\n"
"end",
"weather_thunderstorm_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.thunderstorm);
}
TEST_F(weather_bindings, test_temperature_property) {
weather.temperature = 23;
LuaTestSupportScript script { "function test(weather)\n"
"assert(weather.temperature == 23)\n"
"weather.temperature = 42\n"
"return weather\n"
"end",
"weather_temperature_test"
};
auto retval = script.test<WeatherStruct, WeatherStruct>(weather);
EXPECT_EQ(42, retval.temperature);
}
auto main(int argc, char **argv) -> int {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLIndexMarkExport.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:06:39 $
*
* 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 _XMLOFF_XMLINDEXMARKEXPORT_HXX_
#define _XMLOFF_XMLINDEXMARKEXPORT_HXX_
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
class SvXMLExport;
class XMLTextParagraphExport;
namespace com { namespace sun { namespace star {
namespace beans { class XPropertySet; }
} } }
namespace rtl {
class OUString;
class OUStringBuffer;
}
/**
* This class handles the export of index marks for table of content,
* alphabetical and user index.
*
* Marks for bibliography indices are internally modelled as text
* fields and thus handled in txtparae.cxx
*/
class XMLIndexMarkExport
{
::rtl::OUString sLevel;
::rtl::OUString sUserIndexName;
::rtl::OUString sPrimaryKey;
::rtl::OUString sSecondaryKey;
::rtl::OUString sDocumentIndexMark;
::rtl::OUString sIsStart;
::rtl::OUString sIsCollapsed;
::rtl::OUString sAlternativeText;
::rtl::OUString sTextReading;
::rtl::OUString sPrimaryKeyReading;
::rtl::OUString sSecondaryKeyReading;
::rtl::OUString sMainEntry;
SvXMLExport& rExport;
XMLTextParagraphExport& rParaExport;
public:
XMLIndexMarkExport(SvXMLExport& rExp,
XMLTextParagraphExport& rParaExp);
~XMLIndexMarkExport();
/**
* export by the property set of its *text* *portion*.
*
* The text portion supplies us with the properties of the index
* mark itself, as well as the information whether we are at the
* start or end of an index mark, or whether the index mark is
* collapsed.
*/
void ExportIndexMark(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet,
sal_Bool bAutoStyles);
protected:
/// export attributes of table-of-content index marks
void ExportTOCMarkAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
/// export attributes of user index marks
void ExportUserIndexMarkAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
/// export attributes of alphabetical index marks
void ExportAlphabeticalIndexMarkAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
/// create a numerical ID for this index mark
/// (represented by its properties)
void GetID(
::rtl::OUStringBuffer& sBuffer,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.450); FILE MERGED 2008/04/01 16:10:06 thb 1.4.450.2: #i85898# Stripping all external header guards 2008/03/31 16:28:33 rt 1.4.450.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: XMLIndexMarkExport.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 _XMLOFF_XMLINDEXMARKEXPORT_HXX_
#define _XMLOFF_XMLINDEXMARKEXPORT_HXX_
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
class SvXMLExport;
class XMLTextParagraphExport;
namespace com { namespace sun { namespace star {
namespace beans { class XPropertySet; }
} } }
namespace rtl {
class OUString;
class OUStringBuffer;
}
/**
* This class handles the export of index marks for table of content,
* alphabetical and user index.
*
* Marks for bibliography indices are internally modelled as text
* fields and thus handled in txtparae.cxx
*/
class XMLIndexMarkExport
{
::rtl::OUString sLevel;
::rtl::OUString sUserIndexName;
::rtl::OUString sPrimaryKey;
::rtl::OUString sSecondaryKey;
::rtl::OUString sDocumentIndexMark;
::rtl::OUString sIsStart;
::rtl::OUString sIsCollapsed;
::rtl::OUString sAlternativeText;
::rtl::OUString sTextReading;
::rtl::OUString sPrimaryKeyReading;
::rtl::OUString sSecondaryKeyReading;
::rtl::OUString sMainEntry;
SvXMLExport& rExport;
XMLTextParagraphExport& rParaExport;
public:
XMLIndexMarkExport(SvXMLExport& rExp,
XMLTextParagraphExport& rParaExp);
~XMLIndexMarkExport();
/**
* export by the property set of its *text* *portion*.
*
* The text portion supplies us with the properties of the index
* mark itself, as well as the information whether we are at the
* start or end of an index mark, or whether the index mark is
* collapsed.
*/
void ExportIndexMark(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet,
sal_Bool bAutoStyles);
protected:
/// export attributes of table-of-content index marks
void ExportTOCMarkAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
/// export attributes of user index marks
void ExportUserIndexMarkAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
/// export attributes of alphabetical index marks
void ExportAlphabeticalIndexMarkAttributes(
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
/// create a numerical ID for this index mark
/// (represented by its properties)
void GetID(
::rtl::OUStringBuffer& sBuffer,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> & rPropSet);
};
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include "std.h"
#include "eval.h"
std::chrono::milliseconds get_current_time()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
}
static bool is_int(std::shared_ptr<SchemeObject> p)
{
return bool(std::dynamic_pointer_cast<SchemeInt>(p));
}
static bool is_float(std::shared_ptr<SchemeObject> p)
{
return bool(std::dynamic_pointer_cast<SchemeFloat>(p));
}
static double get_value(std::shared_ptr<SchemeObject> p, const std::string &error_msg)
{
if(is_int(p))
return std::dynamic_pointer_cast<SchemeInt>(p)->value;
if(is_float(p))
return std::dynamic_pointer_cast<SchemeFloat>(p)->value;
throw eval_error(error_msg);
}
static long long get_int(std::shared_ptr<SchemeObject> p, const std::string &error_msg)
{
if(is_int(p))
return std::dynamic_pointer_cast<SchemeInt>(p)->value;
throw eval_error(error_msg);
}
std::function<std::shared_ptr<SchemeObject>(const std::list<std::shared_ptr<SchemeObject>> &)>
math_function(const std::string &name, double (*fun)(double))
{
return [name, fun](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error(name + ": number required");
double arg = get_value(l.front(), name + ": number required");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeFloat>(fun(arg)));
};
}
static std::shared_ptr<SchemeObject> fold(const std::list<std::shared_ptr<SchemeObject>> &l, long long start,
long long (*llf)(long long, long long), double (*df)(double, double),
bool start_with_first = false)
{
long long n = start;
double d = start;
bool is_double = false;
for(auto i : l)
{
if(!is_int(i) && !is_float(i))
{
throw eval_error(i->toString() + " is not an number");
}
if(start_with_first)
{
if(is_float(i))
{
is_double = true;
d = std::dynamic_pointer_cast<SchemeFloat>(i)->value;
}
else
{
d = n = std::dynamic_pointer_cast<SchemeInt>(i)->value;
}
start_with_first = false;
continue;
}
if(is_float(i))
{
is_double = true;
d = df(d, std::dynamic_pointer_cast<SchemeFloat>(i)->value);
}
else if(is_double)
{
d = df(d, std::dynamic_pointer_cast<SchemeInt>(i)->value);
}
else
{
n = llf(n, std::dynamic_pointer_cast<SchemeInt>(i)->value);
d = df(d, std::dynamic_pointer_cast<SchemeInt>(i)->value);
}
}
if(is_double)
return std::make_shared<SchemeFloat>(d);
else
return std::make_shared<SchemeInt>(n);
}
std::unordered_map<std::string, std::function<std::shared_ptr<SchemeObject>(
const std::list<std::shared_ptr<SchemeObject>> &)>> functions = {
{"+", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
return fold(l, 0, [](long long a, long long b) { return a + b; },
[](double a, double b) { return a + b; });
}
},
{"-", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
return fold(l, 0, [](long long a, long long b) { return a - b; },
[](double a, double b) { return a - b; }, l.size() > 1);
}
},
{"*", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
return fold(l, 1, [](long long a, long long b) { return a * b; }, [](double a, double b) { return a * b; });
}
},
{"/", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("/: two arguments required");
auto ap = l.front();
auto bp = (*next(l.begin()));
if(is_int(ap) && is_int(bp))
{
long long a = std::dynamic_pointer_cast<SchemeInt>(ap)->value;
long long b = std::dynamic_pointer_cast<SchemeInt>(bp)->value;
if(b == 0)
throw eval_error("Integer division by zero");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(a / b));
}
double a = get_value(ap, "/: numbers required");
double b = get_value(bp, "/: numbers required");
if(b == 0)
throw eval_error("Division by zero");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeFloat>(a / b));
}
},
{"remainder", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("remainder: two arguments required");
auto a = l.front();
auto b = (*next(l.begin()));
if(!is_int(a) || !is_int(b))
throw eval_error("remainder: two ints required");
long long x = std::dynamic_pointer_cast<SchemeInt>(a)->value;
long long y = std::dynamic_pointer_cast<SchemeInt>(b)->value;
if(y == 0)
throw eval_error("Division by zero");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(x % y));
}
},
{"random", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("random: an integer required");
long long max = get_int(l.front(), "random: an integer required");
long long res = (rand() * 1ll * RAND_MAX + rand()) % max;
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(res));
}
},
{"<", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("<: two arguments required");
if(get_value(l.front(), "<: numbers required") <
get_value((*next(l.begin())), "<: numbers required"))
return scheme_true;
else
return scheme_false;
}
},
{"=", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("=: two arguments required");
if(get_value(l.front(), "=: numbers required") ==
get_value((*next(l.begin())), "=: numbers required"))
return scheme_true;
else
return scheme_false;
}
},
{"random", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("random: an integer required");
long long max = get_int(l.front(), "random: an integer required");
long long res = (rand() * 1ll * RAND_MAX + rand()) % max;
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(res));
}
},
{"display", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("display: one argument required");
std::cout << l.front()->toString();
return scheme_empty;
}
},
{"runtime", [](const std::list<std::shared_ptr<SchemeObject>> &) {
return std::dynamic_pointer_cast<SchemeObject>(
std::make_shared<SchemeInt>((get_current_time() - start_time).count()));
}
},
{"error", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
std::string res = "error: ";
for(auto i : l)
{
res += i->toString() + " ";
}
throw eval_error(res);
return scheme_empty;
}
},
{"sin", math_function("sin", sin)},
{"cos", math_function("cos", cos)},
{"exp", math_function("exp", exp)},
{"log", math_function("log", log)},
{"tan", math_function("tan", tan)},
{"asin", math_function("asin", asin)},
{"acos", math_function("acos", acos)},
{"atan", math_function("atan", atan)},
{"sqrt", math_function("sqrt", sqrt)},
{"cons", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("cons: 2 arguments required");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemePair>(l.front(), l.back()));
}
},
{"pair?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("pair?: one argument required");
auto p = std::dynamic_pointer_cast<SchemePair>(l.front());
return (p && p != scheme_nil) ? scheme_true : scheme_false;
}
},
{"eq?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("eq?: 2 arguments required");
if(l.front() == l.back())
return scheme_true;
{
auto p1 = std::dynamic_pointer_cast<SchemeName>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeName>(l.back());
if(p1 && p2)
return p1->value == p2->value ? scheme_true : scheme_false;
}
{
auto p1 = std::dynamic_pointer_cast<SchemeBool>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeBool>(l.back());
if(p1 && p2)
return p1->value == p2->value ? scheme_true : scheme_false;
}
{
auto p1 = std::dynamic_pointer_cast<SchemeBuiltinFunc>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeBuiltinFunc>(l.back());
if(p1 && p2)
return p1->name == p2->name ? scheme_true : scheme_false;
}
if((is_int(l.front()) || is_float(l.front())) && (is_int(l.back()) || is_float(l.back())))
return get_value(l.front(), "") == get_value(l.back(), "") ? scheme_true : scheme_false;
{
auto p1 = std::dynamic_pointer_cast<SchemeString>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeString>(l.back());
if(p1 && p2)
return p1->value == p2->value ? scheme_true : scheme_false;
}
return scheme_false;
}
},
{"symbol?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("symbol?: one argument required");
auto p = std::dynamic_pointer_cast<SchemeName>(l.front());
return p ? scheme_true : scheme_false;
}
},
{"number?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("number?: one argument required");
return is_int(l.front()) || is_float(l.front()) ? scheme_true : scheme_false;
}
},
{"set-car!", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("set-car!: 2 arguments required");
auto p = std::dynamic_pointer_cast<SchemePair>(l.front());
if(!p || p == scheme_nil)
throw eval_error("set-car!: a pair required");
p->car = l.back();
return l.front();
}
},
{"set-cdr!", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("set-cdr!: 2 arguments required");
auto p = std::dynamic_pointer_cast<SchemePair>(l.front());
if(!p || p == scheme_nil)
throw eval_error("set-cdr!: a pair required");
p->cdr = l.back();
return l.front();
}
},
};
<commit_msg>atan2<commit_after>#include <iostream>
#include <cmath>
#include "std.h"
#include "eval.h"
std::chrono::milliseconds get_current_time()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
}
static bool is_int(std::shared_ptr<SchemeObject> p)
{
return bool(std::dynamic_pointer_cast<SchemeInt>(p));
}
static bool is_float(std::shared_ptr<SchemeObject> p)
{
return bool(std::dynamic_pointer_cast<SchemeFloat>(p));
}
static double get_value(std::shared_ptr<SchemeObject> p, const std::string &error_msg)
{
if(is_int(p))
return std::dynamic_pointer_cast<SchemeInt>(p)->value;
if(is_float(p))
return std::dynamic_pointer_cast<SchemeFloat>(p)->value;
throw eval_error(error_msg);
}
static long long get_int(std::shared_ptr<SchemeObject> p, const std::string &error_msg)
{
if(is_int(p))
return std::dynamic_pointer_cast<SchemeInt>(p)->value;
throw eval_error(error_msg);
}
std::function<std::shared_ptr<SchemeObject>(const std::list<std::shared_ptr<SchemeObject>> &)>
math_function(const std::string &name, double (*fun)(double))
{
return [name, fun](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error(name + ": number required");
double arg = get_value(l.front(), name + ": number required");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeFloat>(fun(arg)));
};
}
static std::shared_ptr<SchemeObject> fold(const std::list<std::shared_ptr<SchemeObject>> &l, long long start,
long long (*llf)(long long, long long), double (*df)(double, double),
bool start_with_first = false)
{
long long n = start;
double d = start;
bool is_double = false;
for(auto i : l)
{
if(!is_int(i) && !is_float(i))
{
throw eval_error(i->toString() + " is not an number");
}
if(start_with_first)
{
if(is_float(i))
{
is_double = true;
d = std::dynamic_pointer_cast<SchemeFloat>(i)->value;
}
else
{
d = n = std::dynamic_pointer_cast<SchemeInt>(i)->value;
}
start_with_first = false;
continue;
}
if(is_float(i))
{
is_double = true;
d = df(d, std::dynamic_pointer_cast<SchemeFloat>(i)->value);
}
else if(is_double)
{
d = df(d, std::dynamic_pointer_cast<SchemeInt>(i)->value);
}
else
{
n = llf(n, std::dynamic_pointer_cast<SchemeInt>(i)->value);
d = df(d, std::dynamic_pointer_cast<SchemeInt>(i)->value);
}
}
if(is_double)
return std::make_shared<SchemeFloat>(d);
else
return std::make_shared<SchemeInt>(n);
}
std::unordered_map<std::string, std::function<std::shared_ptr<SchemeObject>(
const std::list<std::shared_ptr<SchemeObject>> &)>> functions = {
{"+", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
return fold(l, 0, [](long long a, long long b) { return a + b; },
[](double a, double b) { return a + b; });
}
},
{"-", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
return fold(l, 0, [](long long a, long long b) { return a - b; },
[](double a, double b) { return a - b; }, l.size() > 1);
}
},
{"*", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
return fold(l, 1, [](long long a, long long b) { return a * b; }, [](double a, double b) { return a * b; });
}
},
{"/", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("/: two arguments required");
auto ap = l.front();
auto bp = (*next(l.begin()));
if(is_int(ap) && is_int(bp))
{
long long a = std::dynamic_pointer_cast<SchemeInt>(ap)->value;
long long b = std::dynamic_pointer_cast<SchemeInt>(bp)->value;
if(b == 0)
throw eval_error("Integer division by zero");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(a / b));
}
double a = get_value(ap, "/: numbers required");
double b = get_value(bp, "/: numbers required");
if(b == 0)
throw eval_error("Division by zero");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeFloat>(a / b));
}
},
{"remainder", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("remainder: two arguments required");
auto a = l.front();
auto b = (*next(l.begin()));
if(!is_int(a) || !is_int(b))
throw eval_error("remainder: two ints required");
long long x = std::dynamic_pointer_cast<SchemeInt>(a)->value;
long long y = std::dynamic_pointer_cast<SchemeInt>(b)->value;
if(y == 0)
throw eval_error("Division by zero");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(x % y));
}
},
{"random", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("random: an integer required");
long long max = get_int(l.front(), "random: an integer required");
long long res = (rand() * 1ll * RAND_MAX + rand()) % max;
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(res));
}
},
{"<", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("<: two arguments required");
if(get_value(l.front(), "<: numbers required") <
get_value((*next(l.begin())), "<: numbers required"))
return scheme_true;
else
return scheme_false;
}
},
{"=", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("=: two arguments required");
if(get_value(l.front(), "=: numbers required") ==
get_value((*next(l.begin())), "=: numbers required"))
return scheme_true;
else
return scheme_false;
}
},
{"random", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("random: an integer required");
long long max = get_int(l.front(), "random: an integer required");
long long res = (rand() * 1ll * RAND_MAX + rand()) % max;
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeInt>(res));
}
},
{"display", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("display: one argument required");
std::cout << l.front()->toString();
return scheme_empty;
}
},
{"runtime", [](const std::list<std::shared_ptr<SchemeObject>> &) {
return std::dynamic_pointer_cast<SchemeObject>(
std::make_shared<SchemeInt>((get_current_time() - start_time).count()));
}
},
{"error", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
std::string res = "error: ";
for(auto i : l)
{
res += i->toString() + " ";
}
throw eval_error(res);
return scheme_empty;
}
},
{"sin", math_function("sin", sin)},
{"cos", math_function("cos", cos)},
{"exp", math_function("exp", exp)},
{"log", math_function("log", log)},
{"tan", math_function("tan", tan)},
{"asin", math_function("asin", asin)},
{"acos", math_function("acos", acos)},
{"sqrt", math_function("sqrt", sqrt)},
{"atan", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() < 1 || l.size() > 2)
throw eval_error("atan: one or two numbers required");
double res, arg = get_value(l.front(), "atan: number required");
if(l.size() == 1)
res = atan(arg);
else
res = atan2(arg, get_value(l.back(), "atan: number required"));
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemeFloat>(res));
}
},
{"cons", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("cons: 2 arguments required");
return std::dynamic_pointer_cast<SchemeObject>(std::make_shared<SchemePair>(l.front(), l.back()));
}
},
{"pair?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("pair?: one argument required");
auto p = std::dynamic_pointer_cast<SchemePair>(l.front());
return (p && p != scheme_nil) ? scheme_true : scheme_false;
}
},
{"eq?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("eq?: 2 arguments required");
if(l.front() == l.back())
return scheme_true;
{
auto p1 = std::dynamic_pointer_cast<SchemeName>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeName>(l.back());
if(p1 && p2)
return p1->value == p2->value ? scheme_true : scheme_false;
}
{
auto p1 = std::dynamic_pointer_cast<SchemeBool>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeBool>(l.back());
if(p1 && p2)
return p1->value == p2->value ? scheme_true : scheme_false;
}
{
auto p1 = std::dynamic_pointer_cast<SchemeBuiltinFunc>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeBuiltinFunc>(l.back());
if(p1 && p2)
return p1->name == p2->name ? scheme_true : scheme_false;
}
if((is_int(l.front()) || is_float(l.front())) && (is_int(l.back()) || is_float(l.back())))
return get_value(l.front(), "") == get_value(l.back(), "") ? scheme_true : scheme_false;
{
auto p1 = std::dynamic_pointer_cast<SchemeString>(l.front());
auto p2 = std::dynamic_pointer_cast<SchemeString>(l.back());
if(p1 && p2)
return p1->value == p2->value ? scheme_true : scheme_false;
}
return scheme_false;
}
},
{"symbol?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("symbol?: one argument required");
auto p = std::dynamic_pointer_cast<SchemeName>(l.front());
return p ? scheme_true : scheme_false;
}
},
{"number?", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 1)
throw eval_error("number?: one argument required");
return is_int(l.front()) || is_float(l.front()) ? scheme_true : scheme_false;
}
},
{"set-car!", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("set-car!: 2 arguments required");
auto p = std::dynamic_pointer_cast<SchemePair>(l.front());
if(!p || p == scheme_nil)
throw eval_error("set-car!: a pair required");
p->car = l.back();
return l.front();
}
},
{"set-cdr!", [](const std::list<std::shared_ptr<SchemeObject>> &l) {
if(l.size() != 2)
throw eval_error("set-cdr!: 2 arguments required");
auto p = std::dynamic_pointer_cast<SchemePair>(l.front());
if(!p || p == scheme_nil)
throw eval_error("set-cdr!: a pair required");
p->cdr = l.back();
return l.front();
}
},
};
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. 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 "modules/control/control.h"
#include <iomanip>
#include <string>
#include "ros/include/std_msgs/String.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/control/common/control_gflags.h"
namespace apollo {
namespace control {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;
using apollo::common::monitor::MonitorMessageItem;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
std::string Control::Name() const {
return FLAGS_node_name;
}
Status Control::Init() {
AINFO << "Control init, starting ...";
CHECK(::apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file,
&control_conf_))
<< "Unable to load control conf file: " + FLAGS_control_conf_file;
AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded.";
AdapterManager::Init(FLAGS_adapter_config_path);
apollo::common::monitor::MonitorBuffer buffer(&monitor_);
// set controller
if (!controller_agent_.Init(&control_conf_).ok()) {
std::string error_msg = "Control init controller failed! Stopping...";
buffer.ERROR(error_msg);
return Status(ErrorCode::CONTROL_INIT_ERROR, error_msg);
}
// lock it in case for after sub, init_vehicle not ready, but msg trigger
// come
CHECK(AdapterManager::GetLocalization())
<< "Localization is not initialized.";
CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
CHECK(AdapterManager::GetPlanning()) << "Planning is not initialized.";
CHECK(AdapterManager::GetPad()) << "Pad is not initialized.";
CHECK(AdapterManager::GetControlCommand())
<< "ControlCommand publisher is not initialized.";
AdapterManager::AddPadCallback(&Control::OnPad, this);
AdapterManager::AddMonitorCallback(&Control::OnMonitor, this);
return Status::OK();
}
Status Control::Start() {
// set initial vehicle state by cmd
// need to sleep, because advertised channel is not ready immediately
// simple test shows a short delay of 80 ms or so
AINFO << "Control resetting vehicle state, sleeping for 1000 ms ...";
usleep(1000 * 1000);
// should init_vehicle first, let car enter work status, then use status msg
// trigger control
AINFO << "Control default driving action is "
<< DrivingAction_Name(control_conf_.action());
pad_msg_.set_action(control_conf_.action());
timer_ = AdapterManager::CreateTimer(
ros::Duration(control_conf_.control_period()), &Control::OnTimer, this);
AINFO << "Control init done!";
apollo::common::monitor::MonitorBuffer buffer(&monitor_);
buffer.INFO("control started");
return Status::OK();
}
void Control::OnPad(const PadMessage &pad) {
pad_msg_ = pad;
ADEBUG << "Received Pad Msg:" << pad.DebugString();
AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!";
// do something according to pad message
if (pad_msg_.action() == DrivingAction::RESET) {
AINFO << "Control received RESET action!";
estop_ = false;
}
pad_received_ = true;
}
void Control::OnMonitor(
const apollo::common::monitor::MonitorMessage &monitor_message) {
for (const auto &item : monitor_message.item()) {
if (item.log_level() == MonitorMessageItem::FATAL) {
estop_ = true;
return;
}
}
}
Status Control::ProduceControlCommand(ControlCommand *control_command) {
Status status = CheckInput();
// check data
if (!status.ok()) {
AERROR << "Control input data failed: " << status.error_message();
estop_ = true;
} else {
Status status_ts = CheckTimestamp();
if (!status_ts.ok()) {
AERROR << "Input messages timeout";
estop_ = true;
status = status_ts;
}
}
// check estop
estop_ = estop_ || trajectory_.estop().is_estop();
// if planning set estop, then no control process triggered
if (!estop_) {
if (chassis_.driving_mode() == Chassis::COMPLETE_MANUAL) {
controller_agent_.Reset();
AINFO << "Reset Controllers in Manual Mode";
}
auto debug = control_command->mutable_debug()->mutable_input_debug();
debug->mutable_localization_header()->CopyFrom(localization_.header());
debug->mutable_canbus_header()->CopyFrom(chassis_.header());
debug->mutable_trajectory_header()->CopyFrom(trajectory_.header());
Status status_compute = controller_agent_.ComputeControlCommand(
&localization_, &chassis_, &trajectory_, control_command);
if (!status_compute.ok()) {
AERROR << "Control main function failed"
<< " with localization: " << localization_.ShortDebugString()
<< " with chassis: " << chassis_.ShortDebugString()
<< " with trajectory: " << trajectory_.ShortDebugString()
<< " with cmd: " << control_command->ShortDebugString()
<< " status:" << status_compute.error_message();
estop_ = true;
status = status_compute;
}
}
if (estop_) {
AWARN << "Estop triggered! No control core method executed!";
// set Estop command
control_command->set_speed(0);
control_command->set_throttle(0);
control_command->set_brake(control_conf_.soft_estop_brake());
control_command->set_gear_location(Chassis::GEAR_DRIVE);
}
// check signal
if (trajectory_.has_signal()) {
control_command->mutable_signal()->CopyFrom(trajectory_.signal());
}
return status;
}
void Control::OnTimer(const ros::TimerEvent &) {
double start_timestamp = Clock::NowInSecond();
ControlCommand control_command;
Status status = ProduceControlCommand(&control_command);
if (!status.ok()) {
AERROR << "Failed to produce control command:" << status.error_message();
}
double end_timestamp = Clock::NowInSecond();
if (pad_received_) {
control_command.mutable_pad_msg()->CopyFrom(pad_msg_);
pad_received_ = false;
}
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
AINFO_EVERY(1000) << "control cycle time is: " << time_diff_ms << " ms.";
status.Save(control_command.mutable_header()->mutable_status());
SendCmd(&control_command);
}
Status Control::CheckInput() {
AdapterManager::Observe();
auto localization_adapter = AdapterManager::GetLocalization();
if (localization_adapter->Empty()) {
AWARN_EVERY(100) << "No Localization msg yet. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No localization msg");
}
localization_ = localization_adapter->GetLatestObserved();
ADEBUG << "Received localization:" << localization_.ShortDebugString();
auto chassis_adapter = AdapterManager::GetChassis();
if (chassis_adapter->Empty()) {
AWARN_EVERY(100) << "No Chassis msg yet. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No chassis msg");
}
chassis_ = chassis_adapter->GetLatestObserved();
ADEBUG << "Received chassis:" << chassis_.ShortDebugString();
auto trajectory_adapter = AdapterManager::GetPlanning();
if (trajectory_adapter->Empty()) {
AWARN_EVERY(100) << "No planning msg yet. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No planning msg");
}
trajectory_ = trajectory_adapter->GetLatestObserved();
if (trajectory_.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR,
"planning has no trajectory point.");
}
common::VehicleState::instance()->Update(localization_, chassis_);
return Status::OK();
}
Status Control::CheckTimestamp() {
if (!FLAGS_enable_input_timestamp_check || FLAGS_is_control_test_mode) {
ADEBUG << "Skip input timestamp check by gflags.";
return Status::OK();
}
double current_timestamp = Clock::NowInSecond();
double localization_diff =
current_timestamp - localization_.header().timestamp_sec();
if (localization_diff >
(FLAGS_max_localization_miss_num * control_conf_.localization_period())) {
AERROR << "Localization msg lost for " << std::setprecision(6)
<< localization_diff << "s";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout");
}
double chassis_diff = current_timestamp - chassis_.header().timestamp_sec();
if (chassis_diff >
(FLAGS_max_chassis_miss_num * control_conf_.chassis_period())) {
AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff
<< "s";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout");
}
double trajectory_diff =
current_timestamp - trajectory_.header().timestamp_sec();
if (trajectory_diff >
(FLAGS_max_planning_miss_num * control_conf_.trajectory_period())) {
AERROR << "Trajectory msg lost for " << std::setprecision(6)
<< trajectory_diff << "s";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout");
}
return Status::OK();
}
void Control::SendCmd(ControlCommand *control_command) {
// set header
AdapterManager::FillControlCommandHeader(Name(), control_command);
ADEBUG << control_command->ShortDebugString();
if (FLAGS_is_control_test_mode) {
ADEBUG << "Skip publish control command in test mode";
return;
}
AdapterManager::PublishControlCommand(*control_command);
}
void Control::Stop() {}
} // namespace control
} // namespace apollo
<commit_msg>control: reduce warning text<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. 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 "modules/control/control.h"
#include <iomanip>
#include <string>
#include "ros/include/std_msgs/String.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/control/common/control_gflags.h"
namespace apollo {
namespace control {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;
using apollo::common::monitor::MonitorMessageItem;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
std::string Control::Name() const { return FLAGS_node_name; }
Status Control::Init() {
AINFO << "Control init, starting ...";
CHECK(::apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file,
&control_conf_))
<< "Unable to load control conf file: " + FLAGS_control_conf_file;
AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded.";
AdapterManager::Init(FLAGS_adapter_config_path);
apollo::common::monitor::MonitorBuffer buffer(&monitor_);
// set controller
if (!controller_agent_.Init(&control_conf_).ok()) {
std::string error_msg = "Control init controller failed! Stopping...";
buffer.ERROR(error_msg);
return Status(ErrorCode::CONTROL_INIT_ERROR, error_msg);
}
// lock it in case for after sub, init_vehicle not ready, but msg trigger
// come
CHECK(AdapterManager::GetLocalization())
<< "Localization is not initialized.";
CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
CHECK(AdapterManager::GetPlanning()) << "Planning is not initialized.";
CHECK(AdapterManager::GetPad()) << "Pad is not initialized.";
CHECK(AdapterManager::GetControlCommand())
<< "ControlCommand publisher is not initialized.";
AdapterManager::AddPadCallback(&Control::OnPad, this);
AdapterManager::AddMonitorCallback(&Control::OnMonitor, this);
return Status::OK();
}
Status Control::Start() {
// set initial vehicle state by cmd
// need to sleep, because advertised channel is not ready immediately
// simple test shows a short delay of 80 ms or so
AINFO << "Control resetting vehicle state, sleeping for 1000 ms ...";
usleep(1000 * 1000);
// should init_vehicle first, let car enter work status, then use status msg
// trigger control
AINFO << "Control default driving action is "
<< DrivingAction_Name(control_conf_.action());
pad_msg_.set_action(control_conf_.action());
timer_ = AdapterManager::CreateTimer(
ros::Duration(control_conf_.control_period()), &Control::OnTimer, this);
AINFO << "Control init done!";
apollo::common::monitor::MonitorBuffer buffer(&monitor_);
buffer.INFO("control started");
return Status::OK();
}
void Control::OnPad(const PadMessage &pad) {
pad_msg_ = pad;
ADEBUG << "Received Pad Msg:" << pad.DebugString();
AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!";
// do something according to pad message
if (pad_msg_.action() == DrivingAction::RESET) {
AINFO << "Control received RESET action!";
estop_ = false;
}
pad_received_ = true;
}
void Control::OnMonitor(
const apollo::common::monitor::MonitorMessage &monitor_message) {
for (const auto &item : monitor_message.item()) {
if (item.log_level() == MonitorMessageItem::FATAL) {
estop_ = true;
return;
}
}
}
Status Control::ProduceControlCommand(ControlCommand *control_command) {
Status status = CheckInput();
// check data
if (!status.ok()) {
AERROR << "Control input data failed: " << status.error_message();
estop_ = true;
} else {
Status status_ts = CheckTimestamp();
if (!status_ts.ok()) {
AERROR << "Input messages timeout";
estop_ = true;
status = status_ts;
}
}
// check estop
estop_ = estop_ || trajectory_.estop().is_estop();
// if planning set estop, then no control process triggered
if (!estop_) {
if (chassis_.driving_mode() == Chassis::COMPLETE_MANUAL) {
controller_agent_.Reset();
AINFO << "Reset Controllers in Manual Mode";
}
auto debug = control_command->mutable_debug()->mutable_input_debug();
debug->mutable_localization_header()->CopyFrom(localization_.header());
debug->mutable_canbus_header()->CopyFrom(chassis_.header());
debug->mutable_trajectory_header()->CopyFrom(trajectory_.header());
Status status_compute = controller_agent_.ComputeControlCommand(
&localization_, &chassis_, &trajectory_, control_command);
if (!status_compute.ok()) {
AERROR << "Control main function failed"
<< " with localization: " << localization_.ShortDebugString()
<< " with chassis: " << chassis_.ShortDebugString()
<< " with trajectory: " << trajectory_.ShortDebugString()
<< " with cmd: " << control_command->ShortDebugString()
<< " status:" << status_compute.error_message();
estop_ = true;
status = status_compute;
}
}
if (estop_) {
AWARN_EVERY(100) << "Estop triggered! No control core method executed!";
// set Estop command
control_command->set_speed(0);
control_command->set_throttle(0);
control_command->set_brake(control_conf_.soft_estop_brake());
control_command->set_gear_location(Chassis::GEAR_DRIVE);
}
// check signal
if (trajectory_.has_signal()) {
control_command->mutable_signal()->CopyFrom(trajectory_.signal());
}
return status;
}
void Control::OnTimer(const ros::TimerEvent &) {
double start_timestamp = Clock::NowInSecond();
ControlCommand control_command;
Status status = ProduceControlCommand(&control_command);
if (!status.ok()) {
AERROR << "Failed to produce control command:" << status.error_message();
}
double end_timestamp = Clock::NowInSecond();
if (pad_received_) {
control_command.mutable_pad_msg()->CopyFrom(pad_msg_);
pad_received_ = false;
}
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
AINFO_EVERY(1000) << "control cycle time is: " << time_diff_ms << " ms.";
status.Save(control_command.mutable_header()->mutable_status());
SendCmd(&control_command);
}
Status Control::CheckInput() {
AdapterManager::Observe();
auto localization_adapter = AdapterManager::GetLocalization();
if (localization_adapter->Empty()) {
AWARN_EVERY(100) << "No Localization msg yet. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No localization msg");
}
localization_ = localization_adapter->GetLatestObserved();
ADEBUG << "Received localization:" << localization_.ShortDebugString();
auto chassis_adapter = AdapterManager::GetChassis();
if (chassis_adapter->Empty()) {
AWARN_EVERY(100) << "No Chassis msg yet. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No chassis msg");
}
chassis_ = chassis_adapter->GetLatestObserved();
ADEBUG << "Received chassis:" << chassis_.ShortDebugString();
auto trajectory_adapter = AdapterManager::GetPlanning();
if (trajectory_adapter->Empty()) {
AWARN_EVERY(100) << "No planning msg yet. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No planning msg");
}
trajectory_ = trajectory_adapter->GetLatestObserved();
if (trajectory_.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR,
"planning has no trajectory point.");
}
common::VehicleState::instance()->Update(localization_, chassis_);
return Status::OK();
}
Status Control::CheckTimestamp() {
if (!FLAGS_enable_input_timestamp_check || FLAGS_is_control_test_mode) {
ADEBUG << "Skip input timestamp check by gflags.";
return Status::OK();
}
double current_timestamp = Clock::NowInSecond();
double localization_diff =
current_timestamp - localization_.header().timestamp_sec();
if (localization_diff >
(FLAGS_max_localization_miss_num * control_conf_.localization_period())) {
AERROR << "Localization msg lost for " << std::setprecision(6)
<< localization_diff << "s";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout");
}
double chassis_diff = current_timestamp - chassis_.header().timestamp_sec();
if (chassis_diff >
(FLAGS_max_chassis_miss_num * control_conf_.chassis_period())) {
AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff
<< "s";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout");
}
double trajectory_diff =
current_timestamp - trajectory_.header().timestamp_sec();
if (trajectory_diff >
(FLAGS_max_planning_miss_num * control_conf_.trajectory_period())) {
AERROR << "Trajectory msg lost for " << std::setprecision(6)
<< trajectory_diff << "s";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout");
}
return Status::OK();
}
void Control::SendCmd(ControlCommand *control_command) {
// set header
AdapterManager::FillControlCommandHeader(Name(), control_command);
ADEBUG << control_command->ShortDebugString();
if (FLAGS_is_control_test_mode) {
ADEBUG << "Skip publish control command in test mode";
return;
}
AdapterManager::PublishControlCommand(*control_command);
}
void Control::Stop() {}
} // namespace control
} // namespace apollo
<|endoftext|> |
<commit_before>//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_compute_all_terms_hpp__
#define __se3_compute_all_terms_hpp__
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/spatial/act-on-set.hpp"
#include <iostream>
namespace se3
{
inline void
computeAllTerms(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v);
} // namespace se3
/* --- Details -------------------------------------------------------------------- */
namespace se3
{
struct CATForwardStep : public fusion::JointVisitor<CATForwardStep>
{
typedef boost::fusion::vector< const se3::Model &,
se3::Data &,
const Eigen::VectorXd &,
const Eigen::VectorXd &
> ArgsType;
JOINT_VISITOR_INIT(CATForwardStep);
template<typename JointModel>
static void algo(const se3::JointModelBase<JointModel> & jmodel,
se3::JointDataBase<typename JointModel::JointData> & jdata,
const se3::Model & model,
se3::Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v)
{
using namespace Eigen;
using namespace se3;
const Model::Index & i = (Model::Index) jmodel.id();
const Model::Index & parent = model.parents[i];
jmodel.calc(jdata.derived(),q,v);
// CRBA
data.liMi[i] = model.jointPlacements[i]*jdata.M();
data.Ycrb[i] = model.inertias[i];
// Jacobian + NLE
data.v[i] = jdata.v();
if(parent>0)
{
data.oMi[i] = data.oMi[parent]*data.liMi[i];
data.v[i] += data.liMi[i].actInv(data.v[parent]);
}
else
{
data.oMi[i] = data.liMi[i];
}
jmodel.jointCols(data.J) = data.oMi[i].act(jdata.S());
data.a_gf[i] = data.a[i] = jdata.c() + (data.v[i] ^ jdata.v());
if (parent > 0)
data.a[i] += data.liMi[i].actInv(data.a[parent]);
data.a_gf[i] += data.liMi[i].actInv(data.a_gf[parent]);
data.f[i] = model.inertias[i]*data.a_gf[i] + model.inertias[i].vxiv(data.v[i]); // -f_ext
}
};
struct CATBackwardStep : public fusion::JointVisitor<CATBackwardStep>
{
typedef boost::fusion::vector<const Model &,
Data &> ArgsType;
JOINT_VISITOR_INIT(CATBackwardStep);
template<typename JointModel>
static void algo(const JointModelBase<JointModel> & jmodel,
JointDataBase<typename JointModel::JointData> & jdata,
const Model & model,
Data & data)
{
/*
* F[1:6,i] = Y*S
* M[i,SUBTREE] = S'*F[1:6,SUBTREE]
* if li>0
* Yli += liXi Yi
* F[1:6,SUBTREE] = liXi F[1:6,SUBTREE]
*/
const Model::Index & i = (Model::Index) jmodel.id();
const Model::Index & parent = model.parents[i];
/* F[1:6,i] = Y*S */
jmodel.jointCols(data.Fcrb[i]) = data.Ycrb[i] * jdata.S();
/* M[i,SUBTREE] = S'*F[1:6,SUBTREE] */
data.M.block(jmodel.idx_v(),jmodel.idx_v(),jmodel.nv(),data.nvSubtree[i])
= jdata.S().transpose()*data.Fcrb[i].block(0,jmodel.idx_v(),6,data.nvSubtree[i]);
jmodel.jointVelocitySelector(data.nle) = jdata.S().transpose()*data.f[i];
if(parent>0)
{
/* Yli += liXi Yi */
data.Ycrb[parent] += data.liMi[i].act(data.Ycrb[i]);
/* F[1:6,SUBTREE] = liXi F[1:6,SUBTREE] */
Eigen::Block<typename Data::Matrix6x> jF
= data.Fcrb[parent].block(0,jmodel.idx_v(),6,data.nvSubtree[i]);
Eigen::Block<typename Data::Matrix6x> iF
= data.Fcrb[i].block(0,jmodel.idx_v(),6,data.nvSubtree[i]);
forceSet::se3Action(data.liMi[i], iF, jF);
data.f[parent] += data.liMi[i].act(data.f[i]);
}
}
};
inline void
computeAllTerms(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v)
{
data.v[0].setZero();
data.a[0].setZero();
data.a_gf[0] = -model.gravity;
for(Model::Index i=1;i<(Model::Index) model.nbody;++i)
{
CATForwardStep::run(model.joints[i],data.joints[i],
CATForwardStep::ArgsType(model,data,q,v));
}
for(Model::Index i=(Model::Index)(model.nbody-1);i>0;--i)
{
CATBackwardStep::run(model.joints[i],data.joints[i],
CATBackwardStep::ArgsType(model,data));
}
}
} // namespace se3
#endif // ifndef __se3_compute_all_terms_hpp__
<commit_msg>[C++] Add the computation of center of mass related quantities in computeAllTerms<commit_after>//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_compute_all_terms_hpp__
#define __se3_compute_all_terms_hpp__
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/spatial/act-on-set.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include <iostream>
namespace se3
{
inline void
computeAllTerms(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v);
} // namespace se3
/* --- Details -------------------------------------------------------------------- */
namespace se3
{
struct CATForwardStep : public fusion::JointVisitor<CATForwardStep>
{
typedef boost::fusion::vector< const se3::Model &,
se3::Data &,
const Eigen::VectorXd &,
const Eigen::VectorXd &
> ArgsType;
JOINT_VISITOR_INIT(CATForwardStep);
template<typename JointModel>
static void algo(const se3::JointModelBase<JointModel> & jmodel,
se3::JointDataBase<typename JointModel::JointData> & jdata,
const se3::Model & model,
se3::Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v)
{
using namespace Eigen;
using namespace se3;
const Model::Index & i = (Model::Index) jmodel.id();
const Model::Index & parent = model.parents[i];
jmodel.calc(jdata.derived(),q,v);
// CRBA
data.liMi[i] = model.jointPlacements[i]*jdata.M();
data.Ycrb[i] = model.inertias[i];
// Jacobian + NLE
data.v[i] = jdata.v();
if(parent>0)
{
data.oMi[i] = data.oMi[parent]*data.liMi[i];
data.v[i] += data.liMi[i].actInv(data.v[parent]);
}
else
{
data.oMi[i] = data.liMi[i];
}
jmodel.jointCols(data.J) = data.oMi[i].act(jdata.S());
data.a_gf[i] = data.a[i] = jdata.c() + (data.v[i] ^ jdata.v());
if (parent > 0)
data.a[i] += data.liMi[i].actInv(data.a[parent]);
data.a_gf[i] += data.liMi[i].actInv(data.a_gf[parent]);
data.f[i] = model.inertias[i]*data.a_gf[i] + model.inertias[i].vxiv(data.v[i]); // -f_ext
}
};
struct CATBackwardStep : public fusion::JointVisitor<CATBackwardStep>
{
typedef boost::fusion::vector<const Model &,
Data &> ArgsType;
JOINT_VISITOR_INIT(CATBackwardStep);
template<typename JointModel>
static void algo(const JointModelBase<JointModel> & jmodel,
JointDataBase<typename JointModel::JointData> & jdata,
const Model & model,
Data & data)
{
/*
* F[1:6,i] = Y*S
* M[i,SUBTREE] = S'*F[1:6,SUBTREE]
* if li>0
* Yli += liXi Yi
* F[1:6,SUBTREE] = liXi F[1:6,SUBTREE]
*/
const Model::Index & i = (Model::Index) jmodel.id();
const Model::Index & parent = model.parents[i];
/* F[1:6,i] = Y*S */
jmodel.jointCols(data.Fcrb[i]) = data.Ycrb[i] * jdata.S();
/* M[i,SUBTREE] = S'*F[1:6,SUBTREE] */
data.M.block(jmodel.idx_v(),jmodel.idx_v(),jmodel.nv(),data.nvSubtree[i])
= jdata.S().transpose()*data.Fcrb[i].block(0,jmodel.idx_v(),6,data.nvSubtree[i]);
jmodel.jointVelocitySelector(data.nle) = jdata.S().transpose()*data.f[i];
if(parent>0)
{
/* Yli += liXi Yi */
data.Ycrb[parent] += data.liMi[i].act(data.Ycrb[i]);
/* F[1:6,SUBTREE] = liXi F[1:6,SUBTREE] */
Eigen::Block<typename Data::Matrix6x> jF
= data.Fcrb[parent].block(0,jmodel.idx_v(),6,data.nvSubtree[i]);
Eigen::Block<typename Data::Matrix6x> iF
= data.Fcrb[i].block(0,jmodel.idx_v(),6,data.nvSubtree[i]);
forceSet::se3Action(data.liMi[i], iF, jF);
data.f[parent] += data.liMi[i].act(data.f[i]);
}
}
};
inline void
computeAllTerms(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v)
{
data.v[0].setZero();
data.a[0].setZero();
data.a_gf[0] = -model.gravity;
for(Model::Index i=1;i<(Model::Index) model.nbody;++i)
{
CATForwardStep::run(model.joints[i],data.joints[i],
CATForwardStep::ArgsType(model,data,q,v));
}
for(Model::Index i=(Model::Index)(model.nbody-1);i>0;--i)
{
CATBackwardStep::run(model.joints[i],data.joints[i],
CATBackwardStep::ArgsType(model,data));
}
getJacobianComFromCrba(model, data);
centerOfMassAcceleration(model, data, q, v, v, true, false);
}
} // namespace se3
#endif // ifndef __se3_compute_all_terms_hpp__
<|endoftext|> |
<commit_before>#include "../common/init.h"
#include "../common/timer.h"
#include "util/font.h"
#include "util/pointer.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/gui/animation.h"
#include "util/gui/box.h"
#include "util/gui/container.h"
#include "util/gui/context-box.h"
#include "util/gui/coordinate.h"
#include "util/gui/cutscene.h"
#include "util/gui/fadetool.h"
#include "util/gui/keys.h"
#include "util/gui/keyinput.h"
#include "util/gui/keyinput_manager.h"
#include "util/gui/lineedit.h"
#include "util/gui/rectarea.h"
#include "util/gui/popup-box.h"
#include "util/gui/scroll-list.h"
#include "util/gui/select-list.h"
#include "util/gui/tabbed-box.h"
#include "util/gui/timer.h"
#include "util/gui/widget.h"
#include <string>
#include <vector>
using namespace std;
using namespace Gui;
enum Keys{
Up=0,
Down,
Left,
Right,
Esc,
Enter,
};
/*! Gui Component */
class GuiComponent : public ScrollItem{
public:
GuiComponent(const std::string & name):
name(name),
active(false){
}
virtual ~GuiComponent(){
}
// pure virtual funcs
virtual void up() = 0;
virtual void down() = 0;
virtual void right() = 0;
virtual void left() = 0;
virtual void actComponent() = 0;
virtual void drawComponent(const Graphics::Bitmap & where, const Font & font) = 0;
void draw(int x, int y, const Graphics::Bitmap & where, const Font & font, int distance) const{
if (active){
font.printf(x, y, Graphics::makeColor(255, 0, 255), where, name, 0);
} else {
font.printf(x, y, Graphics::makeColor(255, 255, 255), where, name, 0);
}
}
int size(const Font & font) const{
return font.textLength(name.c_str());
}
void toggle(){
active = !active;
}
protected:
std::string name;
bool active;
};
/*! Box Gui Component */
class TestBox : public GuiComponent {
public:
TestBox():
GuiComponent("Gui::Box"),
size(Gui::RelativePoint(-.5, -.5), Gui::RelativePoint(.5, .5)){
box.colors.body = Graphics::makeColor(255, 255, 255);
box.colors.border = Graphics::makeColor(0, 0, 255);
}
void up(){
size.growVertical(.01);
}
void down(){
size.growVertical(-.01);
}
void right(){
size.growHorizontal(.01);
}
void left(){
size.growHorizontal(-.01);
}
void actComponent(){
box.location.growTo(size);
}
void drawComponent(const Graphics::Bitmap & where, const Font & font){
box.render(where);
}
protected:
Gui::Box box;
Gui::Coordinate size;
};
/*! Gui Handler */
class GuiHandler {
public:
GuiHandler():
selected(false){
// Initialize components and store
components.push_back(new TestBox());
// Set first as active
components[0].convert<GuiComponent>()->toggle();
// Finally add component list to scroll list
list.addItems(components);
}
~GuiHandler(){
}
void up(){
if (!selected){
list.previous();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->up();
}
}
void down(){
if (!selected){
list.next();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->down();
}
}
void left(){
if (!selected){
list.previous();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->left();
}
}
void right(){
if (!selected){
list.next();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->right();
}
}
void act(){
if (!selected){
list.act();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->actComponent();
}
}
void draw(const Graphics::Bitmap & work, const Font & font){
if (!selected){
list.render(work, font);
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->drawComponent(work, font);
}
}
void enter(){
if (!selected) {
selected = true;
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
}
}
void esc(){
if (selected){
selected = false;
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
}
}
bool inComponent(){
return selected;
}
protected:
bool selected;
std::vector<Util::ReferenceCount<Gui::ScrollItem> > components;
Gui::NormalList list;
};
class Logic: public Util::Logic {
public:
Logic(InputMap<Keys> & input, GuiHandler & handler):
is_done(false),
input(input),
handler(handler){
}
bool is_done;
InputMap<Keys> & input;
GuiHandler & handler;
bool done(){
return is_done;
}
void run(){
vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
for (vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
const InputMap<Keys>::InputEvent & event = *it;
if (event.enabled){
if (event.out == Esc){
if (!handler.inComponent()){
is_done = true;
} else {
handler.esc();
}
}
if (event.out == Up){
handler.up();
}
if (event.out == Down){
handler.down();
}
if (event.out == Left){
handler.left();
}
if (event.out == Right){
handler.right();
}
if (event.out == Enter){
handler.enter();
}
}
}
handler.act();
}
double ticks(double system){
return system;
}
};
class Draw: public Util::Draw {
public:
Draw(GuiHandler & handler):
handler(handler){
}
GuiHandler & handler;
void draw(const Graphics::Bitmap & buffer){
//buffer.putPixel(rand() % 640, rand() % 480, Graphics::makeColor(rand() % 255, rand() % 255, rand() % 255));
buffer.clear();
handler.draw(buffer, Font::getDefaultFont());
buffer.BlitToScreen();
}
};
int main(int argc, char ** argv){
Screen::realInit();
Common::startTimers();
InputManager manager;
Graphics::Bitmap screen(Graphics::getScreenBuffer());
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);
InputMap<Keys> input;
input.set(Keyboard::Key_ESC, 0, true, Esc);
input.set(Keyboard::Key_ENTER, 0, true, Enter);
input.set(Keyboard::Key_UP, 0, true, Up);
input.set(Keyboard::Key_DOWN, 0, true, Down);
input.set(Keyboard::Key_LEFT, 0, true, Left);
input.set(Keyboard::Key_RIGHT, 0, true, Right);
GuiHandler handler;
Logic logic(input, handler);
Draw draw(handler);
Util::standardLoop(logic, draw);
Screen::realFinish();
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<commit_msg>Print controls and other information regarding current gui element.<commit_after>#include "../common/init.h"
#include "../common/timer.h"
#include "util/font.h"
#include "util/pointer.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/gui/animation.h"
#include "util/gui/box.h"
#include "util/gui/container.h"
#include "util/gui/context-box.h"
#include "util/gui/coordinate.h"
#include "util/gui/cutscene.h"
#include "util/gui/fadetool.h"
#include "util/gui/keys.h"
#include "util/gui/keyinput.h"
#include "util/gui/keyinput_manager.h"
#include "util/gui/lineedit.h"
#include "util/gui/rectarea.h"
#include "util/gui/popup-box.h"
#include "util/gui/scroll-list.h"
#include "util/gui/select-list.h"
#include "util/gui/tabbed-box.h"
#include "util/gui/timer.h"
#include "util/gui/widget.h"
#include <string>
#include <vector>
using namespace std;
using namespace Gui;
enum Keys{
Up=0,
Down,
Left,
Right,
Esc,
Enter,
};
/*! Gui Component */
class GuiComponent : public ScrollItem{
public:
GuiComponent(const std::string & name):
name(name),
active(false){
}
virtual ~GuiComponent(){
}
// pure virtual funcs
virtual void up() = 0;
virtual void down() = 0;
virtual void right() = 0;
virtual void left() = 0;
virtual void actComponent() = 0;
virtual void drawComponent(const Graphics::Bitmap & where, const Font & font) = 0;
void draw(int x, int y, const Graphics::Bitmap & where, const Font & font, int distance) const{
if (active){
font.printf(x, y, Graphics::makeColor(255, 0, 255), where, name, 0);
} else {
font.printf(x, y, Graphics::makeColor(255, 255, 255), where, name, 0);
}
}
int size(const Font & font) const{
return font.textLength(name.c_str());
}
void toggle(){
active = !active;
}
protected:
std::string name;
bool active;
};
/*! Box Gui Component */
class TestBox : public GuiComponent {
public:
TestBox():
GuiComponent("Gui::Box"),
size(Gui::RelativePoint(-.5, -.5), Gui::RelativePoint(.5, .5)){
box.colors.body = Graphics::makeColor(255, 255, 255);
box.colors.border = Graphics::makeColor(0, 0, 255);
}
void up(){
size.growVertical(.01);
}
void down(){
size.growVertical(-.01);
}
void right(){
size.growHorizontal(.01);
}
void left(){
size.growHorizontal(-.01);
}
void actComponent(){
box.location.growTo(size);
}
void drawComponent(const Graphics::Bitmap & where, const Font & font){
box.render(where);
font.printf(320 - font.textLength(name.c_str())/2, 15, Graphics::makeColor(255, 255, 255), where, "%s", 0, name.c_str());
}
protected:
Gui::Box box;
Gui::Coordinate size;
};
/*! Gui Handler */
class GuiHandler {
public:
GuiHandler():
selected(false){
// Initialize components and store
components.push_back(new TestBox());
// Set first as active
components[0].convert<GuiComponent>()->toggle();
// Finally add component list to scroll list
list.addItems(components);
}
~GuiHandler(){
}
void up(){
if (!selected){
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
list.previous();
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->up();
}
}
void down(){
if (!selected){
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
list.next();
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->down();
}
}
void left(){
if (!selected){
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
list.previous();
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->left();
}
}
void right(){
if (!selected){
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
list.next();
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->right();
}
}
void act(){
if (!selected){
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
list.act();
components[list.getCurrentIndex()].convert<GuiComponent>()->toggle();
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->actComponent();
}
}
void draw(const Graphics::Bitmap & work, const Font & font){
if (!selected){
list.render(work, font);
} else {
components[list.getCurrentIndex()].convert<GuiComponent>()->drawComponent(work, font);
}
}
void enter(){
if (!selected) {
selected = true;
}
}
void esc(){
if (selected){
selected = false;
}
}
bool inComponent(){
return selected;
}
protected:
bool selected;
std::vector<Util::ReferenceCount<Gui::ScrollItem> > components;
Gui::NormalList list;
};
class Logic: public Util::Logic {
public:
Logic(InputMap<Keys> & input, GuiHandler & handler):
is_done(false),
input(input),
handler(handler){
}
bool is_done;
InputMap<Keys> & input;
GuiHandler & handler;
bool done(){
return is_done;
}
void run(){
vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
for (vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
const InputMap<Keys>::InputEvent & event = *it;
if (event.enabled){
if (event.out == Esc){
if (!handler.inComponent()){
is_done = true;
} else {
handler.esc();
}
}
if (event.out == Up){
handler.up();
}
if (event.out == Down){
handler.down();
}
if (event.out == Left){
handler.left();
}
if (event.out == Right){
handler.right();
}
if (event.out == Enter){
handler.enter();
}
}
}
handler.act();
}
double ticks(double system){
return system;
}
};
class Draw: public Util::Draw {
public:
Draw(GuiHandler & handler):
handler(handler),
controls("Controls: Up, Down, Left, Right, Enter, Esc"){
}
GuiHandler & handler;
std::string controls;
void draw(const Graphics::Bitmap & buffer){
//buffer.putPixel(rand() % 640, rand() % 480, Graphics::makeColor(rand() % 255, rand() % 255, rand() % 255));
buffer.clear();
handler.draw(buffer, Font::getDefaultFont());
Font::getDefaultFont().printf(320 - Font::getDefaultFont().textLength(controls.c_str())/2, 460, Graphics::makeColor(255, 255, 255), buffer, "%s", 0, controls.c_str());
buffer.BlitToScreen();
}
};
int main(int argc, char ** argv){
Screen::realInit();
Common::startTimers();
InputManager manager;
Graphics::Bitmap screen(Graphics::getScreenBuffer());
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);
InputMap<Keys> input;
input.set(Keyboard::Key_ESC, 0, true, Esc);
input.set(Keyboard::Key_ENTER, 0, true, Enter);
input.set(Keyboard::Key_UP, 0, true, Up);
input.set(Keyboard::Key_DOWN, 0, true, Down);
input.set(Keyboard::Key_LEFT, 0, true, Left);
input.set(Keyboard::Key_RIGHT, 0, true, Right);
GuiHandler handler;
Logic logic(input, handler);
Draw draw(handler);
Util::standardLoop(logic, draw);
Screen::realFinish();
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<|endoftext|> |
<commit_before>#ifndef INC_CALIBER_SRC_TEST_COMPILER_HPP
#define INC_CALIBER_SRC_TEST_COMPILER_HPP
#include <chrono>
#include <mettle/driver/log/core.hpp>
#include <mettle/suite/compiled_suite.hpp>
#include "detail/optional.hpp"
#include "tool.hpp"
namespace caliber {
class test_compiler {
public:
using timeout_t = CALIBER_OPTIONAL_NS::optional<std::chrono::milliseconds>;
test_compiler(tool compiler, timeout_t timeout = {})
: compiler_(std::move(compiler)), timeout_(timeout) {}
test_compiler(const test_compiler &) = delete;
test_compiler & operator =(const test_compiler &) = delete;
mettle::test_result
operator ()(const std::string &file, const compiler_options &args,
const raw_options &raw_args, bool expect_fail,
mettle::log::test_output &output) const;
const tool & tool() const {
return compiler_;
}
private:
const struct tool compiler_;
timeout_t timeout_;
};
} // namespace caliber
#endif
<commit_msg>Fix invalid declaration changing meaning of symbol<commit_after>#ifndef INC_CALIBER_SRC_TEST_COMPILER_HPP
#define INC_CALIBER_SRC_TEST_COMPILER_HPP
#include <chrono>
#include <mettle/driver/log/core.hpp>
#include <mettle/suite/compiled_suite.hpp>
#include "detail/optional.hpp"
#include "tool.hpp"
namespace caliber {
class test_compiler {
public:
using timeout_t = CALIBER_OPTIONAL_NS::optional<std::chrono::milliseconds>;
test_compiler(caliber::tool compiler, timeout_t timeout = {})
: compiler_(std::move(compiler)), timeout_(timeout) {}
test_compiler(const test_compiler &) = delete;
test_compiler & operator =(const test_compiler &) = delete;
mettle::test_result
operator ()(const std::string &file, const compiler_options &args,
const raw_options &raw_args, bool expect_fail,
mettle::log::test_output &output) const;
const caliber::tool & tool() const {
return compiler_;
}
private:
const struct caliber::tool compiler_;
timeout_t timeout_;
};
} // namespace caliber
#endif
<|endoftext|> |
<commit_before>#ifndef __Data_course__
#define __Data_course__
#include "data-general.hpp"
#include "data-major.hpp"
#include "data-department.hpp"
using namespace std;
class Course {
protected:
string ID;
int number;
string title;
string description;
char section;
vector<Major> majors;
vector<Department> department;
string concentrations;
string conversations;
string professor;
int half_semester;
bool pass_fail;
float credits;
string location;
bool lab;
GenEd* geneds;
bool days[7];
float time[7];
public:
Course(istream &is) {
if (!is) return;
string tmpLine;
getline(is, tmpLine); // do this twice: once to not break the program,
getline(is, tmpLine); // and once to remove the extra data of course status.
vector<string> record = split(tmpLine, ',');
for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
*i = removeAllQuotes(*i);
*i = removeTrailingSlashes(*i);
}
/*
cout << record.at(0) << ", ";
cout << record.at(1) << ", ";
cout << record.at(2) << ", ";
cout << record.at(3) << ", ";
cout << record.at(4) << ", ";
cout << record.at(5) << ", ";
cout << record.at(6) << ", ";
cout << record.at(7) << ", ";
cout << record.at(8) << ", ";
cout << record.at(9) << ", ";
cout << record.at(10) << ", ";
cout << record.at(11) << ", ";
if (record.size() == 13)
cout << record.at(12) << endl;
*/
// Ignore the first column;
record.at(0);
// so, the *first* column (that we care about) has the course ID,
ID = record.at(1);
parseID(ID);
// Second column has the section,
section = record.at(2)[0];
// Third holds the lab boolean,
if (record.at(3).empty()) lab = false;
else lab = true;
// while Fourth contains the title of the course;
title = record.at(4);
cleanTitle();
// Fifth hands over the length (half semester or not)
// it's actually an int that tells us how many times the course is offered per semester.
half_semester = stringToInt(record.at(5));
if (half_semester != 0 && half_semester != 1 && half_semester != 2)
half_semester = 0;
// Sixth tells us the number of credits,
credits = stringToFloat(record.at(6));
// Seventh shows us if it can be taken pass/no-pass,
if (record.at(7) == "Y")
pass_fail = true;
else
pass_fail = false;
// while Eighth gives us the GEs of the course,
// GEreqs = record.at(8);
// and Nine spits out the days and times;
// Times = record.at(9);
// Ten holds the location,
location = record.at(10);
location = deDoubleString(location);
// and Eleven knows who teaches.
if (record.size() == 13) {
string profLastName = record.at(11);
string profFirstName = record.at(12);
profFirstName.erase(0, 1); // remove the extra space from the start of the name
professor = profFirstName + " " + profLastName;
}
else {
professor = record.at(11);
}
}
void cleanTitle() {
vector<string> badEndings, badBeginnings;
badEndings.push_back("Prerequisite");
badEndings.push_back("Prerequsiite");
badEndings.push_back("This course has class");
badEndings.push_back("This course is open to ");
badEndings.push_back("First-Year Students may register only");
badEndings.push_back("Open to ");
badEndings.push_back("Especially for ");
badEndings.push_back("Registration by permission of instructor only.");
badEndings.push_back("Permission of instructor required.");
badEndings.push_back("Not open to first-year students.");
badEndings.push_back("Film screenings");
badEndings.push_back("Open only to ");
badEndings.push_back("This course has been canceled.");
badEndings.push_back("This course has been cancelled.");
badEndings.push_back("Open only to seniors");
badEndings.push_back("Closed during web registration.");
badEndings.push_back("During course submission process");
badEndings.push_back("Taught in English.");
badEndings.push_back("Closed to First-Year Students.");
badEndings.push_back("Closed to first-year students.");
badEndings.push_back("New course");
badEndings.push_back("This course does");
badEndings.push_back("This course open to seniors only.");
badEndings.push_back("This lab has been canceled.");
badEndings.push_back("Permission of the instructor");
badEndings.push_back("Registration restricted");
badBeginnings.push_back("Top: ");
badBeginnings.push_back("Sem: ");
badBeginnings.push_back("Res: ");
badEndings.push_back("Students in " + department[0].getFullName() + " " + tostring(number));
cout << badEndings.back() << endl;
for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
title = removeTrailingText(title, *i);
for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
title = removeStartingText(title, *i);
}
void parseID(string str) {
// Get the number of the course, aka the last three slots.
number = str.substr(str.size() - 3);
// Check if it's one of those dastardly "split courses".
unsigned int foundLoc = str.find('/');
string tempDept = str.substr(0,str.find(' ')-1);
if (foundLoc != str.npos) {
string dept1 = tempDept.substr(0,2);
department.push_back(Department(dept1));
string dept2 = tempDept.substr(2,2);
department.push_back(Department(dept2));
}
else {
department.push_back(Department(tempDept));
}
}
void updateID() {
string dept;
for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i)
dept += i->getName();
ID = dept + " " + tostring(number) + section;
}
string getID() {
return ID;
}
ostream& getData(ostream &os) {
os << ID << section << " - ";
os << title << " | ";
if (professor.length() > 0 && professor != " ")
os << professor;
return os;
}
void display();
void showAll() {
cout << ID << section << endl;
cout << "Title: " << title << endl;
cout << "Professor: " << professor << endl;
cout << "Lab? " << lab << endl;
cout << "Half-semester? " << half_semester << endl;
cout << "Credits: " << credits << endl;
cout << "Pass/Fail? " << pass_fail << endl;
cout << "Location: " << location << endl;
cout << endl;
}
};
ostream &operator<<(ostream &os, Course &item) { return item.getData(os); }
void Course::display() { if(this==0) cout << *this << endl; }
#endif
<commit_msg>Change ID to id<commit_after>#ifndef __Data_course__
#define __Data_course__
#include "data-general.hpp"
#include "data-major.hpp"
#include "data-department.hpp"
using namespace std;
class Course {
protected:
string id;
int number;
string title;
string description;
char section;
vector<Major> majors;
vector<Department> department;
string concentrations;
string conversations;
string professor;
int half_semester;
bool pass_fail;
float credits;
string location;
bool lab;
GenEd* geneds;
bool days[7];
float time[7];
public:
Course(istream &is) {
if (!is) return;
string tmpLine;
getline(is, tmpLine); // do this twice: once to not break the program,
getline(is, tmpLine); // and once to remove the extra data of course status.
vector<string> record = split(tmpLine, ',');
for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
*i = removeAllQuotes(*i);
*i = removeTrailingSlashes(*i);
}
/*
cout << record.at(0) << ", ";
cout << record.at(1) << ", ";
cout << record.at(2) << ", ";
cout << record.at(3) << ", ";
cout << record.at(4) << ", ";
cout << record.at(5) << ", ";
cout << record.at(6) << ", ";
cout << record.at(7) << ", ";
cout << record.at(8) << ", ";
cout << record.at(9) << ", ";
cout << record.at(10) << ", ";
cout << record.at(11) << ", ";
if (record.size() == 13)
cout << record.at(12) << endl;
*/
// Ignore the first column;
record.at(0);
// so, the *first* column (that we care about) has the course id,
id = record.at(1);
parseid(id);
// Second column has the section,
section = record.at(2)[0];
// Third holds the lab boolean,
if (record.at(3).empty()) lab = false;
else lab = true;
// while Fourth contains the title of the course;
title = record.at(4);
cleanTitle();
// Fifth hands over the length (half semester or not)
// it's actually an int that tells us how many times the course is offered per semester.
half_semester = stringToInt(record.at(5));
if (half_semester != 0 && half_semester != 1 && half_semester != 2)
half_semester = 0;
// Sixth tells us the number of credits,
credits = stringToFloat(record.at(6));
// Seventh shows us if it can be taken pass/no-pass,
if (record.at(7) == "Y")
pass_fail = true;
else
pass_fail = false;
// while Eighth gives us the GEs of the course,
// GEreqs = record.at(8);
// and Nine spits out the days and times;
// Times = record.at(9);
// Ten holds the location,
location = record.at(10);
location = deDoubleString(location);
// and Eleven knows who teaches.
if (record.size() == 13) {
string profLastName = record.at(11);
string profFirstName = record.at(12);
profFirstName.erase(0, 1); // remove the extra space from the start of the name
professor = profFirstName + " " + profLastName;
}
else {
professor = record.at(11);
}
}
void cleanTitle() {
vector<string> badEndings, badBeginnings;
badEndings.push_back("Prerequisite");
badEndings.push_back("Prerequsiite");
badEndings.push_back("This course has class");
badEndings.push_back("This course is open to ");
badEndings.push_back("First-Year Students may register only");
badEndings.push_back("Open to ");
badEndings.push_back("Especially for ");
badEndings.push_back("Registration by permission of instructor only.");
badEndings.push_back("Permission of instructor required.");
badEndings.push_back("Not open to first-year students.");
badEndings.push_back("Film screenings");
badEndings.push_back("Open only to ");
badEndings.push_back("This course has been canceled.");
badEndings.push_back("This course has been cancelled.");
badEndings.push_back("Open only to seniors");
badEndings.push_back("Closed during web registration.");
badEndings.push_back("During course submission process");
badEndings.push_back("Taught in English.");
badEndings.push_back("Closed to First-Year Students.");
badEndings.push_back("Closed to first-year students.");
badEndings.push_back("New course");
badEndings.push_back("This course does");
badEndings.push_back("This course open to seniors only.");
badEndings.push_back("This lab has been canceled.");
badEndings.push_back("Permission of the instructor");
badEndings.push_back("Registration restricted");
badBeginnings.push_back("Top: ");
badBeginnings.push_back("Sem: ");
badBeginnings.push_back("Res: ");
badEndings.push_back("Students in " + department[0].getFullName() + " " + tostring(number));
cout << badEndings.back() << endl;
for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
title = removeTrailingText(title, *i);
for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
title = removeStartingText(title, *i);
}
void parseid(string str) {
// Get the number of the course, aka the last three slots.
stringstream(str.substr(str.size() - 3)) >> number;
// Check if it's one of those dastardly "split courses".
unsigned int foundLoc = str.find('/');
string tempDept = str.substr(0,str.find(' ')-1);
if (foundLoc != str.npos) {
string dept1 = tempDept.substr(0,2);
department.push_back(Department(dept1));
string dept2 = tempDept.substr(2,2);
department.push_back(Department(dept2));
}
else {
department.push_back(Department(tempDept));
}
}
void updateid() {
string dept;
for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i)
dept += i->getName() + "/";
id = dept + " " + tostring(number) + section;
}
string getid() {
return id;
}
ostream& getData(ostream &os) {
os << id << section << " - ";
os << title << " | ";
if (professor.length() > 0 && professor != " ")
os << professor;
return os;
}
void display();
void showAll() {
cout << id << section << endl;
cout << "Title: " << title << endl;
cout << "Professor: " << professor << endl;
cout << "Lab? " << lab << endl;
cout << "Half-semester? " << half_semester << endl;
cout << "Credits: " << credits << endl;
cout << "Pass/Fail? " << pass_fail << endl;
cout << "Location: " << location << endl;
cout << endl;
}
};
ostream &operator<<(ostream &os, Course &item) { return item.getData(os); }
void Course::display() { if(this==0) cout << *this << endl; }
#endif
<|endoftext|> |
<commit_before>#ifndef ALEPH_MATH_STEP_FUNCTION_HH__
#define ALEPH_MATH_STEP_FUNCTION_HH__
#include <iterator>
#include <limits>
#include <ostream>
#include <set>
#include <stdexcept>
#include <vector>
#include <cmath>
#include <cstdlib>
namespace aleph
{
namespace math
{
namespace detail
{
template <class T> T next( T x )
{
if( std::numeric_limits<T>::is_integer )
return x+1;
else
return std::nextafter( x, std::numeric_limits<T>::max() );
}
template <class T> T previous( T x )
{
if( std::numeric_limits<T>::is_integer )
return x-1;
else
return std::nextafter( x, std::numeric_limits<T>::lowest() );
}
} // namespace detail
template <class D, class I = D> class StepFunction
{
public:
using Domain = D;
using Image = I;
/**
Auxiliary class for representing an indicator function interval of the step
function. Each indicator function is only non-zero within its interval, and
zero outside.
*/
class IndicatorFunction
{
public:
IndicatorFunction( D a )
: _a( a )
, _b( a )
, _y( I(1) )
{
}
IndicatorFunction( D a, D b, I y )
: _a( a )
, _b( b )
, _y( y )
{
if( a > b )
throw std::runtime_error( "Invalid interval specified" );
}
const D& a() const noexcept { return _a; }
const D& b() const noexcept { return _b; }
I& y() noexcept { return _y; }
const I& y() const noexcept { return _y; }
bool contains( D x ) const noexcept
{
return this->a() <= x && x <= this->b();
}
/** Standard (signed) integral */
I integral() const noexcept
{
return this->y() * static_cast<I>( ( this->b() - this->a() ) );
}
/** Unsigned integral raised to a certain power */
I integral_p( I p ) const noexcept
{
auto value = std::abs( this->integral() );
return std::pow( value, p );
}
I operator()( D x ) const noexcept
{
if( this->contains( x ) )
return this->y();
else
return I();
}
bool operator<( const IndicatorFunction& other ) const
{
// Permits that intervals intersect in a single point, as this is
// simplifies the composition of multiple step functions.
return this->b() <= other.a();
}
private:
D _a;
D _b;
I _y;
};
/** Adds a new indicator function to the step function */
void add( D a, D b, I y ) noexcept
{
_indicatorFunctions.insert( IndicatorFunction(a,b,y) );
}
/** Returns the domain of the function */
template <class OutputIterator> void domain( OutputIterator result ) const noexcept
{
for( auto&& f : _indicatorFunctions )
{
*result++ = f.a();
*result++ = f.b();
}
}
/** Returns the image of the function */
template <class OutputIterator> void image( OutputIterator result ) const noexcept
{
for( auto&& f : _indicatorFunctions )
*result++ = f.y();
}
/** Returns the function value at a certain position */
I operator()( D x ) const noexcept
{
I value = I();
for( auto&& f : _indicatorFunctions )
{
// TODO: Not sure whether I really want this. The step functions must not
// overlap anyway...
if( f.contains(x) && std::abs( f(x) ) > value )
value = f(x);
}
return value;
}
/** Calculates the sum of this step function with another step function */
StepFunction& operator+=( const StepFunction& other ) noexcept
{
auto&& f = *this;
auto&& g = other;
std::set<D> domain;
f.domain( std::inserter( domain, domain.begin() ) );
g.domain( std::inserter( domain, domain.begin() ) );
StepFunction<D,I> h;
if( domain.empty() )
return *this;
auto prev = *domain.begin();
auto curr = *domain.begin();
for( auto it = std::next( domain.begin() ); it != domain.end(); ++it )
{
curr = *it;
auto y1 = f( prev );
auto y2 = g( prev );
auto y3 = f( curr );
auto y4 = g( curr );
auto y5 = f( detail::next( prev ) );
auto y6 = g( detail::next( prev ) );
if( y1 == y3 && y2 == y4 )
h.add( prev, curr, y1+y2 );
// A subdivision of the interval [prev, curr] is required because
// at least one of the functions differs on the end points of the
// interval.
else if( y1 != y3 || y2 != y4 )
{
// Make the interval smaller if we hit a point where at least a
// single function changes.
if( y1 != y5 || y2 != y6 )
prev = detail::next( prev );
if( y5+y6 != y3+y4 )
{
// [prev, curr - epsilon]: y5+y6
// [curr, curr + epsilon]: y3+y4
h.add( prev, detail::previous( curr ), y5+y6 );
h.add( curr, detail::next( curr ), y3+y4 );
}
// FIXME: Not sure whether this is really the best workaround
// here or whether I need a different strategy.
else
h.add( prev, detail::next( curr ), y3+y4 );
// Ensures that the next interval uses the proper start point for the
// indicator function interval.
curr = detail::next( curr );
}
prev = curr;
}
*this = h;
return *this;
}
/** Calculates the sum of this step function with another step function */
StepFunction operator+( const StepFunction& rhs ) const noexcept
{
auto lhs = *this;
lhs += rhs;
return lhs;
}
/** Unary minus: negates all values in the image of the step function */
StepFunction operator-() const noexcept
{
StepFunction f;
for( auto&& indicatorFunction : _indicatorFunctions )
f.add( indicatorFunction.a(), indicatorFunction.b(), -indicatorFunction.y() );
return f;
}
/** Adds a scalar to all step function values */
StepFunction operator+( I lambda ) const noexcept
{
StepFunction f;
for( auto&& indicatorFunction : _indicatorFunctions )
f.add( indicatorFunction.a(), indicatorFunction.b(), lambda + indicatorFunction.y() );
return f;
}
/** Subtracts a scalar from all step function values */
StepFunction operator-( I lambda ) const noexcept
{
return this->operator+( -lambda );
}
/** Multiplies the given step function with a scalar value */
StepFunction operator*( I lambda ) const noexcept
{
StepFunction f;
for( auto&& indicatorFunction : _indicatorFunctions )
f.add( indicatorFunction.a(), indicatorFunction.b(), lambda * indicatorFunction.y() );
return f;
}
/** Divides the given step function by a scalar value */
StepFunction operator/( I lambda ) const
{
// TODO: What about division by zero?
return this->operator*( 1/lambda );
}
/** Calculates the integral over the domain of the step function */
I integral() const noexcept
{
if( _indicatorFunctions.empty() )
return I();
I value = I();
for( auto&& f : _indicatorFunctions )
value += f.integral();
return value;
}
/** Calculates the unsigned integral raised to a certain power */
I integral_p( I p ) const noexcept
{
if( _indicatorFunctions.empty() )
return I();
I value = I();
for( auto&& f : _indicatorFunctions )
value += f.integral_p( p );
return std::pow( value, 1/p );
}
/** Calculates the absolute value of the function */
StepFunction& abs() noexcept
{
std::set<IndicatorFunction> indicatorFunctions;
for( auto&& f : _indicatorFunctions )
indicatorFunctions.insert( IndicatorFunction( f.a(), f.b(), std::abs( f.y() ) ) );
_indicatorFunctions.swap( indicatorFunctions );
return *this;
}
template <class U, class V> friend std::ostream& operator<<( std::ostream&, const StepFunction<U, V>& f );
private:
/** All indicator functions of the step function */
std::set<IndicatorFunction> _indicatorFunctions;
};
// TODO: This does not need to be a friend function; it suffices to be
// implemented using the public interface of the class.
template <class D, class I> std::ostream& operator<<( std::ostream& o, const StepFunction<D, I>& f )
{
for( auto&& indicatorFunction : f._indicatorFunctions )
{
o << indicatorFunction.a() << "\t" << indicatorFunction.y() << "\n"
<< indicatorFunction.b() << "\t" << indicatorFunction.y() << "\n";
}
return o;
}
/**
Auxiliary function for normalizing a step function. Given a range
spanned by a minimum $a$ and a maximum $b$, the image of the step
function will be restricted to $[a,b]$.
The transformed step function will be returned.
*/
template <class D, class I> StepFunction<D,I> normalize( const StepFunction<D,I>& f,
I a = I(),
I b = I(1) )
{
std::set<I> image;
f.image( std::inserter( image, image.end() ) );
if( image.empty() || image.size() == 1 )
return f;
// The minimum value in the image of the function is zero because this
// value is guaranteed to be attained at some point
auto min = I();
auto max = *image.rbegin();
auto g = f - min;
g = g / ( max - min ); // now scaled between [0,1 ]
g = g * ( b - a ); // now scaled between [0,b-a]
g = g + a; // now scaled between [a,b ]
return g;
}
} // namespace math
} // namespace aleph
#endif
<commit_msg>Implemented difference operator for step functions<commit_after>#ifndef ALEPH_MATH_STEP_FUNCTION_HH__
#define ALEPH_MATH_STEP_FUNCTION_HH__
#include <iterator>
#include <limits>
#include <ostream>
#include <set>
#include <stdexcept>
#include <vector>
#include <cmath>
#include <cstdlib>
namespace aleph
{
namespace math
{
namespace detail
{
template <class T> T next( T x )
{
if( std::numeric_limits<T>::is_integer )
return x+1;
else
return std::nextafter( x, std::numeric_limits<T>::max() );
}
template <class T> T previous( T x )
{
if( std::numeric_limits<T>::is_integer )
return x-1;
else
return std::nextafter( x, std::numeric_limits<T>::lowest() );
}
} // namespace detail
template <class D, class I = D> class StepFunction
{
public:
using Domain = D;
using Image = I;
/**
Auxiliary class for representing an indicator function interval of the step
function. Each indicator function is only non-zero within its interval, and
zero outside.
*/
class IndicatorFunction
{
public:
IndicatorFunction( D a )
: _a( a )
, _b( a )
, _y( I(1) )
{
}
IndicatorFunction( D a, D b, I y )
: _a( a )
, _b( b )
, _y( y )
{
if( a > b )
throw std::runtime_error( "Invalid interval specified" );
}
const D& a() const noexcept { return _a; }
const D& b() const noexcept { return _b; }
I& y() noexcept { return _y; }
const I& y() const noexcept { return _y; }
bool contains( D x ) const noexcept
{
return this->a() <= x && x <= this->b();
}
/** Standard (signed) integral */
I integral() const noexcept
{
return this->y() * static_cast<I>( ( this->b() - this->a() ) );
}
/** Unsigned integral raised to a certain power */
I integral_p( I p ) const noexcept
{
auto value = std::abs( this->integral() );
return std::pow( value, p );
}
I operator()( D x ) const noexcept
{
if( this->contains( x ) )
return this->y();
else
return I();
}
bool operator<( const IndicatorFunction& other ) const
{
// Permits that intervals intersect in a single point, as this is
// simplifies the composition of multiple step functions.
return this->b() <= other.a();
}
private:
D _a;
D _b;
I _y;
};
/** Adds a new indicator function to the step function */
void add( D a, D b, I y ) noexcept
{
_indicatorFunctions.insert( IndicatorFunction(a,b,y) );
}
/** Returns the domain of the function */
template <class OutputIterator> void domain( OutputIterator result ) const noexcept
{
for( auto&& f : _indicatorFunctions )
{
*result++ = f.a();
*result++ = f.b();
}
}
/** Returns the image of the function */
template <class OutputIterator> void image( OutputIterator result ) const noexcept
{
for( auto&& f : _indicatorFunctions )
*result++ = f.y();
}
/** Returns the function value at a certain position */
I operator()( D x ) const noexcept
{
I value = I();
for( auto&& f : _indicatorFunctions )
{
// TODO: Not sure whether I really want this. The step functions must not
// overlap anyway...
if( f.contains(x) && std::abs( f(x) ) > value )
value = f(x);
}
return value;
}
/** Calculates the sum of this step function with another step function */
StepFunction& operator+=( const StepFunction& other ) noexcept
{
auto&& f = *this;
auto&& g = other;
std::set<D> domain;
f.domain( std::inserter( domain, domain.begin() ) );
g.domain( std::inserter( domain, domain.begin() ) );
StepFunction<D,I> h;
if( domain.empty() )
return *this;
auto prev = *domain.begin();
auto curr = *domain.begin();
for( auto it = std::next( domain.begin() ); it != domain.end(); ++it )
{
curr = *it;
auto y1 = f( prev );
auto y2 = g( prev );
auto y3 = f( curr );
auto y4 = g( curr );
auto y5 = f( detail::next( prev ) );
auto y6 = g( detail::next( prev ) );
if( y1 == y3 && y2 == y4 )
h.add( prev, curr, y1+y2 );
// A subdivision of the interval [prev, curr] is required because
// at least one of the functions differs on the end points of the
// interval.
else if( y1 != y3 || y2 != y4 )
{
// Make the interval smaller if we hit a point where at least a
// single function changes.
if( y1 != y5 || y2 != y6 )
prev = detail::next( prev );
if( y5+y6 != y3+y4 )
{
// [prev, curr - epsilon]: y5+y6
// [curr, curr + epsilon]: y3+y4
h.add( prev, detail::previous( curr ), y5+y6 );
h.add( curr, detail::next( curr ), y3+y4 );
}
// FIXME: Not sure whether this is really the best workaround
// here or whether I need a different strategy.
else
h.add( prev, detail::next( curr ), y3+y4 );
// Ensures that the next interval uses the proper start point for the
// indicator function interval.
curr = detail::next( curr );
}
prev = curr;
}
*this = h;
return *this;
}
/** Calculates the sum of this step function with another step function */
StepFunction operator+( const StepFunction& rhs ) const noexcept
{
auto lhs = *this;
lhs += rhs;
return lhs;
}
/** Calculates the difference of this step function with another step function */
StepFunction& operator-=( const StepFunction& other )
{
return this->operator+=( -other );
}
/** Calculates the difference of this step function with another step function */
StepFunction operator-( const StepFunction& rhs ) const noexcept
{
auto lhs = *this;
lhs -= rhs;
return lhs;
}
/** Unary minus: negates all values in the image of the step function */
StepFunction operator-() const noexcept
{
StepFunction f;
for( auto&& indicatorFunction : _indicatorFunctions )
f.add( indicatorFunction.a(), indicatorFunction.b(), -indicatorFunction.y() );
return f;
}
/** Adds a scalar to all step function values */
StepFunction operator+( I lambda ) const noexcept
{
StepFunction f;
for( auto&& indicatorFunction : _indicatorFunctions )
f.add( indicatorFunction.a(), indicatorFunction.b(), lambda + indicatorFunction.y() );
return f;
}
/** Subtracts a scalar from all step function values */
StepFunction operator-( I lambda ) const noexcept
{
return this->operator+( -lambda );
}
/** Multiplies the given step function with a scalar value */
StepFunction operator*( I lambda ) const noexcept
{
StepFunction f;
for( auto&& indicatorFunction : _indicatorFunctions )
f.add( indicatorFunction.a(), indicatorFunction.b(), lambda * indicatorFunction.y() );
return f;
}
/** Divides the given step function by a scalar value */
StepFunction operator/( I lambda ) const
{
// TODO: What about division by zero?
return this->operator*( 1/lambda );
}
/** Calculates the integral over the domain of the step function */
I integral() const noexcept
{
if( _indicatorFunctions.empty() )
return I();
I value = I();
for( auto&& f : _indicatorFunctions )
value += f.integral();
return value;
}
/** Calculates the unsigned integral raised to a certain power */
I integral_p( I p ) const noexcept
{
if( _indicatorFunctions.empty() )
return I();
I value = I();
for( auto&& f : _indicatorFunctions )
value += f.integral_p( p );
return std::pow( value, 1/p );
}
/** Calculates the absolute value of the function */
StepFunction& abs() noexcept
{
std::set<IndicatorFunction> indicatorFunctions;
for( auto&& f : _indicatorFunctions )
indicatorFunctions.insert( IndicatorFunction( f.a(), f.b(), std::abs( f.y() ) ) );
_indicatorFunctions.swap( indicatorFunctions );
return *this;
}
template <class U, class V> friend std::ostream& operator<<( std::ostream&, const StepFunction<U, V>& f );
private:
/** All indicator functions of the step function */
std::set<IndicatorFunction> _indicatorFunctions;
};
// TODO: This does not need to be a friend function; it suffices to be
// implemented using the public interface of the class.
template <class D, class I> std::ostream& operator<<( std::ostream& o, const StepFunction<D, I>& f )
{
for( auto&& indicatorFunction : f._indicatorFunctions )
{
o << indicatorFunction.a() << "\t" << indicatorFunction.y() << "\n"
<< indicatorFunction.b() << "\t" << indicatorFunction.y() << "\n";
}
return o;
}
/**
Auxiliary function for normalizing a step function. Given a range
spanned by a minimum $a$ and a maximum $b$, the image of the step
function will be restricted to $[a,b]$.
The transformed step function will be returned.
*/
template <class D, class I> StepFunction<D,I> normalize( const StepFunction<D,I>& f,
I a = I(),
I b = I(1) )
{
std::set<I> image;
f.image( std::inserter( image, image.end() ) );
if( image.empty() || image.size() == 1 )
return f;
// The minimum value in the image of the function is zero because this
// value is guaranteed to be attained at some point
auto min = I();
auto max = *image.rbegin();
auto g = f - min;
g = g / ( max - min ); // now scaled between [0,1 ]
g = g * ( b - a ); // now scaled between [0,b-a]
g = g + a; // now scaled between [a,b ]
return g;
}
} // namespace math
} // namespace aleph
#endif
<|endoftext|> |
<commit_before><commit_msg>Output format change to allow longer durations. BUG=20289 TEST=run media_bench on sonyh2.ogv. formatting looks bad<commit_after><|endoftext|> |
<commit_before>// log_exp.cpp: numerical test programs for fpbench tests for functions constructed with log and exp
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal project, which is released under an MIT Open Source license.
#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
// select your number system
#include <universal/areal/areal>
#include <universal/posit/posit>
#include <universal/valid/valid>
// ln(e^x) -> should always yield x
template<typename Scalar>
Scalar ln_of_exp_x(const Scalar& x) {
Scalar exponent(exp(x));
Scalar result = log(exponent);
return result;
}
// ln(1 + e^x)
template<typename Scalar>
Scalar ln_of_one_plus_exp_x(const Scalar& x) {
Scalar one_plus_exponent(Scalar(1) + exp(x));
Scalar result = log(exponent);
return result;
}
template<typename Scalar>
void SampleFunctionEvaluation(size_t nrSamples) {
using namespace std;
using namespace sw::unum;
// Use random_device to generate a seed for Mersenne twister engine.
random_device rd{};
// Use Mersenne twister engine to generate pseudo-random numbers.
mt19937 engine{ rd() };
// "Filter" MT engine's output to generate pseudo-random double values,
// **uniformly distributed** on the closed interval [lowerbound, upperbound].
// (Note that the range is [inclusive, inclusive].)
double lowerbound = -5;
double upperbound = 5;
uniform_real_distribution<double> dist{ lowerbound, upperbound };
// Pattern to generate pseudo-random number.
// double rnd_value = dist(engine);
vector<Scalar> samples(nrSamples);
for_each(begin(samples), end(samples), [&](Scalar &n) { n = Scalar(dist(engine)); });
vector<Scalar> results(nrSamples);
for (size_t i = 0; i < nrSamples; ++i) {
results[i] = ln_of_exp_x(samples[i]);
}
vector<Scalar> diffs(nrSamples);
for (size_t i = 0; i < nrSamples; ++i) {
diffs[i] = samples[i] - results[i];
}
for_each(begin(diffs), end(diffs), [](Scalar n) {
if (n != 0) {
cout << "FAIL: " << hex_format(n) << " " << n << endl;
}
else {
// cout << "PASS: " << hex_format(n) << endl;
}
});
}
int main(int argc, char* argv[])
try {
using namespace std;
using namespace sw::unum;
// preserve the existing ostream precision
auto precision = cout.precision();
cout << setprecision(12);
const size_t NR_SAMPLES = 64;
SampleFunctionEvaluation < float >(NR_SAMPLES);
SampleFunctionEvaluation < posit< 8, 0> >(NR_SAMPLES);
SampleFunctionEvaluation < posit<16, 1> >(NR_SAMPLES);
SampleFunctionEvaluation < posit<32, 2> >(NR_SAMPLES);
SampleFunctionEvaluation < posit<64, 3> >(NR_SAMPLES);
// restore the previous ostream precision
cout << setprecision(precision);
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}<commit_msg>Adding the nr of epsilons of error<commit_after>// log_exp.cpp: numerical test programs for fpbench tests for functions constructed with log and exp
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal project, which is released under an MIT Open Source license.
#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
// select your number system
//#include <universal/areal/areal>
#include <universal/posit/posit>
#include <universal/valid/valid>
// ln(e^x) -> should always yield x
template<typename Scalar>
Scalar ln_of_exp_x(const Scalar& x) {
Scalar exponent(exp(x));
Scalar result = log(exponent);
return result;
}
// ln(1 + e^x)
template<typename Scalar>
Scalar ln_of_one_plus_exp_x(const Scalar& x) {
Scalar one_plus_exponent(Scalar(1) + exp(x));
Scalar result = log(one_plus_exponent);
return result;
}
template<typename Scalar>
void SampleFunctionEvaluation(size_t nrSamples) {
using namespace std;
using namespace sw::unum;
// Use random_device to generate a seed for Mersenne twister engine.
random_device rd{};
// Use Mersenne twister engine to generate pseudo-random numbers.
mt19937 engine{ rd() };
// "Filter" MT engine's output to generate pseudo-random double values,
// **uniformly distributed** on the closed interval [lowerbound, upperbound].
// (Note that the range is [inclusive, inclusive].)
double lowerbound = -5;
double upperbound = 5;
uniform_real_distribution<double> dist{ lowerbound, upperbound };
// Pattern to generate pseudo-random number.
// double rnd_value = dist(engine);
vector<Scalar> samples(nrSamples);
for_each(begin(samples), end(samples), [&](Scalar &n) { n = Scalar(dist(engine)); });
vector<Scalar> results(nrSamples);
for (size_t i = 0; i < nrSamples; ++i) {
results[i] = ln_of_exp_x(samples[i]);
}
vector<Scalar> diffs(nrSamples);
for (size_t i = 0; i < nrSamples; ++i) {
diffs[i] = samples[i] - results[i];
}
Scalar eps = numeric_limits<Scalar>::epsilon();
for_each(begin(diffs), end(diffs), [=](Scalar n) {
if (n != 0) {
Scalar nrEps = n / eps;
cout << "FAIL: " << hex_format(n) << " " << n << " nr of epsilons of error: " << nrEps << endl;
}
else {
// cout << "PASS: " << hex_format(n) << endl;
}
});
}
int main(int argc, char* argv[])
try {
using namespace std;
using namespace sw::unum;
// preserve the existing ostream precision
auto precision = cout.precision();
cout << setprecision(12);
const size_t NR_SAMPLES = 64;
SampleFunctionEvaluation < float >(NR_SAMPLES);
SampleFunctionEvaluation < posit< 8, 0> >(NR_SAMPLES);
SampleFunctionEvaluation < posit<16, 1> >(NR_SAMPLES);
SampleFunctionEvaluation < posit<32, 2> >(NR_SAMPLES);
SampleFunctionEvaluation < posit<64, 3> >(NR_SAMPLES);
// restore the previous ostream precision
cout << setprecision(precision);
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#define BOTAN_NO_DEPRECATED_WARNINGS
#if defined(BOTAN_HAS_PACKAGE_TRANSFORM)
#include <botan/package.h>
#endif
namespace Botan_Tests {
#if defined(BOTAN_HAS_PACKAGE_TRANSFORM)
class Package_Transform_Tests : public Test
{
public:
std::vector<Test::Result> run() override
{
Test::Result result("Package transform");
std::unique_ptr<Botan::BlockCipher> cipher(Botan::BlockCipher::create("AES-128"));
std::vector<uint8_t> input = unlock(Test::rng().random_vec(Test::rng().next_byte()));
std::vector<uint8_t> output(input.size() + cipher->block_size());
// aont_package owns/deletes the passed cipher object, kind of a bogus API
Botan::aont_package(Test::rng(),
cipher->clone(),
input.data(), input.size(),
output.data());
std::vector<uint8_t> decoded(output.size() - cipher->block_size());
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_eq("Package transform is reversible", decoded, input);
#if 0
// Broken - https://github.com/randombit/botan/issues/825
output[0] ^= 1;
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_ne("Bitflip breaks package transform", decoded, input);
output[0] ^= 1;
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_eq("Package transform is still reversible", decoded, input);
#endif
// More tests including KATs would be useful for these functions
return std::vector<Test::Result> {result};
}
};
BOTAN_REGISTER_TEST("package_transform", Package_Transform_Tests);
#endif
}
<commit_msg>Avoid deprecation warnings in test<commit_after>/*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#define BOTAN_NO_DEPRECATED_WARNINGS
#include "tests.h"
#if defined(BOTAN_HAS_PACKAGE_TRANSFORM)
#include <botan/package.h>
#endif
namespace Botan_Tests {
#if defined(BOTAN_HAS_PACKAGE_TRANSFORM)
class Package_Transform_Tests : public Test
{
public:
std::vector<Test::Result> run() override
{
Test::Result result("Package transform");
std::unique_ptr<Botan::BlockCipher> cipher(Botan::BlockCipher::create("AES-128"));
std::vector<uint8_t> input = unlock(Test::rng().random_vec(Test::rng().next_byte()));
std::vector<uint8_t> output(input.size() + cipher->block_size());
// aont_package owns/deletes the passed cipher object, kind of a bogus API
Botan::aont_package(Test::rng(),
cipher->clone(),
input.data(), input.size(),
output.data());
std::vector<uint8_t> decoded(output.size() - cipher->block_size());
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_eq("Package transform is reversible", decoded, input);
#if 0
// Broken - https://github.com/randombit/botan/issues/825
output[0] ^= 1;
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_ne("Bitflip breaks package transform", decoded, input);
output[0] ^= 1;
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_eq("Package transform is still reversible", decoded, input);
#endif
// More tests including KATs would be useful for these functions
return std::vector<Test::Result> {result};
}
};
BOTAN_REGISTER_TEST("package_transform", Package_Transform_Tests);
#endif
}
<|endoftext|> |
<commit_before>/*
* MusicBrainz -- The Internet music metadatabase
*
* Copyright (C) 2006 Lukas Lalinsky
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id$
*/
#include <cstdlib>
#include <cstring>
#include <cstdarg>
#include <iostream>
#include <map>
#include <ne_uri.h>
#include "utils_private.h"
using namespace std;
using namespace MusicBrainz;
string
MusicBrainz::intToString(const int i)
{
char temp[32];
sprintf(temp, "%d", i);
return string(temp);
}
int
MusicBrainz::stringToInt(const std::string &s)
{
return atoi(s.c_str());
}
string
MusicBrainz::uriEscape(const string &uri)
{
char *esc_uri_str = ne_path_escape(uri.c_str());
string esc_uri = string((const char *)esc_uri_str);
free(esc_uri_str);
return esc_uri;
}
string
MusicBrainz::urlEncode(const vector<pair<string, string> > ¶ms)
{
string encodedStr;
bool first = true;
for (vector<pair<string, string> >::const_iterator i = params.begin(); i != params.end(); i++) {
string name = i->first;
string value = i->second;
if (first)
first = false;
else
encodedStr += "&";
encodedStr += name + "=" + uriEscape(value);
}
return encodedStr;
}
#ifndef NDEBUG
void
MusicBrainz::debug(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "MusicBrainz: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
#endif
<commit_msg>One more iostream reference...<commit_after>/*
* MusicBrainz -- The Internet music metadatabase
*
* Copyright (C) 2006 Lukas Lalinsky
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id$
*/
#include <cstdlib>
#include <cstring>
#include <cstdarg>
#include <map>
#include <ne_uri.h>
#include "utils_private.h"
using namespace std;
using namespace MusicBrainz;
string
MusicBrainz::intToString(const int i)
{
char temp[32];
sprintf(temp, "%d", i);
return string(temp);
}
int
MusicBrainz::stringToInt(const std::string &s)
{
return atoi(s.c_str());
}
string
MusicBrainz::uriEscape(const string &uri)
{
char *esc_uri_str = ne_path_escape(uri.c_str());
string esc_uri = string((const char *)esc_uri_str);
free(esc_uri_str);
return esc_uri;
}
string
MusicBrainz::urlEncode(const vector<pair<string, string> > ¶ms)
{
string encodedStr;
bool first = true;
for (vector<pair<string, string> >::const_iterator i = params.begin(); i != params.end(); i++) {
string name = i->first;
string value = i->second;
if (first)
first = false;
else
encodedStr += "&";
encodedStr += name + "=" + uriEscape(value);
}
return encodedStr;
}
#ifndef NDEBUG
void
MusicBrainz::debug(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "MusicBrainz: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <stdint.h>
#include <malloc.h>
#include <assert.h>
#include "src/validator/null.h"
#include "gmp.h"
#include "iml.h"
using namespace std;
namespace stoke {
long mpz_to_long(mpz_t z)
{
long result = 0;
mpz_export(&result, 0, -1, sizeof result, 0, 0, z);
return result;
}
size_t Nullspace::z_nullspace(uint64_t* inputs, size_t rows, size_t cols, uint64_t*** output) {
mpz_t *mp_result;
cout << "computing the nullspace" << endl;
size_t dim = nullspaceLong(rows, cols, (long*)inputs, &mp_result);
cout << "nullspace computation complete" << endl;
// For each row of the nullspace, find the gcd and divide by it.
for (size_t i = 0; i < dim; ++i) {
mpz_t gcd;
mpz_init_set(gcd, mp_result[0*dim+i]);
for (size_t j = 1; j < cols; ++j) {
mpz_gcd(gcd, gcd, mp_result[j*dim+i]);
}
mpz_t val;
mpz_init(val);
for (size_t j = 0; j < cols; ++j) {
mpz_divexact(val, mp_result[j*dim+i], gcd);
mpz_set(mp_result[j*dim+i], val);
}
}
// Allocate the output matrix
*output = new uint64_t*[dim];
for(size_t i = 0; i < dim; ++i) {
cout << "can I have values? " << i << ": " << (*output)[i] << endl;
(*output)[i] = new uint64_t[cols];
}
// Fill the output matrix
for(size_t i = 0; i < dim; ++i) {
for(size_t j = 0; j < cols; ++j) {
(*output)[i][j] = (uint64_t)mpz_get_si(mp_result[j*dim + i]);
}
}
return dim;
}
}
namespace BitvectorNullspace {
//Any number is odd*2^x. Return odd
uint64_t getOdd(uint64_t p)
{
if(p==0) return 0;
while((p%2)==0)
p=p/2;
return p;
}
//2^{64-input}, not needed
uint64_t invertPow2(uint64_t a)
{
if(a==0) return 1;
if(a==1) return 1;
if(a==2) return (((uint64_t)1)<<63);
else return ((((uint64_t)1)<<63)/(a/2));
}
//Use extended gcd to find v s.t vb=1 mod 2^64
uint64_t invert(uint64_t b)
{
uint64_t a = ((uint64_t)1)<<63;
uint64_t alpha, beta, u, v;
u=1; v=0;
alpha=a; beta = b;
while(a>0)
{
a=a>>1;
if((u&1)==0)
{
u = u>>1; v = v>>1;
}
else
{
u = ((u^beta)>>1) + (u & beta);
v = (v>>1) + alpha;
}
}
return -v;
}
//Create [A^T|I]^T
uint64_t* augmentIdentity(uint64_t* inputs, size_t rows, size_t cols)
{
uint64_t* augmented = new uint64_t[(rows+cols)*cols];
for(size_t i=0;i<rows;i++)
for(size_t j=0; j<cols;j++)
augmented[i*cols+j]=inputs[i*cols+j];
for(size_t i=rows; i<rows+cols;i++)
for(size_t j=0; j<cols;j++)
if(i==rows+j)
augmented[i*cols+j]=1;
else
augmented[i*cols+j]=0;
return augmented;
}
//print a matrix
/*void printMat(uint64_t* mat, size_t rows, size_t cols)
{
cout << "START" << endl;
for(size_t i=0;i<rows;i++)
{
for(size_t j=0;j<cols;j++)
cout << mat[i*cols+j] << " " ;
cout << endl;
}
cout << "END" << endl;
}*/
//compute gcd of two positive numbers
uint64_t gcd(uint64_t a, uint64_t b)
{
if(a==0) return b;
if(b==0) return a;
if(a>b) return gcd(b,a%b);
if(b>a) return gcd(a,b%a);
return a;
}
//absolute value function useful for pretty printing
int64_t abs(uint64_t a)
{
int64_t retval = a;
if(retval>=0) return retval;
else return -retval;
}
//compute gcd of a vector of integers
uint64_t rowGcd(uint64_t* vec, size_t num)
{
size_t i =0;
uint64_t retval = abs(vec[i]);
for(i=1;i<num;i++)
{
retval = gcd(retval,abs(vec[i]));
}
return retval;
}
//for prettier output
void makePretty(uint64_t*** output,size_t rows,size_t cols)
{
/*
for(size_t i=0;i<rows;i++)
{
uint64_t g = rowGcd(*output[i],cols);
assert(g!=0 && "NULL ROW");
for(size_t j=0;j<cols;j++)
{
int64_t l = ((int64_t)*output[i][j]);
l = l/((int64_t)g);
*output[i][j]= (uint64_t)(l);
}
}
*/
}
bool checkInvariants(uint64_t* augmented,size_t rows,size_t cols)
{
for(size_t i=rows;i<rows+cols;i++)
{
bool flag = false;
for(size_t j=0;j<cols;j++)
flag = flag || augmented[i*cols+j]!=0;
if(!flag)
return false;
}
return true;
}
size_t rank(uint64_t a)
{
if(a==0) return 64;
size_t rank =0;
while(a%2==0)
{
a=a/2;
rank++;
}
return rank;
}
#define SUB(X,Y) augmented[(X)*cols+(Y)]
//rowspace of output is nullspace of input
size_t nullspace(long* inputs, size_t rows, size_t cols, uint64_t*** output)
{
size_t rowrank = 0;
uint64_t* augmented = augmentIdentity((uint64_t*)inputs,rows, cols);
//cout << "STARTING" << endl;
//printMat(augmented,rows+cols,cols);
size_t currcol=0;
for(size_t i=0;i<rows;i++)
{
size_t minrank = rank(SUB(i,currcol));
size_t idx = currcol;
for(size_t j=currcol;j<cols;j++)
{
size_t val = rank(SUB(i,j));
if(val<minrank)
{
minrank = val;
idx = j;
}
}
if(minrank==64)
{
i++;
continue;
}
rowrank++;
assert(rowrank<cols);
//We have found the column with the pivot
for(size_t j=i;j<rows+cols;j++)
{
uint64_t temp = SUB(j,idx);
SUB(j,idx)=SUB(j,currcol);
SUB(j,currcol)=temp;
}
//cout << "Swap column" << currcol << " and " << idx << endl;
//printMat(augmented,rows+cols,cols);
uint64_t pivot = SUB(i,currcol);
assert(pivot!=0);
uint64_t odd = getOdd(pivot);
uint64_t twopow = pivot/odd;
uint64_t oddinv = invert(odd);
for(size_t j=i;j<rows+cols;j++)
{
SUB(j,currcol) = SUB(j,currcol)*oddinv;
}
//cout << "The pivot at column " << currcol << " is now a power of 2" << endl;
//printMat(augmented,rows+cols,cols);
assert(SUB(i,currcol)==twopow && "inversion failed");
for(size_t k=currcol+1;k<cols;k++)
{
uint64_t initval = SUB(i,k)/twopow;
for(size_t j =i;j<rows+cols;j++)
{
SUB(j,k) = SUB(j,k) - initval*SUB(j,currcol);
}
// cout << "Column" << k << " - " << initval << " times column " << currcol << endl;
//printMat(augmented,rows+cols,cols);
assert(SUB(i,k)==0);
assert(checkInvariants(augmented,rows,cols));
}
currcol++;
}
size_t nullity = cols-rowrank;
//cout << "Nullity is " << nullity << endl;
*output = new uint64_t*[nullity];
for(size_t i=cols-nullity;i<cols;i++)
{
(*output)[i-cols+nullity]= new uint64_t[cols];
for(size_t j=rows;j<rows+cols;j++)
{
(*output)[i-cols+nullity][j-rows]=SUB(j,i);
}
}
makePretty(output,nullity,cols);
delete augmented;
return nullity;
}
}
<commit_msg>bug fix<commit_after>#include <iostream>
#include <fstream>
#include <stdint.h>
#include <malloc.h>
#include <assert.h>
#include "src/validator/null.h"
#include "gmp.h"
#include "iml.h"
using namespace std;
namespace stoke {
long mpz_to_long(mpz_t z)
{
long result = 0;
mpz_export(&result, 0, -1, sizeof result, 0, 0, z);
return result;
}
size_t Nullspace::z_nullspace(uint64_t* inputs, size_t rows, size_t cols, uint64_t*** output) {
mpz_t *mp_result;
cout << "computing the nullspace" << endl;
size_t dim = nullspaceLong(rows, cols, (long*)inputs, &mp_result);
cout << "nullspace computation complete" << endl;
// For each row of the nullspace, find the gcd and divide by it.
for (size_t i = 0; i < dim; ++i) {
mpz_t gcd;
mpz_init_set(gcd, mp_result[0*dim+i]);
for (size_t j = 1; j < cols; ++j) {
mpz_gcd(gcd, gcd, mp_result[j*dim+i]);
}
mpz_t val;
mpz_init(val);
for (size_t j = 0; j < cols; ++j) {
mpz_divexact(val, mp_result[j*dim+i], gcd);
mpz_set(mp_result[j*dim+i], val);
}
}
// Allocate the output matrix
*output = new uint64_t*[dim];
for(size_t i = 0; i < dim; ++i) {
cout << "can I have values? " << i << ": " << (*output)[i] << endl;
(*output)[i] = new uint64_t[cols];
}
// Fill the output matrix
for(size_t i = 0; i < dim; ++i) {
for(size_t j = 0; j < cols; ++j) {
(*output)[i][j] = (uint64_t)mpz_get_si(mp_result[j*dim + i]);
}
}
return dim;
}
}
namespace BitvectorNullspace {
//Any number is odd*2^x. Return odd
uint64_t getOdd(uint64_t p)
{
if(p==0) return 0;
while((p%2)==0)
p=p/2;
return p;
}
//2^{64-input}, not needed
uint64_t invertPow2(uint64_t a)
{
if(a==0) return 1;
if(a==1) return 1;
if(a==2) return (((uint64_t)1)<<63);
else return ((((uint64_t)1)<<63)/(a/2));
}
//Use extended gcd to find v s.t vb=1 mod 2^64
uint64_t invert(uint64_t b)
{
uint64_t a = ((uint64_t)1)<<63;
uint64_t alpha, beta, u, v;
u=1; v=0;
alpha=a; beta = b;
while(a>0)
{
a=a>>1;
if((u&1)==0)
{
u = u>>1; v = v>>1;
}
else
{
u = ((u^beta)>>1) + (u & beta);
v = (v>>1) + alpha;
}
}
return -v;
}
//Create [A^T|I]^T
uint64_t* augmentIdentity(uint64_t* inputs, size_t rows, size_t cols)
{
uint64_t* augmented = new uint64_t[(rows+cols)*cols];
for(size_t i=0;i<rows;i++)
for(size_t j=0; j<cols;j++)
augmented[i*cols+j]=inputs[i*cols+j];
for(size_t i=rows; i<rows+cols;i++)
for(size_t j=0; j<cols;j++)
if(i==rows+j)
augmented[i*cols+j]=1;
else
augmented[i*cols+j]=0;
return augmented;
}
//print a matrix
/*void printMat(uint64_t* mat, size_t rows, size_t cols)
{
cout << "START" << endl;
for(size_t i=0;i<rows;i++)
{
for(size_t j=0;j<cols;j++)
cout << mat[i*cols+j] << " " ;
cout << endl;
}
cout << "END" << endl;
}*/
//compute gcd of two positive numbers
uint64_t gcd(uint64_t a, uint64_t b)
{
if(a==0) return b;
if(b==0) return a;
if(a>b) return gcd(b,a%b);
if(b>a) return gcd(a,b%a);
return a;
}
//absolute value function useful for pretty printing
int64_t abs(uint64_t a)
{
int64_t retval = a;
if(retval>=0) return retval;
else return -retval;
}
//compute gcd of a vector of integers
uint64_t rowGcd(uint64_t* vec, size_t num)
{
size_t i =0;
uint64_t retval = abs(vec[i]);
for(i=1;i<num;i++)
{
retval = gcd(retval,abs(vec[i]));
}
return retval;
}
//for prettier output
void makePretty(uint64_t*** output,size_t rows,size_t cols)
{
/*
for(size_t i=0;i<rows;i++)
{
uint64_t g = rowGcd(*output[i],cols);
assert(g!=0 && "NULL ROW");
for(size_t j=0;j<cols;j++)
{
int64_t l = ((int64_t)*output[i][j]);
l = l/((int64_t)g);
*output[i][j]= (uint64_t)(l);
}
}
*/
}
void printOutput(uint64_t** output,size_t rows,size_t cols)
{
for(size_t i=0;i<rows;i++)
{
for(size_t j=0;j<cols;j++)
{
cout << output[i][j] << " " ;
}
cout << endl;
}
}
bool checkInvariants(uint64_t* augmented,size_t rows,size_t cols)
{
for(size_t i=rows;i<rows+cols;i++)
{
bool flag = false;
for(size_t j=0;j<cols;j++)
flag = flag || augmented[i*cols+j]!=0;
if(!flag)
return false;
}
return true;
}
size_t rank(uint64_t a)
{
if(a==0) return 64;
size_t rank =0;
while(a%2==0)
{
a=a/2;
rank++;
}
return rank;
}
uint64_t multiplyRow(uint64_t* r1, uint64_t* r2, size_t num)
{
uint64_t acc = 0;
for(size_t i=0; i< num; i++)
acc += r1[i]*r2[i];
return acc;
}
bool checkOutput(uint64_t** output, uint64_t* inputs, size_t nullity, size_t rows, size_t cols)
{
assert(nullity > 0);
for(size_t i = 0; i< nullity; i++)
for(size_t j=0; j< rows;j++)
if(multiplyRow(output[i],inputs+j*cols,cols))
{
cout << "!!!!!!!!!NULLSPACE WRONG!!!!!!!!" << endl;
return false;
}
return true;
}
#define SUB(X,Y) augmented[(X)*cols+(Y)]
//rowspace of output is nullspace of input
//rowspace of output is nullspace of input
size_t nullspace(uint64_t* inputs, size_t rows, size_t cols, uint64_t** output)
{
size_t rowrank = 0;
uint64_t* augmented = augmentIdentity(inputs,rows, cols);
#ifdef RSDEBUG
cout << "STARTING" << endl;
printMat(augmented,rows+cols,cols);
#endif
size_t currcol=0;
for(size_t i=0;i<rows;i++)
{
size_t minrank = rank(SUB(i,currcol));
size_t idx = currcol;
for(size_t j=currcol;j<cols;j++)
{
size_t val = rank(SUB(i,j));
if(val<minrank)
{
minrank = val;
idx = j;
}
}
if(minrank==64)
{
continue;
}
rowrank++;
#ifdef RSDEBUG
cout << "Rank " << rowrank << endl;
#endif
assert(rowrank<cols);
//We have found the column with the pivot
for(size_t j=i;j<rows+cols;j++)
{
uint64_t temp = SUB(j,idx);
SUB(j,idx)=SUB(j,currcol);
SUB(j,currcol)=temp;
}
#ifdef RSDEBUG
cout << "Swap column" << currcol << " and " << idx << endl;
printMat(augmented,rows+cols,cols);
#endif
uint64_t pivot = SUB(i,currcol);
assert(pivot!=0);
uint64_t odd = getOdd(pivot);
uint64_t twopow = pivot/odd;
uint64_t oddinv = invert(odd);
for(size_t j=i;j<rows+cols;j++)
{
SUB(j,currcol) = SUB(j,currcol)*oddinv;
}
#ifdef RSDEBUG
cout << "The pivot at column " << currcol << " is now a power of 2" << endl;
printMat(augmented,rows+cols,cols);
#endif
assert(SUB(i,currcol)==twopow && "inversion failed");
for(size_t k=currcol+1;k<cols;k++)
{
uint64_t initval = SUB(i,k)/twopow;
for(size_t j =i;j<rows+cols;j++)
{
SUB(j,k) = SUB(j,k) - initval*SUB(j,currcol);
}
#ifdef RSDEBUG
cout << "Column" << k << " - " << initval << " times column " << currcol << endl;
printMat(augmented,rows+cols,cols);
#endif
assert(SUB(i,k)==0);
assert(checkInvariants(augmented,rows,cols));
}
currcol++;
}
size_t nullity = cols-rowrank;
#ifdef RSDEBUG
cout << "Nullity is " << nullity << endl;
#endif
for(size_t i=cols-nullity;i<cols;i++)
{
output[i-cols+nullity]=(uint64_t*)malloc(sizeof(uint64_t)*cols);
for(size_t j=rows;j<rows+cols;j++)
{
output[i-cols+nullity][j-rows]=SUB(j,i);
}
}
makePretty(output,nullity,cols);
#ifdef RSDEBUG
printOutput(output, nullity, cols);
#endif
assert(checkOutput(output,inputs,nullity,rows,cols));
free(augmented);
return nullity;
}
#undef SUB
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "src/traced/probes/probes_producer.h"
#include <stdio.h>
#include <sys/stat.h>
#include <queue>
#include <string>
#include "perfetto/base/logging.h"
#include "perfetto/base/weak_ptr.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "perfetto/tracing/core/ftrace_config.h"
#include "perfetto/tracing/core/trace_config.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/traced/probes/filesystem/inode_file_data_source.h"
#include "perfetto/trace/filesystem/inode_file_map.pbzero.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
#include "perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
uint64_t kInitialConnectionBackoffMs = 100;
uint64_t kMaxConnectionBackoffMs = 30 * 1000;
constexpr char kFtraceSourceName[] = "com.google.perfetto.ftrace";
constexpr char kProcessStatsSourceName[] = "com.google.perfetto.process_stats";
constexpr char kInodeMapSourceName[] = "com.google.perfetto.inode_file_map";
} // namespace.
// State transition diagram:
// +----------------------------+
// v +
// NotStarted -> NotConnected -> Connecting -> Connected
// ^ +
// +--------------+
//
ProbesProducer::ProbesProducer() {}
ProbesProducer::~ProbesProducer() = default;
void ProbesProducer::OnConnect() {
PERFETTO_DCHECK(state_ == kConnecting);
state_ = kConnected;
ResetConnectionBackoff();
PERFETTO_LOG("Connected to the service");
DataSourceDescriptor ftrace_descriptor;
ftrace_descriptor.set_name(kFtraceSourceName);
endpoint_->RegisterDataSource(ftrace_descriptor, [](DataSourceInstanceID) {});
DataSourceDescriptor process_stats_descriptor;
process_stats_descriptor.set_name(kProcessStatsSourceName);
endpoint_->RegisterDataSource(process_stats_descriptor,
[](DataSourceInstanceID) {});
DataSourceDescriptor inode_map_descriptor;
inode_map_descriptor.set_name(kInodeMapSourceName);
endpoint_->RegisterDataSource(inode_map_descriptor,
[](DataSourceInstanceID) {});
}
void ProbesProducer::OnDisconnect() {
PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
state_ = kNotConnected;
PERFETTO_LOG("Disconnected from tracing service");
IncreaseConnectionBackoff();
// TODO(hjd): Erase all sinks and add e2e test for this.
task_runner_->PostDelayedTask([this] { this->Connect(); },
connection_backoff_ms_);
}
void ProbesProducer::CreateDataSourceInstance(DataSourceInstanceID instance_id,
const DataSourceConfig& config) {
// TODO(hjd): This a hack since we don't actually know the session id. For
// now we'll assume anything wit hthe same target buffer is in the same
// session.
TracingSessionID session_id = config.target_buffer();
if (config.name() == kFtraceSourceName) {
if (!CreateFtraceDataSourceInstance(session_id, instance_id, config))
failed_sources_.insert(instance_id);
} else if (config.name() == kInodeMapSourceName) {
CreateInodeFileDataSourceInstance(session_id, instance_id, config);
} else if (config.name() == kProcessStatsSourceName) {
CreateProcessStatsDataSourceInstance(session_id, instance_id, config);
} else {
PERFETTO_ELOG("Data source name: %s not recognised.",
config.name().c_str());
return;
}
std::map<TracingSessionID, InodeFileDataSource*> file_sources;
std::map<TracingSessionID, ProcessStatsDataSource*> ps_sources;
for (const auto& pair : file_map_sources_)
file_sources[pair.second->session_id()] = pair.second.get();
for (const auto& pair : process_stats_sources_)
ps_sources[pair.second->session_id()] = pair.second.get();
for (const auto& id_to_source : delegates_) {
const std::unique_ptr<SinkDelegate>& source = id_to_source.second;
if (session_id != source->session_id())
continue;
if (!source->ps_source() && ps_sources.count(session_id))
source->set_ps_source(ps_sources[session_id]->GetWeakPtr());
if (!source->file_source() && file_sources.count(session_id))
source->set_file_source(file_sources[session_id]->GetWeakPtr());
}
}
void ProbesProducer::AddWatchdogsTimer(DataSourceInstanceID id,
const DataSourceConfig& config) {
if (config.trace_duration_ms() != 0)
watchdogs_.emplace(id, base::Watchdog::GetInstance()->CreateFatalTimer(
5000 + 2 * config.trace_duration_ms()));
}
bool ProbesProducer::CreateFtraceDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
// Don't retry if FtraceController::Create() failed once.
// This can legitimately happen on user builds where we cannot access the
// debug paths, e.g., because of SELinux rules.
if (ftrace_creation_failed_)
return false;
// Lazily create on the first instance.
if (!ftrace_) {
ftrace_ = FtraceController::Create(task_runner_);
if (!ftrace_) {
PERFETTO_ELOG("Failed to create FtraceController");
ftrace_creation_failed_ = true;
return false;
}
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
}
PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
config.target_buffer());
FtraceConfig proto_config = config.ftrace_config();
// TODO(hjd): Static cast is bad, target_buffer() should return a BufferID.
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto delegate = std::unique_ptr<SinkDelegate>(
new SinkDelegate(session_id, task_runner_, std::move(trace_writer)));
auto sink = ftrace_->CreateSink(std::move(proto_config), delegate.get());
if (!sink) {
PERFETTO_ELOG("Failed to start tracing (maybe someone else is using it?)");
return false;
}
delegate->set_sink(std::move(sink));
delegates_.emplace(id, std::move(delegate));
AddWatchdogsTimer(id, config);
return true;
}
void ProbesProducer::CreateInodeFileDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& source_config) {
PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
id, source_config.target_buffer());
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(source_config.target_buffer()));
if (system_inodes_.empty())
CreateStaticDeviceToInodeMap("/system/", &system_inodes_);
auto file_map_source =
std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
session_id, &system_inodes_, &cache_, std::move(trace_writer)));
file_map_sources_.emplace(id, std::move(file_map_source));
AddWatchdogsTimer(id, source_config);
}
void ProbesProducer::CreateProcessStatsDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
PERFETTO_DCHECK(process_stats_sources_.count(id) == 0);
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto source = std::unique_ptr<ProcessStatsDataSource>(
new ProcessStatsDataSource(session_id, std::move(trace_writer)));
auto it_and_inserted = process_stats_sources_.emplace(id, std::move(source));
PERFETTO_DCHECK(it_and_inserted.second);
it_and_inserted.first->second->WriteAllProcesses();
}
void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
// |id| could be the id of any of the datasources we handle:
PERFETTO_DCHECK((failed_sources_.count(id) +
process_stats_sources_.count(id) +
file_map_sources_.count(id)) == 1);
failed_sources_.erase(id);
delegates_.erase(id);
process_stats_sources_.erase(id);
file_map_sources_.erase(id);
watchdogs_.erase(id);
}
void ProbesProducer::OnTracingStart() {}
void ProbesProducer::OnTracingStop() {}
void ProbesProducer::ConnectWithRetries(const char* socket_name,
base::TaskRunner* task_runner) {
PERFETTO_DCHECK(state_ == kNotStarted);
state_ = kNotConnected;
ResetConnectionBackoff();
socket_name_ = socket_name;
task_runner_ = task_runner;
Connect();
}
void ProbesProducer::Connect() {
PERFETTO_DCHECK(state_ == kNotConnected);
state_ = kConnecting;
endpoint_ = ProducerIPCClient::Connect(socket_name_, this, task_runner_);
}
void ProbesProducer::IncreaseConnectionBackoff() {
connection_backoff_ms_ *= 2;
if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
connection_backoff_ms_ = kMaxConnectionBackoffMs;
}
void ProbesProducer::ResetConnectionBackoff() {
connection_backoff_ms_ = kInitialConnectionBackoffMs;
}
ProbesProducer::SinkDelegate::SinkDelegate(TracingSessionID id,
base::TaskRunner* task_runner,
std::unique_ptr<TraceWriter> writer)
: session_id_(id),
task_runner_(task_runner),
writer_(std::move(writer)),
weak_factory_(this) {}
ProbesProducer::SinkDelegate::~SinkDelegate() = default;
ProbesProducer::FtraceBundleHandle
ProbesProducer::SinkDelegate::GetBundleForCpu(size_t) {
trace_packet_ = writer_->NewTracePacket();
return FtraceBundleHandle(trace_packet_->set_ftrace_events());
}
void ProbesProducer::SinkDelegate::OnBundleComplete(
size_t,
FtraceBundleHandle,
const FtraceMetadata& metadata) {
trace_packet_->Finalize();
if (file_source_ && !metadata.inode_and_device.empty()) {
auto inodes = metadata.inode_and_device;
auto weak_file_source = file_source_;
task_runner_->PostTask([weak_file_source, inodes] {
if (weak_file_source)
weak_file_source->OnInodes(inodes);
});
}
}
} // namespace perfetto
<commit_msg>traced_probes: Fix DCHECK am: aa69aff056 am: 02a5813876<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "src/traced/probes/probes_producer.h"
#include <stdio.h>
#include <sys/stat.h>
#include <queue>
#include <string>
#include "perfetto/base/logging.h"
#include "perfetto/base/weak_ptr.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "perfetto/tracing/core/ftrace_config.h"
#include "perfetto/tracing/core/trace_config.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/traced/probes/filesystem/inode_file_data_source.h"
#include "perfetto/trace/filesystem/inode_file_map.pbzero.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
#include "perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
uint64_t kInitialConnectionBackoffMs = 100;
uint64_t kMaxConnectionBackoffMs = 30 * 1000;
constexpr char kFtraceSourceName[] = "com.google.perfetto.ftrace";
constexpr char kProcessStatsSourceName[] = "com.google.perfetto.process_stats";
constexpr char kInodeMapSourceName[] = "com.google.perfetto.inode_file_map";
} // namespace.
// State transition diagram:
// +----------------------------+
// v +
// NotStarted -> NotConnected -> Connecting -> Connected
// ^ +
// +--------------+
//
ProbesProducer::ProbesProducer() {}
ProbesProducer::~ProbesProducer() = default;
void ProbesProducer::OnConnect() {
PERFETTO_DCHECK(state_ == kConnecting);
state_ = kConnected;
ResetConnectionBackoff();
PERFETTO_LOG("Connected to the service");
DataSourceDescriptor ftrace_descriptor;
ftrace_descriptor.set_name(kFtraceSourceName);
endpoint_->RegisterDataSource(ftrace_descriptor, [](DataSourceInstanceID) {});
DataSourceDescriptor process_stats_descriptor;
process_stats_descriptor.set_name(kProcessStatsSourceName);
endpoint_->RegisterDataSource(process_stats_descriptor,
[](DataSourceInstanceID) {});
DataSourceDescriptor inode_map_descriptor;
inode_map_descriptor.set_name(kInodeMapSourceName);
endpoint_->RegisterDataSource(inode_map_descriptor,
[](DataSourceInstanceID) {});
}
void ProbesProducer::OnDisconnect() {
PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
state_ = kNotConnected;
PERFETTO_LOG("Disconnected from tracing service");
IncreaseConnectionBackoff();
// TODO(hjd): Erase all sinks and add e2e test for this.
task_runner_->PostDelayedTask([this] { this->Connect(); },
connection_backoff_ms_);
}
void ProbesProducer::CreateDataSourceInstance(DataSourceInstanceID instance_id,
const DataSourceConfig& config) {
// TODO(hjd): This a hack since we don't actually know the session id. For
// now we'll assume anything wit hthe same target buffer is in the same
// session.
TracingSessionID session_id = config.target_buffer();
if (config.name() == kFtraceSourceName) {
if (!CreateFtraceDataSourceInstance(session_id, instance_id, config))
failed_sources_.insert(instance_id);
} else if (config.name() == kInodeMapSourceName) {
CreateInodeFileDataSourceInstance(session_id, instance_id, config);
} else if (config.name() == kProcessStatsSourceName) {
CreateProcessStatsDataSourceInstance(session_id, instance_id, config);
} else {
PERFETTO_ELOG("Data source name: %s not recognised.",
config.name().c_str());
return;
}
std::map<TracingSessionID, InodeFileDataSource*> file_sources;
std::map<TracingSessionID, ProcessStatsDataSource*> ps_sources;
for (const auto& pair : file_map_sources_)
file_sources[pair.second->session_id()] = pair.second.get();
for (const auto& pair : process_stats_sources_)
ps_sources[pair.second->session_id()] = pair.second.get();
for (const auto& id_to_source : delegates_) {
const std::unique_ptr<SinkDelegate>& source = id_to_source.second;
if (session_id != source->session_id())
continue;
if (!source->ps_source() && ps_sources.count(session_id))
source->set_ps_source(ps_sources[session_id]->GetWeakPtr());
if (!source->file_source() && file_sources.count(session_id))
source->set_file_source(file_sources[session_id]->GetWeakPtr());
}
}
void ProbesProducer::AddWatchdogsTimer(DataSourceInstanceID id,
const DataSourceConfig& config) {
if (config.trace_duration_ms() != 0)
watchdogs_.emplace(id, base::Watchdog::GetInstance()->CreateFatalTimer(
5000 + 2 * config.trace_duration_ms()));
}
bool ProbesProducer::CreateFtraceDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
// Don't retry if FtraceController::Create() failed once.
// This can legitimately happen on user builds where we cannot access the
// debug paths, e.g., because of SELinux rules.
if (ftrace_creation_failed_)
return false;
// Lazily create on the first instance.
if (!ftrace_) {
ftrace_ = FtraceController::Create(task_runner_);
if (!ftrace_) {
PERFETTO_ELOG("Failed to create FtraceController");
ftrace_creation_failed_ = true;
return false;
}
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
}
PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
config.target_buffer());
FtraceConfig proto_config = config.ftrace_config();
// TODO(hjd): Static cast is bad, target_buffer() should return a BufferID.
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto delegate = std::unique_ptr<SinkDelegate>(
new SinkDelegate(session_id, task_runner_, std::move(trace_writer)));
auto sink = ftrace_->CreateSink(std::move(proto_config), delegate.get());
if (!sink) {
PERFETTO_ELOG("Failed to start tracing (maybe someone else is using it?)");
return false;
}
delegate->set_sink(std::move(sink));
delegates_.emplace(id, std::move(delegate));
AddWatchdogsTimer(id, config);
return true;
}
void ProbesProducer::CreateInodeFileDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& source_config) {
PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
id, source_config.target_buffer());
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(source_config.target_buffer()));
if (system_inodes_.empty())
CreateStaticDeviceToInodeMap("/system/", &system_inodes_);
auto file_map_source =
std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
session_id, &system_inodes_, &cache_, std::move(trace_writer)));
file_map_sources_.emplace(id, std::move(file_map_source));
AddWatchdogsTimer(id, source_config);
}
void ProbesProducer::CreateProcessStatsDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
PERFETTO_DCHECK(process_stats_sources_.count(id) == 0);
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto source = std::unique_ptr<ProcessStatsDataSource>(
new ProcessStatsDataSource(session_id, std::move(trace_writer)));
auto it_and_inserted = process_stats_sources_.emplace(id, std::move(source));
PERFETTO_DCHECK(it_and_inserted.second);
it_and_inserted.first->second->WriteAllProcesses();
}
void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
// |id| could be the id of any of the datasources we handle:
PERFETTO_DCHECK((failed_sources_.count(id) + delegates_.count(id) +
process_stats_sources_.count(id) +
file_map_sources_.count(id)) == 1);
failed_sources_.erase(id);
delegates_.erase(id);
process_stats_sources_.erase(id);
file_map_sources_.erase(id);
watchdogs_.erase(id);
}
void ProbesProducer::OnTracingStart() {}
void ProbesProducer::OnTracingStop() {}
void ProbesProducer::ConnectWithRetries(const char* socket_name,
base::TaskRunner* task_runner) {
PERFETTO_DCHECK(state_ == kNotStarted);
state_ = kNotConnected;
ResetConnectionBackoff();
socket_name_ = socket_name;
task_runner_ = task_runner;
Connect();
}
void ProbesProducer::Connect() {
PERFETTO_DCHECK(state_ == kNotConnected);
state_ = kConnecting;
endpoint_ = ProducerIPCClient::Connect(socket_name_, this, task_runner_);
}
void ProbesProducer::IncreaseConnectionBackoff() {
connection_backoff_ms_ *= 2;
if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
connection_backoff_ms_ = kMaxConnectionBackoffMs;
}
void ProbesProducer::ResetConnectionBackoff() {
connection_backoff_ms_ = kInitialConnectionBackoffMs;
}
ProbesProducer::SinkDelegate::SinkDelegate(TracingSessionID id,
base::TaskRunner* task_runner,
std::unique_ptr<TraceWriter> writer)
: session_id_(id),
task_runner_(task_runner),
writer_(std::move(writer)),
weak_factory_(this) {}
ProbesProducer::SinkDelegate::~SinkDelegate() = default;
ProbesProducer::FtraceBundleHandle
ProbesProducer::SinkDelegate::GetBundleForCpu(size_t) {
trace_packet_ = writer_->NewTracePacket();
return FtraceBundleHandle(trace_packet_->set_ftrace_events());
}
void ProbesProducer::SinkDelegate::OnBundleComplete(
size_t,
FtraceBundleHandle,
const FtraceMetadata& metadata) {
trace_packet_->Finalize();
if (file_source_ && !metadata.inode_and_device.empty()) {
auto inodes = metadata.inode_and_device;
auto weak_file_source = file_source_;
task_runner_->PostTask([weak_file_source, inodes] {
if (weak_file_source)
weak_file_source->OnInodes(inodes);
});
}
}
} // namespace perfetto
<|endoftext|> |
<commit_before>/*
Copyright(c) 2016-2019 Panos Karabelas
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.
*/
//= INCLUDES =======================
#include "Widget_Viewport.h"
#include "Rendering/Renderer.h"
#include "World/Entity.h"
#include "World/Components/Camera.h"
#include "Widget_World.h"
#include "Core/Settings.h"
#include "../DragDrop.h"
//==================================
//= NAMESPACES ==========
using namespace std;
using namespace Spartan;
using namespace Math;
//=======================
namespace _Widget_Viewport
{
static Renderer* g_renderer = nullptr;
static World* g_world = nullptr;
float g_window_padding = 4.0f;
}
Widget_Viewport::Widget_Viewport(Context* context) : Widget(context)
{
m_title = "Viewport";
m_timeSinceLastResChange = 0.0f;
m_windowFlags |= ImGuiWindowFlags_NoScrollbar;
_Widget_Viewport::g_renderer = m_context->GetSubsystem<Renderer>().get();
_Widget_Viewport::g_world = m_context->GetSubsystem<World>().get();
m_xMin = 400;
m_yMin = 250;
}
bool Widget_Viewport::Begin()
{
ImGui::SetNextWindowSize(ImVec2(m_xMin, m_yMin), ImGuiCond_FirstUseEver);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(_Widget_Viewport::g_window_padding, _Widget_Viewport::g_window_padding));
ImGui::Begin(m_title.c_str(), &m_isVisible, m_windowFlags);
return true;
}
void Widget_Viewport::Tick(const float delta_time)
{
if (!_Widget_Viewport::g_renderer)
return;
ShowFrame(delta_time);
ImGui::PopStyleVar();
}
void Widget_Viewport::ShowFrame(const float delta_time)
{
// Get current frame window resolution
auto width = static_cast<unsigned int>(ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x);
auto height = static_cast<unsigned int>(ImGui::GetWindowContentRegionMax().y - ImGui::GetWindowContentRegionMin().y);
const auto max_res = _Widget_Viewport::g_renderer->GetMaxResolution();
if (width > max_res || height > max_res)
return;
// Make pixel perfect
width -= (width % 2 != 0) ? 1 : 0;
height -= (height % 2 != 0) ? 1 : 0;
// Update engine's viewport
_Widget_Viewport::g_renderer->viewport_editor_offset = Vector2(ImGui::GetWindowPos()) + _Widget_Viewport::g_window_padding;
_Widget_Viewport::g_renderer->SetViewport(RHI_Viewport(0.0f, 0.0f, static_cast<float>(width), static_cast<float>(height)));
// Update engine's resolution
if (m_timeSinceLastResChange >= 0.1f) // Don't stress the GPU too much
{
_Widget_Viewport::g_renderer->SetResolution(width, height);
m_timeSinceLastResChange = 0;
}
m_timeSinceLastResChange += delta_time;
// Draw the image after a potential Renderer::SetResolution() call has been made
ImGui::Image(
_Widget_Viewport::g_renderer->GetFrameShaderResource(),
ImVec2(static_cast<float>(width), static_cast<float>(height)),
ImVec2(0, 0),
ImVec2(1, 1),
ImColor(255, 255, 255, 255),
ImColor(50, 127, 166, 255)
);
// If this widget was clicked, make the engine pick an entity
if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered())
{
EditorHelper::Get().PickEntity();
}
// Handle model drop
if (auto payload = DragDrop::Get().GetPayload(DragPayload_Model))
{
EditorHelper::Get().LoadModel(get<const char*>(payload->data));
}
}<commit_msg>Fixed a bug where the transform gizmo would snap to a different entity even if another enitty was previously selected via the world pane.<commit_after>/*
Copyright(c) 2016-2019 Panos Karabelas
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.
*/
//= INCLUDES =======================
#include "Widget_Viewport.h"
#include "Rendering/Renderer.h"
#include "World/Entity.h"
#include "World/Components/Camera.h"
#include "Widget_World.h"
#include "Core/Settings.h"
#include "../DragDrop.h"
//==================================
//= NAMESPACES ==========
using namespace std;
using namespace Spartan;
using namespace Math;
//=======================
namespace _Widget_Viewport
{
static Renderer* g_renderer = nullptr;
static World* g_world = nullptr;
float g_window_padding = 4.0f;
}
Widget_Viewport::Widget_Viewport(Context* context) : Widget(context)
{
m_title = "Viewport";
m_timeSinceLastResChange = 0.0f;
m_windowFlags |= ImGuiWindowFlags_NoScrollbar;
_Widget_Viewport::g_renderer = m_context->GetSubsystem<Renderer>().get();
_Widget_Viewport::g_world = m_context->GetSubsystem<World>().get();
m_xMin = 400;
m_yMin = 250;
}
bool Widget_Viewport::Begin()
{
ImGui::SetNextWindowSize(ImVec2(m_xMin, m_yMin), ImGuiCond_FirstUseEver);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(_Widget_Viewport::g_window_padding, _Widget_Viewport::g_window_padding));
ImGui::Begin(m_title.c_str(), &m_isVisible, m_windowFlags);
return true;
}
void Widget_Viewport::Tick(const float delta_time)
{
if (!_Widget_Viewport::g_renderer)
return;
ShowFrame(delta_time);
ImGui::PopStyleVar();
}
void Widget_Viewport::ShowFrame(const float delta_time)
{
// Get current frame window resolution
auto width = static_cast<unsigned int>(ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x);
auto height = static_cast<unsigned int>(ImGui::GetWindowContentRegionMax().y - ImGui::GetWindowContentRegionMin().y);
const auto max_res = _Widget_Viewport::g_renderer->GetMaxResolution();
if (width > max_res || height > max_res)
return;
// Make pixel perfect
width -= (width % 2 != 0) ? 1 : 0;
height -= (height % 2 != 0) ? 1 : 0;
// Update engine's viewport
_Widget_Viewport::g_renderer->viewport_editor_offset = Vector2(ImGui::GetWindowPos()) + _Widget_Viewport::g_window_padding;
_Widget_Viewport::g_renderer->SetViewport(RHI_Viewport(0.0f, 0.0f, static_cast<float>(width), static_cast<float>(height)));
// Update engine's resolution
if (m_timeSinceLastResChange >= 0.1f) // Don't stress the GPU too much
{
_Widget_Viewport::g_renderer->SetResolution(width, height);
m_timeSinceLastResChange = 0;
}
m_timeSinceLastResChange += delta_time;
// Draw the image after a potential Renderer::SetResolution() call has been made
ImGui::Image(
_Widget_Viewport::g_renderer->GetFrameShaderResource(),
ImVec2(static_cast<float>(width), static_cast<float>(height)),
ImVec2(0, 0),
ImVec2(1, 1),
ImColor(255, 255, 255, 255),
ImColor(50, 127, 166, 255)
);
// If this widget was released, make the engine pick an entity.
// Don't do that on mouse down as a mouse down event might also mean that the user is currently transforming the entity.
if (ImGui::IsMouseReleased(0) && ImGui::IsItemHovered())
{
EditorHelper::Get().PickEntity();
}
// Handle model drop
if (auto payload = DragDrop::Get().GetPayload(DragPayload_Model))
{
EditorHelper::Get().LoadModel(get<const char*>(payload->data));
}
}<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "MiniAppManager.h"
#include "ctkCommandLineParser.h"
#include "mitkImage.h"
#include "mitkImageStatisticsCalculator.h"
#include "mitkIOUtil.h"
#include <iostream>
#include <usAny.h>
#include <fstream>
int ExtractImageStatistics(int argc, char* argv[])
{
ctkCommandLineParser parser;
parser.setTitle("Extract Image Statistics");
parser.setCategory("Preprocessing Tools");
parser.setDescription("");
parser.setContributor("MBI");
parser.setArgumentPrefix("--", "-");
parser.addArgument("help", "h", ctkCommandLineParser::String, "Help:", "Show this help text");
parser.addArgument("input", "i", ctkCommandLineParser::InputFile, "Input:", "input image", us::Any(),false);
parser.addArgument("mask", "m", ctkCommandLineParser::InputFile, "Mask:", "mask image / roi image denotin area on which statistics are calculated", us::Any(),false);
parser.addArgument("out", "o", ctkCommandLineParser::OutputFile, "Output", "output file (default: filenameOfRoi.nrrd_statistics.txt)", us::Any());
map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0 || parsedArgs.count("help") || parsedArgs.count("h"))
{
std::cout << "\n\n MiniApp Description: \nCalculates statistics on the supplied image using given mask." << endl;
std::cout << "Output is written to the designated output file in this order:" << endl;
std::cout << "Mean, Standard Deviation, RMS, Max, Min, Number of Voxels, Volume [mm3]" << endl;
std::cout << "\n\n Parameters:"<< endl;
std::cout << parser.helpText();
return EXIT_SUCCESS;
}
// Parameters:
bool ignoreZeroValues = false;
unsigned int timeStep = 0;
std::string inputImageFile = us::any_cast<string>(parsedArgs["input"]);
std::string maskImageFile = us::any_cast<string>(parsedArgs["mask"]);
std::string outFile;
if (parsedArgs.count("out") || parsedArgs.count("o") )
outFile = us::any_cast<string>(parsedArgs["out"]);
else
outFile = inputImageFile + "_statistics.txt";
// Load image and mask
mitk::Image::Pointer maskImage = mitk::IOUtil::LoadImage(maskImageFile);
mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(inputImageFile);
// Calculate statistics
mitk::ImageStatisticsCalculator::Statistics statisticsStruct;
mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();
try
{
calculator->SetImage(inputImage);
calculator->SetImageMask(maskImage);
calculator->SetMaskingModeToImage();
}
catch( const itk::ExceptionObject& e)
{
MITK_ERROR << "Statistic Calculation Failed - ITK Exception:" << e.what();
return -1;
}
calculator->SetDoIgnorePixelValue(ignoreZeroValues);
calculator->SetIgnorePixelValue(0);
try
{
calculator->ComputeStatistics(timeStep);
}
catch ( mitk::Exception& e)
{
MITK_ERROR<< "MITK Exception: " << e.what();
return -1;
}
statisticsStruct = calculator->GetStatistics(timeStep);
// Calculate Volume
double volume = 0;
const mitk::BaseGeometry *geometry = inputImage->GetGeometry();
if ( geometry != NULL )
{
const mitk::Vector3D &spacing = inputImage->GetGeometry()->GetSpacing();
volume = spacing[0] * spacing[1] * spacing[2] * (double) statisticsStruct.N;
}
// Write Results to file
std::ofstream output;
output.open(outFile.c_str());
output << statisticsStruct.Mean << " , ";
output << statisticsStruct.Sigma << " , ";
output << statisticsStruct.RMS << " , ";
output << statisticsStruct.Max << " , ";
output << statisticsStruct.Min << " , ";
output << statisticsStruct.N << " , ";
output << volume << "\n";
output.flush();
output.close();
return 0;
}
RegisterDiffusionMiniApp(ExtractImageStatistics);
<commit_msg>using getter instead of trying to access private member<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "MiniAppManager.h"
#include "ctkCommandLineParser.h"
#include "mitkImage.h"
#include "mitkImageStatisticsCalculator.h"
#include "mitkIOUtil.h"
#include <iostream>
#include <usAny.h>
#include <fstream>
int ExtractImageStatistics(int argc, char* argv[])
{
ctkCommandLineParser parser;
parser.setTitle("Extract Image Statistics");
parser.setCategory("Preprocessing Tools");
parser.setDescription("");
parser.setContributor("MBI");
parser.setArgumentPrefix("--", "-");
parser.addArgument("help", "h", ctkCommandLineParser::String, "Help:", "Show this help text");
parser.addArgument("input", "i", ctkCommandLineParser::InputFile, "Input:", "input image", us::Any(),false);
parser.addArgument("mask", "m", ctkCommandLineParser::InputFile, "Mask:", "mask image / roi image denotin area on which statistics are calculated", us::Any(),false);
parser.addArgument("out", "o", ctkCommandLineParser::OutputFile, "Output", "output file (default: filenameOfRoi.nrrd_statistics.txt)", us::Any());
map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0 || parsedArgs.count("help") || parsedArgs.count("h"))
{
std::cout << "\n\n MiniApp Description: \nCalculates statistics on the supplied image using given mask." << endl;
std::cout << "Output is written to the designated output file in this order:" << endl;
std::cout << "Mean, Standard Deviation, RMS, Max, Min, Number of Voxels, Volume [mm3]" << endl;
std::cout << "\n\n Parameters:"<< endl;
std::cout << parser.helpText();
return EXIT_SUCCESS;
}
// Parameters:
bool ignoreZeroValues = false;
unsigned int timeStep = 0;
std::string inputImageFile = us::any_cast<string>(parsedArgs["input"]);
std::string maskImageFile = us::any_cast<string>(parsedArgs["mask"]);
std::string outFile;
if (parsedArgs.count("out") || parsedArgs.count("o") )
outFile = us::any_cast<string>(parsedArgs["out"]);
else
outFile = inputImageFile + "_statistics.txt";
// Load image and mask
mitk::Image::Pointer maskImage = mitk::IOUtil::LoadImage(maskImageFile);
mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(inputImageFile);
// Calculate statistics
mitk::ImageStatisticsCalculator::Statistics statisticsStruct;
mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();
try
{
calculator->SetImage(inputImage);
calculator->SetImageMask(maskImage);
calculator->SetMaskingModeToImage();
}
catch( const itk::ExceptionObject& e)
{
MITK_ERROR << "Statistic Calculation Failed - ITK Exception:" << e.what();
return -1;
}
calculator->SetDoIgnorePixelValue(ignoreZeroValues);
calculator->SetIgnorePixelValue(0);
try
{
calculator->ComputeStatistics(timeStep);
}
catch ( mitk::Exception& e)
{
MITK_ERROR<< "MITK Exception: " << e.what();
return -1;
}
statisticsStruct = calculator->GetStatistics(timeStep);
// Calculate Volume
double volume = 0;
const mitk::BaseGeometry *geometry = inputImage->GetGeometry();
if ( geometry != NULL )
{
const mitk::Vector3D &spacing = inputImage->GetGeometry()->GetSpacing();
volume = spacing[0] * spacing[1] * spacing[2] * (double) statisticsStruct.GetN();
}
// Write Results to file
std::ofstream output;
output.open(outFile.c_str());
output << statisticsStruct.GetMean() << " , ";
output << statisticsStruct.GetSigma() << " , ";
output << statisticsStruct.GetRMS() << " , ";
output << statisticsStruct.GetMax() << " , ";
output << statisticsStruct.GetMin() << " , ";
output << statisticsStruct.GetN() << " , ";
output << volume << "\n";
output.flush();
output.close();
return 0;
}
RegisterDiffusionMiniApp(ExtractImageStatistics);
<|endoftext|> |
<commit_before>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__
#define __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__
#include "vector_tile.pb.h"
namespace mapnik { namespace vector_tile_impl {
class Geometry {
public:
inline explicit Geometry(vector_tile::Tile_Feature const& f,
double tile_x, double tile_y,
double scale_x, double scale_y);
enum command : uint8_t {
end = 0,
move_to = 1,
line_to = 2,
close = 7
};
inline command next(double& rx, double& ry);
private:
vector_tile::Tile_Feature const& f_;
double scale_x_;
double scale_y_;
uint32_t k;
uint32_t geoms_;
uint8_t cmd;
uint32_t length;
double x, y;
double ox, oy;
};
mapnik::geometry::geometry decode_geometry(vector_tile::Tile_Feature const& f,
double tile_x, double tile_y,
double scale_x, double scale_y)
{
Geometry::command cmd;
Geometry geoms(f,tile_x,tile_y,scale_x,scale_y);
double x1, y1;
switch (f.type())
{
case vector_tile::Tile_GeomType_POINT:
{
mapnik::geometry::multi_point mp;
while ((cmd = geoms.next(x1, y1)) != Geometry::end) {
mp.emplace_back(mapnik::geometry::point(x1,y1));
}
std::size_t num_points = mp.size();
if (num_points == 1)
{
// return the single point
return mapnik::geometry::geometry(std::move(mp[0]));;
}
else if (num_points > 1)
{
// return multipoint
return mapnik::geometry::geometry(std::move(mp));;
}
break;
}
case vector_tile::Tile_GeomType_LINESTRING:
{
mapnik::geometry::multi_line_string mp;
mapnik::geometry::line_string line;
while ((cmd = geoms.next(x1, y1)) != Geometry::end) {
if (cmd == Geometry::move_to) {
mp.emplace_back(std::move(line));
line.clear();
}
mp.back().add_coord(x1,y1);
}
std::size_t num_lines = mp.size();
if (num_lines == 1)
{
// return the single line
return mapnik::geometry::geometry(std::move(mp[0]));;
}
else if (num_lines > 1)
{
// return multiline
return mapnik::geometry::geometry(std::move(mp));;
}
break;
}
case vector_tile::Tile_GeomType_POLYGON:
{
// TODO
break;
}
case vector_tile::Tile_GeomType_UNKNOWN:
default:
{
throw std::runtime_error("unhandled geometry type during decoding");
break;
}
}
return mapnik::geometry::geometry();
}
Geometry::Geometry(vector_tile::Tile_Feature const& f,
double tile_x, double tile_y,
double scale_x, double scale_y)
: f_(f),
scale_x_(scale_x),
scale_y_(scale_y),
k(0),
geoms_(f_.geometry_size()),
cmd(1),
length(0),
x(tile_x), y(tile_y),
ox(0), oy(0) {}
Geometry::command Geometry::next(double& rx, double& ry) {
if (k < geoms_) {
if (length == 0) {
uint32_t cmd_length = static_cast<uint32_t>(f_.geometry(k++));
cmd = cmd_length & 0x7;
length = cmd_length >> 3;
}
--length;
if (cmd == move_to || cmd == line_to) {
int32_t dx = f_.geometry(k++);
int32_t dy = f_.geometry(k++);
dx = ((dx >> 1) ^ (-(dx & 1)));
dy = ((dy >> 1) ^ (-(dy & 1)));
x += (static_cast<double>(dx) / scale_x_);
y += (static_cast<double>(dy) / scale_y_);
rx = x;
ry = y;
if (cmd == move_to) {
ox = x;
oy = y;
return move_to;
} else {
return line_to;
}
} else if (cmd == close) {
rx = ox;
ry = oy;
return close;
} else {
fprintf(stderr, "unknown command: %d\n", cmd);
return end;
}
} else {
return end;
}
}
}} // end ns
#endif // __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__
<commit_msg>first pass at polygon support in decoder<commit_after>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__
#define __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__
#include "vector_tile.pb.h"
namespace mapnik { namespace vector_tile_impl {
class Geometry {
public:
inline explicit Geometry(vector_tile::Tile_Feature const& f,
double tile_x, double tile_y,
double scale_x, double scale_y);
enum command : uint8_t {
end = 0,
move_to = 1,
line_to = 2,
close = 7
};
inline command next(double& rx, double& ry);
private:
vector_tile::Tile_Feature const& f_;
double scale_x_;
double scale_y_;
uint32_t k;
uint32_t geoms_;
uint8_t cmd;
uint32_t length;
double x, y;
double ox, oy;
};
mapnik::geometry::geometry decode_geometry(vector_tile::Tile_Feature const& f,
double tile_x, double tile_y,
double scale_x, double scale_y)
{
Geometry::command cmd;
Geometry geoms(f,tile_x,tile_y,scale_x,scale_y);
double x1, y1;
switch (f.type())
{
case vector_tile::Tile_GeomType_POINT:
{
mapnik::geometry::multi_point mp;
while ((cmd = geoms.next(x1, y1)) != Geometry::end) {
mp.emplace_back(mapnik::geometry::point(x1,y1));
}
std::size_t num_points = mp.size();
if (num_points == 1)
{
// return the single point
return mapnik::geometry::geometry(std::move(mp[0]));;
}
else if (num_points > 1)
{
// return multipoint
return mapnik::geometry::geometry(std::move(mp));;
}
break;
}
case vector_tile::Tile_GeomType_LINESTRING:
{
mapnik::geometry::multi_line_string mp;
mp.emplace_back();
bool first = true;
while ((cmd = geoms.next(x1, y1)) != Geometry::end) {
if (cmd == Geometry::move_to) {
if (first)
{
first = false;
}
else
{
mp.emplace_back();
}
}
mp.back().add_coord(x1,y1);
}
std::size_t num_lines = mp.size();
if (num_lines == 1)
{
// return the single line
return mapnik::geometry::geometry(std::move(mp[0]));;
}
else if (num_lines > 1)
{
// return multiline
return mapnik::geometry::geometry(std::move(mp));;
}
break;
}
case vector_tile::Tile_GeomType_POLYGON:
{
// TODO - support for multipolygons
//mapnik::geometry::multi_polygon;
mapnik::geometry::polygon poly;
std::vector<mapnik::geometry::linear_ring> rings;
rings.emplace_back();
double x2,y2;
bool first = true;
while ((cmd = geoms.next(x1, y1)) != Geometry::end) {
if (cmd == Geometry::move_to)
{
x2 = x1;
y2 = y1;
if (first)
{
first = false;
}
else
{
rings.emplace_back();
}
}
else if (cmd == Geometry::close)
{
rings.back().add_coord(x2,y2);
continue;
}
rings.back().add_coord(x1,y1);
}
std::size_t num_rings = rings.size();
if (num_rings == 1)
{
// return the single polygon
mapnik::geometry::polygon poly;
poly.set_exterior_ring(std::move(rings[0]));
return mapnik::geometry::geometry(std::move(poly));
}
for (unsigned i = 0; i < num_rings;++i)
{
mapnik::geometry::polygon poly;
if (i == 0)
{
poly.set_exterior_ring(std::move(rings[i]));
}
else
{
poly.add_hole(std::move(rings[i]));
}
return mapnik::geometry::geometry(std::move(poly));
}
return poly;
break;
}
case vector_tile::Tile_GeomType_UNKNOWN:
default:
{
throw std::runtime_error("unhandled geometry type during decoding");
break;
}
}
return mapnik::geometry::geometry();
}
Geometry::Geometry(vector_tile::Tile_Feature const& f,
double tile_x, double tile_y,
double scale_x, double scale_y)
: f_(f),
scale_x_(scale_x),
scale_y_(scale_y),
k(0),
geoms_(f_.geometry_size()),
cmd(1),
length(0),
x(tile_x), y(tile_y),
ox(0), oy(0) {}
Geometry::command Geometry::next(double& rx, double& ry) {
if (k < geoms_) {
if (length == 0) {
uint32_t cmd_length = static_cast<uint32_t>(f_.geometry(k++));
cmd = cmd_length & 0x7;
length = cmd_length >> 3;
}
--length;
if (cmd == move_to || cmd == line_to) {
int32_t dx = f_.geometry(k++);
int32_t dy = f_.geometry(k++);
dx = ((dx >> 1) ^ (-(dx & 1)));
dy = ((dy >> 1) ^ (-(dy & 1)));
x += (static_cast<double>(dx) / scale_x_);
y += (static_cast<double>(dy) / scale_y_);
rx = x;
ry = y;
if (cmd == move_to) {
ox = x;
oy = y;
return move_to;
} else {
return line_to;
}
} else if (cmd == close) {
rx = ox;
ry = oy;
return close;
} else {
fprintf(stderr, "unknown command: %d\n", cmd);
return end;
}
} else {
return end;
}
}
}} // end ns
#endif // __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__
<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 "itktubeTubeExtractor.h"
#include "itktubeTubeExtractorIO.h"
#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkGroupSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <itkTimeProbesCollectorBase.h>
#include "SegmentTubesCLP.h"
#include <sstream>
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );
// Must follow include of "...CLP.h" and
// forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
// The timeCollector is used to perform basic profiling of the components
// of your algorithm.
itk::TimeProbesCollectorBase timeCollector;
// CLIProgressReporter is used to communicate progress with the Slicer GUI
tube::CLIProgressReporter progressReporter( "RidgeExtractor",
CLPProcessInformation );
progressReporter.Start();
typedef TPixel PixelType;
typedef itk::Image< PixelType, VDimension > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::tube::TubeExtractor< ImageType > TubeOpType;
typedef typename TubeOpType::TubeMaskImageType MaskImageType;
typedef itk::ImageFileReader< MaskImageType > MaskReaderType;
typedef itk::ImageFileWriter< MaskImageType > MaskWriterType;
typedef float ScaleType;
typedef itk::Image< ScaleType, VDimension > ScaleImageType;
typedef itk::ImageFileReader< ScaleImageType > ScaleReaderType;
typedef itk::ContinuousIndex< double, VDimension > IndexType;
typedef std::vector< IndexType > IndexListType;
typedef std::vector< ScaleType > ScaleListType;
typedef itk::VesselTubeSpatialObject< VDimension > TubeType;
typedef typename TubeType::TransformType TransformType;
typedef itk::SpatialObjectWriter< VDimension > SpatialObjectWriterType;
timeCollector.Start("Load data");
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputVolume.c_str() );
try
{
reader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading volume: Exception caught: "
+ std::string(err.GetDescription()) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop("Load data");
double progress = 0.1;
progressReporter.Report( progress );
typename ImageType::Pointer inputImage = reader->GetOutput();
double scaleNorm = inputImage->GetSpacing()[0];
double radius = scale * scaleNorm;
if( radius < 0.3 )
{
std::stringstream ss;
ss<<"Error: Radius (=spacing*scale = "<<radius<<") < 0.3 is unsupported.";
tube::ErrorMessage( ss.str() );
return EXIT_FAILURE;
}
typename TubeOpType::Pointer tubeOp = TubeOpType::New();
tubeOp->SetInputImage( inputImage );
tubeOp->SetRadius( radius );
IndexType seedIndex;
IndexListType seedIndexList;
seedIndexList.clear();
ScaleListType seedScaleList;
seedScaleList.clear();
if( !seedI.empty() )
{
for( unsigned int seedINum=0; seedINum<seedI.size(); ++seedINum )
{
for( unsigned int i=0; i<VDimension; i++ )
{
seedIndex[i] = seedI[seedINum][i];
}
seedIndexList.push_back( seedIndex );
seedScaleList.push_back( radius );
}
}
if( !seedP.empty() )
{
for(size_t seedNum=0; seedNum<seedP.size(); ++seedNum)
{
typename ImageType::PointType point;
for( unsigned int i=0; i<VDimension; i++ )
{
point[i] = seedP[seedNum][i];
}
bool transformSuccess =
inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);
if (!transformSuccess)
{
std::cerr<<"Could not transform point #"
<<seedNum<<" to seed index."<<std::endl;
continue;
}
seedIndexList.push_back( seedIndex );
seedScaleList.push_back( radius );
}
}
if( !seedListFile.empty() )
{
std::ifstream readStream;
readStream.open( seedListFile.c_str(), std::ios::binary |
std::ios::in );
std::string line;
double seedScale;
while( std::getline( readStream, line ) )
{
std::istringstream iss(line);
for( unsigned int i = 0; i < VDimension; ++i )
{
iss >> seedIndex[i];
}
iss >> seedScale;
}
seedIndexList.push_back( seedIndex );
seedScaleList.push_back( seedScale );
}
if( !seedMask.empty() )
{
typename MaskReaderType::Pointer maskReader = MaskReaderType::New();
maskReader->SetFileName( seedMask.c_str() );
try
{
maskReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading mask: Exception caught: "
+ std::string(err.GetDescription()) );
timeCollector.Report();
return EXIT_FAILURE;
}
typename MaskImageType::Pointer maskImage = maskReader->GetOutput();
if( !scaleMask.empty() )
{
typename ScaleReaderType::Pointer scaleReader =
ScaleReaderType::New();
scaleReader->SetFileName( scaleMask.c_str() );
try
{
scaleReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading scale: Exception caught: "
+ std::string(err.GetDescription()) );
timeCollector.Report();
return EXIT_FAILURE;
}
typename ScaleImageType::Pointer scaleImage = scaleReader->GetOutput();
itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
maskImage->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator< ScaleImageType > iterS( scaleImage,
scaleImage->GetLargestPossibleRegion() );
while( !iter.IsAtEnd() )
{
if( iter.Get() )
{
seedIndexList.push_back( iter.GetIndex() );
seedScaleList.push_back( iterS.Get() * scaleNorm );
}
++iter;
++iterS;
}
}
else
{
itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
maskImage->GetLargestPossibleRegion() );
while( !iter.IsAtEnd() )
{
if( iter.Get() )
{
seedIndexList.push_back( iter.GetIndex() );
seedScaleList.push_back( radius );
}
++iter;
}
}
}
if( !parametersFile.empty() )
{
itk::tube::TubeExtractorIO< ImageType > teReader;
teReader.SetTubeExtractor( tubeOp );
teReader.Read( parametersFile.c_str() );
}
typename IndexListType::iterator seedIndexIter =
seedIndexList.begin();
ScaleListType::iterator seedScaleIter =
seedScaleList.begin();
tubeOp->SetDebug( false );
tubeOp->GetRidgeOp()->SetDebug( false );
tubeOp->GetRadiusOp()->SetDebug( false );
if( border > 0 )
{
typename ImageType::IndexType minIndx = inputImage->
GetLargestPossibleRegion().GetIndex();
typename ImageType::SizeType size = inputImage->
GetLargestPossibleRegion().GetSize();
typename ImageType::IndexType maxIndx = minIndx + size;
for( unsigned int i=0; i<VDimension; ++i )
{
minIndx[i] += border;
maxIndx[i] -= border;
}
tubeOp->SetExtractBoundMin( minIndx );
tubeOp->SetExtractBoundMax( maxIndx );
}
timeCollector.Start("Ridge Extractor");
unsigned int count = 1;
bool foundOneTube = false;
tubeOp->GetRidgeOp()->SetDebug( false );
while( seedIndexIter != seedIndexList.end() )
{
tubeOp->SetRadius( *seedScaleIter );
std::cout << "Extracting from index point " << *seedIndexIter << " at radius "
<< *seedScaleIter << std::endl;
typename TubeType::Pointer xTube =
tubeOp->ExtractTube( *seedIndexIter, count );
if( !xTube.IsNull() )
{
tubeOp->AddTube( xTube );
std::cout << " Extracted " << xTube->GetPoints().size() << " points."
<< std::endl;
foundOneTube = true;
}
else
{
std::stringstream ss;
ss << "Error: Ridge not found for seed #" << count;
tube::Message(ss.str());
}
++seedIndexIter;
++seedScaleIter;
++count;
}
if (!foundOneTube)
{
tube::ErrorMessage("No Ridge found at all");
return EXIT_FAILURE;
}
// Update tubes transform
typename TransformType::InputVectorType scaleVector;
typename TransformType::OffsetType offsetVector;
typename TransformType::MatrixType directionMatrix;
typename ImageType::SpacingType spacing = inputImage->GetSpacing();
typename ImageType::PointType origin = inputImage->GetOrigin();
for (unsigned int i = 0; i < VDimension; ++i)
{
scaleVector[i] = spacing[i];
offsetVector[i] = origin[i];
}
tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetScale( scaleVector );
tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetOffset( offsetVector );
tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetMatrix( inputImage->GetDirection() );
tubeOp->GetTubeGroup()->ComputeObjectToWorldTransform();
// Save Tubes
typename SpatialObjectWriterType::Pointer soWriter =
SpatialObjectWriterType::New();
soWriter->SetFileName( outputTubeFile );
soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );
soWriter->Update();
// Save Tube Mask Image
if( !outputTubeImage.empty() )
{
typename MaskWriterType::Pointer writer = MaskWriterType::New();
writer->SetFileName( outputTubeImage );
writer->SetInput( tubeOp->GetTubeMaskImage() );
writer->SetUseCompression( true );
writer->Update();
}
timeCollector.Stop("Ridge Extractor");
progressReporter.Report( 1.0 );
progressReporter.End();
timeCollector.Report();
return EXIT_SUCCESS;
}
// Main
int main( int argc, char * argv[] )
{
try
{
PARSE_ARGS;
}
catch( const std::exception & err )
{
tube::ErrorMessage( err.what() );
return EXIT_FAILURE;
}
PARSE_ARGS;
// You may need to update this line if, in the project's .xml CLI file,
// you change the variable name for the inputVolume.
return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );
}
<commit_msg>Revert "Fix scale normalization"<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 "itktubeTubeExtractor.h"
#include "itktubeTubeExtractorIO.h"
#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkGroupSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <itkTimeProbesCollectorBase.h>
#include "SegmentTubesCLP.h"
#include <sstream>
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );
// Must follow include of "...CLP.h" and
// forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
// The timeCollector is used to perform basic profiling of the components
// of your algorithm.
itk::TimeProbesCollectorBase timeCollector;
// CLIProgressReporter is used to communicate progress with the Slicer GUI
tube::CLIProgressReporter progressReporter( "RidgeExtractor",
CLPProcessInformation );
progressReporter.Start();
typedef TPixel PixelType;
typedef itk::Image< PixelType, VDimension > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::tube::TubeExtractor< ImageType > TubeOpType;
typedef typename TubeOpType::TubeMaskImageType MaskImageType;
typedef itk::ImageFileReader< MaskImageType > MaskReaderType;
typedef itk::ImageFileWriter< MaskImageType > MaskWriterType;
typedef float ScaleType;
typedef itk::Image< ScaleType, VDimension > ScaleImageType;
typedef itk::ImageFileReader< ScaleImageType > ScaleReaderType;
typedef itk::ContinuousIndex< double, VDimension > IndexType;
typedef std::vector< IndexType > IndexListType;
typedef std::vector< ScaleType > ScaleListType;
typedef itk::VesselTubeSpatialObject< VDimension > TubeType;
typedef typename TubeType::TransformType TransformType;
typedef itk::SpatialObjectWriter< VDimension > SpatialObjectWriterType;
timeCollector.Start("Load data");
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputVolume.c_str() );
try
{
reader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading volume: Exception caught: "
+ std::string(err.GetDescription()) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop("Load data");
double progress = 0.1;
progressReporter.Report( progress );
typename ImageType::Pointer inputImage = reader->GetOutput();
double scaleNorm = inputImage->GetSpacing()[0];
if( scale / scaleNorm < 0.3 )
{
tube::ErrorMessage( "Error: Scale < 0.3 is unsupported." );
return EXIT_FAILURE;
}
typename TubeOpType::Pointer tubeOp = TubeOpType::New();
tubeOp->SetInputImage( inputImage );
tubeOp->SetRadius( scale / scaleNorm );
IndexType seedIndex;
IndexListType seedIndexList;
seedIndexList.clear();
ScaleListType seedScaleList;
seedScaleList.clear();
if( !seedI.empty() )
{
for( unsigned int seedINum=0; seedINum<seedI.size(); ++seedINum )
{
for( unsigned int i=0; i<VDimension; i++ )
{
seedIndex[i] = seedI[seedINum][i];
}
seedIndexList.push_back( seedIndex );
seedScaleList.push_back( scale / scaleNorm );
}
}
if( !seedP.empty() )
{
for(size_t seedNum=0; seedNum<seedP.size(); ++seedNum)
{
typename ImageType::PointType point;
for( unsigned int i=0; i<VDimension; i++ )
{
point[i] = seedP[seedNum][i];
}
bool transformSuccess =
inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);
if (!transformSuccess)
{
std::cerr<<"Could not transform point #"
<<seedNum<<" to seed index."<<std::endl;
continue;
}
seedIndexList.push_back( seedIndex );
seedScaleList.push_back( scale / scaleNorm );
}
}
if( !seedListFile.empty() )
{
std::ifstream readStream;
readStream.open( seedListFile.c_str(), std::ios::binary |
std::ios::in );
std::string line;
double seedScale;
while( std::getline( readStream, line ) )
{
std::istringstream iss(line);
for( unsigned int i = 0; i < VDimension; ++i )
{
iss >> seedIndex[i];
}
iss >> seedScale;
}
seedIndexList.push_back( seedIndex );
seedScaleList.push_back( seedScale );
}
if( !seedMask.empty() )
{
typename MaskReaderType::Pointer maskReader = MaskReaderType::New();
maskReader->SetFileName( seedMask.c_str() );
try
{
maskReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading mask: Exception caught: "
+ std::string(err.GetDescription()) );
timeCollector.Report();
return EXIT_FAILURE;
}
typename MaskImageType::Pointer maskImage = maskReader->GetOutput();
if( !scaleMask.empty() )
{
typename ScaleReaderType::Pointer scaleReader =
ScaleReaderType::New();
scaleReader->SetFileName( scaleMask.c_str() );
try
{
scaleReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading scale: Exception caught: "
+ std::string(err.GetDescription()) );
timeCollector.Report();
return EXIT_FAILURE;
}
typename ScaleImageType::Pointer scaleImage = scaleReader->GetOutput();
itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
maskImage->GetLargestPossibleRegion() );
itk::ImageRegionConstIterator< ScaleImageType > iterS( scaleImage,
scaleImage->GetLargestPossibleRegion() );
while( !iter.IsAtEnd() )
{
if( iter.Get() )
{
seedIndexList.push_back( iter.GetIndex() );
seedScaleList.push_back( iterS.Get() / scaleNorm );
}
++iter;
++iterS;
}
}
else
{
itk::ImageRegionConstIteratorWithIndex< MaskImageType > iter( maskImage,
maskImage->GetLargestPossibleRegion() );
while( !iter.IsAtEnd() )
{
if( iter.Get() )
{
seedIndexList.push_back( iter.GetIndex() );
seedScaleList.push_back( scale / scaleNorm );
}
++iter;
}
}
}
if( !parametersFile.empty() )
{
itk::tube::TubeExtractorIO< ImageType > teReader;
teReader.SetTubeExtractor( tubeOp );
teReader.Read( parametersFile.c_str() );
}
typename IndexListType::iterator seedIndexIter =
seedIndexList.begin();
ScaleListType::iterator seedScaleIter =
seedScaleList.begin();
tubeOp->SetDebug( false );
tubeOp->GetRidgeOp()->SetDebug( false );
tubeOp->GetRadiusOp()->SetDebug( false );
if( border > 0 )
{
typename ImageType::IndexType minIndx = inputImage->
GetLargestPossibleRegion().GetIndex();
typename ImageType::SizeType size = inputImage->
GetLargestPossibleRegion().GetSize();
typename ImageType::IndexType maxIndx = minIndx + size;
for( unsigned int i=0; i<VDimension; ++i )
{
minIndx[i] += border;
maxIndx[i] -= border;
}
tubeOp->SetExtractBoundMin( minIndx );
tubeOp->SetExtractBoundMax( maxIndx );
}
timeCollector.Start("Ridge Extractor");
unsigned int count = 1;
bool foundOneTube = false;
tubeOp->GetRidgeOp()->SetDebug( true );
while( seedIndexIter != seedIndexList.end() )
{
tubeOp->SetRadius( *seedScaleIter );
std::cout << "Extracting from index point " << *seedIndexIter << " at radius "
<< *seedScaleIter << std::endl;
typename TubeType::Pointer xTube =
tubeOp->ExtractTube( *seedIndexIter, count );
if( !xTube.IsNull() )
{
tubeOp->AddTube( xTube );
std::cout << " Extracted " << xTube->GetPoints().size() << " points."
<< std::endl;
foundOneTube = true;
}
else
{
std::stringstream ss;
ss << "Error: Ridge not found for seed #" << count;
tube::Message(ss.str());
}
++seedIndexIter;
++seedScaleIter;
++count;
}
if (!foundOneTube)
{
tube::ErrorMessage("No Ridge found at all");
return EXIT_FAILURE;
}
// Update tubes transform
typename TransformType::InputVectorType scaleVector;
typename TransformType::OffsetType offsetVector;
typename TransformType::MatrixType directionMatrix;
typename ImageType::SpacingType spacing = inputImage->GetSpacing();
typename ImageType::PointType origin = inputImage->GetOrigin();
for (unsigned int i = 0; i < VDimension; ++i)
{
scaleVector[i] = spacing[i];
offsetVector[i] = origin[i];
}
tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetScale( scaleVector );
tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetOffset( offsetVector );
tubeOp->GetTubeGroup()->GetObjectToParentTransform()->SetMatrix( inputImage->GetDirection() );
tubeOp->GetTubeGroup()->ComputeObjectToWorldTransform();
// Save Tubes
typename SpatialObjectWriterType::Pointer soWriter =
SpatialObjectWriterType::New();
soWriter->SetFileName( outputTubeFile );
soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );
soWriter->Update();
// Save Tube Mask Image
if( !outputTubeImage.empty() )
{
typename MaskWriterType::Pointer writer = MaskWriterType::New();
writer->SetFileName( outputTubeImage );
writer->SetInput( tubeOp->GetTubeMaskImage() );
writer->SetUseCompression( true );
writer->Update();
}
timeCollector.Stop("Ridge Extractor");
progressReporter.Report( 1.0 );
progressReporter.End();
timeCollector.Report();
return EXIT_SUCCESS;
}
// Main
int main( int argc, char * argv[] )
{
try
{
PARSE_ARGS;
}
catch( const std::exception & err )
{
tube::ErrorMessage( err.what() );
return EXIT_FAILURE;
}
PARSE_ARGS;
// You may need to update this line if, in the project's .xml CLI file,
// you change the variable name for the inputVolume.
return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );
}
<|endoftext|> |
<commit_before>/* <x0/connection.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <[email protected]>
*/
#include <x0/connection.hpp>
#include <x0/listener.hpp>
#include <x0/request.hpp>
#include <x0/response.hpp>
#include <x0/server.hpp>
#include <x0/types.hpp>
#include <x0/sysconfig.h>
#if defined(WITH_SSL)
# include <gnutls/gnutls.h>
# include <gnutls/extra.h>
#endif
#include <functional>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
namespace x0 {
connection::connection(x0::listener& lst) :
secure(false),
listener_(lst),
server_(lst.server()),
// socket_(), // initialized in constructor body
remote_ip_(),
remote_port_(0),
buffer_(8192),
request_(new request(*this)),
request_parser_(),
response_(0),
watcher_(server_.loop()),
timer_(server_.loop())
{
//DEBUG("connection(%p)", this);
socklen_t slen = sizeof(saddr_);
memset(&saddr_, 0, slen);
socket_ = ::accept(listener_.handle(), reinterpret_cast<sockaddr *>(&saddr_), &slen);
if (socket_ < 0)
throw std::runtime_error(strerror(errno));
if (fcntl(socket_, F_SETFL, O_NONBLOCK) < 0)
printf("could not set server socket into non-blocking mode: %s\n", strerror(errno));
#if defined(TCP_CORK)
{
int flag = 1;
setsockopt(socket_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
}
#endif
#if 0 // defined(TCP_NODELAY)
{
int flag = 1;
setsockopt(socket_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
}
#endif
watcher_.set<connection, &connection::io_callback>(this);
timer_.set<connection, &connection::timeout_callback>(this);
server_.connection_open(this);
}
connection::~connection()
{
delete request_;
delete response_;
request_ = 0;
response_ = 0;
//DEBUG("~connection(%p)", this);
try
{
server_.connection_close(this); // we cannot pass a shared pointer here as use_count is already zero and it would just lead into an exception though
}
catch (...)
{
DEBUG("~connection(%p): unexpected exception", this);
}
#if defined(WITH_SSL)
if (ssl_enabled())
gnutls_deinit(ssl_session_);
#endif
::close(socket_);
}
void connection::io_callback(ev::io& w, int revents)
{
watcher_.stop();
timer_.stop();
//ev_unloop(loop(), EVUNLOOP_ONE);
if (revents & ev::READ)
handle_read();
if (revents & ev::WRITE)
handle_write();
}
void connection::timeout_callback(ev::timer& watcher, int revents)
{
handle_timeout();
}
#if defined(WITH_SSL)
void connection::ssl_initialize()
{
gnutls_init(&ssl_session_, GNUTLS_SERVER);
gnutls_priority_set(ssl_session_, listener_.priority_cache_);
gnutls_credentials_set(ssl_session_, GNUTLS_CRD_CERTIFICATE, listener_.x509_cred_);
gnutls_certificate_server_set_request(ssl_session_, GNUTLS_CERT_REQUEST);
gnutls_dh_set_prime_bits(ssl_session_, 1024);
gnutls_session_enable_compatibility_mode(ssl_session_);
gnutls_transport_set_ptr(ssl_session_, (gnutls_transport_ptr_t)handle());
listener_.ssl_db().bind(ssl_session_);
}
#endif
#if defined(WITH_SSL)
bool connection::ssl_enabled() const
{
return listener_.secure();
}
#endif
void connection::start()
{
//DEBUG("connection(%p).start()", this);
#if defined(WITH_SSL)
if (ssl_enabled())
{
state_ = handshaking;
ssl_initialize();
ssl_handshake();
return;
}
else
state_ = requesting;
#endif
#if defined(TCP_DEFER_ACCEPT)
// it is ensured, that we have data pending, so directly start reading
handle_read();
#else
// client connected, but we do not yet know if we have data pending
async_read_some();
#endif
}
#if defined(WITH_SSL)
bool connection::ssl_handshake()
{
int rv = gnutls_handshake(ssl_session_);
if (rv == GNUTLS_E_SUCCESS)
{
// handshake either completed or failed
state_ = requesting;
async_read_some();
return true;
}
if (rv != GNUTLS_E_AGAIN && rv != GNUTLS_E_INTERRUPTED)
{
#if !defined(NDEBUG)
fprintf(stderr, "SSL handshake failed (%d): %s\n", rv, gnutls_strerror(rv));
fflush(stderr);
#endif
delete this;
return false;
}
switch (gnutls_record_get_direction(ssl_session_))
{
case 0: // read
async_read_some();
break;
case 1: // write
async_write_some();
break;
default:
break;
}
return false;
}
#endif
/** processes the next request on the connection. */
void connection::resume()
{
//DEBUG("connection(%p).resume()", this);
delete request_;
request_ = 0;
delete response_;
response_ = 0;
std::size_t offset = request_parser_.next_offset();
request_parser_.reset();
request_ = new request(*this);
if (offset < buffer_.size()) // HTTP pipelining
parse_request(offset, buffer_.size() - offset);
else
{
buffer_.clear();
async_read_some();
}
}
void connection::async_read_some()
{
buffer_.clear();
if (server_.max_read_idle() != -1)
timer_.start(server_.max_read_idle(), 0.0);
watcher_.start(socket_, ev::READ);
}
void connection::async_write_some()
{
if (server_.max_write_idle() != -1)
timer_.start(server_.max_write_idle(), 0.0);
watcher_.start(socket_, ev::WRITE);
}
void connection::handle_write()
{
//DEBUG("connection(%p).handle_write()", this);
#if defined(WITH_SSL)
if (state_ == handshaking)
return (void) ssl_handshake();
// if (ssl_enabled())
// rv = gnutls_write(ssl_session_, buffer_.capacity() - buffer_.size());
// else if (write_some)
// write_some(this);
#else
#endif
#if 0
buffer write_buffer_;
int write_offset_ = 0;
int rv = ::write(socket_, write_buffer_.begin() + write_offset_, write_buffer_.size() - write_offset_);
if (rv < 0)
; // error
else
{
write_offset_ += rv;
async_write_some();
}
#else
if (write_some)
write_some(this);
#endif
}
/**
* This method gets invoked when there is data in our connection ready to read.
*
* We assume, that we are in request-parsing state.
*/
void connection::handle_read()
{
//DEBUG("connection(%p).handle_read()", this);
#if defined(WITH_SSL)
if (state_ == handshaking)
return (void) ssl_handshake();
#endif
std::size_t lower_bound = buffer_.size();
int rv;
#if defined(WITH_SSL)
if (ssl_enabled())
rv = gnutls_read(ssl_session_, buffer_.end(), buffer_.capacity() - buffer_.size());
else
rv = ::read(socket_, buffer_.end(), buffer_.capacity() - buffer_.size());
#else
rv = ::read(socket_, buffer_.end(), buffer_.capacity() - buffer_.size());
#endif
// printf("connection::handle_read(): read %d bytes (%s)\n", rv, strerror(errno));
if (rv < 0)
; // error
else if (rv == 0)
; // EOF
else
{
buffer_.resize(lower_bound + rv);
parse_request(lower_bound, rv);
}
}
/** parses (partial) request from buffer's given \p offset of \p count bytes.
*/
void connection::parse_request(std::size_t offset, std::size_t count)
{
// parse request (partial)
boost::tribool result = request_parser_.parse(*request_, buffer_.ref(offset, count));
if (result) // request fully parsed
{
if (response *response_ = new response(this, request_))
{
try
{
server_.handle_request(response_->request(), response_);
}
catch (const host_not_found& e)
{
// fprintf(stderr, "exception caught: %s\n", e.what());
// fflush(stderr);
response_->status = 404;
response_->finish();
}
catch (response::code_type reply)
{
// fprintf(stderr, "response::code exception caught (%d %s)\n", reply, response::status_cstr(reply));
// fflush(stderr);
response_->status = reply;
response_->finish();
}
}
}
else if (!result) // received an invalid request
{
// -> send stock response: BAD_REQUEST
(new response(this, request_, response::bad_request))->finish();
}
else // result indeterminate: request still incomplete
{
// -> continue reading for request
async_read_some();
}
}
void connection::handle_timeout()
{
//DEBUG("connection(%p): timed out", this);
watcher_.stop();
ev_unloop(loop(), EVUNLOOP_ONE);
delete this;
}
std::string connection::remote_ip() const
{
if (remote_ip_.empty())
{
char buf[128];
if (inet_ntop(AF_INET6, &saddr_.sin6_addr, buf, sizeof(buf)))
remote_ip_ = buf;
}
return remote_ip_;
}
int connection::remote_port() const
{
if (!remote_port_)
{
remote_port_ = ntohs(saddr_.sin6_port);
}
return remote_port_;
}
std::string connection::local_ip() const
{
return std::string(); //! \todo implementation
}
int connection::local_port() const
{
return 0; //! \todo implementation
}
} // namespace x0
<commit_msg>core: implemented connection::local_{port,ip}()<commit_after>/* <x0/connection.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <[email protected]>
*/
#include <x0/connection.hpp>
#include <x0/listener.hpp>
#include <x0/request.hpp>
#include <x0/response.hpp>
#include <x0/server.hpp>
#include <x0/types.hpp>
#include <x0/sysconfig.h>
#if defined(WITH_SSL)
# include <gnutls/gnutls.h>
# include <gnutls/extra.h>
#endif
#include <functional>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
namespace x0 {
connection::connection(x0::listener& lst) :
secure(false),
listener_(lst),
server_(lst.server()),
// socket_(), // initialized in constructor body
remote_ip_(),
remote_port_(0),
buffer_(8192),
request_(new request(*this)),
request_parser_(),
response_(0),
watcher_(server_.loop()),
timer_(server_.loop())
{
//DEBUG("connection(%p)", this);
socklen_t slen = sizeof(saddr_);
memset(&saddr_, 0, slen);
socket_ = ::accept(listener_.handle(), reinterpret_cast<sockaddr *>(&saddr_), &slen);
if (socket_ < 0)
throw std::runtime_error(strerror(errno));
if (fcntl(socket_, F_SETFL, O_NONBLOCK) < 0)
printf("could not set server socket into non-blocking mode: %s\n", strerror(errno));
#if defined(TCP_CORK)
{
int flag = 1;
setsockopt(socket_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
}
#endif
#if 0 // defined(TCP_NODELAY)
{
int flag = 1;
setsockopt(socket_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
}
#endif
watcher_.set<connection, &connection::io_callback>(this);
timer_.set<connection, &connection::timeout_callback>(this);
server_.connection_open(this);
}
connection::~connection()
{
delete request_;
delete response_;
request_ = 0;
response_ = 0;
//DEBUG("~connection(%p)", this);
try
{
server_.connection_close(this); // we cannot pass a shared pointer here as use_count is already zero and it would just lead into an exception though
}
catch (...)
{
DEBUG("~connection(%p): unexpected exception", this);
}
#if defined(WITH_SSL)
if (ssl_enabled())
gnutls_deinit(ssl_session_);
#endif
::close(socket_);
}
void connection::io_callback(ev::io& w, int revents)
{
watcher_.stop();
timer_.stop();
//ev_unloop(loop(), EVUNLOOP_ONE);
if (revents & ev::READ)
handle_read();
if (revents & ev::WRITE)
handle_write();
}
void connection::timeout_callback(ev::timer& watcher, int revents)
{
handle_timeout();
}
#if defined(WITH_SSL)
void connection::ssl_initialize()
{
gnutls_init(&ssl_session_, GNUTLS_SERVER);
gnutls_priority_set(ssl_session_, listener_.priority_cache_);
gnutls_credentials_set(ssl_session_, GNUTLS_CRD_CERTIFICATE, listener_.x509_cred_);
gnutls_certificate_server_set_request(ssl_session_, GNUTLS_CERT_REQUEST);
gnutls_dh_set_prime_bits(ssl_session_, 1024);
gnutls_session_enable_compatibility_mode(ssl_session_);
gnutls_transport_set_ptr(ssl_session_, (gnutls_transport_ptr_t)handle());
listener_.ssl_db().bind(ssl_session_);
}
#endif
#if defined(WITH_SSL)
bool connection::ssl_enabled() const
{
return listener_.secure();
}
#endif
void connection::start()
{
//DEBUG("connection(%p).start()", this);
#if defined(WITH_SSL)
if (ssl_enabled())
{
state_ = handshaking;
ssl_initialize();
ssl_handshake();
return;
}
else
state_ = requesting;
#endif
#if defined(TCP_DEFER_ACCEPT)
// it is ensured, that we have data pending, so directly start reading
handle_read();
#else
// client connected, but we do not yet know if we have data pending
async_read_some();
#endif
}
#if defined(WITH_SSL)
bool connection::ssl_handshake()
{
int rv = gnutls_handshake(ssl_session_);
if (rv == GNUTLS_E_SUCCESS)
{
// handshake either completed or failed
state_ = requesting;
async_read_some();
return true;
}
if (rv != GNUTLS_E_AGAIN && rv != GNUTLS_E_INTERRUPTED)
{
#if !defined(NDEBUG)
fprintf(stderr, "SSL handshake failed (%d): %s\n", rv, gnutls_strerror(rv));
fflush(stderr);
#endif
delete this;
return false;
}
switch (gnutls_record_get_direction(ssl_session_))
{
case 0: // read
async_read_some();
break;
case 1: // write
async_write_some();
break;
default:
break;
}
return false;
}
#endif
/** processes the next request on the connection. */
void connection::resume()
{
//DEBUG("connection(%p).resume()", this);
delete request_;
request_ = 0;
delete response_;
response_ = 0;
std::size_t offset = request_parser_.next_offset();
request_parser_.reset();
request_ = new request(*this);
if (offset < buffer_.size()) // HTTP pipelining
parse_request(offset, buffer_.size() - offset);
else
{
buffer_.clear();
async_read_some();
}
}
void connection::async_read_some()
{
buffer_.clear();
if (server_.max_read_idle() != -1)
timer_.start(server_.max_read_idle(), 0.0);
watcher_.start(socket_, ev::READ);
}
void connection::async_write_some()
{
if (server_.max_write_idle() != -1)
timer_.start(server_.max_write_idle(), 0.0);
watcher_.start(socket_, ev::WRITE);
}
void connection::handle_write()
{
//DEBUG("connection(%p).handle_write()", this);
#if defined(WITH_SSL)
if (state_ == handshaking)
return (void) ssl_handshake();
// if (ssl_enabled())
// rv = gnutls_write(ssl_session_, buffer_.capacity() - buffer_.size());
// else if (write_some)
// write_some(this);
#else
#endif
#if 0
buffer write_buffer_;
int write_offset_ = 0;
int rv = ::write(socket_, write_buffer_.begin() + write_offset_, write_buffer_.size() - write_offset_);
if (rv < 0)
; // error
else
{
write_offset_ += rv;
async_write_some();
}
#else
if (write_some)
write_some(this);
#endif
}
/**
* This method gets invoked when there is data in our connection ready to read.
*
* We assume, that we are in request-parsing state.
*/
void connection::handle_read()
{
//DEBUG("connection(%p).handle_read()", this);
#if defined(WITH_SSL)
if (state_ == handshaking)
return (void) ssl_handshake();
#endif
std::size_t lower_bound = buffer_.size();
int rv;
#if defined(WITH_SSL)
if (ssl_enabled())
rv = gnutls_read(ssl_session_, buffer_.end(), buffer_.capacity() - buffer_.size());
else
rv = ::read(socket_, buffer_.end(), buffer_.capacity() - buffer_.size());
#else
rv = ::read(socket_, buffer_.end(), buffer_.capacity() - buffer_.size());
#endif
// printf("connection::handle_read(): read %d bytes (%s)\n", rv, strerror(errno));
if (rv < 0)
; // error
else if (rv == 0)
; // EOF
else
{
buffer_.resize(lower_bound + rv);
parse_request(lower_bound, rv);
}
}
/** parses (partial) request from buffer's given \p offset of \p count bytes.
*/
void connection::parse_request(std::size_t offset, std::size_t count)
{
// parse request (partial)
boost::tribool result = request_parser_.parse(*request_, buffer_.ref(offset, count));
if (result) // request fully parsed
{
if (response *response_ = new response(this, request_))
{
try
{
server_.handle_request(response_->request(), response_);
}
catch (const host_not_found& e)
{
// fprintf(stderr, "exception caught: %s\n", e.what());
// fflush(stderr);
response_->status = 404;
response_->finish();
}
catch (response::code_type reply)
{
// fprintf(stderr, "response::code exception caught (%d %s)\n", reply, response::status_cstr(reply));
// fflush(stderr);
response_->status = reply;
response_->finish();
}
}
}
else if (!result) // received an invalid request
{
// -> send stock response: BAD_REQUEST
(new response(this, request_, response::bad_request))->finish();
}
else // result indeterminate: request still incomplete
{
// -> continue reading for request
async_read_some();
}
}
void connection::handle_timeout()
{
//DEBUG("connection(%p): timed out", this);
watcher_.stop();
ev_unloop(loop(), EVUNLOOP_ONE);
delete this;
}
std::string connection::remote_ip() const
{
if (remote_ip_.empty())
{
char buf[128];
if (inet_ntop(AF_INET6, &saddr_.sin6_addr, buf, sizeof(buf)))
remote_ip_ = buf;
}
return remote_ip_;
}
int connection::remote_port() const
{
if (!remote_port_)
{
remote_port_ = ntohs(saddr_.sin6_port);
}
return remote_port_;
}
std::string connection::local_ip() const
{
return listener_.address();
}
int connection::local_port() const
{
return listener_.port();
}
} // namespace x0
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <direct.h>
#include "MagicCube.h"
using namespace std;
MagicCube a, b;
void simulation()//ģ
{
int t1, t2;
while (cin >> t1 >> t2)
{
//b = a;
a.rotate(t1, t2);
//a.output_compare(b, 1);
}
a.output_detailed();
//a.output_compare(b);
}
void check_rotate()//debugת
{
b.set_different_number();
for (int i = 0; i < Face_Count; ++i)
{
a.set_different_number();
a.rotate(i, 0);
//a.output_check(b, 1);
//if (!a.accuracy_check()) puts("ERR");
a.set_different_number();
a.rotate(i, 1);
//a.output_check(b, 1);
//if (!a.accuracy_check()) puts("ERR");
}
}
void work()
{
//simulation();
pii c = a.query(0, 5);
printf("%d,%d", c.first, c.second);
}
int main()
{
freopen("mf.in", "r", stdin);
freopen("mf.out", "w", stdout);
work();
return 0;
}<commit_msg>第一层还原<commit_after>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <direct.h>
#include "MagicCube.h"
using namespace std;
typedef pair<int, int> pii;
MagicCube a, b;
void simulation()//ģ
{
int t1, t2;
while (cin >> t1 >> t2)
{
b = a;
a.rotate(t1, t2);
a.output_compare(b, 1);
}
a.output_detailed();
//a.output_compare(b);
}
void check_rotate()//debugת
{
b.set_different_number();
for (int i = 0; i < Face_Count; ++i)
{
a.set_different_number();
a.rotate(i, 0);
//a.output_check(b, 1);
//if (!a.accuracy_check()) puts("ERR");
a.set_different_number();
a.rotate(i, 1);
//a.output_check(b, 1);
//if (!a.accuracy_check()) puts("ERR");
}
}
void work()
{
//simulation();
pii c = a.query(0, 5);
printf("%d,%d", c.first, c.second);
}
//rel��¼����������������棬rel[0]�����ǰ����[1]����ĺ��
const int rel[2][6] = { { -1,4,1,2,3,-1, },{ -1, 2, 3, 4, 1, -1 } };
const int r[9] = { 2,1,1,2,-1,4,3,3,4 };//�ײ������
void solve_bottom_cross_one()
{
pii cur = a.query(0, 1);
int flag = 0;
if (cur == make_pair(0, 1)) return;
if (cur.first == 0)
for (int i = 0; i < 2; ++i)
a.rotate(r[cur.second], 0);
cur = a.query(0, 1);
if (0 < cur.first&&cur.first < 5)
{
if (cur.second == 1)
{
for (cur = a.query(0, 1); cur.first != 1; cur = a.query(0, 1)) a.rotate(5, 0);
a.rotate(1, 0);
}
cur = a.query(0, 1);
if (cur.second == 7) a.rotate(cur.first, 0);
cur = a.query(0, 1);
if (cur.second ==3||cur.second==5)
{
flag = (cur.second == 3);
a.rotate(rel[flag][cur.first], 0);
a.rotate(5, flag);
a.rotate(rel[flag][cur.first], 1);
}
}
for (cur = a.query(0, 1); cur.first == 5 && cur.second != 7; cur = a.query(0, 1))
{
a.rotate(5, 0);
}
if (cur.first == 5)
for (int i = 0; i < 2; ++i) a.rotate(1, 0);
}
void solve_bottom_cross()
{
for (int i = 0; i < 4; ++i)
{
solve_bottom_cross_one();
if (a.query(0, 1) != make_pair(0, 1)) throw 1;//check
a.rotate_direction();
}
}
void solve_first_level_one()
{
#define C a.query(0,2)
int t1;
if (C == make_pair(0, 2)) return;
if (C.first == 0 || (C.first < 5 && C.second>5))
{
if (C.first == 0) t1 = rel[0][r[C.second]];
else
{
if (C.second == 8) t1 = rel[0][C.first];
else t1 = C.first;
}
a.rotate(t1, 0);
a.rotate(5, 0);
a.rotate(t1, 1);
}
if (C.first == 5)
{
while (C.second != 8) a.rotate(5, 0);
a.rotate(4, 0);
a.rotate(5, 1);
a.rotate(4, 1);
}
if (C.second == 2)
{
while (C.first != 1) a.rotate(5, 0);
a.rotate(5, 0);
a.rotate(4, 0);
a.rotate(5, 1);
a.rotate(4, 1);
}
if (C.second == 0)
{
while (C.first != 4) a.rotate(5, 0);
a.rotate(4, 0);
a.rotate(5, 0);
a.rotate(4, 1);
}
#undef C
}
void solve_first_level()
{
for (int i = 0; i < 4; ++i)
{
solve_first_level_one();
if (a.query(0, 2) != make_pair(0, 2)) throw 1;//check
a.rotate_direction();
}
}
void solve_second_level()
{
for (int i = 0; i < 4; ++i)
{
//solve_second_level_one();
if (a.query(0, 2) != make_pair(0, 2)) throw 1;//check
a.rotate_direction();
}
}
void solve()
{
solve_bottom_cross();
solve_first_level();
a.output();
}
int main()
{
//freopen("mf.in", "r", stdin);
//freopen("mf.out", "w", stdout);
a.randomize();
solve();
puts("GET TO GETCHAR()");
getchar(); getchar();
return 0;
}<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file FlightAutoLine.cpp
*/
#include "FlightTaskAutoLineSmoothVel.hpp"
#include <mathlib/mathlib.h>
#include <float.h>
using namespace matrix;
bool FlightTaskAutoLineSmoothVel::activate()
{
bool ret = FlightTaskAutoMapper2::activate();
for (int i = 0; i < 3; ++i) {
_trajectory[i].reset(0.f, _velocity(i), _position(i));
}
_yaw_sp_prev = _yaw;
_updateTrajConstraints();
return ret;
}
void FlightTaskAutoLineSmoothVel::reActivate()
{
// Don't reset during takeoff TODO: Find a proper solution
// The issue here is that with a small increment of velocity setpoint (generated by this flight task), the
// land detector doesn't detect takeoff and without takeoff detection, the
// flight task is always reset.
}
void FlightTaskAutoLineSmoothVel::_setDefaultConstraints()
{
FlightTaskAuto::_setDefaultConstraints();
_constraints.speed_xy = MPC_XY_VEL_MAX.get(); // TODO : Should be computed using heading
}
void FlightTaskAutoLineSmoothVel::_generateSetpoints()
{
_prepareSetpoints();
_generateTrajectory();
if (!PX4_ISFINITE(_yaw_setpoint)) {
// no valid heading -> generate heading in this flight task
_generateHeading();
}
}
void FlightTaskAutoLineSmoothVel::_generateHeading()
{
// Generate heading along trajectory if possible, otherwise hold the previous yaw setpoint
if (!_generateHeadingAlongTraj()) {
_yaw_setpoint = _yaw_sp_prev;
}
_yaw_sp_prev = _yaw_setpoint;
}
bool FlightTaskAutoLineSmoothVel::_generateHeadingAlongTraj()
{
bool res = false;
Vector2f vel_sp_xy(_velocity_setpoint);
if (vel_sp_xy.length() > .01f) {
// Generate heading from velocity vector, only if it is long enough
_compute_heading_from_2D_vector(_yaw_setpoint, vel_sp_xy);
res = true;
}
return res;
}
/* Constrain some value vith a constrain depending on the sign of the constrain
* Example: - if the constrain is -5, the value will be constrained between -5 and 0
* - if the constrain is 5, the value will be constrained between 0 and 5
*/
inline float FlightTaskAutoLineSmoothVel::_constrainOneSide(float val, float constrain)
{
const float min = (constrain < FLT_EPSILON) ? constrain : 0.f;
const float max = (constrain > FLT_EPSILON) ? constrain : 0.f;
return math::constrain(val, min, max);
}
void FlightTaskAutoLineSmoothVel::_checkEkfResetCounters()
{
// Check if a reset event has happened.
if (_sub_vehicle_local_position->get().xy_reset_counter != _reset_counters.xy) {
_trajectory[0].setCurrentPosition(_position(0));
_trajectory[1].setCurrentPosition(_position(1));
_reset_counters.xy = _sub_vehicle_local_position->get().xy_reset_counter;
}
if (_sub_vehicle_local_position->get().vxy_reset_counter != _reset_counters.vxy) {
_trajectory[0].setCurrentVelocity(_velocity(0));
_trajectory[1].setCurrentVelocity(_velocity(1));
_reset_counters.vxy = _sub_vehicle_local_position->get().vxy_reset_counter;
}
if (_sub_vehicle_local_position->get().z_reset_counter != _reset_counters.z) {
_trajectory[2].setCurrentPosition(_position(2));
_reset_counters.z = _sub_vehicle_local_position->get().z_reset_counter;
}
if (_sub_vehicle_local_position->get().vz_reset_counter != _reset_counters.vz) {
_trajectory[2].setCurrentVelocity(_velocity(2));
_reset_counters.vz = _sub_vehicle_local_position->get().vz_reset_counter;
}
}
void FlightTaskAutoLineSmoothVel::_prepareSetpoints()
{
// Interface: A valid position setpoint generates a velocity target using a P controller. If a velocity is specified
// that one is used as a velocity limit.
// If the position setpoints are set to NAN, the values in the velocity setpoints are used as velocity targets: nothing to do here.
_checkEkfResetCounters();
if (PX4_ISFINITE(_position_setpoint(0)) &&
PX4_ISFINITE(_position_setpoint(1))) {
// Use position setpoints to generate velocity setpoints
// Get various path specific vectors. */
Vector2f pos_traj;
pos_traj(0) = _trajectory[0].getCurrentPosition();
pos_traj(1) = _trajectory[1].getCurrentPosition();
Vector2f pos_sp_xy(_position_setpoint);
Vector2f pos_traj_to_dest(pos_sp_xy - pos_traj);
Vector2f u_prev_to_dest = Vector2f(pos_sp_xy - Vector2f(_prev_wp)).unit_or_zero();
Vector2f prev_to_pos(pos_traj - Vector2f(_prev_wp));
Vector2f closest_pt = Vector2f(_prev_wp) + u_prev_to_dest * (prev_to_pos * u_prev_to_dest);
Vector2f u_pos_traj_to_dest_xy(Vector2f(pos_traj_to_dest).unit_or_zero());
float speed_sp_track = Vector2f(pos_traj_to_dest).length() * MPC_XY_TRAJ_P.get();
speed_sp_track = math::constrain(speed_sp_track, 0.0f, MPC_XY_CRUISE.get());
Vector2f vel_sp_xy = u_pos_traj_to_dest_xy * speed_sp_track;
for (int i = 0; i < 2; i++) {
// If available, constrain the velocity using _velocity_setpoint(.)
if (PX4_ISFINITE(_velocity_setpoint(i))) {
_velocity_setpoint(i) = _constrainOneSide(vel_sp_xy(i), _velocity_setpoint(i));
} else {
_velocity_setpoint(i) = vel_sp_xy(i);
}
_velocity_setpoint(i) += (closest_pt(i) - _trajectory[i].getCurrentPosition()) *
MPC_XY_TRAJ_P.get(); // Along-track setpoint + cross-track P controller
}
}
if (PX4_ISFINITE(_position_setpoint(2))) {
const float vel_sp_z = (_position_setpoint(2) - _trajectory[2].getCurrentPosition()) *
MPC_Z_TRAJ_P.get(); // Generate a velocity target for the trajectory using a simple P loop
// If available, constrain the velocity using _velocity_setpoint(.)
if (PX4_ISFINITE(_velocity_setpoint(2))) {
_velocity_setpoint(2) = _constrainOneSide(vel_sp_z, _velocity_setpoint(2));
} else {
_velocity_setpoint(2) = vel_sp_z;
}
}
}
void FlightTaskAutoLineSmoothVel::_updateTrajConstraints()
{
// Update the constraints of the trajectories
_trajectory[0].setMaxAccel(MPC_ACC_HOR_MAX.get()); // TODO : Should be computed using heading
_trajectory[1].setMaxAccel(MPC_ACC_HOR_MAX.get());
_trajectory[0].setMaxVel(_constraints.speed_xy);
_trajectory[1].setMaxVel(_constraints.speed_xy);
_trajectory[0].setMaxJerk(MPC_JERK_MIN.get()); // TODO : Should be computed using heading
_trajectory[1].setMaxJerk(MPC_JERK_MIN.get());
_trajectory[2].setMaxJerk(MPC_JERK_MIN.get());
if (_velocity_setpoint(2) < 0.f) { // up
_trajectory[2].setMaxAccel(MPC_ACC_UP_MAX.get());
_trajectory[2].setMaxVel(MPC_Z_VEL_MAX_UP.get());
} else { // down
_trajectory[2].setMaxAccel(MPC_ACC_DOWN_MAX.get());
_trajectory[2].setMaxVel(MPC_Z_VEL_MAX_DN.get());
}
}
void FlightTaskAutoLineSmoothVel::_generateTrajectory()
{
if (!PX4_ISFINITE(_velocity_setpoint(0)) || !PX4_ISFINITE(_velocity_setpoint(1))
|| !PX4_ISFINITE(_velocity_setpoint(2))) {
return;
}
/* Slow down the trajectory by decreasing the integration time based on the position error.
* This is only performed when the drone is behind the trajectory
*/
Vector2f position_trajectory_xy(_trajectory[0].getCurrentPosition(), _trajectory[1].getCurrentPosition());
Vector2f position_xy(_position);
Vector2f vel_traj_xy(_trajectory[0].getCurrentVelocity(), _trajectory[1].getCurrentVelocity());
Vector2f drone_to_trajectory_xy(position_trajectory_xy - position_xy);
float position_error = drone_to_trajectory_xy.length();
float time_stretch = 1.f - math::constrain(position_error * 0.5f, 0.f, 1.f);
// Don't stretch time if the drone is ahead of the position setpoint
if (drone_to_trajectory_xy.dot(vel_traj_xy) < 0.f) {
time_stretch = 1.f;
}
Vector3f jerk_sp_smooth;
Vector3f accel_sp_smooth;
Vector3f vel_sp_smooth;
Vector3f pos_sp_smooth;
for (int i = 0; i < 3; ++i) {
_trajectory[i].integrate(_deltatime, time_stretch, accel_sp_smooth(i), vel_sp_smooth(i), pos_sp_smooth(i));
jerk_sp_smooth(i) = _trajectory[i].getCurrentJerk();
}
_updateTrajConstraints();
for (int i = 0; i < 3; ++i) {
_trajectory[i].updateDurations(_deltatime, _velocity_setpoint(i));
}
VelocitySmoothing::timeSynchronization(_trajectory, 2); // Synchronize x and y only
_jerk_setpoint = jerk_sp_smooth;
_acceleration_setpoint = accel_sp_smooth;
_velocity_setpoint = vel_sp_smooth;
_position_setpoint = pos_sp_smooth;
}
<commit_msg>FlightTasks: fix mission DO_CHANGE_SPEED<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file FlightAutoLine.cpp
*/
#include "FlightTaskAutoLineSmoothVel.hpp"
#include <mathlib/mathlib.h>
#include <float.h>
using namespace matrix;
bool FlightTaskAutoLineSmoothVel::activate()
{
bool ret = FlightTaskAutoMapper2::activate();
for (int i = 0; i < 3; ++i) {
_trajectory[i].reset(0.f, _velocity(i), _position(i));
}
_yaw_sp_prev = _yaw;
_updateTrajConstraints();
return ret;
}
void FlightTaskAutoLineSmoothVel::reActivate()
{
// Don't reset during takeoff TODO: Find a proper solution
// The issue here is that with a small increment of velocity setpoint (generated by this flight task), the
// land detector doesn't detect takeoff and without takeoff detection, the
// flight task is always reset.
}
void FlightTaskAutoLineSmoothVel::_setDefaultConstraints()
{
FlightTaskAuto::_setDefaultConstraints();
_constraints.speed_xy = MPC_XY_VEL_MAX.get(); // TODO : Should be computed using heading
}
void FlightTaskAutoLineSmoothVel::_generateSetpoints()
{
_prepareSetpoints();
_generateTrajectory();
if (!PX4_ISFINITE(_yaw_setpoint)) {
// no valid heading -> generate heading in this flight task
_generateHeading();
}
}
void FlightTaskAutoLineSmoothVel::_generateHeading()
{
// Generate heading along trajectory if possible, otherwise hold the previous yaw setpoint
if (!_generateHeadingAlongTraj()) {
_yaw_setpoint = _yaw_sp_prev;
}
_yaw_sp_prev = _yaw_setpoint;
}
bool FlightTaskAutoLineSmoothVel::_generateHeadingAlongTraj()
{
bool res = false;
Vector2f vel_sp_xy(_velocity_setpoint);
if (vel_sp_xy.length() > .01f) {
// Generate heading from velocity vector, only if it is long enough
_compute_heading_from_2D_vector(_yaw_setpoint, vel_sp_xy);
res = true;
}
return res;
}
/* Constrain some value vith a constrain depending on the sign of the constrain
* Example: - if the constrain is -5, the value will be constrained between -5 and 0
* - if the constrain is 5, the value will be constrained between 0 and 5
*/
inline float FlightTaskAutoLineSmoothVel::_constrainOneSide(float val, float constrain)
{
const float min = (constrain < FLT_EPSILON) ? constrain : 0.f;
const float max = (constrain > FLT_EPSILON) ? constrain : 0.f;
return math::constrain(val, min, max);
}
void FlightTaskAutoLineSmoothVel::_checkEkfResetCounters()
{
// Check if a reset event has happened.
if (_sub_vehicle_local_position->get().xy_reset_counter != _reset_counters.xy) {
_trajectory[0].setCurrentPosition(_position(0));
_trajectory[1].setCurrentPosition(_position(1));
_reset_counters.xy = _sub_vehicle_local_position->get().xy_reset_counter;
}
if (_sub_vehicle_local_position->get().vxy_reset_counter != _reset_counters.vxy) {
_trajectory[0].setCurrentVelocity(_velocity(0));
_trajectory[1].setCurrentVelocity(_velocity(1));
_reset_counters.vxy = _sub_vehicle_local_position->get().vxy_reset_counter;
}
if (_sub_vehicle_local_position->get().z_reset_counter != _reset_counters.z) {
_trajectory[2].setCurrentPosition(_position(2));
_reset_counters.z = _sub_vehicle_local_position->get().z_reset_counter;
}
if (_sub_vehicle_local_position->get().vz_reset_counter != _reset_counters.vz) {
_trajectory[2].setCurrentVelocity(_velocity(2));
_reset_counters.vz = _sub_vehicle_local_position->get().vz_reset_counter;
}
}
void FlightTaskAutoLineSmoothVel::_prepareSetpoints()
{
// Interface: A valid position setpoint generates a velocity target using a P controller. If a velocity is specified
// that one is used as a velocity limit.
// If the position setpoints are set to NAN, the values in the velocity setpoints are used as velocity targets: nothing to do here.
_checkEkfResetCounters();
if (PX4_ISFINITE(_position_setpoint(0)) &&
PX4_ISFINITE(_position_setpoint(1))) {
// Use position setpoints to generate velocity setpoints
// Get various path specific vectors. */
Vector2f pos_traj;
pos_traj(0) = _trajectory[0].getCurrentPosition();
pos_traj(1) = _trajectory[1].getCurrentPosition();
Vector2f pos_sp_xy(_position_setpoint);
Vector2f pos_traj_to_dest(pos_sp_xy - pos_traj);
Vector2f u_prev_to_dest = Vector2f(pos_sp_xy - Vector2f(_prev_wp)).unit_or_zero();
Vector2f prev_to_pos(pos_traj - Vector2f(_prev_wp));
Vector2f closest_pt = Vector2f(_prev_wp) + u_prev_to_dest * (prev_to_pos * u_prev_to_dest);
Vector2f u_pos_traj_to_dest_xy(Vector2f(pos_traj_to_dest).unit_or_zero());
float speed_sp_track = Vector2f(pos_traj_to_dest).length() * MPC_XY_TRAJ_P.get();
speed_sp_track = math::constrain(speed_sp_track, 0.0f, _mc_cruise_speed);
Vector2f vel_sp_xy = u_pos_traj_to_dest_xy * speed_sp_track;
for (int i = 0; i < 2; i++) {
// If available, constrain the velocity using _velocity_setpoint(.)
if (PX4_ISFINITE(_velocity_setpoint(i))) {
_velocity_setpoint(i) = _constrainOneSide(vel_sp_xy(i), _velocity_setpoint(i));
} else {
_velocity_setpoint(i) = vel_sp_xy(i);
}
_velocity_setpoint(i) += (closest_pt(i) - _trajectory[i].getCurrentPosition()) *
MPC_XY_TRAJ_P.get(); // Along-track setpoint + cross-track P controller
}
}
if (PX4_ISFINITE(_position_setpoint(2))) {
const float vel_sp_z = (_position_setpoint(2) - _trajectory[2].getCurrentPosition()) *
MPC_Z_TRAJ_P.get(); // Generate a velocity target for the trajectory using a simple P loop
// If available, constrain the velocity using _velocity_setpoint(.)
if (PX4_ISFINITE(_velocity_setpoint(2))) {
_velocity_setpoint(2) = _constrainOneSide(vel_sp_z, _velocity_setpoint(2));
} else {
_velocity_setpoint(2) = vel_sp_z;
}
}
}
void FlightTaskAutoLineSmoothVel::_updateTrajConstraints()
{
// Update the constraints of the trajectories
_trajectory[0].setMaxAccel(MPC_ACC_HOR_MAX.get()); // TODO : Should be computed using heading
_trajectory[1].setMaxAccel(MPC_ACC_HOR_MAX.get());
_trajectory[0].setMaxVel(_constraints.speed_xy);
_trajectory[1].setMaxVel(_constraints.speed_xy);
_trajectory[0].setMaxJerk(MPC_JERK_MIN.get()); // TODO : Should be computed using heading
_trajectory[1].setMaxJerk(MPC_JERK_MIN.get());
_trajectory[2].setMaxJerk(MPC_JERK_MIN.get());
if (_velocity_setpoint(2) < 0.f) { // up
_trajectory[2].setMaxAccel(MPC_ACC_UP_MAX.get());
_trajectory[2].setMaxVel(MPC_Z_VEL_MAX_UP.get());
} else { // down
_trajectory[2].setMaxAccel(MPC_ACC_DOWN_MAX.get());
_trajectory[2].setMaxVel(MPC_Z_VEL_MAX_DN.get());
}
}
void FlightTaskAutoLineSmoothVel::_generateTrajectory()
{
if (!PX4_ISFINITE(_velocity_setpoint(0)) || !PX4_ISFINITE(_velocity_setpoint(1))
|| !PX4_ISFINITE(_velocity_setpoint(2))) {
return;
}
/* Slow down the trajectory by decreasing the integration time based on the position error.
* This is only performed when the drone is behind the trajectory
*/
Vector2f position_trajectory_xy(_trajectory[0].getCurrentPosition(), _trajectory[1].getCurrentPosition());
Vector2f position_xy(_position);
Vector2f vel_traj_xy(_trajectory[0].getCurrentVelocity(), _trajectory[1].getCurrentVelocity());
Vector2f drone_to_trajectory_xy(position_trajectory_xy - position_xy);
float position_error = drone_to_trajectory_xy.length();
float time_stretch = 1.f - math::constrain(position_error * 0.5f, 0.f, 1.f);
// Don't stretch time if the drone is ahead of the position setpoint
if (drone_to_trajectory_xy.dot(vel_traj_xy) < 0.f) {
time_stretch = 1.f;
}
Vector3f jerk_sp_smooth;
Vector3f accel_sp_smooth;
Vector3f vel_sp_smooth;
Vector3f pos_sp_smooth;
for (int i = 0; i < 3; ++i) {
_trajectory[i].integrate(_deltatime, time_stretch, accel_sp_smooth(i), vel_sp_smooth(i), pos_sp_smooth(i));
jerk_sp_smooth(i) = _trajectory[i].getCurrentJerk();
}
_updateTrajConstraints();
for (int i = 0; i < 3; ++i) {
_trajectory[i].updateDurations(_deltatime, _velocity_setpoint(i));
}
VelocitySmoothing::timeSynchronization(_trajectory, 2); // Synchronize x and y only
_jerk_setpoint = jerk_sp_smooth;
_acceleration_setpoint = accel_sp_smooth;
_velocity_setpoint = vel_sp_smooth;
_position_setpoint = pos_sp_smooth;
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. 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 "tensorflow/c/eager/gradients_util.h"
#include <memory>
#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/c_api_experimental.h"
#include "tensorflow/c/eager/c_api_unified_experimental.h"
#include "tensorflow/c/eager/c_api_unified_experimental_internal.h"
#include "tensorflow/c/eager/gradients.h"
#include "tensorflow/c/eager/gradients_internal.h"
#include "tensorflow/c/experimental/ops/array_ops.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/experimental/ops/nn_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/lib/llvm_rtti/llvm_rtti.h"
#include "tensorflow/core/platform/errors.h"
namespace tensorflow {
namespace gradients {
using namespace std;
TFE_TensorHandle* ScalarTensorHandleHelper(TFE_Context* ctx, float value) {
float data[] = {value};
TF_Status* status = TF_NewStatus();
TF_Tensor* t = TFE_AllocateHostTensor(ctx, TF_FLOAT, nullptr, 0, status);
memcpy(TF_TensorData(t), &data[0], TF_TensorByteSize(t));
TFE_TensorHandle* th = TFE_NewTensorHandleFromTensor(ctx, t, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteTensor(t);
TF_DeleteStatus(status);
return th;
}
TFE_TensorHandle* TensorHandleWithDimsFloatHelper(TFE_Context* ctx,
float data[], int64_t dims[],
int num_dims) {
TF_Status* status = TF_NewStatus();
TF_Tensor* t =
TFE_AllocateHostTensor(ctx, TF_FLOAT, &dims[0], num_dims, status);
memcpy(TF_TensorData(t), &data[0], TF_TensorByteSize(t));
TFE_TensorHandle* th = TFE_NewTensorHandleFromTensor(ctx, t, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteTensor(t);
TF_DeleteStatus(status);
return th;
}
TFE_TensorHandle* TensorHandleWithDimsIntHelper(TFE_Context* ctx, int data[],
int64_t dims[], int num_dims) {
TF_Status* status = TF_NewStatus();
TF_Tensor* t =
TFE_AllocateHostTensor(ctx, TF_INT32, &dims[0], num_dims, status);
memcpy(TF_TensorData(t), &data[0], TF_TensorByteSize(t));
TFE_TensorHandle* th = TFE_NewTensorHandleFromTensor(ctx, t, status);
CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
TF_DeleteTensor(t);
TF_DeleteStatus(status);
return th;
}
// Get a scalar TensorHandle with given value
Status ScalarTensorHandle(AbstractContext* ctx, float value,
AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager = ScalarTensorHandleHelper(eager_ctx, value);
*tensor =
unwrap(TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return StatusFromTF_Status(status.get());
}
// Get a TensorHandle with given float values and dimensions
Status TensorHandleWithDimsFloat(AbstractContext* ctx, float data[],
int64_t dims[], int num_dims,
AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager =
TensorHandleWithDimsFloatHelper(eager_ctx, data, dims, num_dims);
*tensor =
unwrap(TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return StatusFromTF_Status(status.get());
}
// Get a TensorHandle with given int values and dimensions
Status TensorHandleWithDimsInt(AbstractContext* ctx, int data[], int64_t dims[],
int num_dims, AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager =
TensorHandleWithDimsIntHelper(eager_ctx, data, dims, num_dims);
*tensor =
unwrap(TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return StatusFromTF_Status(status.get());
}
Status GetValue(AbstractTensorHandle* t, TF_Tensor** result_tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_TensorHandle* result_t =
TF_AbstractTensorGetEagerTensor(wrap(t), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
*result_tensor = TFE_TensorHandleResolve(result_t, status.get());
return StatusFromTF_Status(status.get());
}
AbstractTensorHandlePtr GetTensorHandleUtilFloat(AbstractContext* ctx,
float vals[], int64_t dims[],
int num_dims) {
AbstractTensorHandlePtr A;
AbstractTensorHandle* a_raw = nullptr;
Status s = TensorHandleWithDimsFloat(ctx, vals, dims, num_dims, &a_raw);
if (s.ok()) {
A.reset(a_raw);
}
return A;
}
AbstractTensorHandlePtr GetTensorHandleUtilInt(AbstractContext* ctx, int vals[],
int64_t dims[], int num_dims) {
AbstractTensorHandlePtr A;
AbstractTensorHandle* a_raw = nullptr;
Status s = TensorHandleWithDimsInt(ctx, vals, dims, num_dims, &a_raw);
if (s.ok()) {
A.reset(a_raw);
}
return A;
}
AbstractTensorHandlePtr GetScalarTensorHandleUtil(AbstractContext* ctx,
float val) {
AbstractTensorHandlePtr y;
AbstractTensorHandle* y_raw = nullptr;
Status s = ScalarTensorHandle(ctx, val, &y_raw);
if (s.ok()) {
y.reset(y_raw);
}
return y;
}
Status UpdateWeights(AbstractContext* ctx, vector<AbstractTensorHandle*>& grads,
vector<AbstractTensorHandle*>& weights,
AbstractTensorHandle* learning_rate) {
/* Update weights one by one using gradient update rule:
*
* w -= lr*grad[w]
*
* NOTE: assuming learning rate is positive
*/
int num_grads = grads.size();
vector<AbstractTensorHandle*> temp_outputs(1);
std::string update_str;
// Negate learning rate for gradient descent
TF_RETURN_IF_ERROR(ops::Neg(ctx, {learning_rate},
absl::MakeSpan(temp_outputs),
"neg_lr")); // Compute -lr
learning_rate = temp_outputs[0];
for (int i = 0; i < num_grads; i++) {
// Compute dW = -lr * grad(w[i])
update_str = "update_mul_" + std::to_string(i);
TF_RETURN_IF_ERROR(ops::Mul(ctx, {learning_rate, grads[i]},
absl::MakeSpan(temp_outputs),
update_str.c_str()));
AbstractTensorHandle* dW = temp_outputs[0];
// Compute temp = weights[i] + dW
update_str = "update_add_" + std::to_string(i);
TF_RETURN_IF_ERROR(ops::Add(ctx, {weights[i], dW},
absl::MakeSpan(temp_outputs),
update_str.c_str()));
// Update the weights
weights[i] = temp_outputs[0];
}
return Status::OK();
}
AbstractContext* BuildFunction(const char* fn_name) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_ExecutionContext* graph_ctx = TF_CreateFunction(fn_name, status.get());
return unwrap(graph_ctx);
}
Status CreateParamsForInputs(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
vector<AbstractTensorHandle*>* params) {
tracing::TracingTensorHandle* handle = nullptr;
for (auto input : inputs) {
TF_RETURN_IF_ERROR(dyn_cast<tracing::TracingContext>(ctx)->AddParameter(
input->DataType(), &handle));
params->emplace_back(handle);
}
return Status::OK();
}
Status RunModel(Model model, AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs, bool use_function,
const GradientRegistry& registry) {
if (use_function) {
const char* fn_name = "test_fn";
std::unique_ptr<AbstractFunction> scoped_func;
// Returning null tensors from a tf.function is not supported, so we keep
// track of indices in the model's outputs are nullptr in this set.
// The FunctionDef only outputs the non-null tensors. We later pad the
// function op outputs to have nullptrs at the `null_indices`.
absl::flat_hash_set<int> null_indices;
{
AbstractContextPtr func_ctx(BuildFunction(fn_name));
vector<AbstractTensorHandle*> func_inputs;
func_inputs.reserve(inputs.size());
TF_RETURN_IF_ERROR(
CreateParamsForInputs(func_ctx.get(), inputs, &func_inputs));
vector<AbstractTensorHandle*> model_outputs;
model_outputs.resize(outputs.size());
TF_RETURN_IF_ERROR(model(func_ctx.get(), absl::MakeSpan(func_inputs),
absl::MakeSpan(model_outputs), registry));
for (auto func_input : func_inputs) {
func_input->Unref();
}
AbstractFunction* func = nullptr;
OutputList output_list;
output_list.expected_num_outputs = 0;
output_list.outputs.reserve(outputs.size());
for (int i = 0; i < model_outputs.size(); i++) {
if (model_outputs[i]) {
output_list.outputs.emplace_back(model_outputs[i]);
output_list.expected_num_outputs += 1;
} else {
null_indices.insert(i);
}
}
TF_RETURN_IF_ERROR(dyn_cast<tracing::TracingContext>(func_ctx.get())
->Finalize(&output_list, &func));
scoped_func.reset(func);
for (auto output : output_list.outputs) {
output->Unref();
}
TF_RETURN_IF_ERROR(ctx->RegisterFunction(func));
}
AbstractOperationPtr fn_op(ctx->CreateOperation());
TF_RETURN_IF_ERROR(fn_op->Reset(fn_name, /*raw_device_name=*/nullptr));
for (auto input : inputs) {
TF_RETURN_IF_ERROR(fn_op->AddInput(input));
}
int retvals = outputs.size() - null_indices.size();
vector<AbstractTensorHandle*> fn_outputs(retvals);
TF_RETURN_IF_ERROR(fn_op->Execute(
absl::Span<AbstractTensorHandle*>(fn_outputs.data(), fn_outputs.size()),
&retvals));
int skipped_indices = 0;
for (int i = 0; i < outputs.size(); i++) {
if (!null_indices.contains(i)) {
outputs[i] = fn_outputs[i - skipped_indices];
} else {
skipped_indices += 1;
}
}
TF_RETURN_IF_ERROR(ctx->RemoveFunction(fn_name));
return Status::OK();
} else {
return model(ctx, inputs, outputs, registry);
}
}
Status BuildImmediateExecutionContext(bool use_tfrt, AbstractContext** ctx) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetTfrt(opts, use_tfrt);
*ctx = unwrap(TF_NewEagerExecutionContext(opts, status.get()));
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_DeleteContextOptions(opts);
return Status::OK();
}
} // namespace gradients
} // namespace tensorflow<commit_msg>returning status instead of Tensorhandle in helper functions<commit_after>/* Copyright 2020 The TensorFlow Authors. 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 "tensorflow/c/eager/gradients_util.h"
#include <memory>
#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/c_api_experimental.h"
#include "tensorflow/c/eager/c_api_unified_experimental.h"
#include "tensorflow/c/eager/c_api_unified_experimental_internal.h"
#include "tensorflow/c/eager/gradients.h"
#include "tensorflow/c/eager/gradients_internal.h"
#include "tensorflow/c/experimental/ops/array_ops.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/experimental/ops/nn_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/lib/llvm_rtti/llvm_rtti.h"
#include "tensorflow/core/platform/errors.h"
namespace tensorflow {
namespace gradients {
using namespace std;
Status ScalarTensorHandleHelper(TFE_Context* ctx, float value,
TFE_TensorHandle** result) {
float data[] = {value};
// TF_Status* status = TF_NewStatus();
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_Tensor* t =
TFE_AllocateHostTensor(ctx, TF_FLOAT, nullptr, 0, status.get());
memcpy(TF_TensorData(t), &data[0], TF_TensorByteSize(t));
TFE_TensorHandle* th = TFE_NewTensorHandleFromTensor(ctx, t, status.get());
*result = th;
TF_DeleteTensor(t);
return StatusFromTF_Status(status.get());
}
Status TensorHandleWithDimsFloatHelper(TFE_Context* ctx, float data[],
int64_t dims[], int num_dims,
TFE_TensorHandle** result) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_Tensor* t =
TFE_AllocateHostTensor(ctx, TF_FLOAT, &dims[0], num_dims, status.get());
memcpy(TF_TensorData(t), &data[0], TF_TensorByteSize(t));
TFE_TensorHandle* th = TFE_NewTensorHandleFromTensor(ctx, t, status.get());
*result = th;
TF_DeleteTensor(t);
return StatusFromTF_Status(status.get());
}
Status TensorHandleWithDimsIntHelper(TFE_Context* ctx, int data[],
int64_t dims[], int num_dims,
TFE_TensorHandle** result) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_Tensor* t =
TFE_AllocateHostTensor(ctx, TF_INT32, &dims[0], num_dims, status.get());
memcpy(TF_TensorData(t), &data[0], TF_TensorByteSize(t));
TFE_TensorHandle* th = TFE_NewTensorHandleFromTensor(ctx, t, status.get());
*result = th;
TF_DeleteTensor(t);
return StatusFromTF_Status(status.get());
}
// Get a scalar TensorHandle with given value
Status ScalarTensorHandle(AbstractContext* ctx, float value,
AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager;
Status s = ScalarTensorHandleHelper(eager_ctx, value, &input_eager);
if (!s.ok()) { // If failed, return here.
return s;
}
*tensor =
unwrap(TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return StatusFromTF_Status(status.get());
}
// Get a TensorHandle with given float values and dimensions
Status TensorHandleWithDimsFloat(AbstractContext* ctx, float data[],
int64_t dims[], int num_dims,
AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager;
Status s = TensorHandleWithDimsFloatHelper(eager_ctx, data, dims, num_dims,
&input_eager);
if (!s.ok()) { // If failed, return here.
return s;
}
*tensor =
unwrap(TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return StatusFromTF_Status(status.get());
}
// Get a TensorHandle with given int values and dimensions
Status TensorHandleWithDimsInt(AbstractContext* ctx, int data[], int64_t dims[],
int num_dims, AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager;
Status s = TensorHandleWithDimsIntHelper(eager_ctx, data, dims, num_dims,
&input_eager);
if (!s.ok()) { // If failed, return here.
return s;
}
*tensor =
unwrap(TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return StatusFromTF_Status(status.get());
}
Status GetValue(AbstractTensorHandle* t, TF_Tensor** result_tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_TensorHandle* result_t =
TF_AbstractTensorGetEagerTensor(wrap(t), status.get());
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
*result_tensor = TFE_TensorHandleResolve(result_t, status.get());
return StatusFromTF_Status(status.get());
}
AbstractTensorHandlePtr GetTensorHandleUtilFloat(AbstractContext* ctx,
float vals[], int64_t dims[],
int num_dims) {
AbstractTensorHandlePtr A;
AbstractTensorHandle* a_raw = nullptr;
Status s = TensorHandleWithDimsFloat(ctx, vals, dims, num_dims, &a_raw);
if (s.ok()) {
A.reset(a_raw);
}
return A;
}
AbstractTensorHandlePtr GetTensorHandleUtilInt(AbstractContext* ctx, int vals[],
int64_t dims[], int num_dims) {
AbstractTensorHandlePtr A;
AbstractTensorHandle* a_raw = nullptr;
Status s = TensorHandleWithDimsInt(ctx, vals, dims, num_dims, &a_raw);
if (s.ok()) {
A.reset(a_raw);
}
return A;
}
AbstractTensorHandlePtr GetScalarTensorHandleUtil(AbstractContext* ctx,
float val) {
AbstractTensorHandlePtr y;
AbstractTensorHandle* y_raw = nullptr;
Status s = ScalarTensorHandle(ctx, val, &y_raw);
if (s.ok()) {
y.reset(y_raw);
}
return y;
}
Status UpdateWeights(AbstractContext* ctx, vector<AbstractTensorHandle*>& grads,
vector<AbstractTensorHandle*>& weights,
AbstractTensorHandle* learning_rate) {
/* Update weights one by one using gradient update rule:
*
* w -= lr*grad[w]
*
* NOTE: assuming learning rate is positive
*/
int num_grads = grads.size();
vector<AbstractTensorHandle*> temp_outputs(1);
std::string update_str;
// Negate learning rate for gradient descent
TF_RETURN_IF_ERROR(ops::Neg(ctx, {learning_rate},
absl::MakeSpan(temp_outputs),
"neg_lr")); // Compute -lr
learning_rate = temp_outputs[0];
for (int i = 0; i < num_grads; i++) {
// Compute dW = -lr * grad(w[i])
update_str = "update_mul_" + std::to_string(i);
TF_RETURN_IF_ERROR(ops::Mul(ctx, {learning_rate, grads[i]},
absl::MakeSpan(temp_outputs),
update_str.c_str()));
AbstractTensorHandle* dW = temp_outputs[0];
// Compute temp = weights[i] + dW
update_str = "update_add_" + std::to_string(i);
TF_RETURN_IF_ERROR(ops::Add(ctx, {weights[i], dW},
absl::MakeSpan(temp_outputs),
update_str.c_str()));
// Update the weights
weights[i] = temp_outputs[0];
}
return Status::OK();
}
AbstractContext* BuildFunction(const char* fn_name) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_ExecutionContext* graph_ctx = TF_CreateFunction(fn_name, status.get());
return unwrap(graph_ctx);
}
Status CreateParamsForInputs(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
vector<AbstractTensorHandle*>* params) {
tracing::TracingTensorHandle* handle = nullptr;
for (auto input : inputs) {
TF_RETURN_IF_ERROR(dyn_cast<tracing::TracingContext>(ctx)->AddParameter(
input->DataType(), &handle));
params->emplace_back(handle);
}
return Status::OK();
}
Status RunModel(Model model, AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs, bool use_function,
const GradientRegistry& registry) {
if (use_function) {
const char* fn_name = "test_fn";
std::unique_ptr<AbstractFunction> scoped_func;
// Returning null tensors from a tf.function is not supported, so we keep
// track of indices in the model's outputs are nullptr in this set.
// The FunctionDef only outputs the non-null tensors. We later pad the
// function op outputs to have nullptrs at the `null_indices`.
absl::flat_hash_set<int> null_indices;
{
AbstractContextPtr func_ctx(BuildFunction(fn_name));
vector<AbstractTensorHandle*> func_inputs;
func_inputs.reserve(inputs.size());
TF_RETURN_IF_ERROR(
CreateParamsForInputs(func_ctx.get(), inputs, &func_inputs));
vector<AbstractTensorHandle*> model_outputs;
model_outputs.resize(outputs.size());
TF_RETURN_IF_ERROR(model(func_ctx.get(), absl::MakeSpan(func_inputs),
absl::MakeSpan(model_outputs), registry));
for (auto func_input : func_inputs) {
func_input->Unref();
}
AbstractFunction* func = nullptr;
OutputList output_list;
output_list.expected_num_outputs = 0;
output_list.outputs.reserve(outputs.size());
for (int i = 0; i < model_outputs.size(); i++) {
if (model_outputs[i]) {
output_list.outputs.emplace_back(model_outputs[i]);
output_list.expected_num_outputs += 1;
} else {
null_indices.insert(i);
}
}
TF_RETURN_IF_ERROR(dyn_cast<tracing::TracingContext>(func_ctx.get())
->Finalize(&output_list, &func));
scoped_func.reset(func);
for (auto output : output_list.outputs) {
output->Unref();
}
TF_RETURN_IF_ERROR(ctx->RegisterFunction(func));
}
AbstractOperationPtr fn_op(ctx->CreateOperation());
TF_RETURN_IF_ERROR(fn_op->Reset(fn_name, /*raw_device_name=*/nullptr));
for (auto input : inputs) {
TF_RETURN_IF_ERROR(fn_op->AddInput(input));
}
int retvals = outputs.size() - null_indices.size();
vector<AbstractTensorHandle*> fn_outputs(retvals);
TF_RETURN_IF_ERROR(fn_op->Execute(
absl::Span<AbstractTensorHandle*>(fn_outputs.data(), fn_outputs.size()),
&retvals));
int skipped_indices = 0;
for (int i = 0; i < outputs.size(); i++) {
if (!null_indices.contains(i)) {
outputs[i] = fn_outputs[i - skipped_indices];
} else {
skipped_indices += 1;
}
}
TF_RETURN_IF_ERROR(ctx->RemoveFunction(fn_name));
return Status::OK();
} else {
return model(ctx, inputs, outputs, registry);
}
}
Status BuildImmediateExecutionContext(bool use_tfrt, AbstractContext** ctx) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetTfrt(opts, use_tfrt);
*ctx = unwrap(TF_NewEagerExecutionContext(opts, status.get()));
TF_RETURN_IF_ERROR(StatusFromTF_Status(status.get()));
TFE_DeleteContextOptions(opts);
return Status::OK();
}
} // namespace gradients
} // namespace tensorflow<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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 <functional>
#include <unordered_map>
#include <utility>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename T, typename TIndex>
class UniqueOp : public OpKernel {
public:
explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
// TODO(dga): Make unique polymorphic for returning int32 and int64
// vectors to support large tensors.
OP_REQUIRES(context,
input.NumElements() <= std::numeric_limits<int32>::max(),
errors::InvalidArgument(
"unique does not support input tensors larger than ",
std::numeric_limits<int32>::max(), " elements"));
int64 axis = 0;
std::vector<int64> new_sizes{1, input.NumElements(), 1};
if (context->num_inputs() == 1) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
// In case of UniqueV2, the axis is a 1D vector. The purpose is
// to allow specifying either "no axis" or "axis". The `[]` means
// "no axis", while `[x]` means `axis = x`.
const Tensor& axis_tensor = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(axis_tensor.shape()),
errors::InvalidArgument("axis expects a 1D vector."));
OP_REQUIRES(
context, axis_tensor.NumElements() <= 1,
errors::InvalidArgument(
"axis does not support input tensors larger than 1 elements"));
if (axis_tensor.NumElements() == 0) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
auto axis_vec = axis_tensor.vec<int64>();
axis = axis_vec(0);
axis = axis < 0 ? axis + input.dims() : axis;
OP_REQUIRES(context, 0 <= axis && axis < input.dims(),
errors::InvalidArgument("axis has to be between [0, ",
input.dims(), ")"));
if (axis > 0) {
for (int64 i = 0; i < axis; i++) {
new_sizes[0] *= input.dim_size(i);
}
}
new_sizes[1] = input.dim_size(axis);
if (axis + 1 < input.dims()) {
for (int64 i = axis + 1; i < input.dims(); i++) {
new_sizes[2] *= input.dim_size(i);
}
}
}
}
auto Tin = input.shaped<T, 3>(new_sizes);
Tensor* idx = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
1, TensorShape({Tin.dimension(1)}), &idx));
auto idx_vec = idx->template vec<TIndex>();
auto hash_fn = [&Tin](const int64& key) -> unsigned long {
size_t h = 0;
for (int64 i = 0; i < Tin.dimension(0); i++) {
for (int64 j = 0; j < Tin.dimension(2); j++) {
h = Hash64Combine(h, hash<T>{}(Tin(i, key, j)));
}
}
return h;
};
auto equal_to_fn = [&Tin](const int64& lhs, const int64& rhs) {
for (int64 i = 0; i < Tin.dimension(0); i++) {
for (int64 j = 0; j < Tin.dimension(2); j++) {
if (Tin(i, lhs, j) != Tin(i, rhs, j)) {
return false;
}
}
}
return true;
};
std::unordered_map<int64, int64, decltype(hash_fn), decltype(equal_to_fn)>
uniq(0, hash_fn, equal_to_fn);
uniq.reserve(2 * Tin.dimension(1));
for (int64 i = 0, j = 0; i < Tin.dimension(1); ++i) {
auto it = uniq.insert(std::make_pair(i, j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
int64 uniq_size = static_cast<int64>(uniq.size());
new_sizes[1] = uniq_size;
TensorShape output_shape(input.shape());
output_shape.set_dim(axis, uniq_size);
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto Tout = output->shaped<T, 3>(new_sizes);
for (auto it : uniq) {
for (int64 i = 0; i < Tin.dimension(0); i++) {
for (int64 j = 0; j < Tin.dimension(2); j++) {
Tout(i, it.second, j) = Tin(i, it.first, j);
}
}
}
if (num_outputs() > 2) {
OP_REQUIRES_OK(context, context->allocate_output(
2, TensorShape({uniq_size}), &output));
auto count_output_vec = output->template vec<TIndex>();
count_output_vec.setZero();
for (int64 i = 0; i < Tin.dimension(1); ++i) {
count_output_vec(idx_vec(i))++;
}
}
}
};
#define REGISTER_UNIQUE(type) \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>) \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_UNIQUE);
REGISTER_UNIQUE(string)
#undef REGISTER_UNIQUE
// Fake integer GPU kernels so that the use of Unique in optimizers (to
// de-duplicate sparse gradient indices) does not conflict with gradients being
// located on a GPU. These kernels run on the CPU, their inputs and outputs
// residing in host (not GPU) memory.
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
<commit_msg>Replace loop iteration with `chip` (#15289)<commit_after>/* Copyright 2015 The TensorFlow Authors. 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 <functional>
#include <unordered_map>
#include <utility>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/hash/hash.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename T, typename TIndex>
class UniqueOp : public OpKernel {
public:
explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
// TODO(dga): Make unique polymorphic for returning int32 and int64
// vectors to support large tensors.
OP_REQUIRES(context,
input.NumElements() <= std::numeric_limits<int32>::max(),
errors::InvalidArgument(
"unique does not support input tensors larger than ",
std::numeric_limits<int32>::max(), " elements"));
int64 axis = 0;
std::vector<int64> new_sizes{1, input.NumElements(), 1};
if (context->num_inputs() == 1) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
// In case of UniqueV2, the axis is a 1D vector. The purpose is
// to allow specifying either "no axis" or "axis". The `[]` means
// "no axis", while `[x]` means `axis = x`.
const Tensor& axis_tensor = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(axis_tensor.shape()),
errors::InvalidArgument("axis expects a 1D vector."));
OP_REQUIRES(
context, axis_tensor.NumElements() <= 1,
errors::InvalidArgument(
"axis does not support input tensors larger than 1 elements"));
if (axis_tensor.NumElements() == 0) {
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
} else {
auto axis_vec = axis_tensor.vec<int64>();
axis = axis_vec(0);
axis = axis < 0 ? axis + input.dims() : axis;
OP_REQUIRES(context, 0 <= axis && axis < input.dims(),
errors::InvalidArgument("axis has to be between [0, ",
input.dims(), ")"));
if (axis > 0) {
for (int64 i = 0; i < axis; i++) {
new_sizes[0] *= input.dim_size(i);
}
}
new_sizes[1] = input.dim_size(axis);
if (axis + 1 < input.dims()) {
for (int64 i = axis + 1; i < input.dims(); i++) {
new_sizes[2] *= input.dim_size(i);
}
}
}
}
auto Tin = input.shaped<T, 3>(new_sizes);
Tensor* idx = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
1, TensorShape({Tin.dimension(1)}), &idx));
auto idx_vec = idx->template vec<TIndex>();
auto hash_fn = [&Tin](const int64& key) -> unsigned long {
size_t h = 0;
for (int64 i = 0; i < Tin.dimension(0); i++) {
for (int64 j = 0; j < Tin.dimension(2); j++) {
h = Hash64Combine(h, hash<T>{}(Tin(i, key, j)));
}
}
return h;
};
auto equal_to_fn = [&Tin](const int64& lhs, const int64& rhs) {
for (int64 i = 0; i < Tin.dimension(0); i++) {
for (int64 j = 0; j < Tin.dimension(2); j++) {
if (Tin(i, lhs, j) != Tin(i, rhs, j)) {
return false;
}
}
}
return true;
};
std::unordered_map<int64, int64, decltype(hash_fn), decltype(equal_to_fn)>
uniq(0, hash_fn, equal_to_fn);
uniq.reserve(2 * Tin.dimension(1));
for (int64 i = 0, j = 0; i < Tin.dimension(1); ++i) {
auto it = uniq.insert(std::make_pair(i, j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
int64 uniq_size = static_cast<int64>(uniq.size());
new_sizes[1] = uniq_size;
TensorShape output_shape(input.shape());
output_shape.set_dim(axis, uniq_size);
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto Tout = output->shaped<T, 3>(new_sizes);
for (auto it : uniq) {
Tout.chip(it.second, 1) = Tin.chip(it.first, 1);
}
if (num_outputs() > 2) {
OP_REQUIRES_OK(context, context->allocate_output(
2, TensorShape({uniq_size}), &output));
auto count_output_vec = output->template vec<TIndex>();
count_output_vec.setZero();
for (int64 i = 0; i < Tin.dimension(1); ++i) {
count_output_vec(idx_vec(i))++;
}
}
}
};
#define REGISTER_UNIQUE(type) \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>); \
REGISTER_KERNEL_BUILDER(Name("UniqueV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type, int32>) \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int64>("out_idx"), \
UniqueOp<type, int64>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_UNIQUE);
REGISTER_UNIQUE(string)
#undef REGISTER_UNIQUE
// Fake integer GPU kernels so that the use of Unique in optimizers (to
// de-duplicate sparse gradient indices) does not conflict with gradients being
// located on a GPU. These kernels run on the CPU, their inputs and outputs
// residing in host (not GPU) memory.
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32, int64>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_SYCL)
.TypeConstraint<int64>("T")
.TypeConstraint<int64>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64, int64>);
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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 <unordered_map>
#include <utility>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename T>
class UniqueOp : public OpKernel {
public:
explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
// TODO(dga): Make unique polymorphic for returning int32 and int64
// vectors to support large tensors.
OP_REQUIRES(context,
input.NumElements() <= std::numeric_limits<int32>::max(),
errors::InvalidArgument(
"unique does not support input tensors larger than ",
std::numeric_limits<int32>::max(), " elements"));
auto Tin = input.vec<T>();
const int64 N = static_cast<int64>(Tin.size());
Tensor* idx = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 1, input.shape(), &idx));
auto idx_vec = idx->template vec<int32>();
std::unordered_map<T, int32> uniq;
uniq.reserve(2 * N);
for (int64 i = 0, j = 0; i < N; ++i) {
auto it = uniq.insert(std::make_pair(Tin(i), j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
int64 uniq_size = static_cast<int64>(uniq.size());
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
0, TensorShape({uniq_size}), &output));
auto output_vec = output->template vec<T>();
for (auto it : uniq) {
output_vec(it.second) = it.first;
}
if (num_outputs() > 2) {
OP_REQUIRES_OK(context, context->allocate_output(
2, TensorShape({uniq_size}), &output));
auto count_output_vec = output->template vec<int32>();
count_output_vec.setZero();
for (int64 i = 0; i < N; ++i) {
count_output_vec(idx_vec(i))++;
}
}
}
};
#define REGISTER_UNIQUE(type) \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_UNIQUE);
REGISTER_UNIQUE(string)
#undef REGISTER_UNIQUE
// Fake integer GPU kernels so that the use of Unique in optimizers (to
// de-duplicate sparse gradient indices) does not conflict with gradients being
// located on a GPU. These kernels run on the CPU, their inputs and outputs
// residing in host (not GPU) memory.
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64>);
} // namespace tensorflow
<commit_msg>Change Unique op to use gtl::FlatMap instead of std::unordered_map<>. Change: 155070869<commit_after>/* Copyright 2015 The TensorFlow Authors. 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 <utility>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/flatmap.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename T>
class UniqueOp : public OpKernel {
public:
explicit UniqueOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input.shape()),
errors::InvalidArgument("unique expects a 1D vector."));
// TODO(dga): Make unique polymorphic for returning int32 and int64
// vectors to support large tensors.
OP_REQUIRES(context,
input.NumElements() <= std::numeric_limits<int32>::max(),
errors::InvalidArgument(
"unique does not support input tensors larger than ",
std::numeric_limits<int32>::max(), " elements"));
auto Tin = input.vec<T>();
const int64 N = static_cast<int64>(Tin.size());
Tensor* idx = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 1, input.shape(), &idx));
auto idx_vec = idx->template vec<int32>();
gtl::FlatMap<T, int32> uniq(N);
for (int64 i = 0, j = 0; i < N; ++i) {
auto it = uniq.insert(std::make_pair(Tin(i), j));
idx_vec(i) = it.first->second;
if (it.second) {
++j;
}
}
int64 uniq_size = static_cast<int64>(uniq.size());
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
0, TensorShape({uniq_size}), &output));
auto output_vec = output->template vec<T>();
for (auto it : uniq) {
output_vec(it.second) = it.first;
}
if (num_outputs() > 2) {
OP_REQUIRES_OK(context, context->allocate_output(
2, TensorShape({uniq_size}), &output));
auto count_output_vec = output->template vec<int32>();
count_output_vec.setZero();
for (int64 i = 0; i < N; ++i) {
count_output_vec(idx_vec(i))++;
}
}
}
};
#define REGISTER_UNIQUE(type) \
REGISTER_KERNEL_BUILDER(Name("Unique") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type>); \
REGISTER_KERNEL_BUILDER(Name("UniqueWithCounts") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("out_idx"), \
UniqueOp<type>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_UNIQUE);
REGISTER_UNIQUE(string)
#undef REGISTER_UNIQUE
// Fake integer GPU kernels so that the use of Unique in optimizers (to
// de-duplicate sparse gradient indices) does not conflict with gradients being
// located on a GPU. These kernels run on the CPU, their inputs and outputs
// residing in host (not GPU) memory.
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int32>);
REGISTER_KERNEL_BUILDER(Name("Unique")
.Device(DEVICE_GPU)
.TypeConstraint<int64>("T")
.TypeConstraint<int32>("out_idx")
.HostMemory("x")
.HostMemory("y")
.HostMemory("idx"),
UniqueOp<int64>);
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#define EIGEN_USE_THREADS
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/kernels/split_lib.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#ifdef TENSORFLOW_USE_SYCL
typedef Eigen::SyclDevice SYCLDevice;
#endif // TENSORFLOW_USE_SYCL
template <typename Device, typename T>
class UnpackOp : public OpKernel {
public:
explicit UnpackOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("axis", &axis_));
}
void Compute(OpKernelContext* context) override {
const int32 num = num_outputs();
const Tensor& input = context->input(0);
const TensorShape& input_shape = input.shape();
int axis = axis_;
if (axis < 0) axis += input_shape.dims();
OP_REQUIRES(context, 0 <= axis && axis < input_shape.dims(),
errors::InvalidArgument("axis = ", axis_, " not in [",
-input_shape.dims(), ", ",
input_shape.dims(), ")"));
OP_REQUIRES(
context, input_shape.dims() > 0 && input_shape.dim_size(axis) == num,
errors::InvalidArgument("Input shape axis ", axis, " must equal ", num,
", got shape ", input_shape.DebugString()));
auto output_shape = input_shape;
output_shape.RemoveDim(axis);
const int64 output_size = output_shape.num_elements();
OP_REQUIRES(
context, FastBoundsCheck(output_size,
std::numeric_limits<Eigen::DenseIndex>::max()),
errors::InvalidArgument("output size must fit in Eigen DenseIndex"));
// This optimization is currently not applicable for SYCL devices
#ifndef TENSORFLOW_USE_SYCL
// Special case: Aligned, so we can share the underlying buffer.
//
// Apply this optimization conservatively: if input is aligned,
// the resulting tensors must be aligned. It's conservative
// because if the immediate consumer of the resulting tensors are
// not using eigen for computation, its perfectly fine to avoid
// the copying.
if (axis == 0 &&
(output_size == 0 || IsInnerDimsSizeAligned<T>(input_shape))) {
for (int i = 0; i < num; ++i) {
Tensor output;
CHECK(output.CopyFrom(input.Slice(i, i + 1), output_shape));
context->set_output(i, output);
}
return;
}
#endif // TENSORFLOW_USE_SYCL
int64 before_dim = 1;
for (int i = 0; i < axis; ++i) {
before_dim *= input_shape.dim_size(i);
}
int64 after_dim = 1;
for (int i = axis + 1; i < input_shape.dims(); ++i) {
after_dim *= input_shape.dim_size(i);
}
const int64 axis_dim = input_shape.dim_size(axis);
// Except for shape, unpack is a special case of split, so we reuse the
// same computational kernels.
auto input_reshaped =
input.shaped<T, 3>({1, before_dim, axis_dim * after_dim});
for (int i = 0; i < num; ++i) {
Tensor* output;
OP_REQUIRES_OK(context,
context->allocate_output(i, output_shape, &output));
if (output_shape.num_elements() > 0) {
auto output_shaped = output->shaped<T, 3>({1, before_dim, after_dim});
Eigen::DSizes<Eigen::DenseIndex, 3> indices{0, 0, i * after_dim};
Eigen::DSizes<Eigen::DenseIndex, 3> sizes{1, before_dim, after_dim};
functor::Split<Device, T>()(context->eigen_device<Device>(),
output_shaped, input_reshaped, indices,
sizes);
}
}
}
private:
int axis_;
};
#define REGISTER_UNPACK(type) \
REGISTER_KERNEL_BUILDER( \
Name("Unpack").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
UnpackOp<CPUDevice, type>)
TF_CALL_ALL_TYPES(REGISTER_UNPACK);
#undef REGISTER_UNPACK
#if GOOGLE_CUDA
#define REGISTER_GPU(type) \
REGISTER_KERNEL_BUILDER( \
Name("Unpack").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
UnpackOp<GPUDevice, type>)
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);
#undef REGISTER_GPU
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_GPU)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int32>("T"),
UnpackOp<CPUDevice, int32>);
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_GPU)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int64>("T"),
UnpackOp<CPUDevice, int64>);
#endif // GOOGLE_CUDA
#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Unpack").Device(DEVICE_SYCL).TypeConstraint<type>("T"), \
UnpackOp<SYCLDevice, type>)
TF_CALL_GPU_NUMBER_TYPES_NO_HALF(REGISTER_SYCL);
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_SYCL)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int32>("T"),
UnpackOp<CPUDevice, int32>);
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_SYCL)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int64>("T"),
UnpackOp<CPUDevice, int64>);
#undef REGISTER_SYCL
#endif // TENSORFLOW_USE_SYCL
} // end namespace tensorflow
<commit_msg>restart tests<commit_after>/* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#define EIGEN_USE_THREADS
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/kernels/split_lib.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#ifdef TENSORFLOW_USE_SYCL
typedef Eigen::SyclDevice SYCLDevice;
#endif // TENSORFLOW_USE_SYCL
template <typename Device, typename T>
class UnpackOp : public OpKernel {
public:
explicit UnpackOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("axis", &axis_));
}
void Compute(OpKernelContext* context) override {
const int32 num = num_outputs();
const Tensor& input = context->input(0);
const TensorShape& input_shape = input.shape();
int axis = axis_;
if (axis < 0) axis += input_shape.dims();
OP_REQUIRES(context, 0 <= axis && axis < input_shape.dims(),
errors::InvalidArgument("axis = ", axis_, " not in [",
-input_shape.dims(), ", ",
input_shape.dims(), ")"));
OP_REQUIRES(
context, input_shape.dims() > 0 && input_shape.dim_size(axis) == num,
errors::InvalidArgument("Input shape axis ", axis, " must equal ", num,
", got shape ", input_shape.DebugString()));
auto output_shape = input_shape;
output_shape.RemoveDim(axis);
const int64 output_size = output_shape.num_elements();
OP_REQUIRES(
context, FastBoundsCheck(output_size,
std::numeric_limits<Eigen::DenseIndex>::max()),
errors::InvalidArgument("output size must fit in Eigen DenseIndex"));
// This optimization is currently not applicable for SYCL devices
#ifndef TENSORFLOW_USE_SYCL
// Special case: Aligned, so we can share the underlying buffer.
//
// Apply this optimization conservatively: if input is aligned,
// the resulting tensors must be aligned. It's conservative
// because if the immediate consumer of the resulting tensors are
// not using eigen for computation, its perfectly fine to avoid
// the copying.
if (axis == 0 &&
(output_size == 0 || IsInnerDimsSizeAligned<T>(input_shape))) {
for (int i = 0; i < num; ++i) {
Tensor output;
CHECK(output.CopyFrom(input.Slice(i, i + 1), output_shape));
context->set_output(i, output);
}
return;
}
#endif // TENSORFLOW_USE_SYCL
int64 before_dim = 1;
for (int i = 0; i < axis; ++i) {
before_dim *= input_shape.dim_size(i);
}
int64 after_dim = 1;
for (int i = axis + 1; i < input_shape.dims(); ++i) {
after_dim *= input_shape.dim_size(i);
}
const int64 axis_dim = input_shape.dim_size(axis);
// Except for shape, unpack is a special case of split, so we reuse the
// same computational kernels.
auto input_reshaped =
input.shaped<T, 3>({1, before_dim, axis_dim * after_dim});
for (int i = 0; i < num; ++i) {
Tensor* output;
OP_REQUIRES_OK(context,
context->allocate_output(i, output_shape, &output));
if (output_shape.num_elements() > 0) {
auto output_shaped = output->shaped<T, 3>({1, before_dim, after_dim});
Eigen::DSizes<Eigen::DenseIndex, 3> indices{0, 0, i * after_dim};
Eigen::DSizes<Eigen::DenseIndex, 3> sizes{1, before_dim, after_dim};
functor::Split<Device, T>()(context->eigen_device<Device>(),
output_shaped, input_reshaped, indices,
sizes);
}
}
}
private:
int axis_;
};
#define REGISTER_UNPACK(type) \
REGISTER_KERNEL_BUILDER( \
Name("Unpack").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
UnpackOp<CPUDevice, type>)
TF_CALL_ALL_TYPES(REGISTER_UNPACK);
#undef REGISTER_UNPACK
#if GOOGLE_CUDA
#define REGISTER_GPU(type) \
REGISTER_KERNEL_BUILDER( \
Name("Unpack").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
UnpackOp<GPUDevice, type>)
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU);
#undef REGISTER_GPU
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_GPU)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int32>("T"),
UnpackOp<CPUDevice, int32>);
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_GPU)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int64>("T"),
UnpackOp<CPUDevice, int64>);
#endif // GOOGLE_CUDA
#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Unpack").Device(DEVICE_SYCL).TypeConstraint<type>("T"), \
UnpackOp<SYCLDevice, type>)
TF_CALL_GPU_NUMBER_TYPES_NO_HALF(REGISTER_SYCL);
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_SYCL)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int32>("T"),
UnpackOp<CPUDevice, int32>);
REGISTER_KERNEL_BUILDER(Name("Unpack")
.Device(DEVICE_SYCL)
.HostMemory("value")
.HostMemory("output")
.TypeConstraint<int64>("T"),
UnpackOp<CPUDevice, int64>);
#undef REGISTER_SYCL
#endif // TENSORFLOW_USE_SYCL
} // end namespace tensorflow
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: loginerr.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:27:38 $
*
* 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 GCC
#pragma hdrstop
#endif
#include "loginerr.hxx"
//============================================================================
//
// CntLoginErrorHint Implementation.
//
//============================================================================
TYPEINIT1( CntLoginErrorHint, SfxHint );
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.324); FILE MERGED 2006/09/01 17:43:23 kaib 1.3.324.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: loginerr.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 15:16:52 $
*
* 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): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef GCC
#endif
#include "loginerr.hxx"
//============================================================================
//
// CntLoginErrorHint Implementation.
//
//============================================================================
TYPEINIT1( CntLoginErrorHint, SfxHint );
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: SpellAttrib.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#include <SpellAttrib.hxx>
#include <vcl/font.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/linguistic2/XSpellAlternatives.hpp>
using namespace svx;
using namespace com::sun::star::linguistic2;
using namespace com::sun::star::uno;
/*-- 10.09.2003 12:54:34---------------------------------------------------
-----------------------------------------------------------------------*/
SpellErrorAttrib::SpellErrorAttrib(Reference<XSpellAlternatives> xAlt) :
TextAttrib(TEXTATTR_SPELL_ERROR),
m_xAlternatives(xAlt)
{
}
/*-- 10.09.2003 12:54:34---------------------------------------------------
-----------------------------------------------------------------------*/
SpellErrorAttrib::SpellErrorAttrib( const SpellErrorAttrib& rAttr ) :
TextAttrib(TEXTATTR_SPELL_ERROR),
m_xAlternatives( rAttr.m_xAlternatives )
{
}
/*-- 10.09.2003 12:54:34---------------------------------------------------
-----------------------------------------------------------------------*/
SpellErrorAttrib::~SpellErrorAttrib()
{
}
/*-- 10.09.2003 12:54:35---------------------------------------------------
-----------------------------------------------------------------------*/
void SpellErrorAttrib::SetFont( Font& ) const
{
//this attribute doesn't have a visual effect
}
/*-- 10.09.2003 12:54:35---------------------------------------------------
-----------------------------------------------------------------------*/
TextAttrib* SpellErrorAttrib::Clone() const
{
return new SpellErrorAttrib(*this);
}
/*-- 10.09.2003 12:54:35---------------------------------------------------
-----------------------------------------------------------------------*/
int SpellErrorAttrib::operator==( const TextAttrib& rAttr ) const
{
return Which() == rAttr.Which() &&
m_xAlternatives.get() == static_cast<const SpellErrorAttrib&>(rAttr).m_xAlternatives.get();
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
SpellLanguageAttrib::SpellLanguageAttrib(LanguageType eLang) :
TextAttrib(TEXTATTR_SPELL_LANGUAGE),
m_eLanguage(eLang)
{
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
SpellLanguageAttrib::SpellLanguageAttrib( const SpellLanguageAttrib& rAttr ) :
TextAttrib(TEXTATTR_SPELL_LANGUAGE),
m_eLanguage(rAttr.m_eLanguage)
{
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
SpellLanguageAttrib::~SpellLanguageAttrib()
{
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
void SpellLanguageAttrib::SetFont( Font& ) const
{
//no visual effect
}
/*-- 10.09.2003 14:27:44---------------------------------------------------
-----------------------------------------------------------------------*/
TextAttrib* SpellLanguageAttrib::Clone() const
{
return new SpellLanguageAttrib(*this);
}
/*-- 10.09.2003 14:27:44---------------------------------------------------
-----------------------------------------------------------------------*/
int SpellLanguageAttrib::operator==( const TextAttrib& rAttr ) const
{
return Which() == rAttr.Which() &&
m_eLanguage == static_cast<const SpellLanguageAttrib&>(rAttr).m_eLanguage;
}
/*-- 31.10.2003 16:07:45---------------------------------------------------
-----------------------------------------------------------------------*/
SpellBackgroundAttrib::SpellBackgroundAttrib(const Color& rCol) :
TextAttrib(TEXTATTR_SPELL_BACKGROUND),
m_aBackgroundColor(rCol)
{
}
/*-- 31.10.2003 16:07:45---------------------------------------------------
-----------------------------------------------------------------------*/
SpellBackgroundAttrib::SpellBackgroundAttrib( const SpellBackgroundAttrib& rAttr ) :
TextAttrib(TEXTATTR_SPELL_BACKGROUND),
m_aBackgroundColor(rAttr.m_aBackgroundColor)
{
}
/*-- 31.10.2003 16:07:46---------------------------------------------------
-----------------------------------------------------------------------*/
SpellBackgroundAttrib::~SpellBackgroundAttrib()
{
}
/*-- 31.10.2003 16:07:46---------------------------------------------------
-----------------------------------------------------------------------*/
void SpellBackgroundAttrib::SetFont( Font& rFont ) const
{
rFont.SetFillColor(m_aBackgroundColor);
}
/*-- 31.10.2003 16:07:46---------------------------------------------------
-----------------------------------------------------------------------*/
TextAttrib* SpellBackgroundAttrib::Clone() const
{
return new SpellBackgroundAttrib(*this);
}
/*-- 31.10.2003 16:07:47---------------------------------------------------
-----------------------------------------------------------------------*/
int SpellBackgroundAttrib::operator==( const TextAttrib& rAttr ) const
{
return Which() == rAttr.Which() &&
m_aBackgroundColor == static_cast<const SpellBackgroundAttrib&>(rAttr).m_aBackgroundColor;
}
<commit_msg>INTEGRATION: CWS tl55 (1.7.54); FILE MERGED 2008/06/30 08:27:08 tl 1.7.54.2: #i85999# grammar checking framework 2008/06/26 14:23:14 os 1.7.54.1: i85999 interactive grammar checking<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: SpellAttrib.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#include <SpellAttrib.hxx>
#include <vcl/font.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/linguistic2/XSpellAlternatives.hpp>
using namespace svx;
using namespace com::sun::star::linguistic2;
using namespace com::sun::star::uno;
/*-- 26.06.2008 10:41:57---------------------------------------------------
-----------------------------------------------------------------------*/
SpellErrorAttrib::SpellErrorAttrib( const SpellErrorDescription& rDesc ) :
TextAttrib(TEXTATTR_SPELL_ERROR),
m_aSpellErrorDescription( rDesc )
{
}
/*-- 10.09.2003 12:54:34---------------------------------------------------
-----------------------------------------------------------------------*/
SpellErrorAttrib::SpellErrorAttrib( const SpellErrorAttrib& rAttr ) :
TextAttrib(TEXTATTR_SPELL_ERROR),
m_aSpellErrorDescription( rAttr.m_aSpellErrorDescription )
{
}
/*-- 10.09.2003 12:54:34---------------------------------------------------
-----------------------------------------------------------------------*/
SpellErrorAttrib::~SpellErrorAttrib()
{
}
/*-- 10.09.2003 12:54:35---------------------------------------------------
-----------------------------------------------------------------------*/
void SpellErrorAttrib::SetFont( Font& ) const
{
//this attribute doesn't have a visual effect
}
/*-- 10.09.2003 12:54:35---------------------------------------------------
-----------------------------------------------------------------------*/
TextAttrib* SpellErrorAttrib::Clone() const
{
return new SpellErrorAttrib(*this);
}
/*-- 10.09.2003 12:54:35---------------------------------------------------
-----------------------------------------------------------------------*/
int SpellErrorAttrib::operator==( const TextAttrib& rAttr ) const
{
return Which() == rAttr.Which() &&
m_aSpellErrorDescription == static_cast<const SpellErrorAttrib&>(rAttr).m_aSpellErrorDescription;
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
SpellLanguageAttrib::SpellLanguageAttrib(LanguageType eLang) :
TextAttrib(TEXTATTR_SPELL_LANGUAGE),
m_eLanguage(eLang)
{
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
SpellLanguageAttrib::SpellLanguageAttrib( const SpellLanguageAttrib& rAttr ) :
TextAttrib(TEXTATTR_SPELL_LANGUAGE),
m_eLanguage(rAttr.m_eLanguage)
{
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
SpellLanguageAttrib::~SpellLanguageAttrib()
{
}
/*-- 10.09.2003 14:27:43---------------------------------------------------
-----------------------------------------------------------------------*/
void SpellLanguageAttrib::SetFont( Font& ) const
{
//no visual effect
}
/*-- 10.09.2003 14:27:44---------------------------------------------------
-----------------------------------------------------------------------*/
TextAttrib* SpellLanguageAttrib::Clone() const
{
return new SpellLanguageAttrib(*this);
}
/*-- 10.09.2003 14:27:44---------------------------------------------------
-----------------------------------------------------------------------*/
int SpellLanguageAttrib::operator==( const TextAttrib& rAttr ) const
{
return Which() == rAttr.Which() &&
m_eLanguage == static_cast<const SpellLanguageAttrib&>(rAttr).m_eLanguage;
}
/*-- 31.10.2003 16:07:45---------------------------------------------------
-----------------------------------------------------------------------*/
SpellBackgroundAttrib::SpellBackgroundAttrib(const Color& rCol) :
TextAttrib(TEXTATTR_SPELL_BACKGROUND),
m_aBackgroundColor(rCol)
{
}
/*-- 31.10.2003 16:07:45---------------------------------------------------
-----------------------------------------------------------------------*/
SpellBackgroundAttrib::SpellBackgroundAttrib( const SpellBackgroundAttrib& rAttr ) :
TextAttrib(TEXTATTR_SPELL_BACKGROUND),
m_aBackgroundColor(rAttr.m_aBackgroundColor)
{
}
/*-- 31.10.2003 16:07:46---------------------------------------------------
-----------------------------------------------------------------------*/
SpellBackgroundAttrib::~SpellBackgroundAttrib()
{
}
/*-- 31.10.2003 16:07:46---------------------------------------------------
-----------------------------------------------------------------------*/
void SpellBackgroundAttrib::SetFont( Font& rFont ) const
{
rFont.SetFillColor(m_aBackgroundColor);
}
/*-- 31.10.2003 16:07:46---------------------------------------------------
-----------------------------------------------------------------------*/
TextAttrib* SpellBackgroundAttrib::Clone() const
{
return new SpellBackgroundAttrib(*this);
}
/*-- 31.10.2003 16:07:47---------------------------------------------------
-----------------------------------------------------------------------*/
int SpellBackgroundAttrib::operator==( const TextAttrib& rAttr ) const
{
return Which() == rAttr.Which() &&
m_aBackgroundColor == static_cast<const SpellBackgroundAttrib&>(rAttr).m_aBackgroundColor;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlideSorterModel.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2006-12-12 18:36:57 $
*
* 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): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "controller/SlsPageObjectFactory.hxx"
#include "taskpane/SlideSorterCacheDisplay.hxx"
#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif
#ifndef _SDPAGE_HXX
#include "sdpage.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
#ifdef DEBUG
#define DUMP_MODEL ::DumpSlideSorterModel(*this)
namespace {
using namespace ::sd::slidesorter::model;
void DumpSlideSorterModel (const SlideSorterModel& rModel)
{
OSL_TRACE ("SlideSorterModel has %d pages", rModel.GetPageCount());
if (rModel.GetEditMode() == EM_PAGE)
OSL_TRACE ("edit mode is EM_PAGE");
else if (rModel.GetEditMode() == EM_MASTERPAGE)
OSL_TRACE (" edit mode is EM_MASTERPAGE");
else
OSL_TRACE (" edit mode is unknown");
for (int i=0; i<rModel.GetPageCount(); i++)
{
SharedPageDescriptor pDescriptor = rModel.GetRawPageDescriptor(i);
OSL_TRACE (" page %d points to %x", i, pDescriptor);
if (pDescriptor.get() != NULL)
OSL_TRACE (" focused %d, selected %d, visible %d",
pDescriptor->IsFocused()?1:0,
pDescriptor->IsSelected()?1:0,
pDescriptor->IsVisible()?1:0);
}
}
}
#else
#define DUMP_MODEL
#endif
#undef DUMP_MODEL
#define DUMP_MODEL
namespace sd { namespace slidesorter { namespace model {
SlideSorterModel::SlideSorterModel (
SdDrawDocument& rDocument,
PageKind ePageKind,
EditMode eEditMode)
: mrDocument (rDocument),
mePageKind (ePageKind),
meEditMode (eEditMode),
maPageDescriptors(0),
mpPageObjectFactory(NULL)
{
AdaptSize ();
DUMP_MODEL;
}
SlideSorterModel::~SlideSorterModel (void)
{
ClearDescriptorList ();
}
SdDrawDocument* SlideSorterModel::GetDocument (void)
{
return &mrDocument;
}
bool SlideSorterModel::SetEditMode (EditMode eEditMode)
{
bool bEditModeChanged = false;
if (meEditMode!=eEditMode)
{
meEditMode = eEditMode;
ClearDescriptorList();
AdaptSize();
bEditModeChanged = true;
}
DUMP_MODEL;
return bEditModeChanged;
}
EditMode SlideSorterModel::GetEditMode (void) const
{
return meEditMode;
}
PageKind SlideSorterModel::GetPageType (void) const
{
return mePageKind;
}
int SlideSorterModel::GetPageCount (void) const
{
return maPageDescriptors.size();
}
SharedPageDescriptor SlideSorterModel::GetPageDescriptor (int nPageIndex) const
{
::osl::MutexGuard aGuard (maMutex);
SharedPageDescriptor pDescriptor;
if (nPageIndex>=0 && nPageIndex<GetPageCount())
{
pDescriptor = maPageDescriptors[nPageIndex];
if (pDescriptor == NULL)
{
SdPage* pPage;
if (meEditMode == EM_PAGE)
pPage = mrDocument.GetSdPage ((USHORT)nPageIndex, mePageKind);
else
pPage = mrDocument.GetMasterSdPage ((USHORT)nPageIndex, mePageKind);
pDescriptor.reset(new PageDescriptor (
*pPage,
GetPageObjectFactory()));
maPageDescriptors[nPageIndex] = pDescriptor;
}
}
return pDescriptor;
}
SharedPageDescriptor SlideSorterModel::GetRawPageDescriptor (int nPageIndex) const
{
::osl::MutexGuard aGuard (maMutex);
SharedPageDescriptor pDescriptor;
if (nPageIndex>=0 && nPageIndex<GetPageCount())
pDescriptor = maPageDescriptors[nPageIndex];
return pDescriptor;
}
SharedPageDescriptor SlideSorterModel::FindPageDescriptor (
const Reference<drawing::XDrawPage>& rxPage) const
{
::osl::MutexGuard aGuard (maMutex);
SharedPageDescriptor pDescriptor;
for (int i=0; i<GetPageCount(); i++)
{
pDescriptor = GetPageDescriptor(i);
if (pDescriptor.get() != NULL)
{
Reference<drawing::XDrawPage> xPage (
pDescriptor->GetPage()->getUnoPage(), UNO_QUERY);
if (xPage == rxPage)
break;
}
}
return pDescriptor;
}
SlideSorterModel::Enumeration
SlideSorterModel::GetAllPagesEnumeration (void) const
{
return PageEnumeration::Create(*this, PageEnumeration::PET_ALL);
}
SlideSorterModel::Enumeration
SlideSorterModel::GetSelectedPagesEnumeration (void) const
{
return PageEnumeration::Create(*this, PageEnumeration::PET_SELECTED);
}
SlideSorterModel::Enumeration
SlideSorterModel::GetVisiblePagesEnumeration (void) const
{
return PageEnumeration::Create(*this, PageEnumeration::PET_VISIBLE);
}
/** For now this method uses a trivial algorithm: throw away all descriptors
and create them anew (on demand). The main problem that we are facing
when designing a better algorithm is that we can not compare pointers to
pages stored in the PageDescriptor objects and those obtained from the
document: pages may have been deleted and others may have been created
at the exact same memory locations.
*/
void SlideSorterModel::Resync (void)
{
::osl::MutexGuard aGuard (maMutex);
DUMP_MODEL;
ClearDescriptorList ();
AdaptSize();
DUMP_MODEL;
}
void SlideSorterModel::AdaptSize ()
{
::osl::MutexGuard aGuard (maMutex);
if (meEditMode == EM_PAGE)
maPageDescriptors.resize(mrDocument.GetSdPageCount(mePageKind));
else
maPageDescriptors.resize(mrDocument.GetMasterSdPageCount(mePageKind));
#ifdef USE_SLIDE_SORTER_PAGE_CACHE
toolpanel::SlideSorterCacheDisplay* pDisplay = toolpanel::SlideSorterCacheDisplay::Instance(&mrDocument);
if (pDisplay != NULL)
pDisplay->SetPageCount(mrDocument.GetSdPageCount(mePageKind));
#endif
}
void SlideSorterModel::ClearDescriptorList (void)
{
::osl::MutexGuard aGuard (maMutex);
// Clear the cache of page descriptors.
DescriptorContainer::iterator I;
for (I=maPageDescriptors.begin(); I!=maPageDescriptors.end(); I++)
{
if (I->get() != NULL)
{
if ( ! I->unique())
{
OSL_TRACE("SlideSorterModel::ClearDescriptorList: trying to delete page descriptor that is still used with count %d", I->use_count());
// No assertion here because that can hang the office when
// opening a dialog from here.
}
I->reset();
}
}
}
void SlideSorterModel::SynchronizeDocumentSelection (void)
{
::osl::MutexGuard aGuard (maMutex);
Enumeration aAllPages (GetAllPagesEnumeration());
while (aAllPages.HasMoreElements())
{
SharedPageDescriptor pDescriptor (aAllPages.GetNextElement());
pDescriptor->GetPage()->SetSelected (pDescriptor->IsSelected());
}
}
void SlideSorterModel::SynchronizeModelSelection (void)
{
::osl::MutexGuard aGuard (maMutex);
Enumeration aAllPages (GetAllPagesEnumeration());
while (aAllPages.HasMoreElements())
{
SharedPageDescriptor pDescriptor (aAllPages.GetNextElement());
if (pDescriptor->GetPage()->IsSelected())
pDescriptor->Select ();
else
pDescriptor->Deselect ();
}
}
void SlideSorterModel::SetPageObjectFactory(
::std::auto_ptr<controller::PageObjectFactory> pPageObjectFactory)
{
::osl::MutexGuard aGuard (maMutex);
mpPageObjectFactory = pPageObjectFactory;
// When a NULL pointer was given then create a default factory.
const controller::PageObjectFactory& rFactory (GetPageObjectFactory());
Enumeration aAllPages (GetAllPagesEnumeration());
while (aAllPages.HasMoreElements())
{
SharedPageDescriptor pDescriptor (aAllPages.GetNextElement());
pDescriptor->SetPageObjectFactory(rFactory);
}
}
const controller::PageObjectFactory&
SlideSorterModel::GetPageObjectFactory (void) const
{
::osl::MutexGuard aGuard (maMutex);
if (mpPageObjectFactory.get() == NULL)
{
// We have to creat a new factory. The pointer is mutable so we are
// alowed to do so. Note that we pass NULL as pointer to the
// preview cache because we, as a model, have no access to the
// cache. This makes this object clearly a fallback when the
// controller does not provide a factory where the cache is properly
// set.
mpPageObjectFactory = ::std::auto_ptr<controller::PageObjectFactory> (
new controller::PageObjectFactory(::boost::shared_ptr<cache::PageCache>()));
}
return *mpPageObjectFactory.get();
}
::osl::Mutex& SlideSorterModel::GetMutex (void)
{
return maMutex;
}
} } } // end of namespace ::sd::slidesorter::model
<commit_msg>INTEGRATION: CWS custommeta (1.8.236); FILE MERGED 2008/01/21 11:36:39 mst 1.8.236.1: - sd/source/ui/slidesorter/model/SlideSorterModel.cxx: + fix debug-only warning<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlideSorterModel.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2008-02-26 13:45:21 $
*
* 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): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "controller/SlsPageObjectFactory.hxx"
#include "taskpane/SlideSorterCacheDisplay.hxx"
#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif
#ifndef _SDPAGE_HXX
#include "sdpage.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
#ifdef DEBUG
#define DUMP_MODEL ::DumpSlideSorterModel(*this)
namespace {
using namespace ::sd::slidesorter::model;
void DumpSlideSorterModel (const SlideSorterModel& rModel)
{
OSL_TRACE ("SlideSorterModel has %d pages", rModel.GetPageCount());
if (rModel.GetEditMode() == EM_PAGE)
OSL_TRACE ("edit mode is EM_PAGE");
else if (rModel.GetEditMode() == EM_MASTERPAGE)
OSL_TRACE (" edit mode is EM_MASTERPAGE");
else
OSL_TRACE (" edit mode is unknown");
for (int i=0; i<rModel.GetPageCount(); i++)
{
SharedPageDescriptor pDescriptor = rModel.GetRawPageDescriptor(i);
OSL_TRACE (" page %d points to %x", i, pDescriptor.get());
if (pDescriptor.get() != NULL)
OSL_TRACE (" focused %d, selected %d, visible %d",
pDescriptor->IsFocused()?1:0,
pDescriptor->IsSelected()?1:0,
pDescriptor->IsVisible()?1:0);
}
}
}
#else
#define DUMP_MODEL
#endif
#undef DUMP_MODEL
#define DUMP_MODEL
namespace sd { namespace slidesorter { namespace model {
SlideSorterModel::SlideSorterModel (
SdDrawDocument& rDocument,
PageKind ePageKind,
EditMode eEditMode)
: mrDocument (rDocument),
mePageKind (ePageKind),
meEditMode (eEditMode),
maPageDescriptors(0),
mpPageObjectFactory(NULL)
{
AdaptSize ();
DUMP_MODEL;
}
SlideSorterModel::~SlideSorterModel (void)
{
ClearDescriptorList ();
}
SdDrawDocument* SlideSorterModel::GetDocument (void)
{
return &mrDocument;
}
bool SlideSorterModel::SetEditMode (EditMode eEditMode)
{
bool bEditModeChanged = false;
if (meEditMode!=eEditMode)
{
meEditMode = eEditMode;
ClearDescriptorList();
AdaptSize();
bEditModeChanged = true;
}
DUMP_MODEL;
return bEditModeChanged;
}
EditMode SlideSorterModel::GetEditMode (void) const
{
return meEditMode;
}
PageKind SlideSorterModel::GetPageType (void) const
{
return mePageKind;
}
int SlideSorterModel::GetPageCount (void) const
{
return maPageDescriptors.size();
}
SharedPageDescriptor SlideSorterModel::GetPageDescriptor (int nPageIndex) const
{
::osl::MutexGuard aGuard (maMutex);
SharedPageDescriptor pDescriptor;
if (nPageIndex>=0 && nPageIndex<GetPageCount())
{
pDescriptor = maPageDescriptors[nPageIndex];
if (pDescriptor == NULL)
{
SdPage* pPage;
if (meEditMode == EM_PAGE)
pPage = mrDocument.GetSdPage ((USHORT)nPageIndex, mePageKind);
else
pPage = mrDocument.GetMasterSdPage ((USHORT)nPageIndex, mePageKind);
pDescriptor.reset(new PageDescriptor (
*pPage,
GetPageObjectFactory()));
maPageDescriptors[nPageIndex] = pDescriptor;
}
}
return pDescriptor;
}
SharedPageDescriptor SlideSorterModel::GetRawPageDescriptor (int nPageIndex) const
{
::osl::MutexGuard aGuard (maMutex);
SharedPageDescriptor pDescriptor;
if (nPageIndex>=0 && nPageIndex<GetPageCount())
pDescriptor = maPageDescriptors[nPageIndex];
return pDescriptor;
}
SharedPageDescriptor SlideSorterModel::FindPageDescriptor (
const Reference<drawing::XDrawPage>& rxPage) const
{
::osl::MutexGuard aGuard (maMutex);
SharedPageDescriptor pDescriptor;
for (int i=0; i<GetPageCount(); i++)
{
pDescriptor = GetPageDescriptor(i);
if (pDescriptor.get() != NULL)
{
Reference<drawing::XDrawPage> xPage (
pDescriptor->GetPage()->getUnoPage(), UNO_QUERY);
if (xPage == rxPage)
break;
}
}
return pDescriptor;
}
SlideSorterModel::Enumeration
SlideSorterModel::GetAllPagesEnumeration (void) const
{
return PageEnumeration::Create(*this, PageEnumeration::PET_ALL);
}
SlideSorterModel::Enumeration
SlideSorterModel::GetSelectedPagesEnumeration (void) const
{
return PageEnumeration::Create(*this, PageEnumeration::PET_SELECTED);
}
SlideSorterModel::Enumeration
SlideSorterModel::GetVisiblePagesEnumeration (void) const
{
return PageEnumeration::Create(*this, PageEnumeration::PET_VISIBLE);
}
/** For now this method uses a trivial algorithm: throw away all descriptors
and create them anew (on demand). The main problem that we are facing
when designing a better algorithm is that we can not compare pointers to
pages stored in the PageDescriptor objects and those obtained from the
document: pages may have been deleted and others may have been created
at the exact same memory locations.
*/
void SlideSorterModel::Resync (void)
{
::osl::MutexGuard aGuard (maMutex);
DUMP_MODEL;
ClearDescriptorList ();
AdaptSize();
DUMP_MODEL;
}
void SlideSorterModel::AdaptSize ()
{
::osl::MutexGuard aGuard (maMutex);
if (meEditMode == EM_PAGE)
maPageDescriptors.resize(mrDocument.GetSdPageCount(mePageKind));
else
maPageDescriptors.resize(mrDocument.GetMasterSdPageCount(mePageKind));
#ifdef USE_SLIDE_SORTER_PAGE_CACHE
toolpanel::SlideSorterCacheDisplay* pDisplay = toolpanel::SlideSorterCacheDisplay::Instance(&mrDocument);
if (pDisplay != NULL)
pDisplay->SetPageCount(mrDocument.GetSdPageCount(mePageKind));
#endif
}
void SlideSorterModel::ClearDescriptorList (void)
{
::osl::MutexGuard aGuard (maMutex);
// Clear the cache of page descriptors.
DescriptorContainer::iterator I;
for (I=maPageDescriptors.begin(); I!=maPageDescriptors.end(); I++)
{
if (I->get() != NULL)
{
if ( ! I->unique())
{
OSL_TRACE("SlideSorterModel::ClearDescriptorList: trying to delete page descriptor that is still used with count %d", I->use_count());
// No assertion here because that can hang the office when
// opening a dialog from here.
}
I->reset();
}
}
}
void SlideSorterModel::SynchronizeDocumentSelection (void)
{
::osl::MutexGuard aGuard (maMutex);
Enumeration aAllPages (GetAllPagesEnumeration());
while (aAllPages.HasMoreElements())
{
SharedPageDescriptor pDescriptor (aAllPages.GetNextElement());
pDescriptor->GetPage()->SetSelected (pDescriptor->IsSelected());
}
}
void SlideSorterModel::SynchronizeModelSelection (void)
{
::osl::MutexGuard aGuard (maMutex);
Enumeration aAllPages (GetAllPagesEnumeration());
while (aAllPages.HasMoreElements())
{
SharedPageDescriptor pDescriptor (aAllPages.GetNextElement());
if (pDescriptor->GetPage()->IsSelected())
pDescriptor->Select ();
else
pDescriptor->Deselect ();
}
}
void SlideSorterModel::SetPageObjectFactory(
::std::auto_ptr<controller::PageObjectFactory> pPageObjectFactory)
{
::osl::MutexGuard aGuard (maMutex);
mpPageObjectFactory = pPageObjectFactory;
// When a NULL pointer was given then create a default factory.
const controller::PageObjectFactory& rFactory (GetPageObjectFactory());
Enumeration aAllPages (GetAllPagesEnumeration());
while (aAllPages.HasMoreElements())
{
SharedPageDescriptor pDescriptor (aAllPages.GetNextElement());
pDescriptor->SetPageObjectFactory(rFactory);
}
}
const controller::PageObjectFactory&
SlideSorterModel::GetPageObjectFactory (void) const
{
::osl::MutexGuard aGuard (maMutex);
if (mpPageObjectFactory.get() == NULL)
{
// We have to creat a new factory. The pointer is mutable so we are
// alowed to do so. Note that we pass NULL as pointer to the
// preview cache because we, as a model, have no access to the
// cache. This makes this object clearly a fallback when the
// controller does not provide a factory where the cache is properly
// set.
mpPageObjectFactory = ::std::auto_ptr<controller::PageObjectFactory> (
new controller::PageObjectFactory(::boost::shared_ptr<cache::PageCache>()));
}
return *mpPageObjectFactory.get();
}
::osl::Mutex& SlideSorterModel::GetMutex (void)
{
return maMutex;
}
} } } // end of namespace ::sd::slidesorter::model
<|endoftext|> |
<commit_before>// FRAGMENT(includes)
#include <seqan/sequence.h>
#include <seqan/basic.h>
#include <iostream>
using namespace seqan;
// FRAGMENT(showAllLetterOfMyAlphabet)
template <typename TAlphabet>
void showAllLetterOfMyAlphabet(TAlphabet const &)
{
typedef typename Size<TAlphabet>::Type TSize;
TSize alphSize = ValueSize<TAlphabet>::VALUE;
for (TSize i = 0; i < alphSize; ++i)
std::cout << i << ',' << TAlphabet(i) << " ";
std::cout << std::endl;
}
// FRAGMENT(main)
int main()
{
showAllLetterOfMyAlphabet(AminoAcid());
showAllLetterOfMyAlphabet(Dna());
showAllLetterOfMyAlphabet(Dna5());
return 0;
}
<commit_msg>#940<commit_after>// FRAGMENT(includes)
#include <seqan/sequence.h>
#include <seqan/basic.h>
#include <iostream>
using namespace seqan;
// FRAGMENT(showAllLettersOfMyAlphabet)
template <typename TAlphabet>
void showAllLettersOfMyAlphabet(TAlphabet const &)
{
typedef typename Size<TAlphabet>::Type TSize;
TSize alphSize = ValueSize<TAlphabet>::VALUE;
for (TSize i = 0; i < alphSize; ++i)
std::cout << i << ',' << TAlphabet(i) << " ";
std::cout << std::endl;
}
// FRAGMENT(main)
int main()
{
showAllLettersOfMyAlphabet(AminoAcid());
showAllLettersOfMyAlphabet(Dna());
showAllLettersOfMyAlphabet(Dna5());
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP
#ifdef STAN_OPENCL
#include <stan/math/gpu/matrix_gpu.hpp>
#include <stan/math/gpu/kernels/cholesky_decompose.hpp>
#include <stan/math/gpu/multiply.hpp>
#include <stan/math/gpu/multiply_transpose.hpp>
#include <stan/math/gpu/lower_tri_inverse.hpp>
#include <stan/math/gpu/transpose.hpp>
#include <stan/math/gpu/subtract.hpp>
#include <stan/math/gpu/err/check_diagonal_zeros.hpp>
#include <stan/math/gpu/err/check_nan.hpp>
#include <CL/cl.hpp>
#include <algorithm>
#include <cmath>
namespace stan {
namespace math {
inline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block);
namespace internal {
inline matrix_gpu cholesky_decompose_recursion(matrix_gpu& A,
const int min_block) {
matrix_gpu L(A.rows(), A.cols());
if (A.rows() <= min_block || A.rows() < 100) {
try {
opencl_kernels::cholesky_decompose(cl::NDRange(A.rows()),
cl::NDRange(A.rows()), A.buffer(),
L.buffer(), A.rows());
} catch (const cl::Error& e) {
check_opencl_error("cholesky_decompose", e);
}
} else {
L = stan::math::cholesky_decompose(A, min_block);
}
return L;
}
} // namespace internal
/**
* Return the lower-triangular Cholesky factor (i.e., matrix
* square root) of the specified square, symmetric matrix.
* The return value \f$L\f$ will be a lower-traingular matrix such that the
* original matrix \f$A\f$ is given by
* <p>\f$A = L \times L^T\f$.
* The Cholesky decomposition is computed on the GPU. This algorithm is
* recursive. The matrix is subset into a matrix of size
* <code>A.rows() / 2</code>, and if the <code>block</code> size is less than
* 100 then the cholesky decomposition on the GPU is computed
* using that submatrix. If <code>block</code> is greater than
* 100 or <code>min_block</code> then <code>cholesky_decompose</code> is run
* again with <code>block</code> equal to <code>A.rows() / 2</code>. Once the
* Cholesky Decomposition is computed, the full matrix cholesky is created
* by propogating the cholesky forward as given in the reference report below.
*
* For a full guide to how this works
* see the Cholesy decompostion chapter in the reference report
* <a href="https://goo.gl/6kWkJ5"> here</a>.
* @param A Symmetric matrix on the GPU.
* @param min_block The minimum block size to execute the cholesky on.
* @return Square root of matrix on the GPU.
* @throw std::domain_error if m is not
* positive definite (if m has more than 0 elements)
*/
inline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block) {
auto offset = 0;
auto block = floor(A.rows() / 2);
// NOTE: The code in this section follows the naming conventions
// in the report linked in the docs.
matrix_gpu A_11(block, block);
// Repeats the blocked cholesky decomposition until the size of the remaining
// submatrix is smaller or equal to the block size
if ((offset + block) < (A.rows())) {
auto block_subset = A.rows() - offset - block;
matrix_gpu A_21(block_subset, block);
matrix_gpu A_22(block_subset, block_subset);
// Copies a block of the input A into A_11
A_11.sub_block(A, offset, offset, 0, 0, block, block);
// The following function either calls the
// blocked cholesky recursively for the submatrix A_11
// or calls the kernel directly if the size of the block is small enough
matrix_gpu L_11
= stan::math::internal::cholesky_decompose_recursion(A_11, min_block);
// Copies L_11 back to the input matrix
A.sub_block(L_11, 0, 0, offset, offset, block, block);
// Copies a block of the input A into A_21
auto block_offset = offset + block;
A_21.sub_block(A, block_offset, offset, 0, 0, block_subset, block);
// computes A_21*((L_11^-1)^T)
// and copies the resulting submatrix to the input matrix
matrix_gpu L_21 = A_21 * transpose(lower_triangular_inverse(L_11));
A.sub_block(L_21, 0, 0, block_offset, offset, block_subset, block);
A_22.sub_block(A, block_offset, block_offset, 0, 0, block_subset,
block_subset);
// computes A_22 - L_21*(L_21^T)
matrix_gpu L_22 = A_22 - multiply_transpose(L_21);
A.sub_block(L_22, 0, 0, block_offset, block_offset, block_subset,
block_subset);
offset += block;
}
// Computes the Cholesky factor for the remaining submatrix
const auto remaining_rows = A.rows() - offset;
if (remaining_rows > 0) {
matrix_gpu A_11(remaining_rows, remaining_rows);
A_11.sub_block(A, offset, offset, 0, 0, remaining_rows, remaining_rows);
// calculate the cholesky factor for the remaining part of the matrix
matrix_gpu L_11
= stan::math::internal::cholesky_decompose_recursion(A_11, min_block);
A.sub_block(L_11, 0, 0, offset, offset, remaining_rows, remaining_rows);
}
check_nan("cholesky_decompose_gpu", "Matrix m", A);
check_diagonal_zeros("cholesky_decompose_gpu", "Matrix m", A);
A.zeros<stan::math::TriangularViewGPU::Upper>();
return A;
}
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>Restructure GPU cholesky to get rid of the explicit recursion function and make the original method recursive.<commit_after>#ifndef STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP
#ifdef STAN_OPENCL
#include <stan/math/gpu/matrix_gpu.hpp>
#include <stan/math/gpu/kernels/cholesky_decompose.hpp>
#include <stan/math/gpu/multiply.hpp>
#include <stan/math/gpu/multiply_transpose.hpp>
#include <stan/math/gpu/lower_tri_inverse.hpp>
#include <stan/math/gpu/transpose.hpp>
#include <stan/math/gpu/subtract.hpp>
#include <stan/math/gpu/err/check_diagonal_zeros.hpp>
#include <stan/math/gpu/err/check_nan.hpp>
#include <CL/cl.hpp>
#include <algorithm>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the lower-triangular Cholesky factor (i.e., matrix
* square root) of the specified square, symmetric matrix.
* The return value \f$L\f$ will be a lower-traingular matrix such that the
* original matrix \f$A\f$ is given by
* <p>\f$A = L \times L^T\f$.
* The Cholesky decomposition is computed on the GPU. This algorithm is
* recursive. The matrix is subset into a matrix of size
* <code>A.rows() / 2</code>, and if the submatrix size is less than
* 100 then the cholesky decomposition on the GPU is computed
* using that submatrix. If the submatrix is greater than
* 100 or <code>min_block</code> then <code>cholesky_decompose</code> is run
* again with <code>block</code> equal to <code>A.rows() / 2</code>. Once the
* Cholesky Decomposition is computed, the full matrix cholesky is created
* by propogating the cholesky forward as given in the reference report below.
*
* For a full guide to how this works
* see the Cholesy decompostion chapter in the reference report
* <a href="https://goo.gl/6kWkJ5"> here</a>.
* @param A Symmetric matrix on the GPU.
* @param min_block The minimum block size to execute the cholesky on.
* @return Square root of matrix on the GPU.
* @throw std::domain_error if m is not
* positive definite (if m has more than 0 elements)
*/
inline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block) {
if (A.rows() == 0) return A;
matrix_gpu L(A.rows(), A.cols());
// Repeats the blocked cholesky decomposition until the size of the remaining
// submatrix is smaller or equal to the minimum blocks size
// or a heuristic of 100
if (A.rows() <= min_block || A.rows() < 100) {
try {
opencl_kernels::cholesky_decompose(cl::NDRange(A.rows()),
cl::NDRange(A.rows()), A.buffer(),
L.buffer(), A.rows());
} catch (const cl::Error& e) {
check_opencl_error("cholesky_decompose", e);
}
return L;
} else {
// NOTE: The code in this section follows the naming conventions
// in the report linked in the docs.
auto block = floor(A.rows() / 2);
// Subset the top left block of the input A into A_11
matrix_gpu A_11(block, block);
A_11.sub_block(A, 0, 0, 0, 0, block, block);
// The following function either calls the
// blocked cholesky recursively for the submatrix A_11
// or calls the kernel directly if the size of the block is small enough
matrix_gpu L_11
= stan::math::cholesky_decompose(A_11, min_block);
// Copies L_11 back to the input matrix
A.sub_block(L_11, 0, 0, 0, 0, block, block);
auto block_subset = A.rows() - block;
matrix_gpu A_21(block_subset, block);
A_21.sub_block(A, block, 0, 0, 0, block_subset, block);
// computes A_21*((L_11^-1)^T)
// and copies the resulting submatrix to the right hand corner of A
matrix_gpu L_21 = A_21 * transpose(lower_triangular_inverse(L_11));
A.sub_block(L_21, 0, 0, block, 0, block_subset, block);
matrix_gpu A_22(block_subset, block_subset);
A_22.sub_block(A, block, block, 0, 0, block_subset, block_subset);
// computes A_22 - L_21*(L_21^T)
matrix_gpu L_22 = A_22 - multiply_transpose(L_21);
// copy L_22 into A's left hand corner
A.sub_block(L_22, 0, 0, block, block, block_subset, block_subset);
// Computes the Cholesky factor for the remaining submatrix
matrix_gpu A_rem_11(block_subset, block_subset);
A_rem_11.sub_block(A, block, block, 0, 0, block_subset, block_subset);
matrix_gpu L_rem_11
= stan::math::cholesky_decompose(A_rem_11, min_block);
A.sub_block(L_rem_11, 0, 0, block, block, block_subset, block_subset);
check_nan("cholesky_decompose_gpu", "Matrix m", A);
check_diagonal_zeros("cholesky_decompose_gpu", "Matrix m", A);
A.zeros<stan::math::TriangularViewGPU::Upper>();
return A;
}
// This should never happen
return A;
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <realm.hpp>
#include <realm/util/file.hpp>
#include "../util/timer.hpp"
#include "../util/random.hpp"
#include "../util/benchmark_results.hpp"
using namespace realm;
using namespace realm::util;
using namespace realm::test_util;
/**
This bechmark suite represents a number of common use cases,
from the perspective of the bindings. It does *not* benchmark
the type-safe C++ API, but only the things that language bindings
are likely to use internally.
This has the following implications:
- All access is done with a SharedGroup in transactions.
- The SharedGroup has full durability (is backed by a file).
(but all benchmarks are also run with MemOnly durability for comparison)
- Cases have been derived from:
https://github.com/realm/realm-java/blob/bp-performance-test/realm/src/androidTest/java/io/realm/RealmPerformanceTest.java
*/
static const char realm_path[] = "/tmp/benchmark-common-tasks.realm";
static const size_t min_repetitions = 10;
static const size_t max_repetitions = 100;
static const double min_duration_s = 0.05;
struct Benchmark
{
virtual const char* name() const = 0;
virtual void setup(SharedGroup&) {}
virtual void teardown(SharedGroup&) {}
virtual void operator()(SharedGroup&) = 0;
};
struct AddTable : Benchmark {
const char* name() const { return "AddTable"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table(name());
t->add_column(type_String, "first");
t->add_column(type_Int, "second");
t->add_column(type_DateTime, "third");
tr.commit();
}
void teardown(SharedGroup& group)
{
Group& g = group.begin_write();
g.remove_table(name());
group.commit();
}
};
struct BenchmarkWithStringsTable : Benchmark {
void setup(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table("StringOnly");
t->add_column(type_String, "chars");
tr.commit();
}
void teardown(SharedGroup& group)
{
Group& g = group.begin_write();
g.remove_table("StringOnly");
group.commit();
}
};
struct BenchmarkWithStrings : BenchmarkWithStringsTable {
void setup(SharedGroup& group)
{
BenchmarkWithStringsTable::setup(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
t->add_empty_row(1000);
for (size_t i = 0; i < 1000; ++i) {
std::stringstream ss;
ss << rand();
t->set_string(0, i, ss.str());
}
tr.commit();
}
};
struct BenchmarkQuery : BenchmarkWithStrings {
const char* name() const { return "Query"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->find_all_string(0, "200");
}
};
struct BenchmarkSize : BenchmarkWithStrings {
const char* name() const { return "Size"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile size_t dummy = table->size();
static_cast<void>(dummy);
}
};
struct BenchmarkSort : BenchmarkWithStrings {
const char* name() const { return "Sort"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_sorted_view(0);
}
};
struct BenchmarkInsert : BenchmarkWithStringsTable {
const char* name() const { return "Insert"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
for (size_t i = 0; i < 10000; ++i) {
t->add_empty_row();
t->set_string(0, i, "a");
}
tr.commit();
}
};
struct BenchmarkGetString : BenchmarkWithStrings {
const char* name() const { return "GetString"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
size_t len = table->size();
volatile int dummy = 0;
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(0, i);
dummy += str[0]; // to avoid over-optimization
}
}
};
struct BenchmarkSetString : BenchmarkWithStrings {
const char* name() const { return "SetString"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(0, i, "c");
}
tr.commit();
}
};
struct BenchmarkCreateIndex : BenchmarkWithStrings {
const char* name() const { return "CreateIndex"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
table->add_search_index(0);
tr.commit();
}
};
struct BenchmarkQueryNot : Benchmark {
const char* name() const { return "QueryNot"; }
void setup(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.add_table(name());
table->add_column(type_Int, "first");
table->add_empty_row(1000);
for (size_t i = 0; i < 1000; ++i) {
table->set_int(0, i, 1);
}
tr.commit();
}
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table(name());
Query q = table->where();
q.not_equal(0, 2); // never found, = worst case
TableView results = q.find_all();
results.size();
}
void teardown(SharedGroup& group)
{
Group& g = group.begin_write();
g.remove_table(name());
group.commit();
}
};
static const char* durability_level_to_cstr(SharedGroup::DurabilityLevel level)
{
switch (level) {
case SharedGroup::durability_Full: return "Full";
case SharedGroup::durability_MemOnly: return "MemOnly";
#ifndef _WIN32
case SharedGroup::durability_Async: return "Async";
#endif
}
}
void run_benchmark_once(Benchmark& benchmark, SharedGroup& sg, Timer& timer)
{
timer.pause();
benchmark.setup(sg);
timer.unpause();
benchmark(sg);
timer.pause();
benchmark.teardown(sg);
timer.unpause();
}
/// This little piece of likely over-engineering runs the benchmark a number of times,
/// with each durability setting, and reports the results for each run.
template <typename B>
void run_benchmark(BenchmarkResults& results)
{
#ifdef _WIN32
const size_t num_durabilities = 2;
#else
const size_t num_durabilities = 2; // FIXME Figure out how to run the async commit daemon.
#endif
Timer timer(Timer::type_UserTime);
for (size_t i = 0; i < num_durabilities; ++i) {
// Open a SharedGroup:
File::try_remove(realm_path);
std::unique_ptr<SharedGroup> group;
SharedGroup::DurabilityLevel level = static_cast<SharedGroup::DurabilityLevel>(i);
group.reset(new SharedGroup(realm_path, false, level));
B benchmark;
// Generate the benchmark result texts:
std::stringstream lead_text_ss;
std::stringstream ident_ss;
lead_text_ss << benchmark.name() << " (" << durability_level_to_cstr(level) << ")";
ident_ss << benchmark.name() << "_" << durability_level_to_cstr(level);
std::string ident = ident_ss.str();
// Warm-up and initial measuring:
Timer t_unused(Timer::type_UserTime);
run_benchmark_once(benchmark, *group, t_unused);
size_t rep;
double total = 0;
for (rep = 0; rep < max_repetitions && (rep < min_repetitions || total < min_duration_s); ++rep) {
Timer t;
run_benchmark_once(benchmark, *group, t);
double s = t.get_elapsed_time();
total += s;
results.submit(ident.c_str(), s);
}
results.finish(ident, lead_text_ss.str());
}
}
int main(int, const char**)
{
BenchmarkResults results(40);
run_benchmark<AddTable>(results);
run_benchmark<BenchmarkQuery>(results);
run_benchmark<BenchmarkQueryNot>(results);
run_benchmark<BenchmarkSize>(results);
run_benchmark<BenchmarkSort>(results);
run_benchmark<BenchmarkInsert>(results);
run_benchmark<BenchmarkGetString>(results);
run_benchmark<BenchmarkSetString>(results);
run_benchmark<BenchmarkCreateIndex>(results);
return 0;
}
<commit_msg>Benchmark that hits long strings.<commit_after>#include <iostream>
#include <sstream>
#include <realm.hpp>
#include <realm/util/file.hpp>
#include "../util/timer.hpp"
#include "../util/random.hpp"
#include "../util/benchmark_results.hpp"
using namespace realm;
using namespace realm::util;
using namespace realm::test_util;
/**
This bechmark suite represents a number of common use cases,
from the perspective of the bindings. It does *not* benchmark
the type-safe C++ API, but only the things that language bindings
are likely to use internally.
This has the following implications:
- All access is done with a SharedGroup in transactions.
- The SharedGroup has full durability (is backed by a file).
(but all benchmarks are also run with MemOnly durability for comparison)
- Cases have been derived from:
https://github.com/realm/realm-java/blob/bp-performance-test/realm/src/androidTest/java/io/realm/RealmPerformanceTest.java
*/
static const char realm_path[] = "/tmp/benchmark-common-tasks.realm";
static const size_t min_repetitions = 10;
static const size_t max_repetitions = 100;
static const double min_duration_s = 0.05;
struct Benchmark
{
virtual const char* name() const = 0;
virtual void setup(SharedGroup&) {}
virtual void teardown(SharedGroup&) {}
virtual void operator()(SharedGroup&) = 0;
};
struct AddTable : Benchmark {
const char* name() const { return "AddTable"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table(name());
t->add_column(type_String, "first");
t->add_column(type_Int, "second");
t->add_column(type_DateTime, "third");
tr.commit();
}
void teardown(SharedGroup& group)
{
Group& g = group.begin_write();
g.remove_table(name());
group.commit();
}
};
struct BenchmarkWithStringsTable : Benchmark {
void setup(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef t = tr.add_table("StringOnly");
t->add_column(type_String, "chars");
tr.commit();
}
void teardown(SharedGroup& group)
{
Group& g = group.begin_write();
g.remove_table("StringOnly");
group.commit();
}
};
struct BenchmarkWithStrings : BenchmarkWithStringsTable {
void setup(SharedGroup& group)
{
BenchmarkWithStringsTable::setup(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
t->add_empty_row(999);
for (size_t i = 0; i < 999; ++i) {
std::stringstream ss;
ss << rand();
t->set_string(0, i, ss.str());
}
tr.commit();
}
};
struct BenchmarkWithLongStrings : BenchmarkWithStrings {
void setup(SharedGroup& group)
{
BenchmarkWithStrings::setup(group);
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
t->insert_empty_row(0);
t->set_string(0, 0, "A really long string, longer than 63 bytes at least, I guess......");
tr.commit();
}
};
struct BenchmarkQuery : BenchmarkWithStrings {
const char* name() const { return "Query"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->find_all_string(0, "200");
}
};
struct BenchmarkSize : BenchmarkWithStrings {
const char* name() const { return "Size"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
volatile size_t dummy = table->size();
static_cast<void>(dummy);
}
};
struct BenchmarkSort : BenchmarkWithStrings {
const char* name() const { return "Sort"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
ConstTableView view = table->get_sorted_view(0);
}
};
struct BenchmarkInsert : BenchmarkWithStringsTable {
const char* name() const { return "Insert"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef t = tr.get_table("StringOnly");
for (size_t i = 0; i < 10000; ++i) {
t->add_empty_row();
t->set_string(0, i, "a");
}
tr.commit();
}
};
struct BenchmarkGetString : BenchmarkWithStrings {
const char* name() const { return "GetString"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
size_t len = table->size();
volatile int dummy = 0;
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(0, i);
dummy += str[0]; // to avoid over-optimization
}
}
};
struct BenchmarkSetString : BenchmarkWithStrings {
const char* name() const { return "SetString"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(0, i, "c");
}
tr.commit();
}
};
struct BenchmarkCreateIndex : BenchmarkWithStrings {
const char* name() const { return "CreateIndex"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
table->add_search_index(0);
tr.commit();
}
};
struct BenchmarkGetLongString : BenchmarkWithLongStrings {
const char* name() const { return "GetLongString"; }
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table("StringOnly");
size_t len = table->size();
volatile int dummy = 0;
for (size_t i = 0; i < len; ++i) {
StringData str = table->get_string(0, i);
dummy += str[0]; // to avoid over-optimization
}
}
};
struct BenchmarkSetLongString : BenchmarkWithLongStrings {
const char* name() const { return "SetLongString"; }
void operator()(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.get_table("StringOnly");
size_t len = table->size();
for (size_t i = 0; i < len; ++i) {
table->set_string(0, i, "c");
}
tr.commit();
}
};
struct BenchmarkQueryNot : Benchmark {
const char* name() const { return "QueryNot"; }
void setup(SharedGroup& group)
{
WriteTransaction tr(group);
TableRef table = tr.add_table(name());
table->add_column(type_Int, "first");
table->add_empty_row(1000);
for (size_t i = 0; i < 1000; ++i) {
table->set_int(0, i, 1);
}
tr.commit();
}
void operator()(SharedGroup& group)
{
ReadTransaction tr(group);
ConstTableRef table = tr.get_table(name());
Query q = table->where();
q.not_equal(0, 2); // never found, = worst case
TableView results = q.find_all();
results.size();
}
void teardown(SharedGroup& group)
{
Group& g = group.begin_write();
g.remove_table(name());
group.commit();
}
};
static const char* durability_level_to_cstr(SharedGroup::DurabilityLevel level)
{
switch (level) {
case SharedGroup::durability_Full: return "Full";
case SharedGroup::durability_MemOnly: return "MemOnly";
#ifndef _WIN32
case SharedGroup::durability_Async: return "Async";
#endif
}
}
void run_benchmark_once(Benchmark& benchmark, SharedGroup& sg, Timer& timer)
{
timer.pause();
benchmark.setup(sg);
timer.unpause();
benchmark(sg);
timer.pause();
benchmark.teardown(sg);
timer.unpause();
}
/// This little piece of likely over-engineering runs the benchmark a number of times,
/// with each durability setting, and reports the results for each run.
template <typename B>
void run_benchmark(BenchmarkResults& results)
{
#ifdef _WIN32
const size_t num_durabilities = 2;
#else
const size_t num_durabilities = 2; // FIXME Figure out how to run the async commit daemon.
#endif
Timer timer(Timer::type_UserTime);
for (size_t i = 0; i < num_durabilities; ++i) {
// Open a SharedGroup:
File::try_remove(realm_path);
std::unique_ptr<SharedGroup> group;
SharedGroup::DurabilityLevel level = static_cast<SharedGroup::DurabilityLevel>(i);
group.reset(new SharedGroup(realm_path, false, level));
B benchmark;
// Generate the benchmark result texts:
std::stringstream lead_text_ss;
std::stringstream ident_ss;
lead_text_ss << benchmark.name() << " (" << durability_level_to_cstr(level) << ")";
ident_ss << benchmark.name() << "_" << durability_level_to_cstr(level);
std::string ident = ident_ss.str();
// Warm-up and initial measuring:
Timer t_unused(Timer::type_UserTime);
run_benchmark_once(benchmark, *group, t_unused);
size_t rep;
double total = 0;
for (rep = 0; rep < max_repetitions && (rep < min_repetitions || total < min_duration_s); ++rep) {
Timer t;
run_benchmark_once(benchmark, *group, t);
double s = t.get_elapsed_time();
total += s;
results.submit(ident.c_str(), s);
}
results.finish(ident, lead_text_ss.str());
}
}
int main(int, const char**)
{
BenchmarkResults results(40);
run_benchmark<AddTable>(results);
run_benchmark<BenchmarkQuery>(results);
run_benchmark<BenchmarkQueryNot>(results);
run_benchmark<BenchmarkSize>(results);
run_benchmark<BenchmarkSort>(results);
run_benchmark<BenchmarkInsert>(results);
run_benchmark<BenchmarkGetString>(results);
run_benchmark<BenchmarkSetString>(results);
run_benchmark<BenchmarkCreateIndex>(results);
run_benchmark<BenchmarkGetLongString>(results);
run_benchmark<BenchmarkSetLongString>(results);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP
#define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/fun/typedefs.hpp>
#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>
#include <iostream>
#include <iterator>
#include <vector>
namespace stan {
namespace math {
namespace internal {
template <typename ReduceFunction, typename ReturnType, typename M,
typename... Args>
struct reduce_sum_impl<ReduceFunction, require_var_t<ReturnType>, ReturnType, M,
Args...> {
struct recursive_reducer {
size_t num_terms_;
const std::vector<M>& vmapped_;
std::tuple<const Args&...> args_tuple_;
double sum_;
Eigen::VectorXd args_adjoints_;
recursive_reducer(size_t num_terms, const std::vector<M>& vmapped,
const Args&... args)
: num_terms_(num_terms),
vmapped_(vmapped),
args_tuple_(args...),
sum_(0.0),
args_adjoints_(Eigen::VectorXd::Zero(num_terms)) {}
recursive_reducer(recursive_reducer& other, tbb::split)
: num_terms_(other.num_terms_),
vmapped_(other.vmapped_),
args_tuple_(other.args_tuple_),
sum_(other.sum_),
args_adjoints_(other.args_adjoints_) {}
template <typename T>
T& deep_copy(T& arg) {
return arg;
}
var deep_copy(const var& arg) { return var(arg.val()); }
std::vector<var> deep_copy(const std::vector<var>& arg) {
std::vector<var> copy(arg.size());
for (size_t i = 0; i < arg.size(); ++i) {
copy[i] = arg[i].val();
}
return copy;
}
template <int RowType, int ColType>
Eigen::Matrix<var, RowType, ColType> deep_copy(
const Eigen::Matrix<var, RowType, ColType>& arg) {
Eigen::Matrix<var, RowType, ColType> copy(arg.size());
for (size_t i = 0; i < arg.size(); ++i) {
copy(i) = arg(i).val();
}
return copy;
}
template <typename... Pargs>
void accumulate_adjoints(double* dest, const var& x, const Pargs&... args) {
*dest += x.adj();
accumulate_adjoints(dest + 1, args...);
}
// Works with anything that has operator[Integral] defined
template <typename... Pargs, typename Vec, require_vector_like_vt<is_var, Vec>...>
void accumulate_adjoints(double* dest, const Vec& x,
const Pargs&... args) {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] += x[i].adj();
}
accumulate_adjoints(dest + x.size(), args...);
}
// Fails to compile if type T does not have member operator(Integral)
template <typename T>
using operator_paren_access_t = decltype(std::declval<T>()(int{}));
// Works on anything with a operator()
template <typename... Pargs, typename Mat, require_t<is_detected<Mat, operator_paren_access_t>>...,
require_t<is_var<value_type_t<Mat>>>...>
void accumulate_adjoints(double* dest,
const Mat& x,
const Pargs&... args) {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] += x(i).adj();
}
accumulate_adjoints(dest + x.size(), args...);
}
// Anything with a scalar type of Arithmetic gets tossed
template <typename Arith, require_arithmetic_t<scalar_type_t<Arith>>..., typename... Pargs>
void accumulate_adjoints(double* dest, Arith&& x, const Pargs&... args) {
accumulate_adjoints(dest, args...);
}
void accumulate_adjoints(double*) {}
void operator()(const tbb::blocked_range<size_t>& r) {
if (r.empty())
return;
auto start = vmapped_.begin();
std::advance(start, r.begin());
auto end = vmapped_.begin();
std::advance(end, r.end());
const std::vector<M> sub_slice(start, end);
try {
start_nested();
// create a deep copy of all var's so that these are not
// linked to any outer AD tree
auto args_tuple_local_copy = apply(
[&](auto&&... args) { return std::make_tuple(deep_copy(args)...); },
args_tuple_);
var sub_sum_v = apply(
[&](auto&&... args) {
return ReduceFunction()(r.begin(), r.end() - 1, sub_slice,
args...);
},
args_tuple_local_copy);
sub_sum_v.grad();
sum_ += sub_sum_v.val();
// This should accumulate the adjoints from args_tuple_local_copy into
// the memory of args_adjoints_
apply(
[&](auto&&... args) {
accumulate_adjoints(args_adjoints_.data(), args...);
},
args_tuple_local_copy);
} catch (const std::exception& e) {
recover_memory_nested();
throw;
}
recover_memory_nested();
}
void join(const recursive_reducer& rhs) {
sum_ += rhs.sum_;
args_adjoints_ += rhs.args_adjoints_;
}
};
// Fails to compile if type T does not have callable member size()
template <typename T>
using member_size_t = decltype(std::declval<T>().size());
// TODO(Steve): add requires for generic containers
template <typename Container,
require_t<is_detected<Container, member_size_t>>...,
require_t<is_var<value_type_t<Container>>>..., typename... Pargs>
size_t count_var_impl(size_t count, const Container& x,
const Pargs&... args) const {
return count_var_impl(count + x.size(), args...);
}
template <typename Container,
require_t<is_detected<Container, member_size_t>>...,
require_t<std::is_arithmetic<value_type_t<Container>>>...,
typename... Pargs>
size_t count_var_impl(size_t count, const Container& x,
const Pargs&... args) const {
return count_var_impl(count, args...);
}
template <typename... Pargs>
size_t count_var_impl(size_t count, const var& x,
const Pargs&... args) const {
return count_var_impl(count + 1, args...);
}
template <typename... Pargs, typename Arith, require_arithmetic_t<Arith>...>
size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const {
return count_var_impl(count, args...);
}
size_t count_var_impl(size_t count) const { return count; }
/**
* Count the number of scalars of type T in the input argument list
*
* @tparam Pargs Types of input arguments
* @return Number of scalars of type T in input
*/
template <typename... Pargs>
size_t count_var(const Pargs&... args) const {
return count_var_impl(0, args...);
}
template <typename... Pargs>
void save_varis(vari** dest, const var& x, const Pargs&... args) const {
*dest = x.vi_;
save_varis(dest + 1, args...);
}
template <typename... Pargs>
void save_varis(vari** dest, const std::vector<var>& x,
const Pargs&... args) const {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] = x[i].vi_;
}
save_varis(dest + x.size(), args...);
}
template <typename... Pargs, int RowType, int ColType>
void save_varis(vari** dest, const Eigen::Matrix<var, RowType, ColType>& x,
const Pargs&... args) const {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] = x(i).vi_;
}
save_varis(dest + x.size(), args...);
}
template <typename R, typename... Pargs>
void save_varis(vari** dest, const R& x, const Pargs&... args) const {
save_varis(dest, args...);
}
void save_varis(vari**) const {}
var operator()(const std::vector<M>& vmapped, std::size_t grainsize,
const Args&... args) const {
const std::size_t num_jobs = vmapped.size();
if (num_jobs == 0)
return var(0.0);
const std::size_t num_terms = count_var(args...);
recursive_reducer worker(num_terms, vmapped, args...);
#ifdef STAN_DETERMINISTIC
tbb::static_partitioner partitioner;
tbb::parallel_deterministic_reduce(
tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker,
partitioner);
#else
tbb::parallel_reduce(
tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
#endif
vari** varis
= ChainableStack::instance_->memalloc_.alloc_array<vari*>(num_terms);
double* partials
= ChainableStack::instance_->memalloc_.alloc_array<double>(num_terms);
save_varis(varis, args...);
for (size_t i = 0; i < num_terms; ++i) {
partials[i] = worker.args_adjoints_(i);
}
return var(new precomputed_gradients_vari(worker.sum_, num_terms, varis,
partials));
}
};
} // namespace internal
} // namespace math
} // namespace stan
#endif
<commit_msg>Catch arithmetics in count_var_impl<commit_after>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP
#define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/fun/typedefs.hpp>
#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>
#include <iostream>
#include <iterator>
#include <vector>
namespace stan {
namespace math {
namespace internal {
template <typename ReduceFunction, typename ReturnType, typename M,
typename... Args>
struct reduce_sum_impl<ReduceFunction, require_var_t<ReturnType>, ReturnType, M,
Args...> {
struct recursive_reducer {
size_t num_terms_;
const std::vector<M>& vmapped_;
std::tuple<const Args&...> args_tuple_;
double sum_;
Eigen::VectorXd args_adjoints_;
recursive_reducer(size_t num_terms, const std::vector<M>& vmapped,
const Args&... args)
: num_terms_(num_terms),
vmapped_(vmapped),
args_tuple_(args...),
sum_(0.0),
args_adjoints_(Eigen::VectorXd::Zero(num_terms)) {}
recursive_reducer(recursive_reducer& other, tbb::split)
: num_terms_(other.num_terms_),
vmapped_(other.vmapped_),
args_tuple_(other.args_tuple_),
sum_(other.sum_),
args_adjoints_(other.args_adjoints_) {}
template <typename T>
T& deep_copy(T& arg) {
return arg;
}
var deep_copy(const var& arg) { return var(arg.val()); }
std::vector<var> deep_copy(const std::vector<var>& arg) {
std::vector<var> copy(arg.size());
for (size_t i = 0; i < arg.size(); ++i) {
copy[i] = arg[i].val();
}
return copy;
}
template <int RowType, int ColType>
Eigen::Matrix<var, RowType, ColType> deep_copy(
const Eigen::Matrix<var, RowType, ColType>& arg) {
Eigen::Matrix<var, RowType, ColType> copy(arg.size());
for (size_t i = 0; i < arg.size(); ++i) {
copy(i) = arg(i).val();
}
return copy;
}
template <typename... Pargs>
void accumulate_adjoints(double* dest, const var& x, const Pargs&... args) {
*dest += x.adj();
accumulate_adjoints(dest + 1, args...);
}
// Works with anything that has operator[Integral] defined
template <typename... Pargs, typename Vec, require_vector_like_vt<is_var, Vec>...>
void accumulate_adjoints(double* dest, const Vec& x,
const Pargs&... args) {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] += x[i].adj();
}
accumulate_adjoints(dest + x.size(), args...);
}
// Fails to compile if type T does not have member operator(Integral)
template <typename T>
using operator_paren_access_t = decltype(std::declval<T>()(int{}));
// Works on anything with a operator()
template <typename... Pargs, typename Mat, require_t<is_detected<Mat, operator_paren_access_t>>...,
require_t<is_var<value_type_t<Mat>>>...>
void accumulate_adjoints(double* dest,
const Mat& x,
const Pargs&... args) {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] += x(i).adj();
}
accumulate_adjoints(dest + x.size(), args...);
}
// Anything with a scalar type of Arithmetic gets tossed
template <typename Arith, require_arithmetic_t<scalar_type_t<Arith>>..., typename... Pargs>
void accumulate_adjoints(double* dest, Arith&& x, const Pargs&... args) {
accumulate_adjoints(dest, args...);
}
void accumulate_adjoints(double*) {}
void operator()(const tbb::blocked_range<size_t>& r) {
if (r.empty())
return;
auto start = vmapped_.begin();
std::advance(start, r.begin());
auto end = vmapped_.begin();
std::advance(end, r.end());
const std::vector<M> sub_slice(start, end);
try {
start_nested();
// create a deep copy of all var's so that these are not
// linked to any outer AD tree
auto args_tuple_local_copy = apply(
[&](auto&&... args) { return std::make_tuple(deep_copy(args)...); },
args_tuple_);
var sub_sum_v = apply(
[&](auto&&... args) {
return ReduceFunction()(r.begin(), r.end() - 1, sub_slice,
args...);
},
args_tuple_local_copy);
sub_sum_v.grad();
sum_ += sub_sum_v.val();
// This should accumulate the adjoints from args_tuple_local_copy into
// the memory of args_adjoints_
apply(
[&](auto&&... args) {
accumulate_adjoints(args_adjoints_.data(), args...);
},
args_tuple_local_copy);
} catch (const std::exception& e) {
recover_memory_nested();
throw;
}
recover_memory_nested();
}
void join(const recursive_reducer& rhs) {
sum_ += rhs.sum_;
args_adjoints_ += rhs.args_adjoints_;
}
};
// Fails to compile if type T does not have callable member size()
template <typename T>
using member_size_t = decltype(std::declval<T>().size());
// TODO(Steve): add requires for generic containers
template <typename Container,
require_t<is_detected<Container, member_size_t>>...,
require_t<is_var<value_type_t<Container>>>..., typename... Pargs>
size_t count_var_impl(size_t count, const Container& x,
const Pargs&... args) const {
return count_var_impl(count + x.size(), args...);
}
template <typename Container,
require_t<is_detected<Container, member_size_t>>...,
require_t<std::is_arithmetic<value_type_t<Container>>>...,
typename... Pargs>
size_t count_var_impl(size_t count, const Container& x,
const Pargs&... args) const {
return count_var_impl(count, args...);
}
template <typename... Pargs>
size_t count_var_impl(size_t count, const var& x,
const Pargs&... args) const {
return count_var_impl(count + 1, args...);
}
template <typename... Pargs, typename Arith, require_arithmetic_t<scalar_type_t<Arith>>...>
size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const {
return count_var_impl(count, args...);
}
size_t count_var_impl(size_t count) const { return count; }
/**
* Count the number of scalars of type T in the input argument list
*
* @tparam Pargs Types of input arguments
* @return Number of scalars of type T in input
*/
template <typename... Pargs>
size_t count_var(const Pargs&... args) const {
return count_var_impl(0, args...);
}
template <typename... Pargs>
void save_varis(vari** dest, const var& x, const Pargs&... args) const {
*dest = x.vi_;
save_varis(dest + 1, args...);
}
template <typename... Pargs>
void save_varis(vari** dest, const std::vector<var>& x,
const Pargs&... args) const {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] = x[i].vi_;
}
save_varis(dest + x.size(), args...);
}
template <typename... Pargs, int RowType, int ColType>
void save_varis(vari** dest, const Eigen::Matrix<var, RowType, ColType>& x,
const Pargs&... args) const {
for (size_t i = 0; i < x.size(); ++i) {
dest[i] = x(i).vi_;
}
save_varis(dest + x.size(), args...);
}
template <typename R, typename... Pargs>
void save_varis(vari** dest, const R& x, const Pargs&... args) const {
save_varis(dest, args...);
}
void save_varis(vari**) const {}
var operator()(const std::vector<M>& vmapped, std::size_t grainsize,
const Args&... args) const {
const std::size_t num_jobs = vmapped.size();
if (num_jobs == 0)
return var(0.0);
const std::size_t num_terms = count_var(args...);
recursive_reducer worker(num_terms, vmapped, args...);
#ifdef STAN_DETERMINISTIC
tbb::static_partitioner partitioner;
tbb::parallel_deterministic_reduce(
tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker,
partitioner);
#else
tbb::parallel_reduce(
tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
#endif
vari** varis
= ChainableStack::instance_->memalloc_.alloc_array<vari*>(num_terms);
double* partials
= ChainableStack::instance_->memalloc_.alloc_array<double>(num_terms);
save_varis(varis, args...);
for (size_t i = 0; i < num_terms; ++i) {
partials[i] = worker.args_adjoints_(i);
}
return var(new precomputed_gradients_vari(worker.sum_, num_terms, varis,
partials));
}
};
} // namespace internal
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org>
#include <iostream>
#include <chrono>
#include "util.hpp"
#include "gl-api.hpp"
#include "teapot.h"
using namespace tinygizmo;
using namespace minalg;
const linalg::aliases::float4x4 identity4x4 = { { 1, 0, 0, 0 },{ 0, 1, 0, 0 },{ 0, 0, 1, 0 },{ 0, 0, 0, 1 } };
constexpr const char gizmo_vert[] = R"(#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 normal;
layout(location = 2) in vec4 color;
out vec4 v_color;
out vec3 v_world, v_normal;
uniform mat4 u_mvp;
void main()
{
gl_Position = u_mvp * vec4(vertex.xyz, 1);
v_color = color;
v_world = vertex;
v_normal = normal;
}
)";
constexpr const char gizmo_frag[] = R"(#version 330
in vec4 v_color;
in vec3 v_world, v_normal;
out vec4 f_color;
uniform vec3 u_eye;
void main()
{
vec3 light = vec3(1) * max(dot(v_normal, normalize(u_eye - v_world)), 0.50) + 0.25;
f_color = v_color * vec4(light, 1);
}
)";
constexpr const char lit_vert[] = R"(#version 330
uniform mat4 u_modelMatrix;
uniform mat4 u_viewProj;
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inNormal;
out vec3 v_position, v_normal;
void main()
{
vec4 worldPos = u_modelMatrix * vec4(inPosition, 1);
v_position = worldPos.xyz;
v_normal = normalize((u_modelMatrix * vec4(inNormal,0)).xyz);
gl_Position = u_viewProj * worldPos;
}
)";
constexpr const char lit_frag[] = R"(#version 330
uniform vec3 u_diffuse = vec3(1, 1, 1);
uniform vec3 u_eye;
in vec3 v_position;
in vec3 v_normal;
out vec4 f_color;
vec3 compute_lighting(vec3 eyeDir, vec3 position, vec3 color)
{
vec3 light = vec3(0, 0, 0);
vec3 lightDir = normalize(position - v_position);
light += color * u_diffuse * max(dot(v_normal, lightDir), 0);
vec3 halfDir = normalize(lightDir + eyeDir);
light += color * u_diffuse * pow(max(dot(v_normal, halfDir), 0), 128);
return light;
}
void main()
{
vec3 eyeDir = vec3(0, 1, -2);
vec3 light = vec3(0, 0, 0);
light += compute_lighting(eyeDir, vec3(+3, 1, 0), vec3(235.0/255.0, 43.0/255.0, 211.0/255.0));
light += compute_lighting(eyeDir, vec3(-3, 1, 0), vec3(43.0/255.0, 236.0/255.0, 234.0/255.0));
f_color = vec4(light + vec3(0.5, 0.5, 0.5), 1.0);
}
)";
//////////////////////////
// Main Application //
//////////////////////////
geometry_mesh make_teapot()
{
geometry_mesh mesh;
for (int i = 0; i < 4974; i+=6)
{
geometry_vertex v;
v.position = float3(teapot_vertices[i + 0], teapot_vertices[i + 1], teapot_vertices[i + 2]);
v.normal = float3(teapot_vertices[i + 3], teapot_vertices[i + 4], teapot_vertices[i + 5]);
mesh.vertices.push_back(v);
}
for (int i = 0; i < 4680; i+=3) mesh.triangles.push_back(uint3(teapot_triangles[i + 0], teapot_triangles[i + 1], teapot_triangles[i + 2]));
return mesh;
}
void draw_mesh(GlShader & shader, GlMesh & mesh, const linalg::aliases::float3 eye, const linalg::aliases::float4x4 & viewProj, const linalg::aliases::float4x4 & model)
{
linalg::aliases::float4x4 modelViewProjectionMatrix = mul(viewProj, model);
shader.bind();
shader.uniform("u_mvp", modelViewProjectionMatrix);
shader.uniform("u_eye", eye);
mesh.draw_elements();
shader.unbind();
}
void draw_lit_mesh(GlShader & shader, GlMesh & mesh, const linalg::aliases::float3 eye, const linalg::aliases::float4x4 & viewProj, const linalg::aliases::float4x4 & model)
{
shader.bind();
shader.uniform("u_viewProj", viewProj);
shader.uniform("u_modelMatrix", model);
shader.uniform("u_eye", eye);
mesh.draw_elements();
shader.unbind();
}
void upload_mesh(const geometry_mesh & cpu, GlMesh & gpu)
{
const auto & verts = reinterpret_cast<const std::vector<linalg::aliases::float3> &>(cpu.vertices);
const auto & tris = reinterpret_cast<const std::vector<linalg::aliases::uint3> &>(cpu.triangles);
gpu.set_vertices(verts, GL_DYNAMIC_DRAW);
gpu.set_attribute(0, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, position));
gpu.set_attribute(1, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, normal));
gpu.set_attribute(2, 4, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, color));
gpu.set_elements(tris, GL_DYNAMIC_DRAW);
}
std::unique_ptr<Window> win;
int main(int argc, char * argv[])
{
bool ml = 0, mr = 0, bf = 0, bl = 0, bb = 0, br = 0;
camera cam = {};
cam.yfov = 1.0f;
cam.near_clip = 0.01f;
cam.far_clip = 32.0f;
cam.position = { 0,1.5f,4 };
gizmo_application_state gizmo_state;
gizmo_context gizmo_ctx;
try
{
win.reset(new Window(1280, 800, "tiny-gizmo-example-app"));
glfwSwapInterval(1);
}
catch (const std::exception & e)
{
std::cout << "Caught GLFW window exception: " << e.what() << std::endl;
}
auto windowSize = win->get_window_size();
GlShader wireframeShader, litShader;
GlMesh gizmoEditorMesh, teapotMesh;
wireframeShader = GlShader(gizmo_vert, gizmo_frag);
litShader = GlShader(lit_vert, lit_frag);
geometry_mesh teapot = make_teapot();
upload_mesh(teapot, teapotMesh);
gizmo_ctx.render = [&](const geometry_mesh & r)
{
upload_mesh(r, gizmoEditorMesh);
draw_mesh(wireframeShader, gizmoEditorMesh, cam.position, cam.get_viewproj_matrix((float) windowSize.x / (float) windowSize.y), identity4x4);
};
win->on_key = [&](int key, int action, int mods)
{
if (key == GLFW_KEY_LEFT_CONTROL) gizmo_state.hotkey_ctrl = (action != GLFW_RELEASE);
if (key == GLFW_KEY_L) gizmo_state.hotkey_local = (action != GLFW_RELEASE);
if (key == GLFW_KEY_T) gizmo_state.hotkey_translate = (action != GLFW_RELEASE);
if (key == GLFW_KEY_R) gizmo_state.hotkey_rotate = (action != GLFW_RELEASE);
if (key == GLFW_KEY_S) gizmo_state.hotkey_scale = (action != GLFW_RELEASE);
if (key == GLFW_KEY_W) bf = (action != GLFW_RELEASE);
if (key == GLFW_KEY_A) bl = (action != GLFW_RELEASE);
if (key == GLFW_KEY_S) bb = (action != GLFW_RELEASE);
if (key == GLFW_KEY_D) br = (action != GLFW_RELEASE);
if (key == GLFW_KEY_ESCAPE) win->close();
};
win->on_mouse_button = [&](int button, int action, int mods)
{
gizmo_state.mouse_left = (action != GLFW_RELEASE);
if (button == GLFW_MOUSE_BUTTON_LEFT) ml = (action != GLFW_RELEASE);
if (button == GLFW_MOUSE_BUTTON_RIGHT) mr = (action != GLFW_RELEASE);
};
minalg::float2 lastCursor;
win->on_cursor_pos = [&](linalg::aliases::float2 position)
{
gizmo_state.cursor = minalg::float2(position.x, position.y);
auto deltaCursorMotion = gizmo_state.cursor - lastCursor;
if (mr)
{
cam.yaw -= deltaCursorMotion.x * 0.01f;
cam.pitch -= deltaCursorMotion.y * 0.01f;
}
lastCursor = gizmo_state.cursor;
};
rigid_transform xform_a;
xform_a.position = { -2, 0, 0 };
rigid_transform xform_b;
xform_b.position = { +2, 0, 0 };
auto t0 = std::chrono::high_resolution_clock::now();
while (!win->should_close())
{
glfwPollEvents();
auto t1 = std::chrono::high_resolution_clock::now();
float timestep = std::chrono::duration<float>(t1 - t0).count();
t0 = t1;
if (mr)
{
const linalg::aliases::float4 orientation = cam.get_orientation();
linalg::aliases::float3 move;
if (bf) move -= qzdir(orientation);
if (bl) move -= qxdir(orientation);
if (bb) move += qzdir(orientation);
if (br) move += qxdir(orientation);
if (length2(move) > 0) cam.position += normalize(move) * (timestep * 10);
}
glViewport(0, 0, windowSize.x, windowSize.y);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.725f, 0.725f, 0.725f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto cameraOrientation = cam.get_orientation();
// Gizmo input interaction state populated via win->on_input(...) callback above. Update app parameters:
gizmo_state.viewport_size = minalg::float2(windowSize.x, windowSize.y);
gizmo_state.cam.near_clip = cam.near_clip;
gizmo_state.cam.far_clip = cam.far_clip;
gizmo_state.cam.yfov = cam.yfov;
gizmo_state.cam.position = minalg::float3(cam.position.x, cam.position.y, cam.position.z);
gizmo_state.cam.orientation = minalg::float4(cameraOrientation.x, cameraOrientation.y, cameraOrientation.z, cameraOrientation.w);
// gizmo_state.screenspace_scale = 80.f; // optional flag to draw the gizmos at a constant screen-space scale
glDisable(GL_CULL_FACE);
auto teapotModelMatrix_a = reinterpret_cast<const linalg::aliases::float4x4 &>(xform_a.matrix());
draw_lit_mesh(litShader, teapotMesh, cam.position, cam.get_viewproj_matrix((float)windowSize.x / (float)windowSize.y), teapotModelMatrix_a);
auto teapotModelMatrix_b = reinterpret_cast<const linalg::aliases::float4x4 &>(xform_b.matrix());
draw_lit_mesh(litShader, teapotMesh, cam.position, cam.get_viewproj_matrix((float)windowSize.x / (float)windowSize.y), teapotModelMatrix_b);
glClear(GL_DEPTH_BUFFER_BIT);
gizmo_ctx.update(gizmo_state);
transform_gizmo("first-example-gizmo", gizmo_ctx, xform_a);
transform_gizmo("second-example-gizmo", gizmo_ctx, xform_b);
gizmo_ctx.draw();
gl_check_error(__FILE__, __LINE__);
win->swap_buffers();
}
return EXIT_SUCCESS;
}
<commit_msg>example project indicates the active state of a gizmo and shows how (alongside rigid_transform inquality) we can now implement higher-level features like undo/redo<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org>
#include <iostream>
#include <chrono>
#include "util.hpp"
#include "gl-api.hpp"
#include "teapot.h"
using namespace tinygizmo;
using namespace minalg;
static inline uint64_t get_local_time_ns()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
}
const linalg::aliases::float4x4 identity4x4 = { { 1, 0, 0, 0 },{ 0, 1, 0, 0 },{ 0, 0, 1, 0 },{ 0, 0, 0, 1 } };
constexpr const char gizmo_vert[] = R"(#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 normal;
layout(location = 2) in vec4 color;
out vec4 v_color;
out vec3 v_world, v_normal;
uniform mat4 u_mvp;
void main()
{
gl_Position = u_mvp * vec4(vertex.xyz, 1);
v_color = color;
v_world = vertex;
v_normal = normal;
}
)";
constexpr const char gizmo_frag[] = R"(#version 330
in vec4 v_color;
in vec3 v_world, v_normal;
out vec4 f_color;
uniform vec3 u_eye;
void main()
{
vec3 light = vec3(1) * max(dot(v_normal, normalize(u_eye - v_world)), 0.50) + 0.25;
f_color = v_color * vec4(light, 1);
}
)";
constexpr const char lit_vert[] = R"(#version 330
uniform mat4 u_modelMatrix;
uniform mat4 u_viewProj;
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inNormal;
out vec3 v_position, v_normal;
void main()
{
vec4 worldPos = u_modelMatrix * vec4(inPosition, 1);
v_position = worldPos.xyz;
v_normal = normalize((u_modelMatrix * vec4(inNormal,0)).xyz);
gl_Position = u_viewProj * worldPos;
}
)";
constexpr const char lit_frag[] = R"(#version 330
uniform vec3 u_diffuse = vec3(1, 1, 1);
uniform vec3 u_eye;
in vec3 v_position;
in vec3 v_normal;
out vec4 f_color;
vec3 compute_lighting(vec3 eyeDir, vec3 position, vec3 color)
{
vec3 light = vec3(0, 0, 0);
vec3 lightDir = normalize(position - v_position);
light += color * u_diffuse * max(dot(v_normal, lightDir), 0);
vec3 halfDir = normalize(lightDir + eyeDir);
light += color * u_diffuse * pow(max(dot(v_normal, halfDir), 0), 128);
return light;
}
void main()
{
vec3 eyeDir = vec3(0, 1, -2);
vec3 light = vec3(0, 0, 0);
light += compute_lighting(eyeDir, vec3(+3, 1, 0), vec3(235.0/255.0, 43.0/255.0, 211.0/255.0));
light += compute_lighting(eyeDir, vec3(-3, 1, 0), vec3(43.0/255.0, 236.0/255.0, 234.0/255.0));
f_color = vec4(light + vec3(0.5, 0.5, 0.5), 1.0);
}
)";
//////////////////////////
// Main Application //
//////////////////////////
geometry_mesh make_teapot()
{
geometry_mesh mesh;
for (int i = 0; i < 4974; i+=6)
{
geometry_vertex v;
v.position = float3(teapot_vertices[i + 0], teapot_vertices[i + 1], teapot_vertices[i + 2]);
v.normal = float3(teapot_vertices[i + 3], teapot_vertices[i + 4], teapot_vertices[i + 5]);
mesh.vertices.push_back(v);
}
for (int i = 0; i < 4680; i+=3) mesh.triangles.push_back(uint3(teapot_triangles[i + 0], teapot_triangles[i + 1], teapot_triangles[i + 2]));
return mesh;
}
void draw_mesh(GlShader & shader, GlMesh & mesh, const linalg::aliases::float3 eye, const linalg::aliases::float4x4 & viewProj, const linalg::aliases::float4x4 & model)
{
linalg::aliases::float4x4 modelViewProjectionMatrix = mul(viewProj, model);
shader.bind();
shader.uniform("u_mvp", modelViewProjectionMatrix);
shader.uniform("u_eye", eye);
mesh.draw_elements();
shader.unbind();
}
void draw_lit_mesh(GlShader & shader, GlMesh & mesh, const linalg::aliases::float3 eye, const linalg::aliases::float4x4 & viewProj, const linalg::aliases::float4x4 & model)
{
shader.bind();
shader.uniform("u_viewProj", viewProj);
shader.uniform("u_modelMatrix", model);
shader.uniform("u_eye", eye);
mesh.draw_elements();
shader.unbind();
}
void upload_mesh(const geometry_mesh & cpu, GlMesh & gpu)
{
const auto & verts = reinterpret_cast<const std::vector<linalg::aliases::float3> &>(cpu.vertices);
const auto & tris = reinterpret_cast<const std::vector<linalg::aliases::uint3> &>(cpu.triangles);
gpu.set_vertices(verts, GL_DYNAMIC_DRAW);
gpu.set_attribute(0, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, position));
gpu.set_attribute(1, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, normal));
gpu.set_attribute(2, 4, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, color));
gpu.set_elements(tris, GL_DYNAMIC_DRAW);
}
std::unique_ptr<Window> win;
int main(int argc, char * argv[])
{
bool ml = 0, mr = 0, bf = 0, bl = 0, bb = 0, br = 0;
camera cam = {};
cam.yfov = 1.0f;
cam.near_clip = 0.01f;
cam.far_clip = 32.0f;
cam.position = { 0,1.5f,4 };
gizmo_application_state gizmo_state;
gizmo_context gizmo_ctx;
try
{
win.reset(new Window(1280, 800, "tiny-gizmo-example-app"));
glfwSwapInterval(1);
}
catch (const std::exception & e)
{
std::cout << "Caught GLFW window exception: " << e.what() << std::endl;
}
auto windowSize = win->get_window_size();
GlShader wireframeShader, litShader;
GlMesh gizmoEditorMesh, teapotMesh;
wireframeShader = GlShader(gizmo_vert, gizmo_frag);
litShader = GlShader(lit_vert, lit_frag);
geometry_mesh teapot = make_teapot();
upload_mesh(teapot, teapotMesh);
gizmo_ctx.render = [&](const geometry_mesh & r)
{
upload_mesh(r, gizmoEditorMesh);
draw_mesh(wireframeShader, gizmoEditorMesh, cam.position, cam.get_viewproj_matrix((float) windowSize.x / (float) windowSize.y), identity4x4);
};
win->on_key = [&](int key, int action, int mods)
{
if (key == GLFW_KEY_LEFT_CONTROL) gizmo_state.hotkey_ctrl = (action != GLFW_RELEASE);
if (key == GLFW_KEY_L) gizmo_state.hotkey_local = (action != GLFW_RELEASE);
if (key == GLFW_KEY_T) gizmo_state.hotkey_translate = (action != GLFW_RELEASE);
if (key == GLFW_KEY_R) gizmo_state.hotkey_rotate = (action != GLFW_RELEASE);
if (key == GLFW_KEY_S) gizmo_state.hotkey_scale = (action != GLFW_RELEASE);
if (key == GLFW_KEY_W) bf = (action != GLFW_RELEASE);
if (key == GLFW_KEY_A) bl = (action != GLFW_RELEASE);
if (key == GLFW_KEY_S) bb = (action != GLFW_RELEASE);
if (key == GLFW_KEY_D) br = (action != GLFW_RELEASE);
if (key == GLFW_KEY_ESCAPE) win->close();
};
win->on_mouse_button = [&](int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_LEFT) gizmo_state.mouse_left = (action != GLFW_RELEASE);
if (button == GLFW_MOUSE_BUTTON_LEFT) ml = (action != GLFW_RELEASE);
if (button == GLFW_MOUSE_BUTTON_RIGHT) mr = (action != GLFW_RELEASE);
};
minalg::float2 lastCursor;
win->on_cursor_pos = [&](linalg::aliases::float2 position)
{
gizmo_state.cursor = minalg::float2(position.x, position.y);
auto deltaCursorMotion = gizmo_state.cursor - lastCursor;
if (mr)
{
cam.yaw -= deltaCursorMotion.x * 0.01f;
cam.pitch -= deltaCursorMotion.y * 0.01f;
}
lastCursor = gizmo_state.cursor;
};
rigid_transform xform_a;
xform_a.position = { -2, 0, 0 };
rigid_transform xform_a_last;
rigid_transform xform_b;
xform_b.position = { +2, 0, 0 };
auto t0 = std::chrono::high_resolution_clock::now();
while (!win->should_close())
{
glfwPollEvents();
auto t1 = std::chrono::high_resolution_clock::now();
float timestep = std::chrono::duration<float>(t1 - t0).count();
t0 = t1;
if (mr)
{
const linalg::aliases::float4 orientation = cam.get_orientation();
linalg::aliases::float3 move;
if (bf) move -= qzdir(orientation);
if (bl) move -= qxdir(orientation);
if (bb) move += qzdir(orientation);
if (br) move += qxdir(orientation);
if (length2(move) > 0) cam.position += normalize(move) * (timestep * 10);
}
glViewport(0, 0, windowSize.x, windowSize.y);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.725f, 0.725f, 0.725f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto cameraOrientation = cam.get_orientation();
// Gizmo input interaction state populated via win->on_input(...) callback above. Update app parameters:
gizmo_state.viewport_size = minalg::float2(windowSize.x, windowSize.y);
gizmo_state.cam.near_clip = cam.near_clip;
gizmo_state.cam.far_clip = cam.far_clip;
gizmo_state.cam.yfov = cam.yfov;
gizmo_state.cam.position = minalg::float3(cam.position.x, cam.position.y, cam.position.z);
gizmo_state.cam.orientation = minalg::float4(cameraOrientation.x, cameraOrientation.y, cameraOrientation.z, cameraOrientation.w);
//gizmo_state.screenspace_scale = 80.f; // optional flag to draw the gizmos at a constant screen-space scale
glDisable(GL_CULL_FACE);
auto teapotModelMatrix_a = reinterpret_cast<const linalg::aliases::float4x4 &>(xform_a.matrix());
draw_lit_mesh(litShader, teapotMesh, cam.position, cam.get_viewproj_matrix((float)windowSize.x / (float)windowSize.y), teapotModelMatrix_a);
auto teapotModelMatrix_b = reinterpret_cast<const linalg::aliases::float4x4 &>(xform_b.matrix());
draw_lit_mesh(litShader, teapotMesh, cam.position, cam.get_viewproj_matrix((float)windowSize.x / (float)windowSize.y), teapotModelMatrix_b);
glClear(GL_DEPTH_BUFFER_BIT);
gizmo_ctx.update(gizmo_state);
if (transform_gizmo("first-example-gizmo", gizmo_ctx, xform_a))
{
std::cout << get_local_time_ns() << " - " << "First Gizmo Hovered..." << std::endl;
if (xform_a != xform_a_last) std::cout << get_local_time_ns() << " - " << "First Gizmo Changed..." << std::endl;
xform_a_last = xform_a;
}
transform_gizmo("second-example-gizmo", gizmo_ctx, xform_b);
gizmo_ctx.draw();
gl_check_error(__FILE__, __LINE__);
win->swap_buffers();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// ================================================================================
// == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
// == See tb_core.h for more information. ==
// ================================================================================
#include "tb_tab_container.h"
#include <assert.h>
namespace tb {
// == TBTabLayout =======================================================================
void TBTabLayout::OnChildAdded(TBWidget *child)
{
if (TBButton *button = TBSafeCast<TBButton>(child))
{
button->SetSqueezable(true);
button->SetSkinBg(TBIDC("TBTabContainer.tab"));
button->SetID(TBIDC("tab"));
}
}
PreferredSize TBTabLayout::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
{
PreferredSize ps = TBLayout::OnCalculatePreferredContentSize(constraints);
// Make sure the number of tabs doesn't grow parents.
// It is only the content that should do that. The tabs
// will scroll anyway.
if (GetAxis() == AXIS_X)
ps.min_w = MIN(ps.min_w, 1);
else
ps.min_h = MIN(ps.min_h, 1);
return ps;
}
// == TBTabContainer ====================================================================
TBTabContainer::TBTabContainer()
: m_need_page_update(true)
, m_current_page(-1)
, m_align(TB_ALIGN_TOP)
{
AddChild(&m_root_layout);
// Put the tab layout on top of the content in Z order so their skin can make
// a seamless overlap over the border. Control which side they are layouted
// to by calling SetLayoutOrder.
m_root_layout.AddChild(&m_content_root);
m_root_layout.AddChild(&m_tab_layout);
m_root_layout.SetAxis(AXIS_Y);
m_root_layout.SetGravity(WIDGET_GRAVITY_ALL);
m_root_layout.SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
m_root_layout.SetLayoutOrder(LAYOUT_ORDER_TOP_TO_BOTTOM);
m_root_layout.SetSkinBg(TBIDC("TBTabContainer.rootlayout"));
m_tab_layout.SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION_CENTER);
m_tab_layout.SetSkinBg(TBIDC("TBTabContainer.tablayout_x"));
m_tab_layout.SetLayoutPosition(LAYOUT_POSITION_RIGHT_BOTTOM);
m_content_root.SetGravity(WIDGET_GRAVITY_ALL);
m_content_root.SetSkinBg(TBIDC("TBTabContainer.container"));
}
TBTabContainer::~TBTabContainer()
{
m_root_layout.RemoveChild(&m_content_root);
m_root_layout.RemoveChild(&m_tab_layout);
RemoveChild(&m_root_layout);
}
void TBTabContainer::SetAxis(AXIS axis)
{
m_root_layout.SetAxis(axis);
m_tab_layout.SetAxis(axis == AXIS_X ? AXIS_Y : AXIS_X);
m_tab_layout.SetSkinBg(axis == AXIS_X ? TBIDC("TBTabContainer.tablayout_y") :
TBIDC("TBTabContainer.tablayout_x"));
}
void TBTabContainer::SetValue(int index)
{
if (index == m_current_page || !GetNumPages())
return;
m_current_page = index;
// Update the pages visibility and tabs pressed value.
index = 0;
TBWidget *page = m_content_root.GetFirstChild();
TBWidget *tab = m_tab_layout.GetFirstChild();
for ( ; page && tab; page = page->GetNext(), tab = tab->GetNext(), index++)
{
bool active = index == m_current_page;
page->SetVisibilility(active ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_INVISIBLE);
tab->SetValue(active ? 1 : 0);
}
TBWidgetEvent ev(EVENT_TYPE_TAB_CHANGED);
InvokeEvent(ev);
}
int TBTabContainer::GetNumPages()
{
int count = 0;
for (TBWidget *tab = m_tab_layout.GetFirstChild(); tab; tab = tab->GetNext())
count++;
if (!count)
m_current_page = -1;
return count;
}
TBWidget *TBTabContainer::GetCurrentPageWidget() const
{
if (m_current_page == -1)
return nullptr;
return m_content_root.GetChildFromIndex(m_current_page);
}
void TBTabContainer::SetAlignment(TB_ALIGN align)
{
bool horizontal = (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM);
bool reverse = (align == TB_ALIGN_TOP || align == TB_ALIGN_LEFT);
SetAxis(horizontal ? AXIS_Y : AXIS_X);
m_root_layout.SetLayoutOrder(reverse ? LAYOUT_ORDER_TOP_TO_BOTTOM : LAYOUT_ORDER_BOTTOM_TO_TOP);
m_tab_layout.SetLayoutPosition(reverse ? LAYOUT_POSITION_RIGHT_BOTTOM : LAYOUT_POSITION_LEFT_TOP);
m_align = align;
}
bool TBTabContainer::OnEvent(const TBWidgetEvent &ev)
{
if ((ev.type == EVENT_TYPE_CLICK || ev.type == EVENT_TYPE_POINTER_DOWN) &&
ev.target->GetID() == TBIDC("tab") &&
ev.target->GetParent() == &m_tab_layout)
{
int clicked_index = m_tab_layout.GetIndexFromChild(ev.target);
SetValue(clicked_index);
return true;
}
return false;
}
void TBTabContainer::OnProcess()
{
if (m_need_page_update)
{
m_need_page_update = false;
// Force update value
int current_page = m_current_page;
m_current_page = -1;
SetValue(current_page);
}
}
}; // namespace tb
<commit_msg>Fix for UITabContainer<commit_after>// ================================================================================
// == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
// == See tb_core.h for more information. ==
// ================================================================================
#include "tb_tab_container.h"
#include <assert.h>
namespace tb {
// == TBTabLayout =======================================================================
void TBTabLayout::OnChildAdded(TBWidget *child)
{
if (TBButton *button = TBSafeCast<TBButton>(child))
{
button->SetSqueezable(true);
button->SetSkinBg(TBIDC("TBTabContainer.tab"));
button->SetID(TBIDC("tab"));
}
}
PreferredSize TBTabLayout::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
{
PreferredSize ps = TBLayout::OnCalculatePreferredContentSize(constraints);
// Make sure the number of tabs doesn't grow parents.
// It is only the content that should do that. The tabs
// will scroll anyway.
if (GetAxis() == AXIS_X)
ps.min_w = MIN(ps.min_w, 1);
else
ps.min_h = MIN(ps.min_h, 1);
return ps;
}
// == TBTabContainer ====================================================================
TBTabContainer::TBTabContainer()
: m_need_page_update(true)
, m_current_page(-1)
, m_align(TB_ALIGN_TOP)
{
AddChild(&m_root_layout);
// Put the tab layout on top of the content in Z order so their skin can make
// a seamless overlap over the border. Control which side they are layouted
// to by calling SetLayoutOrder.
m_root_layout.AddChild(&m_content_root);
m_root_layout.AddChild(&m_tab_layout);
m_root_layout.SetAxis(AXIS_Y);
m_root_layout.SetGravity(WIDGET_GRAVITY_ALL);
m_root_layout.SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
m_root_layout.SetLayoutOrder(LAYOUT_ORDER_TOP_TO_BOTTOM);
m_root_layout.SetSkinBg(TBIDC("TBTabContainer.rootlayout"));
m_root_layout.SetID("root_layout");
m_tab_layout.SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION_CENTER);
m_tab_layout.SetSkinBg(TBIDC("TBTabContainer.tablayout_x"));
m_tab_layout.SetLayoutPosition(LAYOUT_POSITION_RIGHT_BOTTOM);
m_tab_layout.SetID("tab_layout");
m_content_root.SetGravity(WIDGET_GRAVITY_ALL);
m_content_root.SetSkinBg(TBIDC("TBTabContainer.container"));
m_content_root.SetID("content_root");
}
TBTabContainer::~TBTabContainer()
{
m_root_layout.RemoveChild(&m_content_root);
m_root_layout.RemoveChild(&m_tab_layout);
RemoveChild(&m_root_layout);
}
void TBTabContainer::SetAxis(AXIS axis)
{
m_root_layout.SetAxis(axis);
m_tab_layout.SetAxis(axis == AXIS_X ? AXIS_Y : AXIS_X);
m_tab_layout.SetSkinBg(axis == AXIS_X ? TBIDC("TBTabContainer.tablayout_y") :
TBIDC("TBTabContainer.tablayout_x"));
}
void TBTabContainer::SetValue(int index)
{
if (index == m_current_page || !GetNumPages())
return;
m_current_page = index;
// Update the pages visibility and tabs pressed value.
index = 0;
TBWidget *page = m_content_root.GetFirstChild();
TBWidget *tab = m_tab_layout.GetFirstChild();
for ( ; page && tab; page = page->GetNext(), tab = tab->GetNext(), index++)
{
bool active = index == m_current_page;
page->SetVisibilility(active ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_INVISIBLE);
tab->SetValue(active ? 1 : 0);
if (active)
{
// m_content_root is a widget and not a layout, so ensure page
// is sized correctly (ie. takes up full content rect)
TBRect rect = m_content_root.GetRect();
page->SetRect(TBRect(0, 0, rect.w, rect.h));
}
}
TBWidgetEvent ev(EVENT_TYPE_TAB_CHANGED);
InvokeEvent(ev);
}
int TBTabContainer::GetNumPages()
{
int count = 0;
for (TBWidget *tab = m_tab_layout.GetFirstChild(); tab; tab = tab->GetNext())
count++;
if (!count)
m_current_page = -1;
return count;
}
TBWidget *TBTabContainer::GetCurrentPageWidget() const
{
if (m_current_page == -1)
return nullptr;
return m_content_root.GetChildFromIndex(m_current_page);
}
void TBTabContainer::SetAlignment(TB_ALIGN align)
{
bool horizontal = (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM);
bool reverse = (align == TB_ALIGN_TOP || align == TB_ALIGN_LEFT);
SetAxis(horizontal ? AXIS_Y : AXIS_X);
m_root_layout.SetLayoutOrder(reverse ? LAYOUT_ORDER_TOP_TO_BOTTOM : LAYOUT_ORDER_BOTTOM_TO_TOP);
m_tab_layout.SetLayoutPosition(reverse ? LAYOUT_POSITION_RIGHT_BOTTOM : LAYOUT_POSITION_LEFT_TOP);
m_align = align;
}
bool TBTabContainer::OnEvent(const TBWidgetEvent &ev)
{
if ((ev.type == EVENT_TYPE_CLICK || ev.type == EVENT_TYPE_POINTER_DOWN) &&
ev.target->GetID() == TBIDC("tab") &&
ev.target->GetParent() == &m_tab_layout)
{
int clicked_index = m_tab_layout.GetIndexFromChild(ev.target);
SetValue(clicked_index);
return true;
}
return false;
}
void TBTabContainer::OnProcess()
{
if (m_need_page_update)
{
m_need_page_update = false;
// Force update value
int current_page = m_current_page;
m_current_page = -1;
SetValue(current_page);
}
}
}; // namespace tb
<|endoftext|> |
<commit_before>/* worker.cpp
Copyright (C) 2003-2005 Tommi Maekitalo
This file is part of tntnet.
Tntnet 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 2 of the License, or
(at your option) any later version.
Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
#include "tnt/worker.h"
#include "tnt/dispatcher.h"
#include "tnt/job.h"
#include <tnt/httprequest.h>
#include <tnt/httpreply.h>
#include <tnt/http.h>
#include <tnt/poller.h>
#include <tnt/sessionscope.h>
#include <cxxtools/log.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
log_define("tntnet.worker")
namespace
{
class ComponentUnloadLock
{
tnt::Component& comp;
public:
ComponentUnloadLock(tnt::Component& c)
: comp(c)
{ comp.lock(); }
~ComponentUnloadLock()
{ comp.unlock(); }
};
static const char stateStarting[] = "0 starting";
static const char stateWaitingForJob[] = "1 waiting for job";
static const char stateParsing[] = "2 parsing request";
static const char statePostParsing[] = "3 post parsing";
static const char stateDispatch[] = "4 dispatch";
static const char stateProcessingRequest[] = "5 processing request";
static const char stateFlush[] = "6 flush";
static const char stateSendReply[] = "7 send reply";
static const char stateSendError[] = "8 send error";
static const char stateStopping[] = "9 stopping";
}
namespace tnt
{
cxxtools::Mutex Worker::mutex;
unsigned Worker::nextThreadNumber = 0;
Worker::workers_type Worker::workers;
unsigned Worker::compLifetime = 600;
unsigned Worker::maxRequestTime = 600;
unsigned Worker::reportStateTime = 0;
time_t Worker::nextReportStateTime = 0;
unsigned Worker::minThreads = 5;
bool Worker::enableCompression = false;
Worker::ComploaderPoolType Worker::comploaderPool;
Worker::Worker(Tntnet& app)
: application(app),
comploaderObject(comploaderPool.get()),
comploader(comploaderObject),
threadId(0),
state(stateStarting),
lastWaitTime(0)
{
log_debug("initialize thread " << threadId);
cxxtools::MutexLock lock(mutex);
workers.insert(this);
}
Worker::~Worker()
{
log_debug("delete worker " << threadId);
cxxtools::MutexLock lock(mutex);
workers.erase(this);
comploader.cleanup(0);
}
void Worker::run()
{
threadId = pthread_self();
Jobqueue& queue = application.getQueue();
log_debug("start thread " << threadId);
while (queue.getWaitThreadCount() < minThreads)
{
log_debug("waiting for job");
state = stateWaitingForJob;
Jobqueue::JobPtr j = queue.get();
log_debug("got job - fd=" << j->getFd());
std::iostream& socket = j->getStream();
try
{
bool keepAlive;
do
{
time(&lastWaitTime);
keepAlive = false;
log_debug("call parser");
state = stateParsing;
j->getParser().parse(socket);
state = statePostParsing;
if (socket.eof())
log_debug("eof");
else if (j->getParser().failed())
log_error("end parser");
else if (socket.fail())
log_error("socket failed");
else
{
j->getRequest().doPostParse();
j->setWrite();
keepAlive = processRequest(j->getRequest(), socket,
j->decrementKeepAliveCounter());
if (keepAlive)
{
j->setRead();
j->clear();
}
}
} while (keepAlive);
}
catch (const cxxtools::net::Timeout& e)
{
log_debug("timeout - put job in poller");
application.getPoller().addIdleJob(j);
}
}
time(&lastWaitTime);
log_info("end worker-thread " << threadId);
state = stateStopping;
}
bool Worker::processRequest(HttpRequest& request, std::iostream& socket,
unsigned keepAliveCount)
{
// log message
log_info("process request: " << request.getMethod() << ' ' << request.getUrl()
<< " from client " << request.getPeerIp());
log_info("user-Agent \"" << request.getUserAgent() << '"');
// create reply-object
HttpReply reply(socket);
reply.setVersion(request.getMajorVersion(), request.getMinorVersion());
reply.setMethod(request.getMethod());
if (request.keepAlive())
reply.setKeepAliveCounter(keepAliveCount);
// process request
try
{
try
{
dispatch(request, reply);
if (!request.keepAlive() || !reply.keepAlive())
keepAliveCount = 0;
if (keepAliveCount > 0)
log_debug("keep alive");
else
{
log_debug("no keep alive request/reply="
<< request.keepAlive() << '/' << reply.keepAlive());
}
}
catch (const HttpError& e)
{
throw;
}
//catch (const cxxtools::Net::Timeout& t)
//{
// TODO pass job to writer-thread
// return false;
//}
catch (const std::exception& e)
{
throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());
}
}
catch (const HttpError& e)
{
state = stateSendError;
log_warn("http-Error: " << e.what());
socket << "HTTP/1.0 " << e.what()
<< "\r\n\r\n"
<< "<html><body><h1>Error</h1><p>"
<< e.what() << "</p></body></html>" << std::endl;
return false;
}
return keepAliveCount > 0;
}
void Worker::dispatch(HttpRequest& request, HttpReply& reply)
{
state = stateDispatch;
const std::string& url = request.getUrl();
log_info("dispatch " << request.getQuery());
if (!HttpRequest::checkUrl(url))
throw HttpError(HTTP_BAD_REQUEST, "illegal url");
Dispatcher::PosType pos(application.getDispatcher(), request.getUrl());
while (true)
{
state = stateDispatch;
// pos.getNext() throws NotFoundException at end
Dispatcher::CompidentType ci = pos.getNext();
try
{
log_debug("load component " << ci);
Component& comp = comploader.fetchComp(ci, application.getDispatcher());
ComponentUnloadLock unload_lock(comp);
request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);
request.setArgs(ci.getArgs());
application.getScopemanager().preCall(request, ci.libname);
log_info("call component " << ci << " path " << request.getPathInfo());
state = stateProcessingRequest;
unsigned http_return = comp(request, reply, request.getQueryParams());
if (http_return != DECLINED)
{
if (reply.isDirectMode())
{
log_info("request ready, returncode " << http_return);
state = stateFlush;
reply.out().flush();
}
else
{
log_info("request ready, returncode " << http_return << " - ContentSize: " << reply.getContentSize());
application.getScopemanager().postCall(request, reply, ci.libname);
if (enableCompression)
reply.setAcceptEncoding(request.getEncoding());
state = stateSendReply;
reply.sendReply(http_return);
}
if (reply.out())
log_info("reply sent");
return;
}
else
log_debug("component " << ci << " returned DECLINED");
}
catch (const cxxtools::dl::DlopenError& e)
{
log_warn("dl::DlopenError catched - libname " << e.getLibname());
}
catch (const cxxtools::dl::SymbolNotFound& e)
{
log_warn("dl::SymbolNotFound catched - symbol " << e.getSymbol());
}
}
throw NotFoundException(request.getUrl());
}
void Worker::timer()
{
time_t currentTime;
time(¤tTime);
bool reportState = false;
if (reportStateTime > 0 && currentTime > nextReportStateTime)
{
if (nextReportStateTime)
reportState = true;
nextReportStateTime = currentTime + reportStateTime;
}
cxxtools::MutexLock lock(mutex);
for (workers_type::iterator it = workers.begin();
it != workers.end(); ++it)
{
(*it)->healthCheck(currentTime);
(*it)->cleanup(compLifetime);
if (reportState)
log_info("threadstate " << (*it)->threadId << ": " << (*it)->state);
}
}
void Worker::healthCheck(time_t currentTime)
{
if (state != stateWaitingForJob
&& lastWaitTime != 0
&& maxRequestTime > 0)
{
if (currentTime - lastWaitTime > maxRequestTime)
{
log_fatal("requesttime " << maxRequestTime << " seconds in thread "
<< threadId << " exceeded - exit process");
log_info("current state: " << state);
exit(111);
}
}
}
Worker::workers_type::size_type Worker::getCountThreads()
{
cxxtools::MutexLock lock(mutex);
return workers.size();
}
}
<commit_msg>catch unexpected exceptions in worker<commit_after>/* worker.cpp
Copyright (C) 2003-2005 Tommi Maekitalo
This file is part of tntnet.
Tntnet 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 2 of the License, or
(at your option) any later version.
Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
#include "tnt/worker.h"
#include "tnt/dispatcher.h"
#include "tnt/job.h"
#include <tnt/httprequest.h>
#include <tnt/httpreply.h>
#include <tnt/http.h>
#include <tnt/poller.h>
#include <tnt/sessionscope.h>
#include <cxxtools/log.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
log_define("tntnet.worker")
namespace
{
class ComponentUnloadLock
{
tnt::Component& comp;
public:
ComponentUnloadLock(tnt::Component& c)
: comp(c)
{ comp.lock(); }
~ComponentUnloadLock()
{ comp.unlock(); }
};
static const char stateStarting[] = "0 starting";
static const char stateWaitingForJob[] = "1 waiting for job";
static const char stateParsing[] = "2 parsing request";
static const char statePostParsing[] = "3 post parsing";
static const char stateDispatch[] = "4 dispatch";
static const char stateProcessingRequest[] = "5 processing request";
static const char stateFlush[] = "6 flush";
static const char stateSendReply[] = "7 send reply";
static const char stateSendError[] = "8 send error";
static const char stateStopping[] = "9 stopping";
}
namespace tnt
{
cxxtools::Mutex Worker::mutex;
unsigned Worker::nextThreadNumber = 0;
Worker::workers_type Worker::workers;
unsigned Worker::compLifetime = 600;
unsigned Worker::maxRequestTime = 600;
unsigned Worker::reportStateTime = 0;
time_t Worker::nextReportStateTime = 0;
unsigned Worker::minThreads = 5;
bool Worker::enableCompression = false;
Worker::ComploaderPoolType Worker::comploaderPool;
Worker::Worker(Tntnet& app)
: application(app),
comploaderObject(comploaderPool.get()),
comploader(comploaderObject),
threadId(0),
state(stateStarting),
lastWaitTime(0)
{
log_debug("initialize thread " << threadId);
cxxtools::MutexLock lock(mutex);
workers.insert(this);
}
Worker::~Worker()
{
cxxtools::MutexLock lock(mutex);
workers.erase(this);
comploader.cleanup(0);
log_debug("delete worker " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads");
}
void Worker::run()
{
threadId = pthread_self();
Jobqueue& queue = application.getQueue();
log_debug("start thread " << threadId);
while (queue.getWaitThreadCount() < minThreads)
{
log_debug("waiting for job");
state = stateWaitingForJob;
Jobqueue::JobPtr j = queue.get();
log_debug("got job - fd=" << j->getFd());
std::iostream& socket = j->getStream();
try
{
bool keepAlive;
do
{
time(&lastWaitTime);
keepAlive = false;
log_debug("call parser");
state = stateParsing;
j->getParser().parse(socket);
state = statePostParsing;
if (socket.eof())
log_debug("eof");
else if (j->getParser().failed())
log_error("end parser");
else if (socket.fail())
log_error("socket failed");
else
{
j->getRequest().doPostParse();
j->setWrite();
keepAlive = processRequest(j->getRequest(), socket,
j->decrementKeepAliveCounter());
if (keepAlive)
{
j->setRead();
j->clear();
}
}
} while (keepAlive);
}
catch (const cxxtools::net::Timeout& e)
{
log_debug("timeout - put job in poller");
application.getPoller().addIdleJob(j);
}
catch (const std::exception& e)
{
log_warn("unexpected exception: " << e.what());
}
}
time(&lastWaitTime);
log_debug("end worker-thread " << threadId);
state = stateStopping;
}
bool Worker::processRequest(HttpRequest& request, std::iostream& socket,
unsigned keepAliveCount)
{
// log message
log_info("process request: " << request.getMethod() << ' ' << request.getUrl()
<< " from client " << request.getPeerIp());
log_info("user-Agent \"" << request.getUserAgent() << '"');
// create reply-object
HttpReply reply(socket);
reply.setVersion(request.getMajorVersion(), request.getMinorVersion());
reply.setMethod(request.getMethod());
if (request.keepAlive())
reply.setKeepAliveCounter(keepAliveCount);
// process request
try
{
try
{
dispatch(request, reply);
if (!request.keepAlive() || !reply.keepAlive())
keepAliveCount = 0;
if (keepAliveCount > 0)
log_debug("keep alive");
else
{
log_debug("no keep alive request/reply="
<< request.keepAlive() << '/' << reply.keepAlive());
}
}
catch (const HttpError& e)
{
throw;
}
//catch (const cxxtools::Net::Timeout& t)
//{
// TODO pass job to writer-thread
// return false;
//}
catch (const std::exception& e)
{
throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());
}
}
catch (const HttpError& e)
{
state = stateSendError;
log_warn("http-Error: " << e.what());
socket << "HTTP/1.0 " << e.what()
<< "\r\n\r\n"
<< "<html><body><h1>Error</h1><p>"
<< e.what() << "</p></body></html>" << std::endl;
return false;
}
return keepAliveCount > 0;
}
void Worker::dispatch(HttpRequest& request, HttpReply& reply)
{
state = stateDispatch;
const std::string& url = request.getUrl();
log_info("dispatch " << request.getQuery());
if (!HttpRequest::checkUrl(url))
throw HttpError(HTTP_BAD_REQUEST, "illegal url");
Dispatcher::PosType pos(application.getDispatcher(), request.getUrl());
while (true)
{
state = stateDispatch;
// pos.getNext() throws NotFoundException at end
Dispatcher::CompidentType ci = pos.getNext();
try
{
log_debug("load component " << ci);
Component& comp = comploader.fetchComp(ci, application.getDispatcher());
ComponentUnloadLock unload_lock(comp);
request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);
request.setArgs(ci.getArgs());
application.getScopemanager().preCall(request, ci.libname);
log_info("call component " << ci << " path " << request.getPathInfo());
state = stateProcessingRequest;
unsigned http_return = comp(request, reply, request.getQueryParams());
if (http_return != DECLINED)
{
if (reply.isDirectMode())
{
log_info("request ready, returncode " << http_return);
state = stateFlush;
reply.out().flush();
}
else
{
log_info("request ready, returncode " << http_return << " - ContentSize: " << reply.getContentSize());
application.getScopemanager().postCall(request, reply, ci.libname);
if (enableCompression)
reply.setAcceptEncoding(request.getEncoding());
state = stateSendReply;
reply.sendReply(http_return);
}
if (reply.out())
log_info("reply sent");
return;
}
else
log_debug("component " << ci << " returned DECLINED");
}
catch (const cxxtools::dl::DlopenError& e)
{
log_warn("dl::DlopenError catched - libname " << e.getLibname());
}
catch (const cxxtools::dl::SymbolNotFound& e)
{
log_warn("dl::SymbolNotFound catched - symbol " << e.getSymbol());
}
}
throw NotFoundException(request.getUrl());
}
void Worker::timer()
{
time_t currentTime;
time(¤tTime);
bool reportState = false;
if (reportStateTime > 0 && currentTime > nextReportStateTime)
{
if (nextReportStateTime)
reportState = true;
nextReportStateTime = currentTime + reportStateTime;
}
cxxtools::MutexLock lock(mutex);
for (workers_type::iterator it = workers.begin();
it != workers.end(); ++it)
{
(*it)->healthCheck(currentTime);
(*it)->cleanup(compLifetime);
if (reportState)
log_info("threadstate " << (*it)->threadId << ": " << (*it)->state);
}
}
void Worker::healthCheck(time_t currentTime)
{
if (state != stateWaitingForJob
&& lastWaitTime != 0
&& maxRequestTime > 0)
{
if (currentTime - lastWaitTime > maxRequestTime)
{
log_fatal("requesttime " << maxRequestTime << " seconds in thread "
<< threadId << " exceeded - exit process");
log_info("current state: " << state);
exit(111);
}
}
}
Worker::workers_type::size_type Worker::getCountThreads()
{
cxxtools::MutexLock lock(mutex);
return workers.size();
}
}
<|endoftext|> |
<commit_before>#include "shaderreflection.h"
#include <Tempest/Except>
#include <algorithm>
#include "thirdparty/spirv_cross/spirv_common.hpp"
using namespace Tempest;
using namespace Tempest::Detail;
void ShaderReflection::getVertexDecl(std::vector<Decl::ComponentType>& data, spirv_cross::Compiler& comp) {
if(comp.get_execution_model()!=spv::ExecutionModelVertex)
return;
spirv_cross::ShaderResources resources = comp.get_shader_resources();
for(auto &resource : resources.stage_inputs) {
auto& t = comp.get_type_from_variable(resource.id);
unsigned loc = comp.get_decoration(resource.id, spv::DecorationLocation);
data.resize(std::max<size_t>(loc+1,data.size()));
switch(t.basetype) {
case spirv_cross::SPIRType::Float: {
data[loc] = Decl::ComponentType(Decl::float1+t.vecsize-1);
break;
}
case spirv_cross::SPIRType::Int: {
data[loc] = Decl::ComponentType(Decl::int1+t.vecsize-1);
break;
}
case spirv_cross::SPIRType::UInt: {
data[loc] = Decl::ComponentType(Decl::uint1+t.vecsize-1);
break;
}
// TODO: add support for uint32_t packed color
default:
// not supported
throw std::system_error(Tempest::GraphicsErrc::InvalidShaderModule);
}
}
}
void ShaderReflection::getBindings(std::vector<Binding>& lay,
spirv_cross::Compiler& comp) {
Stage s = Stage::Compute;
switch(comp.get_execution_model()) {
case spv::ExecutionModelGLCompute:
s = Stage::Compute;
break;
case spv::ExecutionModelVertex:
s = Stage::Vertex;
break;
case spv::ExecutionModelTessellationControl:
s = Stage::Control;
break;
case spv::ExecutionModelTessellationEvaluation:
s = Stage::Evaluate;
break;
case spv::ExecutionModelGeometry:
s = Stage::Geometry;
break;
case spv::ExecutionModelFragment:
s = Stage::Fragment;
break;
default: // unimplemented
throw std::system_error(Tempest::GraphicsErrc::InvalidShaderModule);
}
spirv_cross::ShaderResources resources = comp.get_shader_resources();
for(auto &resource : resources.sampled_images) {
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
Binding b;
b.layout = binding;
b.cls = Texture;
b.stage = s;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.uniform_buffers) {
auto& t = comp.get_type_from_variable(resource.id);
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
auto sz = comp.get_declared_struct_size(t);
Binding b;
b.layout = binding;
b.cls = Ubo;
b.stage = s;
b.size = sz;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.storage_buffers) {
auto& t = comp.get_type_from_variable(resource.id);
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
auto readonly = comp.get_buffer_block_flags(resource.id);
auto sz = comp.get_declared_struct_size(t);
Binding b;
b.layout = binding;
b.cls = (readonly.get(spv::DecorationNonWritable) ? SsboR : SsboRW);
b.stage = s;
b.size = sz;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.storage_images) {
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
Binding b;
b.layout = binding;
b.cls = ImgRW; // (readonly.get(spv::DecorationNonWritable) ? UniformsLayout::ImgR : UniformsLayout::ImgRW);
b.stage = s;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.push_constant_buffers) {
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
auto& t = comp.get_type_from_variable(resource.id);
auto sz = comp.get_declared_struct_size(t);
Binding b;
b.layout = binding;
b.cls = Push;
b.stage = s;
b.size = sz;
b.spvId = resource.id;
lay.push_back(b);
}
}
void ShaderReflection::merge(std::vector<ShaderReflection::Binding>& ret,
ShaderReflection::PushBlock& pb,
const std::vector<ShaderReflection::Binding>& comp) {
ret.reserve(comp.size());
size_t id=0;
for(size_t i=0; i<comp.size(); ++i, ++id) {
auto& u = comp[i];
if(u.cls==ShaderReflection::Push) {
pb.stage = ShaderReflection::Compute;
pb.size = u.size;
continue;
}
ret.push_back(u);
ret.back().stage = ShaderReflection::Compute;
}
finalize(ret);
}
void ShaderReflection::merge(std::vector<Binding>& ret,
PushBlock& pb,
const std::vector<Binding>* sh[],
size_t count) {
size_t expectedSz = 0;
for(size_t i=0; i<count; ++i)
if(sh[i]!=nullptr)
expectedSz+=sh[i]->size();
ret.reserve(expectedSz);
for(size_t shId=0; shId<count; ++shId) {
if(sh[shId]==nullptr)
continue;
auto& vs = *sh[shId];
for(size_t i=0; i<vs.size(); ++i) {
auto& u = vs[i];
if(u.cls==Push) {
pb.stage = Stage(pb.stage | u.stage);
pb.size = std::max(pb.size, u.size);
continue;
}
if(shId>0) {
bool ins = false;
for(auto& r:ret)
if(r.layout==u.layout) {
r.stage = Stage(r.stage | u.stage);
r.size = std::max(pb.size, u.size);
ins = true;
break;
}
if(ins)
continue;
}
ret.push_back(u);
}
}
finalize(ret);
}
void ShaderReflection::finalize(std::vector<Binding>& ret) {
std::sort(ret.begin(),ret.end(),[](const Binding& a, const Binding& b){
return a.layout<b.layout;
});
for(size_t i=0; i<ret.size(); ++i)
if(ret[i].layout!=i) {
Binding fill;
fill.layout = uint32_t(i);
fill.stage = Stage(0);
ret.insert(ret.begin()+int(i),fill);
}
}
<commit_msg>fix shaders reflector<commit_after>#include "shaderreflection.h"
#include <Tempest/Except>
#include <Tempest/Log>
#include <algorithm>
#include "thirdparty/spirv_cross/spirv_common.hpp"
using namespace Tempest;
using namespace Tempest::Detail;
void ShaderReflection::getVertexDecl(std::vector<Decl::ComponentType>& data, spirv_cross::Compiler& comp) {
if(comp.get_execution_model()!=spv::ExecutionModelVertex)
return;
spirv_cross::ShaderResources resources = comp.get_shader_resources();
for(auto &resource : resources.stage_inputs) {
auto& t = comp.get_type_from_variable(resource.id);
unsigned loc = comp.get_decoration(resource.id, spv::DecorationLocation);
data.resize(std::max<size_t>(loc+1,data.size()));
switch(t.basetype) {
case spirv_cross::SPIRType::Float: {
data[loc] = Decl::ComponentType(Decl::float1+t.vecsize-1);
break;
}
case spirv_cross::SPIRType::Int: {
data[loc] = Decl::ComponentType(Decl::int1+t.vecsize-1);
break;
}
case spirv_cross::SPIRType::UInt: {
data[loc] = Decl::ComponentType(Decl::uint1+t.vecsize-1);
break;
}
// TODO: add support for uint32_t packed color
default:
// not supported
throw std::system_error(Tempest::GraphicsErrc::InvalidShaderModule);
}
}
}
void ShaderReflection::getBindings(std::vector<Binding>& lay,
spirv_cross::Compiler& comp) {
Stage s = Stage::Compute;
switch(comp.get_execution_model()) {
case spv::ExecutionModelGLCompute:
s = Stage::Compute;
break;
case spv::ExecutionModelVertex:
s = Stage::Vertex;
break;
case spv::ExecutionModelTessellationControl:
s = Stage::Control;
break;
case spv::ExecutionModelTessellationEvaluation:
s = Stage::Evaluate;
break;
case spv::ExecutionModelGeometry:
s = Stage::Geometry;
break;
case spv::ExecutionModelFragment:
s = Stage::Fragment;
break;
default: // unimplemented
throw std::system_error(Tempest::GraphicsErrc::InvalidShaderModule);
}
spirv_cross::ShaderResources resources = comp.get_shader_resources();
for(auto &resource : resources.sampled_images) {
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
Binding b;
b.layout = binding;
b.cls = Texture;
b.stage = s;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.uniform_buffers) {
auto& t = comp.get_type_from_variable(resource.id);
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
auto sz = comp.get_declared_struct_size(t);
Binding b;
b.layout = binding;
b.cls = Ubo;
b.stage = s;
b.size = sz;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.storage_buffers) {
auto& t = comp.get_type_from_variable(resource.id);
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
auto readonly = comp.get_buffer_block_flags(resource.id);
auto sz = comp.get_declared_struct_size(t);
Binding b;
b.layout = binding;
b.cls = (readonly.get(spv::DecorationNonWritable) ? SsboR : SsboRW);
b.stage = s;
b.size = sz;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.storage_images) {
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
Binding b;
b.layout = binding;
b.cls = ImgRW; // (readonly.get(spv::DecorationNonWritable) ? UniformsLayout::ImgR : UniformsLayout::ImgRW);
b.stage = s;
b.spvId = resource.id;
lay.push_back(b);
}
for(auto &resource : resources.push_constant_buffers) {
unsigned binding = comp.get_decoration(resource.id, spv::DecorationBinding);
auto& t = comp.get_type_from_variable(resource.id);
auto sz = comp.get_declared_struct_size(t);
Binding b;
b.layout = binding;
b.cls = Push;
b.stage = s;
b.size = sz;
b.spvId = resource.id;
lay.push_back(b);
}
}
void ShaderReflection::merge(std::vector<ShaderReflection::Binding>& ret,
ShaderReflection::PushBlock& pb,
const std::vector<ShaderReflection::Binding>& comp) {
ret.reserve(comp.size());
size_t id=0;
for(size_t i=0; i<comp.size(); ++i, ++id) {
auto& u = comp[i];
if(u.cls==ShaderReflection::Push) {
pb.stage = ShaderReflection::Compute;
pb.size = u.size;
continue;
}
ret.push_back(u);
ret.back().stage = ShaderReflection::Compute;
}
finalize(ret);
}
void ShaderReflection::merge(std::vector<Binding>& ret,
PushBlock& pb,
const std::vector<Binding>* sh[],
size_t count) {
size_t expectedSz = 0;
for(size_t i=0; i<count; ++i)
if(sh[i]!=nullptr)
expectedSz+=sh[i]->size();
ret.reserve(expectedSz);
for(size_t shId=0; shId<count; ++shId) {
if(sh[shId]==nullptr)
continue;
auto& vs = *sh[shId];
for(size_t i=0; i<vs.size(); ++i) {
auto& u = vs[i];
if(u.cls==Push) {
pb.stage = Stage(pb.stage | u.stage);
pb.size = std::max(pb.size, u.size);
continue;
}
if(shId>0) {
bool ins = false;
for(auto& r:ret)
if(r.layout==u.layout) {
r.stage = Stage(r.stage | u.stage);
r.size = std::max(r.size, u.size);
ins = true;
break;
}
if(ins)
continue;
}
ret.push_back(u);
}
}
finalize(ret);
}
void ShaderReflection::finalize(std::vector<Binding>& ret) {
std::sort(ret.begin(),ret.end(),[](const Binding& a, const Binding& b){
return a.layout<b.layout;
});
for(size_t i=0; i<ret.size(); ++i)
if(ret[i].layout!=i) {
Binding fill;
fill.layout = uint32_t(i);
fill.stage = Stage(0);
ret.insert(ret.begin()+int(i),fill);
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <sstream>
#include <cmath>
#include "filtrations/Data.hh"
#include "geometry/RipsExpander.hh"
#include "persistentHomology/ConnectedComponents.hh"
#include "topology/CliqueGraph.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"
#include "topology/io/EdgeLists.hh"
#include "topology/io/GML.hh"
#include "utilities/Filesystem.hh"
using DataType = double;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
std::string formatOutput( const std::string& prefix, unsigned k, unsigned K )
{
std::ostringstream stream;
stream << prefix;
stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k;
stream << ".txt";
return stream.str();
}
int main( int argc, char** argv )
{
if( argc <= 2 )
{
// TODO: Show usage
return -1;
}
std::string filename = argv[1];
unsigned maxK = static_cast<unsigned>( std::stoul( argv[2] ) );
SimplicialComplex K;
// Input -------------------------------------------------------------
std::cerr << "* Reading '" << filename << "'...";
if( aleph::utilities::extension( filename ) == ".gml" )
{
aleph::topology::io::GMLReader reader;
reader( filename, K );
}
else
{
aleph::io::EdgeListReader reader;
reader.setReadWeights( true );
reader.setTrimLines( true );
reader( filename, K );
}
std::cerr << "finished\n";
DataType maxWeight = std::numeric_limits<DataType>::lowest();
for( auto&& simplex : K )
maxWeight = std::max( maxWeight, simplex.data() );
// Expansion ---------------------------------------------------------
aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;
K = ripsExpander( K, maxK );
K = ripsExpander.assignMaximumWeight( K );
K.sort( aleph::filtrations::Data<Simplex>() );
for( unsigned k = 1; k <= maxK; k++ )
{
std::cerr << "* Extracting " << k << "-cliques graph...";
auto C
= aleph::topology::getCliqueGraph( K, k );
C.sort( aleph::filtrations::Data<Simplex>() );
std::cerr << "finished\n";
std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n";
if( C.empty() )
{
std::cerr << "* Stopping here because no further cliques for processing exist\n";
break;
}
auto pd
= aleph::calculateZeroDimensionalPersistenceDiagram( C );
{
using namespace aleph::utilities;
auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK );
std::cerr << "* Storing output in '" << outputFilename << "'...\n";
pd.removeDiagonal();
std::transform( pd.begin(), pd.end(), pd.begin(),
[&maxWeight] ( const PersistenceDiagram::Point& p )
{
if( !std::isfinite( p.y() ) )
return PersistenceDiagram::Point( p.x(), maxWeight );
else
return p;
} );
std::ofstream out( outputFilename );
out << "# Original filename: " << filename << "\n";
out << "# k : " << k << "\n";
out << pd << "\n";
}
}
}
<commit_msg>Added usage information for clique persistence diagram tool<commit_after>#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <sstream>
#include <cmath>
#include "filtrations/Data.hh"
#include "geometry/RipsExpander.hh"
#include "persistentHomology/ConnectedComponents.hh"
#include "topology/CliqueGraph.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"
#include "topology/io/EdgeLists.hh"
#include "topology/io/GML.hh"
#include "utilities/Filesystem.hh"
using DataType = double;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
std::string formatOutput( const std::string& prefix, unsigned k, unsigned K )
{
std::ostringstream stream;
stream << prefix;
stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k;
stream << ".txt";
return stream.str();
}
void usage()
{
std::cerr << "Usage: clique-persistence-diagram FILE K\n"
<< "\n"
<< "Calculates the clique persistence diagram for FILE, which is\n"
<< "supposed to be a weighted graph. The K parameter denotes the\n"
<< "maximum dimension of a simplex for extracting a clique graph\n"
<< "and tracking persistence of clique communities.\n\n";
}
int main( int argc, char** argv )
{
if( argc <= 2 )
{
usage();
return -1;
}
std::string filename = argv[1];
unsigned maxK = static_cast<unsigned>( std::stoul( argv[2] ) );
SimplicialComplex K;
// Input -------------------------------------------------------------
std::cerr << "* Reading '" << filename << "'...";
if( aleph::utilities::extension( filename ) == ".gml" )
{
aleph::topology::io::GMLReader reader;
reader( filename, K );
}
else
{
aleph::io::EdgeListReader reader;
reader.setReadWeights( true );
reader.setTrimLines( true );
reader( filename, K );
}
std::cerr << "finished\n";
DataType maxWeight = std::numeric_limits<DataType>::lowest();
for( auto&& simplex : K )
maxWeight = std::max( maxWeight, simplex.data() );
// Expansion ---------------------------------------------------------
aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;
K = ripsExpander( K, maxK );
K = ripsExpander.assignMaximumWeight( K );
K.sort( aleph::filtrations::Data<Simplex>() );
for( unsigned k = 1; k <= maxK; k++ )
{
std::cerr << "* Extracting " << k << "-cliques graph...";
auto C
= aleph::topology::getCliqueGraph( K, k );
C.sort( aleph::filtrations::Data<Simplex>() );
std::cerr << "finished\n";
std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n";
if( C.empty() )
{
std::cerr << "* Stopping here because no further cliques for processing exist\n";
break;
}
auto pd
= aleph::calculateZeroDimensionalPersistenceDiagram( C );
{
using namespace aleph::utilities;
auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK );
std::cerr << "* Storing output in '" << outputFilename << "'...\n";
pd.removeDiagonal();
std::transform( pd.begin(), pd.end(), pd.begin(),
[&maxWeight] ( const PersistenceDiagram::Point& p )
{
if( !std::isfinite( p.y() ) )
return PersistenceDiagram::Point( p.x(), maxWeight );
else
return p;
} );
std::ofstream out( outputFilename );
out << "# Original filename: " << filename << "\n";
out << "# k : " << k << "\n";
out << pd << "\n";
}
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2012 Benjamin Wild
*
* 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 "stdafx.h"
#include "CLSimulator.h"
#include "CPUSimulator.h"
#include "Definitions.h"
#include "util.h"
#include "cpplog/cpplog.hpp"
#include "gnuplot_i/gnuplot_i.h"
#include <numeric>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
void measureTimes(Logger const& logger, state const& state0, const size_t timesteps, float dt, boost::filesystem::path const& path)
{
const size_t start = 1;
const size_t powers = 12;
std::vector<const size_t> numNeurons;
std::vector<const double> avgTimesCalculationsCL, avgTimesFFTW, avgTimesClFFT;
std::vector<const double> avgTimesCalculationsCPU, avgTimesConvolutionsCPU;
std::string vendor, name;
for (int i = start; i < powers; ++i)
{
auto neurons = static_cast<const size_t>(pow(2.f, i));
numNeurons.push_back(neurons);
CLSimulator clSim = CLSimulator(
neurons,
1,
1,
timesteps,
dt,
state0,
CLSimulator::NO_PLOT,
CLSimulator::MEASURE,
CLSimulator::FFTW,
CLSimulator::CLFFT,
path,
logger);
clSim.simulate();
CPUSimulator cpuSim = CPUSimulator(
neurons,
1,
1,
timesteps,
dt,
state0,
CPUSimulator::CONVOLUTION);
cpuSim.simulate();
name = clSim.getClWrapper().getDeviceName();
auto const& timesCalculationsCL = clSim.getTimesCalculations();
auto const& timesFFTW = clSim.getTimesFFTW();
auto const& timesClFFT = clSim.getTimesClFFT();
auto const& timesCalculationsCPU = cpuSim.getTimesCalculations();
auto const& timesConvolutionsCPU = cpuSim.getTimesConvolutions();
avgTimesCalculationsCL.push_back(
std::accumulate(
timesCalculationsCL.begin(),
timesCalculationsCL.end(), 0.0)
/ timesCalculationsCL.size());
avgTimesFFTW.push_back(
std::accumulate(
timesFFTW.begin(),
timesFFTW.end(), 0.0)
/ timesFFTW.size());
avgTimesClFFT.push_back(
std::accumulate(
timesClFFT.begin(),
timesClFFT.end(), 0.0)
/ timesClFFT.size());
avgTimesCalculationsCPU.push_back(
std::accumulate(
timesCalculationsCPU.begin(),
timesCalculationsCPU.end(), 0.0)
/ timesCalculationsCPU.size());
avgTimesConvolutionsCPU.push_back(
std::accumulate(
timesConvolutionsCPU.begin(),
timesConvolutionsCPU.end(), 0.0)
/ timesConvolutionsCPU.size());
}
std::cout << std::endl << "Results" << std::endl << "=======" << std::endl;
for (int i = 0; i < powers - start; ++i)
{
std::cout << static_cast<const size_t>(pow(2.f, (int)(i + start))) << "\t" << avgTimesCalculationsCL[i] << "\t" << avgTimesFFTW[i] << "\t" << avgTimesClFFT[i] << std::endl;
}
{
Gnuplot plot_performance;
plot_performance.set_title(boost::str(boost::format("Performance measurements (%1%)") % name));
plot_performance.set_style("linespoints");
plot_performance.set_xlogscale(2);
plot_performance.set_xlabel("Neurons");
plot_performance.set_ylabel("Average execution time (us)");
plot_performance.plot_xy(numNeurons, avgTimesCalculationsCPU, "Runge-kutta approximations on CPU");
plot_performance.plot_xy(numNeurons, avgTimesConvolutionsCPU, "Manual convolutions on CPU");
plot_performance.plot_xy(numNeurons, avgTimesCalculationsCL, "Runge-kutta approximations using OpenCL");
plot_performance.plot_xy(numNeurons, avgTimesFFTW, "Convolutions using FFTW");
plot_performance.plot_xy(numNeurons, avgTimesClFFT, "Convolutions using ClFFT");
getchar();
}
}
int finish(const int rc)
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
_CrtDumpMemoryLeaks();
#endif // if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
return rc;
}
int main(int ac, char **av)
{
float V0, h0, n0, z0, sAMPA0, sNMDA0, xNMDA0, sGABAA0, IApp0, dt;
size_t nX, nY, nZ, timesteps;
std::string plotStr, measureStr, fftwStr, clfftStr, perfplot;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("V", po::value<float>(&V0)->default_value(-70.0), "initial value for membrane potential")
("h", po::value<float>(&h0)->default_value(1.0), "initial value for h")
("n", po::value<float>(&n0)->default_value(0.0), "initial value for n")
("z", po::value<float>(&z0)->default_value(0.0), "initial value for z")
("sAMPA", po::value<float>(&sAMPA0)->default_value(0.0), "initial value for sAMPA")
("sNMDA", po::value<float>(&sNMDA0)->default_value(0.0), "initial value for sNMDA")
("xNMDA", po::value<float>(&xNMDA0)->default_value(0.0), "initial value for xNMDA")
("sGABAA", po::value<float>(&sGABAA0)->default_value(0.0), "initial value for xNMDA")
("IApp", po::value<float>(&IApp0)->default_value(1.0), "initial value for IApp")
("dt", po::value<float>(&dt)->default_value(0.1f), "length of one timestep")
("timesteps", po::value<size_t>(×teps)->default_value(500), "number of timesteps")
("nX", po::value<size_t>(&nX)->default_value(1024), "number of neurons in network (X axis)")
("nY", po::value<size_t>(&nY)->default_value(1), "number of neurons in network (Y axis)")
("nZ", po::value<size_t>(&nZ)->default_value(1), "number of neurons in network (Z axis)")
("plot", po::value<std::string>(&plotStr)->default_value("false"), "plot results (false | gnuplot | opengl)")
("measure", po::value<std::string>(&measureStr)->default_value("true"), "measure execution time")
("fftw", po::value<std::string>(&fftwStr)->default_value("false"), "compute synaptic fields using fftw")
("clfft", po::value<std::string>(&clfftStr)->default_value("true"), "compute synaptic fields using clFFT")
("perfplot", po::value<std::string>(&perfplot)->default_value("false"), "measure and plot performance for various network sizes")
;
po::variables_map vm;
try {
po::store(po::parse_command_line(ac, av, desc), vm);
} catch (po::error&) {
std::cout << desc << std::endl;
return finish(1);
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return finish(1);
}
if (stringToBool(clfftStr) && !isPowerOfTwo(nX * nY * nZ))
{
std::cout << "Error: numNeurons (nX * nY * nZ) must be radix 2" << std::endl;
return finish(1);
}
auto logger = std::make_shared<cpplog::StdErrLogger>();
state state0;
state0.V = V0;
state0.h = h0;
state0.n = n0;
state0.z = z0;
state0.s_AMPA = sAMPA0;
state0.s_NMDA = sNMDA0;
state0.x_NMDA = xNMDA0;
state0.s_GABAA = sGABAA0;
state0.I_app = IApp0;
auto path = boost::filesystem::path(CL_SOURCE_DIR);
path /= "/kernels.cl";
if (stringToBool(perfplot))
{
measureTimes(logger, state0, timesteps, dt, path);
} else
{
CLSimulator::Plot plot;
if (boost::iequals(plotStr, "gnuplot"))
{
plot = CLSimulator::PLOT_GNUPLOT;
} else if (boost::iequals(plotStr, "opengl"))
{
plot = CLSimulator::PLOT_OPENGL;
} else
{
plot = CLSimulator::NO_PLOT;
}
CLSimulator sim = CLSimulator(
nX,
nY,
nZ,
timesteps,
dt,
state0,
plot,
stringToBool(measureStr) ? CLSimulator::MEASURE : CLSimulator::NO_MEASURE,
stringToBool(fftwStr) ? CLSimulator::FFTW : CLSimulator::NO_FFTW,
stringToBool(clfftStr) ? CLSimulator::CLFFT : CLSimulator::NO_CLFFT,
path,
logger);
sim.simulate();
}
return finish(0);
}
<commit_msg>more fixes for gcc build<commit_after>/**
* Copyright (C) 2012 Benjamin Wild
*
* 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 "stdafx.h"
#include "CLSimulator.h"
#include "CPUSimulator.h"
#include "Definitions.h"
#include "util.h"
#include "cpplog/cpplog.hpp"
#include "gnuplot_i/gnuplot_i.h"
#include <numeric>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
void measureTimes(Logger const& logger, state const& state0, const size_t timesteps, float dt, boost::filesystem::path const& path)
{
const size_t start = 1;
const size_t powers = 12;
std::vector<double> avgTimesCalculationsCL, avgTimesFFTW, avgTimesClFFT;
std::vector<double> avgTimesCalculationsCPU, avgTimesConvolutionsCPU;
std::vector<size_t> numNeurons;
std::string vendor, name;
for (int i = start; i < powers; ++i)
{
auto neurons = static_cast<const size_t>(pow(2.f, i));
numNeurons.push_back(neurons);
CLSimulator clSim (
neurons,
1,
1,
timesteps,
dt,
state0,
CLSimulator::NO_PLOT,
CLSimulator::MEASURE,
CLSimulator::FFTW,
CLSimulator::CLFFT,
path,
logger);
clSim.simulate();
CPUSimulator cpuSim (
neurons,
1,
1,
timesteps,
dt,
state0,
CPUSimulator::CONVOLUTION);
cpuSim.simulate();
name = clSim.getClWrapper().getDeviceName();
auto const& timesCalculationsCL = clSim.getTimesCalculations();
auto const& timesFFTW = clSim.getTimesFFTW();
auto const& timesClFFT = clSim.getTimesClFFT();
auto const& timesCalculationsCPU = cpuSim.getTimesCalculations();
auto const& timesConvolutionsCPU = cpuSim.getTimesConvolutions();
avgTimesCalculationsCL.push_back(
std::accumulate(
timesCalculationsCL.begin(),
timesCalculationsCL.end(), 0.0)
/ timesCalculationsCL.size());
avgTimesFFTW.push_back(
std::accumulate(
timesFFTW.begin(),
timesFFTW.end(), 0.0)
/ timesFFTW.size());
avgTimesClFFT.push_back(
std::accumulate(
timesClFFT.begin(),
timesClFFT.end(), 0.0)
/ timesClFFT.size());
avgTimesCalculationsCPU.push_back(
std::accumulate(
timesCalculationsCPU.begin(),
timesCalculationsCPU.end(), 0.0)
/ timesCalculationsCPU.size());
avgTimesConvolutionsCPU.push_back(
std::accumulate(
timesConvolutionsCPU.begin(),
timesConvolutionsCPU.end(), 0.0)
/ timesConvolutionsCPU.size());
}
std::cout << std::endl << "Results" << std::endl << "=======" << std::endl;
for (int i = 0; i < powers - start; ++i)
{
std::cout << static_cast<const size_t>(pow(2.f, (int)(i + start))) << "\t" << avgTimesCalculationsCL[i] << "\t" << avgTimesFFTW[i] << "\t" << avgTimesClFFT[i] << std::endl;
}
{
Gnuplot plot_performance;
plot_performance.set_title(boost::str(boost::format("Performance measurements (%1%)") % name));
plot_performance.set_style("linespoints");
plot_performance.set_xlogscale(2);
plot_performance.set_xlabel("Neurons");
plot_performance.set_ylabel("Average execution time (us)");
plot_performance.plot_xy(numNeurons, avgTimesCalculationsCPU, "Runge-kutta approximations on CPU");
plot_performance.plot_xy(numNeurons, avgTimesConvolutionsCPU, "Manual convolutions on CPU");
plot_performance.plot_xy(numNeurons, avgTimesCalculationsCL, "Runge-kutta approximations using OpenCL");
plot_performance.plot_xy(numNeurons, avgTimesFFTW, "Convolutions using FFTW");
plot_performance.plot_xy(numNeurons, avgTimesClFFT, "Convolutions using ClFFT");
getchar();
}
}
int finish(const int rc)
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
_CrtDumpMemoryLeaks();
#endif // if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
return rc;
}
int main(int ac, char **av)
{
float V0, h0, n0, z0, sAMPA0, sNMDA0, xNMDA0, sGABAA0, IApp0, dt;
size_t nX, nY, nZ, timesteps;
std::string plotStr, measureStr, fftwStr, clfftStr, perfplot;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("V", po::value<float>(&V0)->default_value(-70.0), "initial value for membrane potential")
("h", po::value<float>(&h0)->default_value(1.0), "initial value for h")
("n", po::value<float>(&n0)->default_value(0.0), "initial value for n")
("z", po::value<float>(&z0)->default_value(0.0), "initial value for z")
("sAMPA", po::value<float>(&sAMPA0)->default_value(0.0), "initial value for sAMPA")
("sNMDA", po::value<float>(&sNMDA0)->default_value(0.0), "initial value for sNMDA")
("xNMDA", po::value<float>(&xNMDA0)->default_value(0.0), "initial value for xNMDA")
("sGABAA", po::value<float>(&sGABAA0)->default_value(0.0), "initial value for xNMDA")
("IApp", po::value<float>(&IApp0)->default_value(1.0), "initial value for IApp")
("dt", po::value<float>(&dt)->default_value(0.1f), "length of one timestep")
("timesteps", po::value<size_t>(×teps)->default_value(500), "number of timesteps")
("nX", po::value<size_t>(&nX)->default_value(1024), "number of neurons in network (X axis)")
("nY", po::value<size_t>(&nY)->default_value(1), "number of neurons in network (Y axis)")
("nZ", po::value<size_t>(&nZ)->default_value(1), "number of neurons in network (Z axis)")
("plot", po::value<std::string>(&plotStr)->default_value("false"), "plot results (false | gnuplot | opengl)")
("measure", po::value<std::string>(&measureStr)->default_value("true"), "measure execution time")
("fftw", po::value<std::string>(&fftwStr)->default_value("false"), "compute synaptic fields using fftw")
("clfft", po::value<std::string>(&clfftStr)->default_value("true"), "compute synaptic fields using clFFT")
("perfplot", po::value<std::string>(&perfplot)->default_value("false"), "measure and plot performance for various network sizes")
;
po::variables_map vm;
try {
po::store(po::parse_command_line(ac, av, desc), vm);
} catch (po::error&) {
std::cout << desc << std::endl;
return finish(1);
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return finish(1);
}
if (stringToBool(clfftStr) && !isPowerOfTwo(nX * nY * nZ))
{
std::cout << "Error: numNeurons (nX * nY * nZ) must be radix 2" << std::endl;
return finish(1);
}
auto logger = std::make_shared<cpplog::StdErrLogger>();
state state0;
state0.V = V0;
state0.h = h0;
state0.n = n0;
state0.z = z0;
state0.s_AMPA = sAMPA0;
state0.s_NMDA = sNMDA0;
state0.x_NMDA = xNMDA0;
state0.s_GABAA = sGABAA0;
state0.I_app = IApp0;
auto path = boost::filesystem::path(CL_SOURCE_DIR);
path /= "/kernels.cl";
if (stringToBool(perfplot))
{
measureTimes(logger, state0, timesteps, dt, path);
} else
{
CLSimulator::Plot plot;
if (boost::iequals(plotStr, "gnuplot"))
{
plot = CLSimulator::PLOT_GNUPLOT;
} else if (boost::iequals(plotStr, "opengl"))
{
plot = CLSimulator::PLOT_OPENGL;
} else
{
plot = CLSimulator::NO_PLOT;
}
CLSimulator sim (
nX,
nY,
nZ,
timesteps,
dt,
state0,
plot,
stringToBool(measureStr) ? CLSimulator::MEASURE : CLSimulator::NO_MEASURE,
stringToBool(fftwStr) ? CLSimulator::FFTW : CLSimulator::NO_FFTW,
stringToBool(clfftStr) ? CLSimulator::CLFFT : CLSimulator::NO_CLFFT,
path,
logger);
sim.simulate();
}
return finish(0);
}
<|endoftext|> |
<commit_before>// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O1 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O2 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O3 %s -o %t && %run %t >%t.out 2>&1
// Test that (no_sanitize_memory) functions DO NOT propagate shadow.
#include <stdlib.h>
#include <stdio.h>
__attribute__((noinline))
__attribute__((no_sanitize_memory))
int f(int x) {
return x;
}
int main(void) {
int x;
int * volatile p = &x;
int y = f(*p);
if (y)
exit(0);
return 0;
}
<commit_msg>Revert of r212265.<commit_after>// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// Test that (no_sanitize_memory) functions propagate shadow.
// Note that at -O0 there is no report, because 'x' in 'f' is spilled to the
// stack, and then loaded back as a fully initialiazed value (due to
// no_sanitize_memory attribute).
#include <stdlib.h>
#include <stdio.h>
__attribute__((noinline))
__attribute__((no_sanitize_memory))
int f(int x) {
return x;
}
int main(void) {
int x;
int * volatile p = &x;
int y = f(*p);
// CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK: {{#0 0x.* in main .*no_sanitize_memory_prop.cc:}}[[@LINE+1]]
if (y)
exit(0);
return 0;
}
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2003-2010.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 62023 $
//
// Description : unit test for new assertion construction based on input expression
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MODULE Boost.Test assertion consruction test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/assertion.hpp>
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_basic_value_expression_construction )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = assertion::seed()->*1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
}
{
assertion::expression const& E = seed->*true;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*1.5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#ifndef BOOST_NO_DECLTYPE
{
assertion::expression const& E = seed->* "abc";
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#endif
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_comparison_expression )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
{
assertion::expression const& E = seed->* 100 < 50;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "100>=50" );
}
{
assertion::expression const& E = seed->* 5<=4;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5>4" );
}
{
assertion::expression const& E = seed->* 10>=20;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10<20" );
}
{
int i = 10;
assertion::expression const& E = seed->* i != 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10==10" );
}
{
int i = 5;
assertion::expression const& E = seed->* i == 3;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5!=3" );
}
}
//____________________________________________________________________________//
#ifndef BOOST_NO_DECLTYPE
BOOST_AUTO_TEST_CASE( test_arithmetic_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i+j !=8;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3+5==8" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* 2*i-j > 1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2*3-5<=1" );
}
{
int j = 5;
assertion::expression const& E = seed->* 2<<j < 30;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2<<5>=30" );
}
{
int i = 2;
int j = 5;
assertion::expression const& E = seed->* i&j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2&5" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i^j^6;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3^5^6" );
}
// do not support
// assertion::expression const& E = seed->*99/2 == 48 || 101/2 > 50;
// assertion::expression const& E = seed->* a ? 100 < 50 : 25*2 == 50;
// assertion::expression const& E = seed->* true,false;
}
//____________________________________________________________________________//
#endif // BOOST_NO_DECLTYPE
struct Testee {
static int s_copy_counter;
Testee() : m_value( false ) {}
Testee( Testee const& ) : m_value(false) { s_copy_counter++; }
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee( Testee&& ) : m_value(false) {}
#endif
bool foo() { return m_value; }
operator bool() const { return m_value; }
friend std::ostream& operator<<( std::ostream& ostr, Testee const& ) { return ostr << "Testee"; }
bool m_value;
};
int Testee::s_copy_counter = 0;
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee get_obj() { return std::move( Testee() ); }
Testee const get_const_obj() { return std::move( Testee() ); }
#else
Testee get_obj() { return Testee(); }
Testee const get_const_obj() { return Testee(); }
#endif
BOOST_AUTO_TEST_CASE( test_objects )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee const obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 ); // !! ??
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_const_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 ); // !! ??
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_pointers )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee* ptr = 0;
assertion::expression const& E = seed->* ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj1;
Testee obj2;
assertion::expression const& E = seed->* &obj1 == &obj2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj;
Testee* ptr =&obj;
assertion::expression const& E = seed->* *ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
}
#ifndef BOOST_NO_DECLTYPE
{
Testee obj;
Testee* ptr =&obj;
bool Testee::* mem_ptr =&Testee::m_value;
assertion::expression const& E = seed->* ptr->*mem_ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
#endif
// do not support
// Testee obj;
// bool Testee::* mem_ptr =&Testee::m_value;
// assertion::expression const& E = seed->* obj.*mem_ptr;
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_mutating_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int j = 5;
assertion::expression const& E = seed->* j = 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j -= 5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j *= 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j /= 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 4;
assertion::expression const& E = seed->* j %= 2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 4 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j ^= j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
}
//____________________________________________________________________________//
// EOF
<commit_msg>comment fix<commit_after>// (C) Copyright Gennadiy Rozental 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 62023 $
//
// Description : unit test for new assertion construction based on input expression
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MODULE Boost.Test assertion consruction test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/assertion.hpp>
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_basic_value_expression_construction )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = assertion::seed()->*1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
}
{
assertion::expression const& E = seed->*true;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*1.5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#ifndef BOOST_NO_DECLTYPE
{
assertion::expression const& E = seed->* "abc";
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#endif
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_comparison_expression )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
{
assertion::expression const& E = seed->* 100 < 50;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "100>=50" );
}
{
assertion::expression const& E = seed->* 5<=4;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5>4" );
}
{
assertion::expression const& E = seed->* 10>=20;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10<20" );
}
{
int i = 10;
assertion::expression const& E = seed->* i != 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10==10" );
}
{
int i = 5;
assertion::expression const& E = seed->* i == 3;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5!=3" );
}
}
//____________________________________________________________________________//
#ifndef BOOST_NO_DECLTYPE
BOOST_AUTO_TEST_CASE( test_arithmetic_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i+j !=8;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3+5==8" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* 2*i-j > 1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2*3-5<=1" );
}
{
int j = 5;
assertion::expression const& E = seed->* 2<<j < 30;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2<<5>=30" );
}
{
int i = 2;
int j = 5;
assertion::expression const& E = seed->* i&j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2&5" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i^j^6;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3^5^6" );
}
// do not support
// assertion::expression const& E = seed->*99/2 == 48 || 101/2 > 50;
// assertion::expression const& E = seed->* a ? 100 < 50 : 25*2 == 50;
// assertion::expression const& E = seed->* true,false;
}
//____________________________________________________________________________//
#endif // BOOST_NO_DECLTYPE
struct Testee {
static int s_copy_counter;
Testee() : m_value( false ) {}
Testee( Testee const& ) : m_value(false) { s_copy_counter++; }
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee( Testee&& ) : m_value(false) {}
#endif
bool foo() { return m_value; }
operator bool() const { return m_value; }
friend std::ostream& operator<<( std::ostream& ostr, Testee const& ) { return ostr << "Testee"; }
bool m_value;
};
int Testee::s_copy_counter = 0;
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee get_obj() { return std::move( Testee() ); }
Testee const get_const_obj() { return std::move( Testee() ); }
#else
Testee get_obj() { return Testee(); }
Testee const get_const_obj() { return Testee(); }
#endif
BOOST_AUTO_TEST_CASE( test_objects )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee const obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 ); // !! ??
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_const_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 ); // !! ??
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_pointers )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee* ptr = 0;
assertion::expression const& E = seed->* ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj1;
Testee obj2;
assertion::expression const& E = seed->* &obj1 == &obj2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj;
Testee* ptr =&obj;
assertion::expression const& E = seed->* *ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
}
#ifndef BOOST_NO_DECLTYPE
{
Testee obj;
Testee* ptr =&obj;
bool Testee::* mem_ptr =&Testee::m_value;
assertion::expression const& E = seed->* ptr->*mem_ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
#endif
// do not support
// Testee obj;
// bool Testee::* mem_ptr =&Testee::m_value;
// assertion::expression const& E = seed->* obj.*mem_ptr;
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_mutating_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int j = 5;
assertion::expression const& E = seed->* j = 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j -= 5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j *= 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j /= 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 4;
assertion::expression const& E = seed->* j %= 2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 4 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j ^= j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
}
//____________________________________________________________________________//
// EOF
<|endoftext|> |
<commit_before><commit_msg>Improved documentation etc. of normalize method<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2013 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstring>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h> // Needed for OriPriv
#include <errno.h>
#include <sys/un.h>
#include <string>
#include <map>
#include <oriutil/debug.h>
#include <oriutil/oriutil.h>
#include <oriutil/systemexception.h>
#include <ori/repostore.h>
#include <ori/localrepo.h>
#include <ori/udsserver.h>
#include "oricmd.h"
#include "oripriv.h"
using namespace std;
extern OriPriv *priv;
static UDSServer *server;
string
UDSExtensionCB(LocalRepo *repo, const string &data)
{
OriCommand cmd = OriCommand(priv);
return cmd.process(data);
}
void
UDSServerStart(LocalRepo *repo)
{
LOG("Starting Unix domain socket server");
server = new UDSServer(repo);
server->registerExt("FUSE", UDSExtensionCB);
server->start();
return;
}
void
UDSServerStop()
{
server->shutdown();
delete server;
}
<commit_msg>Fix: UDSServer might have been uninitialised upon deletion<commit_after>/*
* Copyright (c) 2012-2013 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstring>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h> // Needed for OriPriv
#include <errno.h>
#include <sys/un.h>
#include <string>
#include <map>
#include <oriutil/debug.h>
#include <oriutil/oriutil.h>
#include <oriutil/systemexception.h>
#include <ori/repostore.h>
#include <ori/localrepo.h>
#include <ori/udsserver.h>
#include "oricmd.h"
#include "oripriv.h"
using namespace std;
extern OriPriv *priv;
static UDSServer *server = NULL;
string
UDSExtensionCB(LocalRepo *repo, const string &data)
{
OriCommand cmd = OriCommand(priv);
return cmd.process(data);
}
void
UDSServerStart(LocalRepo *repo)
{
LOG("Starting Unix domain socket server");
server = new UDSServer(repo);
server->registerExt("FUSE", UDSExtensionCB);
server->start();
return;
}
void
UDSServerStop()
{
server->shutdown();
delete server;
}
<|endoftext|> |
<commit_before><commit_msg>Build fix.<commit_after><|endoftext|> |
<commit_before>// Expose declared constants to matlab for convenience.
#include <mex.h>
#include "mexximp_constants.h"
#include "mexximp_util.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if (1 != nrhs || !mxIsChar(prhs[0])) {
plhs[0] = mexximp::emptyDouble();
return;
}
char* whichConstant = mxArrayToString(prhs[0]);
if (!whichConstant) {
plhs[0] = mexximp::emptyDouble();
return;
}
if (0 == strcmp("scene", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::scene_field_names, COUNT(mexximp::scene_field_names));
} else if(0 == strcmp("camera", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::camera_field_names, COUNT(mexximp::camera_field_names));
} else if(0 == strcmp("light", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::light_field_names, COUNT(mexximp::light_field_names));
} else if(0 == strcmp("material", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::material_field_names, COUNT(mexximp::material_field_names));
} else if(0 == strcmp("materialProperty", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::material_property_field_names, COUNT(mexximp::material_property_field_names));
} else if(0 == strcmp("mesh", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::mesh_field_names, COUNT(mexximp::mesh_field_names));
} else if(0 == strcmp("face", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::face_field_names, COUNT(mexximp::face_field_names));
} else if(0 == strcmp("node", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::node_field_names, COUNT(mexximp::node_field_names));
} else if(0 == strcmp("texture", whichConstant)) {
plhs[0] = mexximp::create_blank_struct(mexximp::texture_field_names, COUNT(mexximp::texture_field_names));
} else if(0 == strcmp("meshPrimitive", whichConstant)) {
plhs[0] = mexximp::mesh_primitive_struct(0);
} else if(0 == strcmp("lightType", whichConstant)) {
plhs[0] = mexximp::create_string_cell(mexximp::light_type_strings, COUNT(mexximp::light_type_strings));
} else if(0 == strcmp("materialPropertyType", whichConstant)) {
plhs[0] = mexximp::create_string_cell(mexximp::material_property_type_strings, COUNT(mexximp::material_property_type_strings));
} else if(0 == strcmp("textureType", whichConstant)) {
plhs[0] = mexximp::create_string_cell(mexximp::texture_type_strings, COUNT(mexximp::texture_type_strings));
} else if(0 == strcmp("materialPropertyKey", whichConstant)) {
plhs[0] = mexximp::create_string_cell(mexximp::nice_key_strings, COUNT(mexximp::nice_key_strings));
} else if(0 == strcmp("postprocessStep", whichConstant)) {
plhs[0] = mexximp::postprocess_step_struct(0);
}
}
<commit_msg>break out list of available constant values<commit_after>// Expose declared constants to matlab for convenience.
#include <mex.h>
#include "mexximp_constants.h"
#include "mexximp_util.h"
static const char* constant_names[] = {
"scene",
"camera",
"light",
"material",
"materialProperty",
"mesh",
"face",
"node",
"texture",
"meshPrimitive",
"lightType",
"materialPropertyType",
"textureType",
"materialPropertyKey",
"postprocessStep",
};
static const mxArray* constant_values[COUNT(constant_names)];
// populate at at call time instead of load
// because they are destroyed between function calls
static const void populate_values() {
unsigned i = 0;
constant_values[i++] = mexximp::create_blank_struct(mexximp::scene_field_names, COUNT(mexximp::scene_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::camera_field_names, COUNT(mexximp::camera_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::light_field_names, COUNT(mexximp::light_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::material_field_names, COUNT(mexximp::material_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::material_property_field_names, COUNT(mexximp::material_property_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::mesh_field_names, COUNT(mexximp::mesh_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::face_field_names, COUNT(mexximp::face_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::node_field_names, COUNT(mexximp::node_field_names));
constant_values[i++] = mexximp::create_blank_struct(mexximp::texture_field_names, COUNT(mexximp::texture_field_names));
constant_values[i++] = mexximp::mesh_primitive_struct(0);
constant_values[i++] = mexximp::create_string_cell(mexximp::light_type_strings, COUNT(mexximp::light_type_strings));
constant_values[i++] = mexximp::create_string_cell(mexximp::material_property_type_strings, COUNT(mexximp::material_property_type_strings));
constant_values[i++] = mexximp::create_string_cell(mexximp::texture_type_strings, COUNT(mexximp::texture_type_strings));
constant_values[i++] = mexximp::create_string_cell(mexximp::nice_key_strings, COUNT(mexximp::nice_key_strings));
constant_values[i++] = mexximp::postprocess_step_struct(0);
}
void printUsage() {
mexPrintf("Get a named constant value declared within mexximp:\n");
mexPrintf(" value = mexximpConstants(name)\n");
mexPrintf("The following named constants are available:\n");
unsigned num_values = COUNT(constant_names);
for (unsigned i=0; i<num_values; i++) {
mexPrintf(" %s\n", constant_names[i]);
}
mexPrintf("\n");
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if (1 != nrhs || !mxIsChar(prhs[0])) {
printUsage();
plhs[0] = mexximp::emptyDouble();
return;
}
char* whichConstant = mxArrayToString(prhs[0]);
int index = mexximp::string_index(constant_names, COUNT(constant_names), whichConstant);
if (0 > index) {
plhs[0] = mexximp::emptyDouble();
return;
}
populate_values();
plhs[0] = mxDuplicateArray(constant_values[index]);
}
<|endoftext|> |
<commit_before>//
// ModifiedRenderingExample.cpp
// ExampleApp
//
// Created by eeGeo on 03/05/2013.
// Copyright (c) 2013 eeGeo. All rights reserved.
//
#include "ModifiedRenderingExample.h"
#include "PooledResource.h"
#include "IStreamingVolume.h"
#include "DiffuseTexturedVertex.h"
#include "MathsHelpers.h"
using namespace Eegeo;
using namespace Eegeo::Rendering;
namespace Examples
{
ModifiedRenderingExample::ModifiedRenderingExample(RenderContext& renderContext,
Eegeo::RenderCamera& renderCamera,
Eegeo::Camera::CameraModel& cameraModel,
Eegeo::Camera::NewGlobeCamera& globeCamera,
Eegeo::Streaming::IStreamingVolume& visibleVolume,
Eegeo::Lighting::GlobalLighting& lighting,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool)
:renderContext(renderContext)
,renderCamera(renderCamera)
,cameraModel(cameraModel)
,visibleVolume(visibleVolume)
,buildingPool(buildingPool)
,shadowPool(shadowPool)
,globeCamera(globeCamera)
,lighting(lighting)
,pCriteria(NULL)
{
}
void ModifiedRenderingExample::Start()
{
//MyPoolFilterCriteria implemented below... uses camera interest point as selection criteria
pCriteria = new ModifiedRenderingExample::MyPoolFilterCriteria(this);
//apply to pools, but lifetime responsibility is ours
buildingPool.SetFilterCriteria(pCriteria);
shadowPool.SetFilterCriteria(pCriteria);
}
void ModifiedRenderingExample::Suspend()
{
//remove it from the pools, and destroy the criteria
buildingPool.SetFilterCriteria(NULL);
shadowPool.SetFilterCriteria(NULL);
delete pCriteria;
pCriteria = NULL;
}
void ModifiedRenderingExample::Update()
{
}
void ModifiedRenderingExample::Draw()
{
//i want to draw the buildings matching the criteria a flat color and transparent...
//if shadows match the filter criteria, just don't draw them
//
//if the buildings match, DrawItems uses my shader and sets state to draw transparently
typedef Eegeo::Resources::PooledMesh<RenderableItem*>* TPooledMeshPtr;
typedef Eegeo::DataStructures::PoolEntry<TPooledMeshPtr> TPoolEntry;
typedef std::vector<TPoolEntry> TResVec;
TResVec filtered;
buildingPool.GetEntriesMeetingFilterCriteria(filtered);
std::vector<RenderableItem*> toRender;
for(TResVec::const_iterator it = filtered.begin(); it != filtered.end(); ++ it)
{
const TPoolEntry& item = *it;
RenderableItem* resource = item.instance->GetResource();
if(item.allocated && resource != NULL && item.instance->ShouldDraw())
{
toRender.push_back(resource);
}
}
//ok, the toRender items were not drawn by the platform, so I should draw them now
DrawItems(toRender);
}
void ModifiedRenderingExample::DrawItems(const std::vector<Eegeo::Rendering::RenderableItem*>& items)
{
GLState& glState = renderContext.GetGLState();
std::vector<Eegeo::Culling::IndexBufferRange> rangesToDraw;
if (glState.UseProgram.TrySet(shader.ProgramHandle))
{
const Eegeo::m44 &colors = lighting.GetColors();
Eegeo_GL(glUniformMatrix4fv(shader.LightColorsUniform, 1, 0, (const GLfloat*)&colors));
}
for(std::vector<RenderableItem*>::const_iterator it = items.begin(); it != items.end(); ++ it)
{
RenderableItem* item = *it;
if(item->IndexCount() == 0) {
continue;
}
//semt-transparent, so we're gonna be blending
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
const Eegeo::dv3& cameraLocalPos = item->GetEcefPosition() - cameraModel.GetWorldPosition();
Eegeo::m44 model, mvp;
Helpers::MathsHelpers::ComputeScaleAndOffset(model, 1.0f, item->GetEcefPosition().Norm().ToSingle(), cameraLocalPos.ToSingle());
Eegeo::m44::Mul(mvp, renderContext.GetViewProjectionMatrix(), model);
Eegeo_GL(glUniformMatrix4fv(shader.ModelViewProjectionUniform, 1, 0, (const GLfloat*)&mvp))
Eegeo_GL(glUniform3f(shader.MinVertRangeUniform,
item->GetMinVertexRange().GetX(),
item->GetMinVertexRange().GetY(),
item->GetMinVertexRange().GetZ()));
Eegeo_GL(glUniform3f(shader.MaxVertRangeUniform,
item->GetMaxVertexRange().GetX(),
item->GetMaxVertexRange().GetY(),
item->GetMaxVertexRange().GetZ()));
Eegeo_GL(glUniform4f(shader.DiffuseColorUniform, 0.0f, 0.0f, 1.0f, 0.1f)); //alpha 10%
Eegeo_GL(glEnableVertexAttribArray(shader.PositionAttribute));
Eegeo_GL(glEnableVertexAttribArray(shader.LightDotAttribute));
glState.BindArrayBuffer(item->GetVertexBuffer());
glState.BindElementArrayBuffer(item->GetIndexBuffer());
//i don't need the UV channel as not texturing them, but it is part of the buulding vertex so must be considered
Eegeo_GL(glVertexAttribPointer(shader.PositionAttribute, 3, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(ShortDiffuseTexturedVertex), 0));
Eegeo_GL(glVertexAttribPointer(shader.LightDotAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(ShortDiffuseTexturedVertex), (GLvoid*) (sizeof(short)*6)));
Eegeo::Culling::CullingVolumeTree& cullingVolumeTree = item->GetCullingVolumeTree();
if(cullingVolumeTree.containsNodes())
{
cullingVolumeTree.ComputeVisibleRanges(visibleVolume, 1.0f, rangesToDraw);
for(std::vector<Eegeo::Culling::IndexBufferRange>::const_iterator range = rangesToDraw.begin(); range != rangesToDraw.end(); ++range)
{
Eegeo_GL(glDrawElements(GL_TRIANGLES, range->NumOfIndices(), GL_UNSIGNED_SHORT, (void*)(range->StartIndex() * 2)));
}
}
else
{
Eegeo_GL(glDrawElements(GL_TRIANGLES, item->IndexCount(), GL_UNSIGNED_SHORT, (void*)0 ));
}
}
glDisable(GL_BLEND);
glState.BindArrayBuffer(0);
glState.BindElementArrayBuffer(0);
}
bool ModifiedRenderingExample::MyPoolFilterCriteria::operator()(Eegeo::Rendering::RenderableItem* item)
{
const double filterRadius = 400.0f;
const double filterRadiusSq = filterRadius*filterRadius;
double delta = (item->GetEcefPosition() - owner->globeCamera.GetInterestPointECEF()).LengthSq();
bool closeToInterest = delta < filterRadiusSq;
if (closeToInterest)
{
return true; //i want to draw with custom semi-transparent rendering method
}
return false; //let the platform do the default rendering
}
}<commit_msg>Fix reference to PooledResource.h, now PooledMesh.h. Buddy: Scott<commit_after>//
// ModifiedRenderingExample.cpp
// ExampleApp
//
// Created by eeGeo on 03/05/2013.
// Copyright (c) 2013 eeGeo. All rights reserved.
//
#include "ModifiedRenderingExample.h"
#include "PooledMesh.h"
#include "IStreamingVolume.h"
#include "DiffuseTexturedVertex.h"
#include "MathsHelpers.h"
using namespace Eegeo;
using namespace Eegeo::Rendering;
namespace Examples
{
ModifiedRenderingExample::ModifiedRenderingExample(RenderContext& renderContext,
Eegeo::RenderCamera& renderCamera,
Eegeo::Camera::CameraModel& cameraModel,
Eegeo::Camera::NewGlobeCamera& globeCamera,
Eegeo::Streaming::IStreamingVolume& visibleVolume,
Eegeo::Lighting::GlobalLighting& lighting,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,
Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool)
:renderContext(renderContext)
,renderCamera(renderCamera)
,cameraModel(cameraModel)
,visibleVolume(visibleVolume)
,buildingPool(buildingPool)
,shadowPool(shadowPool)
,globeCamera(globeCamera)
,lighting(lighting)
,pCriteria(NULL)
{
}
void ModifiedRenderingExample::Start()
{
//MyPoolFilterCriteria implemented below... uses camera interest point as selection criteria
pCriteria = new ModifiedRenderingExample::MyPoolFilterCriteria(this);
//apply to pools, but lifetime responsibility is ours
buildingPool.SetFilterCriteria(pCriteria);
shadowPool.SetFilterCriteria(pCriteria);
}
void ModifiedRenderingExample::Suspend()
{
//remove it from the pools, and destroy the criteria
buildingPool.SetFilterCriteria(NULL);
shadowPool.SetFilterCriteria(NULL);
delete pCriteria;
pCriteria = NULL;
}
void ModifiedRenderingExample::Update()
{
}
void ModifiedRenderingExample::Draw()
{
//i want to draw the buildings matching the criteria a flat color and transparent...
//if shadows match the filter criteria, just don't draw them
//
//if the buildings match, DrawItems uses my shader and sets state to draw transparently
typedef Eegeo::Resources::PooledMesh<RenderableItem*>* TPooledMeshPtr;
typedef Eegeo::DataStructures::PoolEntry<TPooledMeshPtr> TPoolEntry;
typedef std::vector<TPoolEntry> TResVec;
TResVec filtered;
buildingPool.GetEntriesMeetingFilterCriteria(filtered);
std::vector<RenderableItem*> toRender;
for(TResVec::const_iterator it = filtered.begin(); it != filtered.end(); ++ it)
{
const TPoolEntry& item = *it;
RenderableItem* resource = item.instance->GetResource();
if(item.allocated && resource != NULL && item.instance->ShouldDraw())
{
toRender.push_back(resource);
}
}
//ok, the toRender items were not drawn by the platform, so I should draw them now
DrawItems(toRender);
}
void ModifiedRenderingExample::DrawItems(const std::vector<Eegeo::Rendering::RenderableItem*>& items)
{
GLState& glState = renderContext.GetGLState();
std::vector<Eegeo::Culling::IndexBufferRange> rangesToDraw;
if (glState.UseProgram.TrySet(shader.ProgramHandle))
{
const Eegeo::m44 &colors = lighting.GetColors();
Eegeo_GL(glUniformMatrix4fv(shader.LightColorsUniform, 1, 0, (const GLfloat*)&colors));
}
for(std::vector<RenderableItem*>::const_iterator it = items.begin(); it != items.end(); ++ it)
{
RenderableItem* item = *it;
if(item->IndexCount() == 0) {
continue;
}
//semt-transparent, so we're gonna be blending
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
const Eegeo::dv3& cameraLocalPos = item->GetEcefPosition() - cameraModel.GetWorldPosition();
Eegeo::m44 model, mvp;
Helpers::MathsHelpers::ComputeScaleAndOffset(model, 1.0f, item->GetEcefPosition().Norm().ToSingle(), cameraLocalPos.ToSingle());
Eegeo::m44::Mul(mvp, renderContext.GetViewProjectionMatrix(), model);
Eegeo_GL(glUniformMatrix4fv(shader.ModelViewProjectionUniform, 1, 0, (const GLfloat*)&mvp))
Eegeo_GL(glUniform3f(shader.MinVertRangeUniform,
item->GetMinVertexRange().GetX(),
item->GetMinVertexRange().GetY(),
item->GetMinVertexRange().GetZ()));
Eegeo_GL(glUniform3f(shader.MaxVertRangeUniform,
item->GetMaxVertexRange().GetX(),
item->GetMaxVertexRange().GetY(),
item->GetMaxVertexRange().GetZ()));
Eegeo_GL(glUniform4f(shader.DiffuseColorUniform, 0.0f, 0.0f, 1.0f, 0.1f)); //alpha 10%
Eegeo_GL(glEnableVertexAttribArray(shader.PositionAttribute));
Eegeo_GL(glEnableVertexAttribArray(shader.LightDotAttribute));
glState.BindArrayBuffer(item->GetVertexBuffer());
glState.BindElementArrayBuffer(item->GetIndexBuffer());
//i don't need the UV channel as not texturing them, but it is part of the buulding vertex so must be considered
Eegeo_GL(glVertexAttribPointer(shader.PositionAttribute, 3, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(ShortDiffuseTexturedVertex), 0));
Eegeo_GL(glVertexAttribPointer(shader.LightDotAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(ShortDiffuseTexturedVertex), (GLvoid*) (sizeof(short)*6)));
Eegeo::Culling::CullingVolumeTree& cullingVolumeTree = item->GetCullingVolumeTree();
if(cullingVolumeTree.containsNodes())
{
cullingVolumeTree.ComputeVisibleRanges(visibleVolume, 1.0f, rangesToDraw);
for(std::vector<Eegeo::Culling::IndexBufferRange>::const_iterator range = rangesToDraw.begin(); range != rangesToDraw.end(); ++range)
{
Eegeo_GL(glDrawElements(GL_TRIANGLES, range->NumOfIndices(), GL_UNSIGNED_SHORT, (void*)(range->StartIndex() * 2)));
}
}
else
{
Eegeo_GL(glDrawElements(GL_TRIANGLES, item->IndexCount(), GL_UNSIGNED_SHORT, (void*)0 ));
}
}
glDisable(GL_BLEND);
glState.BindArrayBuffer(0);
glState.BindElementArrayBuffer(0);
}
bool ModifiedRenderingExample::MyPoolFilterCriteria::operator()(Eegeo::Rendering::RenderableItem* item)
{
const double filterRadius = 400.0f;
const double filterRadiusSq = filterRadius*filterRadius;
double delta = (item->GetEcefPosition() - owner->globeCamera.GetInterestPointECEF()).LengthSq();
bool closeToInterest = delta < filterRadiusSq;
if (closeToInterest)
{
return true; //i want to draw with custom semi-transparent rendering method
}
return false; //let the platform do the default rendering
}
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2009, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "ConfigurableStoreResultMapper.h"
#include "AnythingUtils.h"
//---- ConfigurableStoreResultMapper ------------------------------------------------------------------
RegisterResultMapper(ConfigurableStoreResultMapper);
void ConfigurableStoreResultMapper::DoGetDestinationAny(const char *key, Anything &targetAny, Context &ctx) {
StartTrace1(ConfigurableStoreResultMapper.DoGetDestinationAny, NotNull(key));
String path = GetDestinationSlot(ctx), kPrefix(key);
if (path.Length() > 0 && kPrefix.Length()) {
path.Append(getDelim());
}
path.Append(kPrefix);
Anything anyConfig;
anyConfig["Store"] = Lookup("Store", "TmpStore");
anyConfig["Slot"] = path;
anyConfig["Delim"] = getDelim();
anyConfig["IndexDelim"] = getIndexDelim();
TraceAny(anyConfig, "StoreFinderConfig");
StoreFinder::Operate(ctx, targetAny, anyConfig);
}
<commit_msg>corrected index-/delim slot values for FindStore call<commit_after>/*
* Copyright (c) 2009, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "ConfigurableStoreResultMapper.h"
#include "AnythingUtils.h"
//---- ConfigurableStoreResultMapper ------------------------------------------------------------------
RegisterResultMapper(ConfigurableStoreResultMapper);
void ConfigurableStoreResultMapper::DoGetDestinationAny(const char *key, Anything &targetAny, Context &ctx) {
StartTrace1(ConfigurableStoreResultMapper.DoGetDestinationAny, NotNull(key));
String path = GetDestinationSlot(ctx), kPrefix(key);
if (path.Length() > 0 && kPrefix.Length()) {
path.Append(getDelim());
}
path.Append(kPrefix);
Anything anyConfig;
anyConfig["Store"] = Lookup("Store", "TmpStore");
anyConfig["Slot"] = path;
anyConfig["Delim"] = String().Append(getDelim());
anyConfig["IndexDelim"] = String().Append(getIndexDelim());
TraceAny(anyConfig, "StoreFinderConfig");
StoreFinder::Operate(ctx, targetAny, anyConfig);
}
<|endoftext|> |
<commit_before>/* ========================================================
* *
* Members 1: Ramiz Alda (100398864) *
* 2: Imina Edebiri (100486339) *
========================================================*/
/* Purpose: Determines the voltage output of an amplifer
depending on the values set for input voltage, resistors,
and type of amplifier selected. */
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
double v_output(double g, double vi, double vsat, double R1, double R2);
double inverting_amplifier(double vi, double vsat, double R1, double R2);
double noninverting_amplifier(double vi, double vsat, double R1, double R2);
double voltage_divider_amplifier(double vi, double vsat, double R1, double R2);
int main () {
// Repeat is set to 'C' to prevent accidental output loss
char repeat('C');
do {
// V saturated is outlined by the problem question as 15 volts
const double vsat(15.0);
double g(0), R1(0), R2(0), vi(0), voutput(0);
cout << " Please enter the input voltage: "; cin >> vi;
cout << "\n The input voltage is v1 = " << vi << " V." << endl;
// The following daisy chains the values from one input into the other. \
There might be a problem with the sample output, where the R1 and R2 may be switched.
int noninvert_output = ceil(noninverting_amplifier(vi, vsat, 75, 5));
cout << " The output voltage of the non-inverting amplifier is v2 = " << noninvert_output << " V." << endl;
int volt_divider_output = ceil(voltage_divider_amplifier(noninvert_output, vsat, 25, 75));
cout << " The output voltage of the voltage divider amplifier is v3 = " << volt_divider_output << " V." << endl;
int invert_output = ceil(inverting_amplifier(volt_divider_output, vsat, 15, 15));
cout << " The output voltage of the inverting amplifier v4 = " << invert_output << " V." << endl;
cout << "\n Would you like to continue? Enter 'C' to continue or 'E' to exit. ";
cin >> repeat;
cout << "\n" << endl;
} while (repeat == 'C' || repeat == 'c');
cout << "\n" << endl;
return 0;
}
//Takes the initial conditions and returns the final v ouput
double v_output(double g, double vi, double vsat, double R1, double R2) {
double v_output(-1);
// Applies modifications for certain condition checks
double vi_g = g*vi;
double neg_vsat = -1*vsat;
// Checks the conditions to set v_output to the approriate value
if (vi_g > vsat) {
v_output = vsat;
} else if (abs(vi_g)) {
v_output = vi_g;
} else if (vi_g < neg_vsat) {
v_output = neg_vsat;
} else { cout << " Invlaid input, check your values." << endl; return -1;}
return v_output;
}
//The difference in amplifiers is only defined by how g is calculated \
the following functions determines the appropriate g and returns the output
double inverting_amplifier(double vi, double vsat, double R1, double R2) {
const double g = -R1/R2; //Gain of the circuit by the inverting amplifier
return v_output(g, vi, vsat, R1, R2);
}
double noninverting_amplifier(double vi, double vsat, double R1, double R2) {
const double g = 1+(R1/R2); //Gain of the circuit by the noninverting amplifier
return v_output(g, vi, vsat, R1, R2);
}
double voltage_divider_amplifier(double vi, double vsat, double R1, double R2) {
const double g = R2/(R1+R2); //Gain of the circuit by the voltage divider amplifier
return v_output(g, vi, vsat, R1, R2);
}<commit_msg>Update 100486339_100398864_assign3_p3.cpp<commit_after>/* ========================================================
* *
* Members 1: Ramiz Alda (100398864) *
* *
========================================================*/
/* Purpose: Determines the voltage output of an amplifer
depending on the values set for input voltage, resistors,
and type of amplifier selected. */
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
double v_output(double g, double vi, double vsat, double R1, double R2);
double inverting_amplifier(double vi, double vsat, double R1, double R2);
double noninverting_amplifier(double vi, double vsat, double R1, double R2);
double voltage_divider_amplifier(double vi, double vsat, double R1, double R2);
int main () {
// Repeat is set to 'C' to prevent accidental output loss
char repeat('C');
do {
// V saturated is outlined by the problem question as 15 volts
const double vsat(15.0);
double g(0), R1(0), R2(0), vi(0), voutput(0);
cout << " Please enter the input voltage: "; cin >> vi;
cout << "\n The input voltage is v1 = " << vi << " V." << endl;
// The following daisy chains the values from one input into the other. \
There might be a problem with the sample output, where the R1 and R2 may be switched.
int noninvert_output = ceil(noninverting_amplifier(vi, vsat, 75, 5));
cout << " The output voltage of the non-inverting amplifier is v2 = " << noninvert_output << " V." << endl;
int volt_divider_output = ceil(voltage_divider_amplifier(noninvert_output, vsat, 25, 75));
cout << " The output voltage of the voltage divider amplifier is v3 = " << volt_divider_output << " V." << endl;
int invert_output = ceil(inverting_amplifier(volt_divider_output, vsat, 15, 15));
cout << " The output voltage of the inverting amplifier v4 = " << invert_output << " V." << endl;
cout << "\n Would you like to continue? Enter 'C' to continue or 'E' to exit. ";
cin >> repeat;
cout << "\n" << endl;
} while (repeat == 'C' || repeat == 'c');
cout << "\n" << endl;
return 0;
}
//Takes the initial conditions and returns the final v ouput
double v_output(double g, double vi, double vsat, double R1, double R2) {
double v_output(-1);
// Applies modifications for certain condition checks
double vi_g = g*vi;
double neg_vsat = -1*vsat;
// Checks the conditions to set v_output to the approriate value
if (vi_g > vsat) {
v_output = vsat;
} else if (abs(vi_g)) {
v_output = vi_g;
} else if (vi_g < neg_vsat) {
v_output = neg_vsat;
} else { cout << " Invlaid input, check your values." << endl; return -1;}
return v_output;
}
//The difference in amplifiers is only defined by how g is calculated \
the following functions determines the appropriate g and returns the output
double inverting_amplifier(double vi, double vsat, double R1, double R2) {
const double g = -R1/R2; //Gain of the circuit by the inverting amplifier
return v_output(g, vi, vsat, R1, R2);
}
double noninverting_amplifier(double vi, double vsat, double R1, double R2) {
const double g = 1+(R1/R2); //Gain of the circuit by the noninverting amplifier
return v_output(g, vi, vsat, R1, R2);
}
double voltage_divider_amplifier(double vi, double vsat, double R1, double R2) {
const double g = R2/(R1+R2); //Gain of the circuit by the voltage divider amplifier
return v_output(g, vi, vsat, R1, R2);
}
<|endoftext|> |
<commit_before>#include "Date.h"
#include "components/debug/Debug.h"
const int Date::INITIAL_YEAR = 389;
const int Date::MONTHS_PER_YEAR = 12;
const int Date::DAYS_PER_MONTH = 30;
const int Date::DAYS_PER_WEEK = 7;
Date::Date(int year, int month, int day)
{
// Make sure each value is in a valid range.
DebugAssert(year >= 1);
DebugAssert(month >= 0);
DebugAssert(month < Date::MONTHS_PER_YEAR);
DebugAssert(day >= 0);
DebugAssert(day < Date::DAYS_PER_MONTH);
this->year = year;
this->month = month;
this->day = day;
}
Date::Date(int month, int day)
: Date(Date::INITIAL_YEAR, month, day) { }
Date::Date()
: Date(Date::INITIAL_YEAR, 0, 0) { }
int Date::getYear() const
{
return this->year;
}
int Date::getMonth() const
{
return this->month;
}
int Date::getWeekday() const
{
// For now, all months start on the same weekday (Monday).
return this->day % Date::DAYS_PER_WEEK;
}
int Date::getDay() const
{
return this->day;
}
std::string Date::getOrdinalDay() const
{
// The current day is zero-based, so add one to get the "actual" day.
const int displayedDay = this->day + 1;
const int ordinalDay = displayedDay % 10;
auto dayString = std::to_string(displayedDay);
if (ordinalDay == 1)
{
dayString += "st";
}
else if (ordinalDay == 2)
{
dayString += "nd";
}
else if (ordinalDay == 3)
{
dayString += "rd";
}
else
{
dayString += "th";
}
return dayString;
}
int Date::getSeason() const
{
return ((this->month + 10) % Date::MONTHS_PER_YEAR) / 3;
}
void Date::incrementYear()
{
this->year++;
}
void Date::incrementMonth()
{
this->month++;
if (this->month == Date::MONTHS_PER_YEAR)
{
this->incrementYear();
this->month = 0;
}
}
void Date::incrementDay()
{
this->day++;
if (this->day == Date::DAYS_PER_MONTH)
{
this->incrementMonth();
this->day = 0;
}
}
<commit_msg>Fixed bug with ordinal days (11st, etc.).<commit_after>#include "Date.h"
#include "components/debug/Debug.h"
const int Date::INITIAL_YEAR = 389;
const int Date::MONTHS_PER_YEAR = 12;
const int Date::DAYS_PER_MONTH = 30;
const int Date::DAYS_PER_WEEK = 7;
Date::Date(int year, int month, int day)
{
// Make sure each value is in a valid range.
DebugAssert(year >= 1);
DebugAssert(month >= 0);
DebugAssert(month < Date::MONTHS_PER_YEAR);
DebugAssert(day >= 0);
DebugAssert(day < Date::DAYS_PER_MONTH);
this->year = year;
this->month = month;
this->day = day;
}
Date::Date(int month, int day)
: Date(Date::INITIAL_YEAR, month, day) { }
Date::Date()
: Date(Date::INITIAL_YEAR, 0, 0) { }
int Date::getYear() const
{
return this->year;
}
int Date::getMonth() const
{
return this->month;
}
int Date::getWeekday() const
{
// For now, all months start on the same weekday (Monday).
return this->day % Date::DAYS_PER_WEEK;
}
int Date::getDay() const
{
return this->day;
}
std::string Date::getOrdinalDay() const
{
// The current day is zero-based, so add one to get the "actual" day.
const int displayedDay = this->day + 1;
const int ordinalDay = displayedDay % 10;
// Days in the teens have some special cases.
auto dayString = std::to_string(displayedDay);
if ((ordinalDay == 1) && (displayedDay != 11))
{
dayString += "st";
}
else if ((ordinalDay == 2) && (displayedDay != 12))
{
dayString += "nd";
}
else if ((ordinalDay == 3) && (displayedDay != 13))
{
dayString += "rd";
}
else
{
dayString += "th";
}
return dayString;
}
int Date::getSeason() const
{
return ((this->month + 10) % Date::MONTHS_PER_YEAR) / 3;
}
void Date::incrementYear()
{
this->year++;
}
void Date::incrementMonth()
{
this->month++;
if (this->month == Date::MONTHS_PER_YEAR)
{
this->incrementYear();
this->month = 0;
}
}
void Date::incrementDay()
{
this->day++;
if (this->day == Date::DAYS_PER_MONTH)
{
this->incrementMonth();
this->day = 0;
}
}
<|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 "base/scoped_temp_dir.h"
#include "base/file_util.h"
#include "base/logging.h"
ScopedTempDir::ScopedTempDir() {
}
ScopedTempDir::~ScopedTempDir() {
if (!path_.empty() && !Delete())
DLOG(WARNING) << "Could not delete temp dir in dtor.";
}
bool ScopedTempDir::CreateUniqueTempDir() {
if (!path_.empty())
return false;
// This "scoped_dir" prefix is only used on Windows and serves as a template
// for the unique name.
if (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_dir"),
&path_))
return false;
return true;
}
bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) {
if (!path_.empty())
return false;
// If |base_path| does not exist, create it.
if (!file_util::CreateDirectory(base_path))
return false;
// Create a new, uniquely named directory under |base_path|.
if (!file_util::CreateTemporaryDirInDir(
base_path,
FILE_PATH_LITERAL("scoped_dir_"),
&path_))
return false;
return true;
}
bool ScopedTempDir::Set(const FilePath& path) {
if (!path_.empty())
return false;
if (!file_util::DirectoryExists(path) &&
!file_util::CreateDirectory(path))
return false;
path_ = path;
return true;
}
bool ScopedTempDir::Delete() {
LOG(WARNING) << "Deleting " << path_.LossyDisplayName() << " " << this;
if (path_.empty())
return false;
bool ret = file_util::Delete(path_, true);
if (ret) {
// We only clear the path if deleted the directory.
path_.clear();
} else {
DLOG(ERROR) << "ScopedTempDir unable to delete " << path_.value();
}
return ret;
}
FilePath ScopedTempDir::Take() {
FilePath ret = path_;
path_ = FilePath();
return ret;
}
bool ScopedTempDir::IsValid() const {
return !path_.empty() && file_util::DirectoryExists(path_);
}
<commit_msg>Remove log spew from scoped_tempdir.cc.<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 "base/scoped_temp_dir.h"
#include "base/file_util.h"
#include "base/logging.h"
ScopedTempDir::ScopedTempDir() {
}
ScopedTempDir::~ScopedTempDir() {
if (!path_.empty() && !Delete())
DLOG(WARNING) << "Could not delete temp dir in dtor.";
}
bool ScopedTempDir::CreateUniqueTempDir() {
if (!path_.empty())
return false;
// This "scoped_dir" prefix is only used on Windows and serves as a template
// for the unique name.
if (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_dir"),
&path_))
return false;
return true;
}
bool ScopedTempDir::CreateUniqueTempDirUnderPath(const FilePath& base_path) {
if (!path_.empty())
return false;
// If |base_path| does not exist, create it.
if (!file_util::CreateDirectory(base_path))
return false;
// Create a new, uniquely named directory under |base_path|.
if (!file_util::CreateTemporaryDirInDir(
base_path,
FILE_PATH_LITERAL("scoped_dir_"),
&path_))
return false;
return true;
}
bool ScopedTempDir::Set(const FilePath& path) {
if (!path_.empty())
return false;
if (!file_util::DirectoryExists(path) &&
!file_util::CreateDirectory(path))
return false;
path_ = path;
return true;
}
bool ScopedTempDir::Delete() {
if (path_.empty())
return false;
bool ret = file_util::Delete(path_, true);
if (ret) {
// We only clear the path if deleted the directory.
path_.clear();
}
return ret;
}
FilePath ScopedTempDir::Take() {
FilePath ret = path_;
path_ = FilePath();
return ret;
}
bool ScopedTempDir::IsValid() const {
return !path_.empty() && file_util::DirectoryExists(path_);
}
<|endoftext|> |
<commit_before>/*
* 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
*
* 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.
*
* Modified by Cloudius Systems
* Copyright 2015 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dht/range_streamer.hh"
#include "utils/fb_utilities.hh"
#include "locator/snitch_base.hh"
#include "database.hh"
#include "gms/gossiper.hh"
#include "gms/failure_detector.hh"
#include "log.hh"
#include "streaming/stream_plan.hh"
#include "streaming/stream_state.hh"
namespace dht {
logging::logger logger("range_streamer");
using inet_address = gms::inet_address;
static std::unordered_map<range<token>, std::unordered_set<inet_address>>
unordered_multimap_to_unordered_map(const std::unordered_multimap<range<token>, inet_address>& multimap) {
std::unordered_map<range<token>, std::unordered_set<inet_address>> ret;
for (auto x : multimap) {
auto& range_token = x.first;
auto& ep = x.second;
auto it = ret.find(range_token);
if (it != ret.end()) {
it->second.emplace(ep);
} else {
ret.emplace(range_token, std::unordered_set<inet_address>{ep});
}
}
return ret;
}
std::unordered_multimap<inet_address, range<token>>
range_streamer::get_range_fetch_map(const std::unordered_multimap<range<token>, inet_address>& ranges_with_sources,
const std::unordered_set<std::unique_ptr<i_source_filter>>& source_filters,
const sstring& keyspace) {
std::unordered_multimap<inet_address, range<token>> range_fetch_map_map;
for (auto x : unordered_multimap_to_unordered_map(ranges_with_sources)) {
const range<token>& range_ = x.first;
const std::unordered_set<inet_address>& addresses = x.second;
bool found_source = false;
for (auto address : addresses) {
if (address == utils::fb_utilities::get_broadcast_address()) {
// If localhost is a source, we have found one, but we don't add it to the map to avoid streaming locally
found_source = true;
continue;
}
auto filtered = false;
for (const auto& filter : source_filters) {
if (!filter->should_include(address)) {
filtered = true;
break;
}
}
if (filtered) {
continue;
}
range_fetch_map_map.emplace(address, range_);
found_source = true;
break; // ensure we only stream from one other node for each range
}
if (!found_source) {
throw std::runtime_error(sprint("unable to find sufficient sources for streaming range %s in keyspace %s", range_, keyspace));
}
}
return range_fetch_map_map;
}
std::unordered_multimap<range<token>, inet_address>
range_streamer::get_all_ranges_with_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges) {
logger.debug("{} ks={}", __func__, keyspace_name);
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strat = ks.get_replication_strategy();
// std::unordered_multimap<range<token>, inet_address>
auto tm = _metadata.clone_only_token_map();
auto range_addresses = unordered_multimap_to_unordered_map(strat.get_range_addresses(tm));
std::unordered_multimap<range<token>, inet_address> range_sources;
auto& snitch = locator::i_endpoint_snitch::get_local_snitch_ptr();
for (auto& desired_range : desired_ranges) {
auto found = false;
for (auto& x : range_addresses) {
const range<token>& src_range = x.first;
if (src_range.contains(desired_range, dht::tri_compare)) {
std::unordered_set<inet_address>& addresses = x.second;
auto preferred = snitch->get_sorted_list_by_proximity(_address, addresses);
for (inet_address& p : preferred) {
range_sources.emplace(desired_range, p);
}
found = true;
}
}
if (!found) {
throw std::runtime_error(sprint("No sources found for %s", desired_range));
}
}
return range_sources;
}
std::unordered_multimap<range<token>, inet_address>
range_streamer::get_all_ranges_with_strict_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges) {
logger.debug("{} ks={}", __func__, keyspace_name);
assert (_tokens.empty() == false);
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strat = ks.get_replication_strategy();
//Active ranges
auto metadata_clone = _metadata.clone_only_token_map();
auto range_addresses = unordered_multimap_to_unordered_map(strat.get_range_addresses(metadata_clone));
//Pending ranges
metadata_clone.update_normal_tokens(_tokens, _address);
auto pending_range_addresses = unordered_multimap_to_unordered_map(strat.get_range_addresses(metadata_clone));
//Collects the source that will have its range moved to the new node
std::unordered_multimap<range<token>, inet_address> range_sources;
for (auto& desired_range : desired_ranges) {
for (auto& x : range_addresses) {
const range<token>& src_range = x.first;
if (src_range.contains(desired_range, dht::tri_compare)) {
std::vector<inet_address> old_endpoints(x.second.begin(), x.second.end());
auto it = pending_range_addresses.find(desired_range);
if (it == pending_range_addresses.end()) {
throw std::runtime_error(sprint("Can not find desired_range = {} in pending_range_addresses", desired_range));
}
std::unordered_set<inet_address> new_endpoints = it->second;
//Due to CASSANDRA-5953 we can have a higher RF then we have endpoints.
//So we need to be careful to only be strict when endpoints == RF
if (old_endpoints.size() == strat.get_replication_factor()) {
auto it = std::remove_if(old_endpoints.begin(), old_endpoints.end(),
[&new_endpoints] (inet_address ep) { return new_endpoints.count(ep); });
old_endpoints.erase(it, old_endpoints.end());
if (old_endpoints.size() != 1) {
throw std::runtime_error(sprint("Expected 1 endpoint but found %d", old_endpoints.size()));
}
}
range_sources.emplace(desired_range, old_endpoints.front());
}
}
//Validate
auto nr = range_sources.count(desired_range);
if (nr < 1) {
throw std::runtime_error(sprint("No sources found for %s", desired_range));
}
if (nr > 1) {
throw std::runtime_error(sprint("Multiple endpoints found for %s", desired_range));
}
inet_address source_ip = range_sources.find(desired_range)->second;
auto& gossiper = gms::get_local_gossiper();
auto source_state = gossiper.get_endpoint_state_for_endpoint(source_ip);
if (gossiper.is_enabled() && source_state && !source_state->is_alive()) {
throw std::runtime_error(sprint("A node required to move the data consistently is down (%s). If you wish to move the data from a potentially inconsistent replica, restart the node with -Dcassandra.consistent.rangemovement=false", source_ip));
}
}
return range_sources;
}
bool range_streamer::use_strict_sources_for_ranges(const sstring& keyspace_name) {
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strat = ks.get_replication_strategy();
// FIXME: DatabaseDescriptor.isReplacing()
auto is_replacing = false;
return !is_replacing
&& use_strict_consistency()
&& !_tokens.empty()
&& _metadata.get_all_endpoints().size() != strat.get_replication_factor();
}
void range_streamer::add_ranges(const sstring& keyspace_name, std::vector<range<token>> ranges) {
auto ranges_for_keyspace = use_strict_sources_for_ranges(keyspace_name)
? get_all_ranges_with_strict_sources_for(keyspace_name, ranges)
: get_all_ranges_with_sources_for(keyspace_name, ranges);
if (logger.is_enabled(logging::log_level::debug)) {
for (auto& x : ranges_for_keyspace) {
logger.debug("{} : range {} exists on {}", _description, x.first, x.second);
}
}
// TODO: share code with unordered_multimap_to_unordered_map
std::unordered_map<inet_address, std::vector<range<token>>> tmp;
for (auto& x : get_range_fetch_map(ranges_for_keyspace, _source_filters, keyspace_name)) {
auto& addr = x.first;
auto& range_ = x.second;
auto it = tmp.find(addr);
if (it != tmp.end()) {
it->second.push_back(range_);
} else {
tmp.emplace(addr, std::vector<range<token>>{range_});
}
}
if (logger.is_enabled(logging::log_level::debug)) {
for (auto& x : tmp) {
logger.debug("{} : range {} from source {} for keyspace {}", _description, x.second, x.first, keyspace_name);
}
}
_to_fetch.emplace(keyspace_name, std::move(tmp));
}
future<streaming::stream_state> range_streamer::fetch_async() {
for (auto& fetch : _to_fetch) {
const auto& keyspace = fetch.first;
for (auto& x : fetch.second) {
auto& source = x.first;
auto& ranges = x.second;
auto preferred = net::get_local_messaging_service().get_preferred_ip(source);
/* Send messages to respective folks to stream data over to me */
if (logger.is_enabled(logging::log_level::debug)) {
logger.debug("{}ing from {} ranges {}", _description, source, ranges);
}
_stream_plan.request_ranges(source, preferred, keyspace, ranges);
}
}
return _stream_plan.execute();
}
std::unordered_multimap<inet_address, range<token>>
range_streamer::get_work_map(const std::unordered_multimap<range<token>, inet_address>& ranges_with_source_target,
const sstring& keyspace) {
auto filter = std::make_unique<dht::range_streamer::failure_detector_source_filter>(gms::get_local_failure_detector());
std::unordered_set<std::unique_ptr<i_source_filter>> source_filters;
source_filters.emplace(std::move(filter));
return get_range_fetch_map(ranges_with_source_target, source_filters, keyspace);
}
} // dht
<commit_msg>range_streamer: Simplify unordered_multimap_to_unordered_map<commit_after>/*
* 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
*
* 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.
*
* Modified by Cloudius Systems
* Copyright 2015 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dht/range_streamer.hh"
#include "utils/fb_utilities.hh"
#include "locator/snitch_base.hh"
#include "database.hh"
#include "gms/gossiper.hh"
#include "gms/failure_detector.hh"
#include "log.hh"
#include "streaming/stream_plan.hh"
#include "streaming/stream_state.hh"
namespace dht {
logging::logger logger("range_streamer");
using inet_address = gms::inet_address;
static std::unordered_map<range<token>, std::unordered_set<inet_address>>
unordered_multimap_to_unordered_map(const std::unordered_multimap<range<token>, inet_address>& multimap) {
std::unordered_map<range<token>, std::unordered_set<inet_address>> ret;
for (auto x : multimap) {
ret[x.first].emplace(x.second);
}
return ret;
}
std::unordered_multimap<inet_address, range<token>>
range_streamer::get_range_fetch_map(const std::unordered_multimap<range<token>, inet_address>& ranges_with_sources,
const std::unordered_set<std::unique_ptr<i_source_filter>>& source_filters,
const sstring& keyspace) {
std::unordered_multimap<inet_address, range<token>> range_fetch_map_map;
for (auto x : unordered_multimap_to_unordered_map(ranges_with_sources)) {
const range<token>& range_ = x.first;
const std::unordered_set<inet_address>& addresses = x.second;
bool found_source = false;
for (auto address : addresses) {
if (address == utils::fb_utilities::get_broadcast_address()) {
// If localhost is a source, we have found one, but we don't add it to the map to avoid streaming locally
found_source = true;
continue;
}
auto filtered = false;
for (const auto& filter : source_filters) {
if (!filter->should_include(address)) {
filtered = true;
break;
}
}
if (filtered) {
continue;
}
range_fetch_map_map.emplace(address, range_);
found_source = true;
break; // ensure we only stream from one other node for each range
}
if (!found_source) {
throw std::runtime_error(sprint("unable to find sufficient sources for streaming range %s in keyspace %s", range_, keyspace));
}
}
return range_fetch_map_map;
}
std::unordered_multimap<range<token>, inet_address>
range_streamer::get_all_ranges_with_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges) {
logger.debug("{} ks={}", __func__, keyspace_name);
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strat = ks.get_replication_strategy();
// std::unordered_multimap<range<token>, inet_address>
auto tm = _metadata.clone_only_token_map();
auto range_addresses = unordered_multimap_to_unordered_map(strat.get_range_addresses(tm));
std::unordered_multimap<range<token>, inet_address> range_sources;
auto& snitch = locator::i_endpoint_snitch::get_local_snitch_ptr();
for (auto& desired_range : desired_ranges) {
auto found = false;
for (auto& x : range_addresses) {
const range<token>& src_range = x.first;
if (src_range.contains(desired_range, dht::tri_compare)) {
std::unordered_set<inet_address>& addresses = x.second;
auto preferred = snitch->get_sorted_list_by_proximity(_address, addresses);
for (inet_address& p : preferred) {
range_sources.emplace(desired_range, p);
}
found = true;
}
}
if (!found) {
throw std::runtime_error(sprint("No sources found for %s", desired_range));
}
}
return range_sources;
}
std::unordered_multimap<range<token>, inet_address>
range_streamer::get_all_ranges_with_strict_sources_for(const sstring& keyspace_name, std::vector<range<token>> desired_ranges) {
logger.debug("{} ks={}", __func__, keyspace_name);
assert (_tokens.empty() == false);
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strat = ks.get_replication_strategy();
//Active ranges
auto metadata_clone = _metadata.clone_only_token_map();
auto range_addresses = unordered_multimap_to_unordered_map(strat.get_range_addresses(metadata_clone));
//Pending ranges
metadata_clone.update_normal_tokens(_tokens, _address);
auto pending_range_addresses = unordered_multimap_to_unordered_map(strat.get_range_addresses(metadata_clone));
//Collects the source that will have its range moved to the new node
std::unordered_multimap<range<token>, inet_address> range_sources;
for (auto& desired_range : desired_ranges) {
for (auto& x : range_addresses) {
const range<token>& src_range = x.first;
if (src_range.contains(desired_range, dht::tri_compare)) {
std::vector<inet_address> old_endpoints(x.second.begin(), x.second.end());
auto it = pending_range_addresses.find(desired_range);
if (it == pending_range_addresses.end()) {
throw std::runtime_error(sprint("Can not find desired_range = {} in pending_range_addresses", desired_range));
}
std::unordered_set<inet_address> new_endpoints = it->second;
//Due to CASSANDRA-5953 we can have a higher RF then we have endpoints.
//So we need to be careful to only be strict when endpoints == RF
if (old_endpoints.size() == strat.get_replication_factor()) {
auto it = std::remove_if(old_endpoints.begin(), old_endpoints.end(),
[&new_endpoints] (inet_address ep) { return new_endpoints.count(ep); });
old_endpoints.erase(it, old_endpoints.end());
if (old_endpoints.size() != 1) {
throw std::runtime_error(sprint("Expected 1 endpoint but found %d", old_endpoints.size()));
}
}
range_sources.emplace(desired_range, old_endpoints.front());
}
}
//Validate
auto nr = range_sources.count(desired_range);
if (nr < 1) {
throw std::runtime_error(sprint("No sources found for %s", desired_range));
}
if (nr > 1) {
throw std::runtime_error(sprint("Multiple endpoints found for %s", desired_range));
}
inet_address source_ip = range_sources.find(desired_range)->second;
auto& gossiper = gms::get_local_gossiper();
auto source_state = gossiper.get_endpoint_state_for_endpoint(source_ip);
if (gossiper.is_enabled() && source_state && !source_state->is_alive()) {
throw std::runtime_error(sprint("A node required to move the data consistently is down (%s). If you wish to move the data from a potentially inconsistent replica, restart the node with -Dcassandra.consistent.rangemovement=false", source_ip));
}
}
return range_sources;
}
bool range_streamer::use_strict_sources_for_ranges(const sstring& keyspace_name) {
auto& ks = _db.local().find_keyspace(keyspace_name);
auto& strat = ks.get_replication_strategy();
// FIXME: DatabaseDescriptor.isReplacing()
auto is_replacing = false;
return !is_replacing
&& use_strict_consistency()
&& !_tokens.empty()
&& _metadata.get_all_endpoints().size() != strat.get_replication_factor();
}
void range_streamer::add_ranges(const sstring& keyspace_name, std::vector<range<token>> ranges) {
auto ranges_for_keyspace = use_strict_sources_for_ranges(keyspace_name)
? get_all_ranges_with_strict_sources_for(keyspace_name, ranges)
: get_all_ranges_with_sources_for(keyspace_name, ranges);
if (logger.is_enabled(logging::log_level::debug)) {
for (auto& x : ranges_for_keyspace) {
logger.debug("{} : range {} exists on {}", _description, x.first, x.second);
}
}
// TODO: share code with unordered_multimap_to_unordered_map
std::unordered_map<inet_address, std::vector<range<token>>> tmp;
for (auto& x : get_range_fetch_map(ranges_for_keyspace, _source_filters, keyspace_name)) {
auto& addr = x.first;
auto& range_ = x.second;
auto it = tmp.find(addr);
if (it != tmp.end()) {
it->second.push_back(range_);
} else {
tmp.emplace(addr, std::vector<range<token>>{range_});
}
}
if (logger.is_enabled(logging::log_level::debug)) {
for (auto& x : tmp) {
logger.debug("{} : range {} from source {} for keyspace {}", _description, x.second, x.first, keyspace_name);
}
}
_to_fetch.emplace(keyspace_name, std::move(tmp));
}
future<streaming::stream_state> range_streamer::fetch_async() {
for (auto& fetch : _to_fetch) {
const auto& keyspace = fetch.first;
for (auto& x : fetch.second) {
auto& source = x.first;
auto& ranges = x.second;
auto preferred = net::get_local_messaging_service().get_preferred_ip(source);
/* Send messages to respective folks to stream data over to me */
if (logger.is_enabled(logging::log_level::debug)) {
logger.debug("{}ing from {} ranges {}", _description, source, ranges);
}
_stream_plan.request_ranges(source, preferred, keyspace, ranges);
}
}
return _stream_plan.execute();
}
std::unordered_multimap<inet_address, range<token>>
range_streamer::get_work_map(const std::unordered_multimap<range<token>, inet_address>& ranges_with_source_target,
const sstring& keyspace) {
auto filter = std::make_unique<dht::range_streamer::failure_detector_source_filter>(gms::get_local_failure_detector());
std::unordered_set<std::unique_ptr<i_source_filter>> source_filters;
source_filters.emplace(std::move(filter));
return get_range_fetch_map(ranges_with_source_target, source_filters, keyspace);
}
} // dht
<|endoftext|> |
<commit_before>#ifndef NEW_AIO_H
#define NEW_AIO_H
/*Defines virtual AIO objects to be instantiated
by concrete implementation in the src/ file.
*/
#include<string>
#include<vector>
#include<stdexcept>
#include<stdint.h>
#include<boost/shared_ptr.hpp>
class Process;
class Symbol;
/*
The AIO is based on event objects. Event
objects are just passive requests; in order to
"arm" an event, it should be added to the global
event waiting set object.
Events are:
1. Write-to-I/O event
2. Read-from-I/O event
3. Accept-from-I/O Socket event
4. Sleep Event
5. System Event (i.e. spawn child OS process)
*/
/*Details are handled by the AIO implementation
This include file deals only in abstractions;
we don't care how they are actually implemented.
*/
class Event;
class ProcessInvoker;
/*Errors in I/O should throw this class*/
/*Could use a Maybe T type I suppose though*/
class IOError : public std::runtime_error {
};
/*
Errors are caught only on:
1. opening a file
2. seeking
3. closing
In all other cases, errors are caught at the time
that events are triggered; they are reported by
sending messages to the process being informed.
*/
/*-----------------------------------------------------------------------------
Implementation-specific
-----------------------------------------------------------------------------*/
/*I/O Ports*/
class IOPort {
public:
void close(void);
/*If the read completed immediately, return a null
pointer and put a value into now_read. Otherwise,
put a null pointer into now_read and return an
event.
*/
virtual boost::shared_ptr<Event> read(
boost::shared_ptr<ProcessInvoker>, size_t
boost::shared_ptr<std::vector<unsigned char> >& now_read
) =0;
/*return a null pointer if data-writing was successfully
completed.
*/
virtual boost::shared_ptr<Event> write(
boost::shared_ptr<ProcessInvoker>,
std::vector<unsigned char> const&
) =0;
virtual boost::shared_ptr<Event> accept(
boost::shared_ptr<ProcessInvoker>
) =0;
virtual ~IOPort() { }
};
/*Will only be called once, at init*/
boost::shared_ptr<IOPort> ioport_stdin(void);
boost::shared_ptr<IOPort> ioport_stdout(void);
boost::shared_ptr<IOPort> ioport_stderr(void);
boost::shared_ptr<IOPort> infile(std::string);
boost::shared_ptr<IOPort> outfile(std::string);
boost::shared_ptr<IOPort> appendfile(std::string);
void close(boost::shared_ptr<IOPort>);
class Event {
public:
virtual void seek(uint64_t) =0;
virtual ~Event() { }
};
boost::shared_ptr<Event> system_event(boost::shared_ptr<ProcessInvoker>,std::string);
/*sleep unit is milliseconds*/
boost::shared_ptr<Event> sleep_event(boost::shared_ptr<ProcessInvoker>,size_t);
/*connect to host's port*/
boost::shared_ptr<Event> connect_event(boost::shared_ptr<ProcessInvoker>,std::string,int);
class ProcessInvokerScanner;
/*used as a Singleton, although we don't enforce it*/
/*specific AIO implementation has to enforce Singleton-ness*/
class EventSetImpl;
class EventSet {
private:
EventSetImpl* pimpl;
public:
void add_event(boost::shared_ptr<Event>);
void remove_event(boost::shared_ptr<Event>);
/*"host" is the process which performed the
'event-wait or 'event-poll bytecode.
*/
void event_poll(Process& host);
void event_wait(Process& host);
EventSet(void);
~EventSet();
/*This member function is called on the global
event set by the thread pool. This function
should then call the traverse() member function
of the given ProcessInvokerScanner on each
process invoker of each live event.
This call is assuredly made when only one thread
is running, and thus does not require any special
threading protection.
*/
void scan_process_invokers(ProcessInvokerScanner*);
};
/*get *the* EventSet*/
EventSet& the_event_set(void);
/*PROMISE: we won't call the above function unless
we have called aio_initialize() below, once, first.
*/
/*initialize and clean-up aio (including creation of *the* EventSet)*/
void aio_initialize(void);
void aio_deinitialize(void);
/*called at the initialization/cleanup of each thread*/
/*NOT called on main process thread*/
void aio_thread_initialize(void);
void aio_thread_deinitialize(void);
/*-----------------------------------------------------------------------------
Shared across Implementations
-----------------------------------------------------------------------------*/
class ProcessInvokerScanner {
public:
virtual void traverse(ProcessInvoker const&) =0;
virtual ~ProcessInvokerScanner() { }
};
/*implementations in src/aio.cpp*/
class ProcessInvoker {
private:
ProcessInvoker(void); //disallowed
public:
Process* P;
/*"host" parameter is just a heap that can be used to
conveniently construct the response before actually
sending it to the target process. It is *not* the
target process: it's just used as a scratch heap.
Reusing an existing process (specifically the process
that called the event waiting/polling) reduces
allocation overhead.
*/
void io_respond(
Process& host,
boost::shared_ptr<IOPort>,
boost::shared_ptr<std::vector<unsigned char> >&
);
void nil_respond(
Process& host,
boost::shared_ptr<IOPort>
);
void accept_respond(
Process& host,
boost::shared_ptr<IOPort> socket,
boost::shared_ptr<IOPort> new_socket
);
void connect_respond(
Process& host,
boost::shared_ptr<Event>, boost::shared_ptr<IOPort> new_socket
);
void sleep_respond(
Process& host,
boost::shared_ptr<Event>, size_t
);
void system_respond(
Process& host,
boost::shared_ptr<Event>, int term_code
);
/*call for errors*/
void io_error_respond(
Process& host,
boost::shared_ptr<IOPort>, std::string const&
);
void other_error_respond(
Process& host,
boost::shared_ptr<Event>, std::string const&
);
explicit ProcessInvoker(Process*);
~ProcessInvoker(void);
};
#endif // NEW_AIO_H
<commit_msg>inc/aio.hpp: Corrected close() member function.<commit_after>#ifndef NEW_AIO_H
#define NEW_AIO_H
/*Defines virtual AIO objects to be instantiated
by concrete implementation in the src/ file.
*/
#include<string>
#include<vector>
#include<stdexcept>
#include<stdint.h>
#include<boost/shared_ptr.hpp>
class Process;
class Symbol;
/*
The AIO is based on event objects. Event
objects are just passive requests; in order to
"arm" an event, it should be added to the global
event waiting set object.
Events are:
1. Write-to-I/O event
2. Read-from-I/O event
3. Accept-from-I/O Socket event
4. Sleep Event
5. System Event (i.e. spawn child OS process)
*/
/*Details are handled by the AIO implementation
This include file deals only in abstractions;
we don't care how they are actually implemented.
*/
class Event;
class ProcessInvoker;
/*Errors in I/O should throw this class*/
/*Could use a Maybe T type I suppose though*/
class IOError : public std::runtime_error {
};
/*
Errors are caught only on:
1. opening a file
2. seeking
3. closing
In all other cases, errors are caught at the time
that events are triggered; they are reported by
sending messages to the process being informed.
*/
/*-----------------------------------------------------------------------------
Implementation-specific
-----------------------------------------------------------------------------*/
/*I/O Ports*/
class IOPort {
public:
virtual void close(void) =0;
/*If the read completed immediately, return a null
pointer and put a value into now_read. Otherwise,
put a null pointer into now_read and return an
event.
*/
virtual boost::shared_ptr<Event> read(
boost::shared_ptr<ProcessInvoker>, size_t
boost::shared_ptr<std::vector<unsigned char> >& now_read
) =0;
/*return a null pointer if data-writing was successfully
completed.
*/
virtual boost::shared_ptr<Event> write(
boost::shared_ptr<ProcessInvoker>,
std::vector<unsigned char> const&
) =0;
virtual boost::shared_ptr<Event> accept(
boost::shared_ptr<ProcessInvoker>
) =0;
virtual ~IOPort() { }
};
/*Will only be called once, at init*/
boost::shared_ptr<IOPort> ioport_stdin(void);
boost::shared_ptr<IOPort> ioport_stdout(void);
boost::shared_ptr<IOPort> ioport_stderr(void);
boost::shared_ptr<IOPort> infile(std::string);
boost::shared_ptr<IOPort> outfile(std::string);
boost::shared_ptr<IOPort> appendfile(std::string);
void close(boost::shared_ptr<IOPort>);
class Event {
public:
virtual void seek(uint64_t) =0;
virtual ~Event() { }
};
boost::shared_ptr<Event> system_event(boost::shared_ptr<ProcessInvoker>,std::string);
/*sleep unit is milliseconds*/
boost::shared_ptr<Event> sleep_event(boost::shared_ptr<ProcessInvoker>,size_t);
/*connect to host's port*/
boost::shared_ptr<Event> connect_event(boost::shared_ptr<ProcessInvoker>,std::string,int);
class ProcessInvokerScanner;
/*used as a Singleton, although we don't enforce it*/
/*specific AIO implementation has to enforce Singleton-ness*/
class EventSetImpl;
class EventSet {
private:
EventSetImpl* pimpl;
public:
void add_event(boost::shared_ptr<Event>);
void remove_event(boost::shared_ptr<Event>);
/*"host" is the process which performed the
'event-wait or 'event-poll bytecode.
*/
void event_poll(Process& host);
void event_wait(Process& host);
EventSet(void);
~EventSet();
/*This member function is called on the global
event set by the thread pool. This function
should then call the traverse() member function
of the given ProcessInvokerScanner on each
process invoker of each live event.
This call is assuredly made when only one thread
is running, and thus does not require any special
threading protection.
*/
void scan_process_invokers(ProcessInvokerScanner*);
};
/*get *the* EventSet*/
EventSet& the_event_set(void);
/*PROMISE: we won't call the above function unless
we have called aio_initialize() below, once, first.
*/
/*initialize and clean-up aio (including creation of *the* EventSet)*/
void aio_initialize(void);
void aio_deinitialize(void);
/*called at the initialization/cleanup of each thread*/
/*NOT called on main process thread*/
void aio_thread_initialize(void);
void aio_thread_deinitialize(void);
/*-----------------------------------------------------------------------------
Shared across Implementations
-----------------------------------------------------------------------------*/
class ProcessInvokerScanner {
public:
virtual void traverse(ProcessInvoker const&) =0;
virtual ~ProcessInvokerScanner() { }
};
/*implementations in src/aio.cpp*/
class ProcessInvoker {
private:
ProcessInvoker(void); //disallowed
public:
Process* P;
/*"host" parameter is just a heap that can be used to
conveniently construct the response before actually
sending it to the target process. It is *not* the
target process: it's just used as a scratch heap.
Reusing an existing process (specifically the process
that called the event waiting/polling) reduces
allocation overhead.
*/
void io_respond(
Process& host,
boost::shared_ptr<IOPort>,
boost::shared_ptr<std::vector<unsigned char> >&
);
void nil_respond(
Process& host,
boost::shared_ptr<IOPort>
);
void accept_respond(
Process& host,
boost::shared_ptr<IOPort> socket,
boost::shared_ptr<IOPort> new_socket
);
void connect_respond(
Process& host,
boost::shared_ptr<Event>, boost::shared_ptr<IOPort> new_socket
);
void sleep_respond(
Process& host,
boost::shared_ptr<Event>, size_t
);
void system_respond(
Process& host,
boost::shared_ptr<Event>, int term_code
);
/*call for errors*/
void io_error_respond(
Process& host,
boost::shared_ptr<IOPort>, std::string const&
);
void other_error_respond(
Process& host,
boost::shared_ptr<Event>, std::string const&
);
explicit ProcessInvoker(Process*);
~ProcessInvoker(void);
};
#endif // NEW_AIO_H
<|endoftext|> |
<commit_before>/* BZWorkbench
* Copyright (c) 1993 - 2007 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "../include/objects/group.h"
// constructor
group::group() :
bz2object("group", "<shift><shear><scale><spin><team><tint><drivethrough><shootthrough><phydrv><matref>") {
this->team = 0;
this->def = NULL;
this->tintColor = RGBA(1, 1, 1, 1);
this->driveThrough = false;
this->shootThrough = false;
this->setName("");
this->setPos( osg::Vec3( 0.0, 0.0, 0.0 ) );
this->container = new Renderable();
this->geoRing = NULL;
}
// constructor with data
group::group(string& data) :
bz2object("group", "<shift><shear><scale><spin><team><tint><drivethrough><shootthrough><phydrv><matref>", data.c_str()) {
this->team = 0;
this->def = NULL;
this->tintColor = RGBA(1, 1, 1, 1);
this->driveThrough = false;
this->shootThrough = false;
this->setName("");
this->setPos( osg::Vec3( 0.0, 0.0, 0.0 ) );
this->container = new Renderable();
this->geoRing = NULL;
this->update(data);
}
// getter
string group::get(void) {
return this->toString();
}
// setter
int group::update(string& data) {
const char* header = this->getHeader().c_str();
// get the section from the data
const vector<string> lines = BZWParser::getSectionsByHeader(header, data.c_str());
if(lines[0] == BZW_NOT_FOUND)
return 0;
if(!hasOnlyOne(lines, "group"))
return 0;
const char* groupData = lines[0].c_str();
// get name (from the first line)
vector<string> headers = BZWParser::getValuesByKey("group", header, groupData);
// get tint
vector<string> tints = BZWParser::getValuesByKey("tint", header, groupData);
if(tints.size() > 1) {
printf("group::update(): Error! Defined \"tint\" %d times\n", tints.size());
return 0;
}
// get team
vector<string> teams = BZWParser::getValuesByKey("team", header, groupData);
if(teams.size() > 1) {
printf("group::update(): Error! Defined \"team\" %d times\n", tints.size());
return 0;
}
// get drivethrough
vector<string> driveThroughs = BZWParser::getValuesByKey("drivethrough", header, groupData);
// get shootthrough
vector<string> shootThroughs = BZWParser::getValuesByKey("shootthrough", header, groupData);
// do base class update
if(!bz2object::update(data))
return 0;
// assign data
// see if the name changed (if so, recompute the object list)
string oldName = this->getName();
this->setName( headers[0] );
if( oldName != this->getName() )
this->updateObjects();
this->tintColor = (tints.size() > 0 ? RGBA( tints[0].c_str() ) : RGBA(-1, -1, -1, -1));
this->team = (teams.size() > 0 ? (int)(atof( teams[0].c_str() )) : -1);
this->driveThrough = (driveThroughs.size() == 0 ? false : true);
this->shootThrough = (shootThroughs.size() == 0 ? false : true);
return 1;
}
// event handler
int group::update( UpdateMessage& message ) {
// superclass update (i.e. handle transformation changes)
int result = bz2object::update( message );
switch( message.type ) {
case UpdateMessage::SET_POSITION: {
this->setPos( *(message.getAsPosition()) );
break;
}
case UpdateMessage::SET_POSITION_FACTOR: { // handle a translation
this->setPos( this->getPos() + *(message.getAsPositionFactor()) );
break;
}
case UpdateMessage::SET_ROTATION: // handle a new rotation
// propogate rotation events to the children objects
this->container->setRotation( *(message.getAsRotation()) );
this->buildGeometry();
break;
case UpdateMessage::SET_ROTATION_FACTOR: // handle an angular translation
this->container->setRotation( *(message.getAsRotationFactor()) + this->container->getRotation() );
this->buildGeometry();
break;
case UpdateMessage::SET_SCALE: // handle a new scale
this->container->setScale( *(message.getAsScale()) );
this->buildGeometry();
break;
case UpdateMessage::SET_SCALE_FACTOR: // handle a scaling factor
this->container->setScale( *(message.getAsScaleFactor()) + this->container->getScale() );
this->buildGeometry();
break;
default: // unknown event; don't handle
return result;
}
return 1;
}
// toString
string group::toString(void) {
osg::Vec3 p = this->getPos();
string tintString = string(""), teamString = string("");
if(tintColor.r() > 0 && tintColor.g() > 0 && tintColor.b() > 0 && tintColor.a() > 0)
tintString = " tint " + tintColor.toString();
if(team > 0)
teamString = " team " + string(itoa(team)) + "\n";
// temporarily set the rotation of the root group node from the container child so BZWLines() translates
// the rotation values into "spin" lines
this->setRotation( this->container->getRotation() );
string ret = string("group ") + this->getName() + "\n" +
tintString +
teamString +
(driveThrough == true ? " drivethrough\n" : "") +
(shootThrough == true ? " shootThrough\n" : "") +
this->BZWLines() +
"end\n";
// reset the rotation to 0 (so only the container has the spin transformations)
this->setRotation( osg::Vec3( 0.0, 0.0, 0.0 ) );
// return the string data
return ret;
}
// build the ring geometry around the objects
void group::buildGeometry() {
// compute the maximum radius outside the center
float maxRadius2 = 25.0f; // radius squared (saves sqrt() calls)
float maxDim = 0.0f;
if( this->container->getNumChildren() > 0 ) {
// get each child
for( unsigned int i = 0; i < this->container->getNumChildren(); i++ ) {
osg::Node* child = this->container->getChild( i );
bz2object* obj = dynamic_cast< bz2object* >(child);
if( obj ) {
// only count bz2object instances
osg::Vec3 p = obj->getPos();
osg::Vec3 size = obj->getSize();
// compute the largest dimension
float maxSizeDim = max( size.x(), max( size.y(), size.z() ) );
maxDim = max( maxSizeDim, maxDim );
// the group's position relative to the objects is (0,0,0), so just square the position and take the length
float len2 = p.x()*p.x() + p.y()*p.y() + p.z()*p.z();
// see if it's bigger than the maximum radius
if( len2 > maxRadius2 ) {
maxRadius2 = len2;
}
}
}
}
// now find the maximum radius
float maxRadius = sqrt( maxRadius2 ) + maxDim;
// NOW we can build the geometry
osg::Vec3Array* points = new osg::Vec3Array();
// primitive set
osg::DrawElementsUInt* primitives = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLE_STRIP, 0 );
int index = 0;
// increment by degrees (less float-point error)
for( float angle = 0.0f; angle < 360.0f; angle += 5.0f, index += 2 ) {
float radAngle = osg::DegreesToRadians( angle );
// add mesh data
points->push_back( osg::Vec3( maxRadius * cos( radAngle ), maxRadius * sin( radAngle ), this->getPos().z() ));
points->push_back( osg::Vec3( maxRadius * cos( radAngle ), maxRadius * sin( radAngle ), this->getPos().z() + 3 ));
// add primitive indexes
primitives->push_back( index );
primitives->push_back( index + 1 );
}
// make it loop back
primitives->push_back( 0 );
primitives->push_back( 1 );
// the geometry node
this->geoRing = new osg::Geode();
// build that geode!
osg::Geometry* geometry = new osg::Geometry();
geometry->setVertexArray( points );
geometry->addPrimitiveSet( primitives );
geoRing->addDrawable( geometry );
// just name it
geoRing->setName("group_container");
// make it fushia
SceneBuilder::assignMaterial( osg::Vec4( 1.0, 0.0, 1.0, 1.0 ),
osg::Vec4( 1.0, 0.0, 1.0, 1.0 ),
osg::Vec4( 1.0, 0.0, 1.0, 1.0 ),
osg::Vec4( 0.0, 0.0, 0.0, 0.0 ),
0.0,
1.0,
geoRing.get(),
osg::StateAttribute::OVERRIDE );
// remove it if it already exists
if( this->containsNode( geoRing.get() ) && geoRing.get() != NULL )
this->removeChild( geoRing.get() );
this->addChild( geoRing.get() );
}
// re-compute the list of objects contained in the group
void group::updateObjects() {
// get the "define" reference
define* def = dynamic_cast< define* >(Model::command( MODEL_GET, "define", this->getName() ));
// reload the children
setDefine( def );
// update the geometry
buildGeometry();
}
// set the associated definition
void group::setDefine( define* def ) {
this->def = def;
setName( def->getName() );
// reload the children
computeChildren();
// recompute the geometry
this->buildGeometry();
}
// set the children
void group::computeChildren() {
// remove all current objects
if( this->container->getNumChildren() > 0 )
this->container->removeChildren(0, this->container->getNumChildren());
// if the def is valid, add the objects
if( def != NULL ) {
this->def = def;
// get the objects
vector< osg::ref_ptr< bz2object > > objects = def->getObjects();
// put each object inside a PositionAttitudeTransform
// add them as children of this object
if( objects.size() > 0 ) {
// first, compute the group's center
float x = 0.0f, y = 0.0f, z = 0.0f;
for( vector< osg::ref_ptr< bz2object > >::iterator i = objects.begin(); i != objects.end(); i++ ) {
x += i->get()->getPos().x();
y += i->get()->getPos().y();
z += i->get()->getPos().z();
}
x /= objects.size();
y /= objects.size();
z /= objects.size();
osg::Vec3 position = osg::Vec3( x, y, z );
this->setPos( position );
for( vector< osg::ref_ptr< bz2object > >::iterator i = objects.begin(); i != objects.end(); i++ ) {
this->container->addChild( i->get() );
i->get()->setPos( i->get()->getPos() - position );
printf(" added %s\n", (*i)->getName().c_str() );
}
}
}
if( !this->containsNode( container.get() ) )
this->addChild( container.get() );
}
<commit_msg>When importing groups from a .bzw file, make sure that the group forwards spin transformations to the child node that actually contains the map objects to ensure that the pink group ring doesn't get transformed along with them.<commit_after>/* BZWorkbench
* Copyright (c) 1993 - 2007 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "../include/objects/group.h"
// constructor
group::group() :
bz2object("group", "<shift><shear><scale><spin><team><tint><drivethrough><shootthrough><phydrv><matref>") {
this->team = 0;
this->def = NULL;
this->tintColor = RGBA(1, 1, 1, 1);
this->driveThrough = false;
this->shootThrough = false;
this->setName("");
this->setPos( osg::Vec3( 0.0, 0.0, 0.0 ) );
this->container = new Renderable();
this->geoRing = NULL;
}
// constructor with data
group::group(string& data) :
bz2object("group", "<shift><shear><scale><spin><team><tint><drivethrough><shootthrough><phydrv><matref>", data.c_str()) {
this->team = 0;
this->def = NULL;
this->tintColor = RGBA(1, 1, 1, 1);
this->driveThrough = false;
this->shootThrough = false;
this->setName("");
this->setPos( osg::Vec3( 0.0, 0.0, 0.0 ) );
this->container = new Renderable();
this->geoRing = NULL;
this->update(data);
}
// getter
string group::get(void) {
return this->toString();
}
// setter
int group::update(string& data) {
const char* header = this->getHeader().c_str();
// get the section from the data
const vector<string> lines = BZWParser::getSectionsByHeader(header, data.c_str());
if(lines[0] == BZW_NOT_FOUND)
return 0;
if(!hasOnlyOne(lines, "group"))
return 0;
const char* groupData = lines[0].c_str();
// get name (from the first line)
vector<string> headers = BZWParser::getValuesByKey("group", header, groupData);
// get tint
vector<string> tints = BZWParser::getValuesByKey("tint", header, groupData);
if(tints.size() > 1) {
printf("group::update(): Error! Defined \"tint\" %d times\n", tints.size());
return 0;
}
// get team
vector<string> teams = BZWParser::getValuesByKey("team", header, groupData);
if(teams.size() > 1) {
printf("group::update(): Error! Defined \"team\" %d times\n", tints.size());
return 0;
}
// get drivethrough
vector<string> driveThroughs = BZWParser::getValuesByKey("drivethrough", header, groupData);
// get shootthrough
vector<string> shootThroughs = BZWParser::getValuesByKey("shootthrough", header, groupData);
// do base class update
if(!bz2object::update(data))
return 0;
// the superclass bz2object will apply "spin" transformations if present. These need to be forewarded
// to the container object, and removed from the group for correct rendering
osg::Vec3 rot = this->getRotation();
if( this->container.get() != NULL )
this->container->setRotation( rot );
this->setRotation( osg::Vec3( 0, 0, 0 ) );
// assign data
// see if the name changed (if so, recompute the object list)
string oldName = this->getName();
this->setName( headers[0] );
if( oldName != this->getName() )
this->updateObjects();
this->tintColor = (tints.size() > 0 ? RGBA( tints[0].c_str() ) : RGBA(-1, -1, -1, -1));
this->team = (teams.size() > 0 ? (int)(atof( teams[0].c_str() )) : -1);
this->driveThrough = (driveThroughs.size() == 0 ? false : true);
this->shootThrough = (shootThroughs.size() == 0 ? false : true);
return 1;
}
// event handler
int group::update( UpdateMessage& message ) {
// superclass update (i.e. handle transformation changes)
int result = bz2object::update( message );
switch( message.type ) {
case UpdateMessage::SET_POSITION: {
this->setPos( *(message.getAsPosition()) );
break;
}
case UpdateMessage::SET_POSITION_FACTOR: { // handle a translation
this->setPos( this->getPos() + *(message.getAsPositionFactor()) );
break;
}
case UpdateMessage::SET_ROTATION: // handle a new rotation
// propogate rotation events to the children objects
this->container->setRotation( *(message.getAsRotation()) );
this->buildGeometry();
break;
case UpdateMessage::SET_ROTATION_FACTOR: // handle an angular translation
this->container->setRotation( *(message.getAsRotationFactor()) + this->container->getRotation() );
this->buildGeometry();
break;
case UpdateMessage::SET_SCALE: // handle a new scale
this->container->setScale( *(message.getAsScale()) );
this->buildGeometry();
break;
case UpdateMessage::SET_SCALE_FACTOR: // handle a scaling factor
this->container->setScale( *(message.getAsScaleFactor()) + this->container->getScale() );
this->buildGeometry();
break;
default: // unknown event; don't handle
return result;
}
return 1;
}
// toString
string group::toString(void) {
osg::Vec3 p = this->getPos();
string tintString = string(""), teamString = string("");
if(tintColor.r() > 0 && tintColor.g() > 0 && tintColor.b() > 0 && tintColor.a() > 0)
tintString = " tint " + tintColor.toString();
if(team > 0)
teamString = " team " + string(itoa(team)) + "\n";
// temporarily set the rotation of the root group node from the container child so BZWLines() translates
// the rotation values into "spin" lines
this->setRotation( this->container->getRotation() );
string ret = string("group ") + this->getName() + "\n" +
tintString +
teamString +
(driveThrough == true ? " drivethrough\n" : "") +
(shootThrough == true ? " shootThrough\n" : "") +
this->BZWLines() +
"end\n";
// reset the rotation to 0 (so only the container has the spin transformations)
this->setRotation( osg::Vec3( 0.0, 0.0, 0.0 ) );
// return the string data
return ret;
}
// build the ring geometry around the objects
void group::buildGeometry() {
// compute the maximum radius outside the center
float maxRadius2 = 25.0f; // radius squared (saves sqrt() calls)
float maxDim = 0.0f;
if( this->container->getNumChildren() > 0 ) {
// get each child
for( unsigned int i = 0; i < this->container->getNumChildren(); i++ ) {
osg::Node* child = this->container->getChild( i );
bz2object* obj = dynamic_cast< bz2object* >(child);
if( obj ) {
// only count bz2object instances
osg::Vec3 p = obj->getPos();
osg::Vec3 size = obj->getSize();
// compute the largest dimension
float maxSizeDim = max( size.x(), max( size.y(), size.z() ) );
maxDim = max( maxSizeDim, maxDim );
// the group's position relative to the objects is (0,0,0), so just square the position and take the length
float len2 = p.x()*p.x() + p.y()*p.y() + p.z()*p.z();
// see if it's bigger than the maximum radius
if( len2 > maxRadius2 ) {
maxRadius2 = len2;
}
}
}
}
// now find the maximum radius
float maxRadius = sqrt( maxRadius2 ) + maxDim;
// NOW we can build the geometry
osg::Vec3Array* points = new osg::Vec3Array();
// primitive set
osg::DrawElementsUInt* primitives = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLE_STRIP, 0 );
int index = 0;
// increment by degrees (less float-point error)
for( float angle = 0.0f; angle < 360.0f; angle += 5.0f, index += 2 ) {
float radAngle = osg::DegreesToRadians( angle );
// add mesh data
points->push_back( osg::Vec3( maxRadius * cos( radAngle ), maxRadius * sin( radAngle ), this->getPos().z() ));
points->push_back( osg::Vec3( maxRadius * cos( radAngle ), maxRadius * sin( radAngle ), this->getPos().z() + 3 ));
// add primitive indexes
primitives->push_back( index );
primitives->push_back( index + 1 );
}
// make it loop back
primitives->push_back( 0 );
primitives->push_back( 1 );
// the geometry node
this->geoRing = new osg::Geode();
// build that geode!
osg::Geometry* geometry = new osg::Geometry();
geometry->setVertexArray( points );
geometry->addPrimitiveSet( primitives );
geoRing->addDrawable( geometry );
// just name it
geoRing->setName("group_container");
// make it fushia
SceneBuilder::assignMaterial( osg::Vec4( 1.0, 0.0, 1.0, 1.0 ),
osg::Vec4( 1.0, 0.0, 1.0, 1.0 ),
osg::Vec4( 1.0, 0.0, 1.0, 1.0 ),
osg::Vec4( 0.0, 0.0, 0.0, 0.0 ),
0.0,
1.0,
geoRing.get(),
osg::StateAttribute::OVERRIDE );
// remove it if it already exists
if( this->containsNode( geoRing.get() ) && geoRing.get() != NULL )
this->removeChild( geoRing.get() );
this->addChild( geoRing.get() );
}
// re-compute the list of objects contained in the group
void group::updateObjects() {
// get the "define" reference
define* def = dynamic_cast< define* >(Model::command( MODEL_GET, "define", this->getName() ));
// reload the children
setDefine( def );
// update the geometry
buildGeometry();
}
// set the associated definition
void group::setDefine( define* def ) {
this->def = def;
setName( def->getName() );
// reload the children
computeChildren();
// recompute the geometry
this->buildGeometry();
}
// set the children
void group::computeChildren() {
// remove all current objects
if( this->container->getNumChildren() > 0 )
this->container->removeChildren(0, this->container->getNumChildren());
// if the def is valid, add the objects
if( def != NULL ) {
this->def = def;
// get the objects
vector< osg::ref_ptr< bz2object > > objects = def->getObjects();
// put each object inside a PositionAttitudeTransform
// add them as children of this object
if( objects.size() > 0 ) {
// first, compute the group's center
float x = 0.0f, y = 0.0f, z = 0.0f;
for( vector< osg::ref_ptr< bz2object > >::iterator i = objects.begin(); i != objects.end(); i++ ) {
x += i->get()->getPos().x();
y += i->get()->getPos().y();
z += i->get()->getPos().z();
}
x /= objects.size();
y /= objects.size();
z /= objects.size();
osg::Vec3 position = osg::Vec3( x, y, z );
this->setPos( position );
for( vector< osg::ref_ptr< bz2object > >::iterator i = objects.begin(); i != objects.end(); i++ ) {
this->container->addChild( i->get() );
i->get()->setPos( i->get()->getPos() - position );
printf(" added %s\n", (*i)->getName().c_str() );
}
}
}
if( !this->containsNode( container.get() ) )
this->addChild( container.get() );
}
<|endoftext|> |
<commit_before>#include "event_scheduler.hpp"
#include <QApplication>
#include <QDebug>
EventScheduler::EventScheduler()
: receiver_(0)
, event_(0)
{
timer_.setSingleShot(true);
}
void EventScheduler::set_receiver(QObject *receiver)
{
receiver_ = receiver;
}
void EventScheduler::schedule_event(QEvent *event, int delay_ms)
{
event_ = event;
timer_.start(delay_ms);
connect(&timer_, SIGNAL(timeout()), this, SLOT(notify()));
}
void EventScheduler::notify()
{
qApp->notify(receiver_, event_);
}<commit_msg>Fixed duplicate signals.<commit_after>#include "event_scheduler.hpp"
#include <QApplication>
#include <QDebug>
EventScheduler::EventScheduler()
: receiver_(0)
, event_(0)
{
timer_.setSingleShot(true);
connect(&timer_, SIGNAL(timeout()), this, SLOT(notify()));
}
void EventScheduler::set_receiver(QObject *receiver)
{
receiver_ = receiver;
}
void EventScheduler::schedule_event(QEvent *event, int delay_ms)
{
event_ = event;
timer_.start(delay_ms);
}
void EventScheduler::notify()
{
qApp->notify(receiver_, event_);
}<|endoftext|> |
<commit_before>/*****************************************************************************
Copyright 2004-2008 Steve Ménard
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 "jpype.h"
#include "jp_field.h"
#include "jp_methoddispatch.h"
#include "jp_method.h"
#include "pyjp.h"
JPClass::JPClass(
const string& name,
jint modifiers)
{
m_Context = NULL;
m_CanonicalName = name;
m_SuperClass = NULL;
m_Interfaces = JPClassList();
m_Modifiers = modifiers;
}
JPClass::JPClass(JPJavaFrame& frame,
jclass clss,
const string& name,
JPClass* super,
const JPClassList& interfaces,
jint modifiers)
: m_Class(frame, clss)
{
m_Context = frame.getContext();
m_CanonicalName = name;
m_SuperClass = super;
m_Interfaces = interfaces;
m_Modifiers = modifiers;
}
JPClass::~JPClass()
{
}
jclass JPClass::getJavaClass() const
{
jclass cls = m_Class.get();
// This sanity check should not be possible to exercise
if (cls == 0)
JP_RAISE(PyExc_RuntimeError, "Class is null"); // GCOVR_EXCL_LINE
return cls;
}
void JPClass::ensureMembers(JPJavaFrame& frame)
{
JPContext* context = frame.getContext();
JPTypeManager* typeManager = context->getTypeManager();
typeManager->populateMembers(this);
}
void JPClass::assignMembers(JPMethodDispatch* ctor,
JPMethodDispatchList& methods,
JPFieldList& fields)
{
m_Constructors = ctor;
m_Methods = methods;
m_Fields = fields;
}
//<editor-fold desc="new" defaultstate="collapsed">
JPValue JPClass::newInstance(JPJavaFrame& frame, JPPyObjectVector& args)
{
if (m_Constructors == NULL)
JP_RAISE(PyExc_TypeError, "Cannot create Interface instances");
return m_Constructors->invokeConstructor(frame, args);
}
jarray JPClass::newArrayInstance(JPJavaFrame& frame, jsize sz)
{
return frame.NewObjectArray(sz, getJavaClass(), NULL);
}
//</editor-fold>
//<editor-fold desc="acccessors" defaultstate="collapsed">
// GCOVR_EXCL_START
// This is currently only used in tracing
string JPClass::toString() const
{
// This sanity check will not be hit in normal operation
if (m_Context == 0)
return m_CanonicalName; // GCOVR_EXCL_LINE
JPJavaFrame frame(m_Context);
return frame.toString(m_Class.get());
}
// GCOVR_EXCL_STOP
string JPClass::getName() const
{
// This sanity check will not be hit in normal operation
if (m_Context == 0)
return m_CanonicalName; // GCOVR_EXCL_LINE
JPJavaFrame frame(m_Context);
return frame.toString(frame.CallObjectMethodA(
(jobject) m_Class.get(), m_Context->m_Class_GetNameID, NULL));
}
//</editor-fold>
//<editor-fold desc="as return type" defaultstate="collapsed">
JPPyObject JPClass::getStaticField(JPJavaFrame& frame, jclass c, jfieldID fid)
{
JP_TRACE_IN("JPClass::getStaticField");
jobject r = frame.GetStaticObjectField(c, fid);
JPClass* type = this;
if (r != NULL)
type = frame.findClassForObject(r);
jvalue v;
v.l = r;
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
JPPyObject JPClass::getField(JPJavaFrame& frame, jobject c, jfieldID fid)
{
JP_TRACE_IN("JPClass::getField");
jobject r = frame.GetObjectField(c, fid);
JPClass* type = this;
if (r != NULL)
type = frame.findClassForObject(r);
jvalue v;
v.l = r;
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
JPPyObject JPClass::invokeStatic(JPJavaFrame& frame, jclass claz, jmethodID mth, jvalue* val)
{
JP_TRACE_IN("JPClass::invokeStatic");
jvalue v;
{
JPPyCallRelease call;
v.l = frame.CallStaticObjectMethodA(claz, mth, val);
}
JPClass *type = this;
if (v.l != NULL)
type = frame.findClassForObject(v.l);
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
JPPyObject JPClass::invoke(JPJavaFrame& frame, jobject obj, jclass clazz, jmethodID mth, jvalue* val)
{
JP_TRACE_IN("JPClass::invoke");
jvalue v;
// Call method
{
JPPyCallRelease call;
if (clazz == NULL)
v.l = frame.CallObjectMethodA(obj, mth, val);
else
v.l = frame.CallNonvirtualObjectMethodA(obj, clazz, mth, val);
}
// Get the return type
JPClass *type = this;
if (v.l != NULL)
type = frame.findClassForObject(v.l);
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
void JPClass::setStaticField(JPJavaFrame& frame, jclass c, jfieldID fid, PyObject* obj)
{
JP_TRACE_IN("JPClass::setStaticField");
JPMatch match(&frame, obj);
if (findJavaConversion(match) < JPMatch::_implicit)
{
stringstream err;
err << "unable to convert to " << getCanonicalName();
JP_RAISE(PyExc_TypeError, err.str().c_str());
}
jobject val = match.convert().l;
frame.SetStaticObjectField(c, fid, val);
JP_TRACE_OUT;
}
void JPClass::setField(JPJavaFrame& frame, jobject c, jfieldID fid, PyObject* obj)
{
JP_TRACE_IN("JPClass::setField");
JPMatch match(&frame, obj);
if (findJavaConversion(match) < JPMatch::_implicit)
{
stringstream err;
err << "unable to convert to " << getCanonicalName();
JP_RAISE(PyExc_TypeError, err.str().c_str());
}
jobject val = match.convert().l;
frame.SetObjectField(c, fid, val);
JP_TRACE_OUT;
}
void JPClass::setArrayRange(JPJavaFrame& frame, jarray a,
jsize start, jsize length, jsize step,
PyObject* vals)
{
JP_TRACE_IN("JPClass::setArrayRange");
jobjectArray array = (jobjectArray) a;
// Verify before we start the conversion, as we wont be able
// to abort once we start
JPPySequence seq(JPPyRef::_use, vals);
JP_TRACE("Verify argument types");
for (int i = 0; i < length; i++)
{
JPPyObject v = seq[i];
JPMatch match(&frame, v.get());
if (findJavaConversion(match) < JPMatch::_implicit)
JP_RAISE(PyExc_TypeError, "Unable to convert");
}
JP_TRACE("Copy");
int index = start;
for (int i = 0; i < length; i++, index += step)
{
JPPyObject v = seq[i];
JPMatch match(&frame, v.get());
findJavaConversion(match);
frame.SetObjectArrayElement(array, index, match.convert().l);
}
JP_TRACE_OUT;
}
void JPClass::setArrayItem(JPJavaFrame& frame, jarray a, jsize ndx, PyObject* val)
{
JP_TRACE_IN("JPClass::setArrayItem");
JPMatch match(&frame, val);
findJavaConversion(match);
JP_TRACE("Type", getCanonicalName());
if ( match.type < JPMatch::_implicit)
{
JP_RAISE(PyExc_TypeError, "Unable to convert");
}
jvalue v = match.convert();
frame.SetObjectArrayElement((jobjectArray) a, ndx, v.l);
JP_TRACE_OUT;
}
JPPyObject JPClass::getArrayItem(JPJavaFrame& frame, jarray a, jsize ndx)
{
JP_TRACE_IN("JPClass::getArrayItem");
jobjectArray array = (jobjectArray) a;
jobject obj = frame.GetObjectArrayElement(array, ndx);
JPClass *retType = this;
jvalue v;
v.l = obj;
if (obj != NULL)
retType = frame.findClassForObject(v.l);
return retType->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
//</editor-fold>
//<editor-fold desc="conversion" defaultstate="collapsed">
JPValue JPClass::getValueFromObject(const JPValue& obj)
{
JP_TRACE_IN("JPClass::getValueFromObject");
return JPValue(this, obj.getJavaObject());
JP_TRACE_OUT;
}
JPPyObject JPClass::convertToPythonObject(JPJavaFrame& frame, jvalue value, bool cast)
{
JP_TRACE_IN("JPClass::convertToPythonObject");
JPClass *cls = this;
if (!cast)
{
// Returning None likely incorrect from java prospective.
// Java still knows the type of null objects thus
// converting to None would pose a problem as we lose type.
// We would need subclass None for this to make sense so we
// can carry both the type and the null, but Python considers
// None a singleton so this is not an option.
//
// Of course if we don't mind that "Object is None" would
// fail, but "Object == None" would be true, the we
// could support null objects properly. However, this would
// need to work as "None == Object" which may be hard to
// achieve.
//
// We will still need to have the concept of null objects
// but we can get those through JObject(None, cls).
if (value.l == NULL)
{
return JPPyObject::getNone();
}
cls = frame.findClassForObject(value.l);
if (cls != this)
return cls->convertToPythonObject(frame, value, true);
}
JPPyObject obj;
JPPyObject wrapper = PyJPClass_create(frame, cls);
if (isThrowable())
{
// Exceptions need new and init
JPPyTuple tuple = JPPyTuple::newTuple(1);
tuple.setItem(0, _JObjectKey);
obj = JPPyObject(JPPyRef::_call, PyObject_Call(wrapper.get(), tuple.get(), NULL));
} else
{
PyTypeObject *type = ((PyTypeObject*) wrapper.get());
// Simple objects don't have a new or init function
PyObject *obj2 = type->tp_alloc(type, 0);
JP_PY_CHECK();
obj = JPPyObject(JPPyRef::_claim, obj2);
}
// Fill in the Java slot
PyJPValue_assignJavaSlot(frame, obj.get(), JPValue(cls, value));
return obj;
JP_TRACE_OUT;
}
JPMatch::Type JPClass::findJavaConversion(JPMatch &match)
{
JP_TRACE_IN("JPClass::getJavaConversion");
if (nullConversion->matches(match, this)
|| objectConversion->matches(match, this)
|| proxyConversion->matches(match, this)
|| hintsConversion->matches(match, this))
return match.type;
JP_TRACE("No match");
return match.type = JPMatch::_none;
JP_TRACE_OUT;
}
//</editor-fold>
//<editor-fold desc="hierarchy" defaultstate="collapsed">
bool JPClass::isAssignableFrom(JPJavaFrame& frame, JPClass* o)
{
return frame.IsAssignableFrom(m_Class.get(), o->getJavaClass()) != 0;
}
//</editor-fold>
<commit_msg>Fix for conversion loading.<commit_after>/*****************************************************************************
Copyright 2004-2008 Steve Ménard
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 "jpype.h"
#include "jp_field.h"
#include "jp_methoddispatch.h"
#include "jp_method.h"
#include "pyjp.h"
JPClass::JPClass(
const string& name,
jint modifiers)
{
m_Context = NULL;
m_CanonicalName = name;
m_SuperClass = NULL;
m_Interfaces = JPClassList();
m_Modifiers = modifiers;
}
JPClass::JPClass(JPJavaFrame& frame,
jclass clss,
const string& name,
JPClass* super,
const JPClassList& interfaces,
jint modifiers)
: m_Class(frame, clss)
{
m_Context = frame.getContext();
m_CanonicalName = name;
m_SuperClass = super;
m_Interfaces = interfaces;
m_Modifiers = modifiers;
}
JPClass::~JPClass()
{
}
jclass JPClass::getJavaClass() const
{
jclass cls = m_Class.get();
// This sanity check should not be possible to exercise
if (cls == 0)
JP_RAISE(PyExc_RuntimeError, "Class is null"); // GCOVR_EXCL_LINE
return cls;
}
void JPClass::ensureMembers(JPJavaFrame& frame)
{
JPContext* context = frame.getContext();
JPTypeManager* typeManager = context->getTypeManager();
typeManager->populateMembers(this);
}
void JPClass::assignMembers(JPMethodDispatch* ctor,
JPMethodDispatchList& methods,
JPFieldList& fields)
{
m_Constructors = ctor;
m_Methods = methods;
m_Fields = fields;
}
//<editor-fold desc="new" defaultstate="collapsed">
JPValue JPClass::newInstance(JPJavaFrame& frame, JPPyObjectVector& args)
{
if (m_Constructors == NULL)
JP_RAISE(PyExc_TypeError, "Cannot create Interface instances");
return m_Constructors->invokeConstructor(frame, args);
}
jarray JPClass::newArrayInstance(JPJavaFrame& frame, jsize sz)
{
return frame.NewObjectArray(sz, getJavaClass(), NULL);
}
//</editor-fold>
//<editor-fold desc="acccessors" defaultstate="collapsed">
// GCOVR_EXCL_START
// This is currently only used in tracing
string JPClass::toString() const
{
// This sanity check will not be hit in normal operation
if (m_Context == 0)
return m_CanonicalName; // GCOVR_EXCL_LINE
JPJavaFrame frame(m_Context);
return frame.toString(m_Class.get());
}
// GCOVR_EXCL_STOP
string JPClass::getName() const
{
// This sanity check will not be hit in normal operation
if (m_Context == 0)
return m_CanonicalName; // GCOVR_EXCL_LINE
JPJavaFrame frame(m_Context);
return frame.toString(frame.CallObjectMethodA(
(jobject) m_Class.get(), m_Context->m_Class_GetNameID, NULL));
}
//</editor-fold>
//<editor-fold desc="as return type" defaultstate="collapsed">
JPPyObject JPClass::getStaticField(JPJavaFrame& frame, jclass c, jfieldID fid)
{
JP_TRACE_IN("JPClass::getStaticField");
jobject r = frame.GetStaticObjectField(c, fid);
JPClass* type = this;
if (r != NULL)
type = frame.findClassForObject(r);
jvalue v;
v.l = r;
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
JPPyObject JPClass::getField(JPJavaFrame& frame, jobject c, jfieldID fid)
{
JP_TRACE_IN("JPClass::getField");
jobject r = frame.GetObjectField(c, fid);
JPClass* type = this;
if (r != NULL)
type = frame.findClassForObject(r);
jvalue v;
v.l = r;
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
JPPyObject JPClass::invokeStatic(JPJavaFrame& frame, jclass claz, jmethodID mth, jvalue* val)
{
JP_TRACE_IN("JPClass::invokeStatic");
jvalue v;
{
JPPyCallRelease call;
v.l = frame.CallStaticObjectMethodA(claz, mth, val);
}
JPClass *type = this;
if (v.l != NULL)
type = frame.findClassForObject(v.l);
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
JPPyObject JPClass::invoke(JPJavaFrame& frame, jobject obj, jclass clazz, jmethodID mth, jvalue* val)
{
JP_TRACE_IN("JPClass::invoke");
jvalue v;
// Call method
{
JPPyCallRelease call;
if (clazz == NULL)
v.l = frame.CallObjectMethodA(obj, mth, val);
else
v.l = frame.CallNonvirtualObjectMethodA(obj, clazz, mth, val);
}
// Get the return type
JPClass *type = this;
if (v.l != NULL)
type = frame.findClassForObject(v.l);
return type->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
void JPClass::setStaticField(JPJavaFrame& frame, jclass c, jfieldID fid, PyObject* obj)
{
JP_TRACE_IN("JPClass::setStaticField");
JPMatch match(&frame, obj);
if (findJavaConversion(match) < JPMatch::_implicit)
{
stringstream err;
err << "unable to convert to " << getCanonicalName();
JP_RAISE(PyExc_TypeError, err.str().c_str());
}
jobject val = match.convert().l;
frame.SetStaticObjectField(c, fid, val);
JP_TRACE_OUT;
}
void JPClass::setField(JPJavaFrame& frame, jobject c, jfieldID fid, PyObject* obj)
{
JP_TRACE_IN("JPClass::setField");
JPMatch match(&frame, obj);
if (findJavaConversion(match) < JPMatch::_implicit)
{
stringstream err;
err << "unable to convert to " << getCanonicalName();
JP_RAISE(PyExc_TypeError, err.str().c_str());
}
jobject val = match.convert().l;
frame.SetObjectField(c, fid, val);
JP_TRACE_OUT;
}
void JPClass::setArrayRange(JPJavaFrame& frame, jarray a,
jsize start, jsize length, jsize step,
PyObject* vals)
{
JP_TRACE_IN("JPClass::setArrayRange");
jobjectArray array = (jobjectArray) a;
// Verify before we start the conversion, as we wont be able
// to abort once we start
JPPySequence seq(JPPyRef::_use, vals);
JP_TRACE("Verify argument types");
for (int i = 0; i < length; i++)
{
JPPyObject v = seq[i];
JPMatch match(&frame, v.get());
if (findJavaConversion(match) < JPMatch::_implicit)
JP_RAISE(PyExc_TypeError, "Unable to convert");
}
JP_TRACE("Copy");
int index = start;
for (int i = 0; i < length; i++, index += step)
{
JPPyObject v = seq[i];
JPMatch match(&frame, v.get());
findJavaConversion(match);
frame.SetObjectArrayElement(array, index, match.convert().l);
}
JP_TRACE_OUT;
}
void JPClass::setArrayItem(JPJavaFrame& frame, jarray a, jsize ndx, PyObject* val)
{
JP_TRACE_IN("JPClass::setArrayItem");
JPMatch match(&frame, val);
findJavaConversion(match);
JP_TRACE("Type", getCanonicalName());
if ( match.type < JPMatch::_implicit)
{
JP_RAISE(PyExc_TypeError, "Unable to convert");
}
jvalue v = match.convert();
frame.SetObjectArrayElement((jobjectArray) a, ndx, v.l);
JP_TRACE_OUT;
}
JPPyObject JPClass::getArrayItem(JPJavaFrame& frame, jarray a, jsize ndx)
{
JP_TRACE_IN("JPClass::getArrayItem");
jobjectArray array = (jobjectArray) a;
jobject obj = frame.GetObjectArrayElement(array, ndx);
JPClass *retType = this;
jvalue v;
v.l = obj;
if (obj != NULL)
retType = frame.findClassForObject(v.l);
return retType->convertToPythonObject(frame, v, false);
JP_TRACE_OUT;
}
//</editor-fold>
//<editor-fold desc="conversion" defaultstate="collapsed">
JPValue JPClass::getValueFromObject(const JPValue& obj)
{
JP_TRACE_IN("JPClass::getValueFromObject");
return JPValue(this, obj.getJavaObject());
JP_TRACE_OUT;
}
JPPyObject JPClass::convertToPythonObject(JPJavaFrame& frame, jvalue value, bool cast)
{
JP_TRACE_IN("JPClass::convertToPythonObject");
JPClass *cls = this;
if (!cast)
{
// Returning None likely incorrect from java prospective.
// Java still knows the type of null objects thus
// converting to None would pose a problem as we lose type.
// We would need subclass None for this to make sense so we
// can carry both the type and the null, but Python considers
// None a singleton so this is not an option.
//
// Of course if we don't mind that "Object is None" would
// fail, but "Object == None" would be true, the we
// could support null objects properly. However, this would
// need to work as "None == Object" which may be hard to
// achieve.
//
// We will still need to have the concept of null objects
// but we can get those through JObject(None, cls).
if (value.l == NULL)
{
return JPPyObject::getNone();
}
cls = frame.findClassForObject(value.l);
if (cls != this)
return cls->convertToPythonObject(frame, value, true);
}
JPPyObject obj;
JPPyObject wrapper = PyJPClass_create(frame, cls);
if (isThrowable())
{
// Exceptions need new and init
JPPyTuple tuple = JPPyTuple::newTuple(1);
tuple.setItem(0, _JObjectKey);
obj = JPPyObject(JPPyRef::_call, PyObject_Call(wrapper.get(), tuple.get(), NULL));
} else
{
PyTypeObject *type = ((PyTypeObject*) wrapper.get());
// Simple objects don't have a new or init function
PyObject *obj2 = type->tp_alloc(type, 0);
JP_PY_CHECK();
obj = JPPyObject(JPPyRef::_claim, obj2);
}
// Fill in the Java slot
PyJPValue_assignJavaSlot(frame, obj.get(), JPValue(cls, value));
return obj;
JP_TRACE_OUT;
}
JPMatch::Type JPClass::findJavaConversion(JPMatch &match)
{
JP_TRACE_IN("JPClass::getJavaConversion");
// Update the Python class cache
if (this->m_Hints.isNull())
PyJPClass_create(*match.frame, this);
if (nullConversion->matches(match, this)
|| objectConversion->matches(match, this)
|| proxyConversion->matches(match, this)
|| hintsConversion->matches(match, this))
return match.type;
JP_TRACE("No match");
return match.type = JPMatch::_none;
JP_TRACE_OUT;
}
//</editor-fold>
//<editor-fold desc="hierarchy" defaultstate="collapsed">
bool JPClass::isAssignableFrom(JPJavaFrame& frame, JPClass* o)
{
return frame.IsAssignableFrom(m_Class.get(), o->getJavaClass()) != 0;
}
//</editor-fold>
<|endoftext|> |
<commit_before>#include "coins.h"
using namespace eigengo::akka;
std::vector<Coin> CoinCounter::countCpu(const cv::Mat &image) {
using namespace cv;
std::vector<Coin> coins;
Mat dst;
std::vector<Vec3f> circles;
cvtColor(image, dst, COLOR_RGB2GRAY);
GaussianBlur(dst, dst, Size(9, 9), 3, 3);
threshold(dst, dst, 150, 255, THRESH_BINARY);
GaussianBlur(dst, dst, Size(3, 3), 3, 3);
//Canny(dst, dst, 1000, 1700, 5);
HoughCircles(dst, circles, HOUGH_GRADIENT,
1, // dp
60, // min dist
200, // canny1
20, // canny2
30, // min radius
100 // max radius
);
for (size_t i = 0; i < circles.size(); i++) {
Coin coin;
coin.center = circles[i][0];
coin.radius = circles[i][1];
coins.push_back(coin);
}
#ifdef TEST
Mat x(image);
for (size_t i = 0; i < circles.size(); i++ ) {
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// draw the circle center
circle(x, center, 3, Scalar(0,255,0), -1, 8, 0 );
// draw the circle outline
circle(x, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
cv::imshow("", dst);
cv::waitKey();
#endif
return coins;
}
/*
std::vector<Coin> CoinCounter::countGpu(const cv::Mat &cpuImage) {
std::vector<Coin> coins;
cv::gpu::GpuMat image(cpuImage);
cv::gpu::GpuMat dst;
cv::gpu::GpuMat circlesMat;
cv::gpu::cvtColor(image, dst, CV_BGR2GRAY);
cv::gpu::GaussianBlur(dst, dst, cv::Size(3, 3), 2, 2);
cv::gpu::Canny(dst, dst, 1000, 1700, 5);
cv::gpu::GaussianBlur(dst, dst, cv::Size(9, 9), 3, 3);
cv::gpu::HoughCircles(dst, circlesMat, CV_HOUGH_GRADIENT,
1, // dp
40, // min dist
100, // canny1
105, // canny2
10, // min radius
200 // max radius
);
std::vector<cv::Vec3f> circles;
cv::gpu::HoughCirclesDownload(circlesMat, circles);
for (size_t i = 0; i < circles.size(); i++) {
Coin coin;
coin.center = circles[i][0];
coin.radius = circles[i][1];
bool dup = false;
for (size_t j = 0; j < coins.size(); j++) {
if (coins.at(j).center == coin.center ||
coins.at(j).radius == coin.radius) {
dup = true;
break;
}
}
if (!dup) coins.push_back(coin);
}
return coins;
}
*/
std::vector<Coin> CoinCounter::count(const cv::Mat &image) {
//if (cv::gpu::getCudaEnabledDeviceCount() > 0) return countGpu(image);
return countCpu(image);
}
<commit_msg>Native components working<commit_after>#include "coins.h"
using namespace eigengo::akka;
std::vector<Coin> CoinCounter::countCpu(const cv::Mat &image) {
using namespace cv;
std::vector<Coin> coins;
Mat dst;
std::vector<Vec3f> circles;
cvtColor(image, dst, COLOR_RGB2GRAY);
GaussianBlur(dst, dst, Size(9, 9), 3, 3);
threshold(dst, dst, 150, 255, THRESH_BINARY);
GaussianBlur(dst, dst, Size(3, 3), 3, 3);
//Canny(dst, dst, 1000, 1700, 5);
HoughCircles(dst, circles, HOUGH_GRADIENT,
1, // dp
60, // min dist
200, // canny1
20, // canny2
30, // min radius
100 // max radius
);
for (size_t i = 0; i < circles.size(); i++) {
Coin coin;
coin.center = circles[i][0];
coin.radius = circles[i][1];
coins.push_back(coin);
}
#ifdef TEST
Mat x(image);
for (size_t i = 0; i < circles.size(); i++ ) {
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// draw the circle center
circle(x, center, 3, Scalar(0,255,0), -1, 8, 0 );
// draw the circle outline
circle(x, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
cv::imshow("", dst);
cv::waitKey();
#endif
return coins;
}
#ifdef GPU
std::vector<Coin> CoinCounter::countGpu(const cv::Mat &cpuImage) {
std::vector<Coin> coins;
cv::gpu::GpuMat image(cpuImage);
cv::gpu::GpuMat dst;
cv::gpu::GpuMat circlesMat;
cv::gpu::cvtColor(image, dst, CV_BGR2GRAY);
cv::gpu::GaussianBlur(dst, dst, cv::Size(3, 3), 2, 2);
cv::gpu::Canny(dst, dst, 1000, 1700, 5);
cv::gpu::GaussianBlur(dst, dst, cv::Size(9, 9), 3, 3);
cv::gpu::HoughCircles(dst, circlesMat, CV_HOUGH_GRADIENT,
1, // dp
40, // min dist
100, // canny1
105, // canny2
10, // min radius
200 // max radius
);
std::vector<cv::Vec3f> circles;
cv::gpu::HoughCirclesDownload(circlesMat, circles);
for (size_t i = 0; i < circles.size(); i++) {
Coin coin;
coin.center = circles[i][0];
coin.radius = circles[i][1];
bool dup = false;
for (size_t j = 0; j < coins.size(); j++) {
if (coins.at(j).center == coin.center ||
coins.at(j).radius == coin.radius) {
dup = true;
break;
}
}
if (!dup) coins.push_back(coin);
}
return coins;
}
#endif
std::vector<Coin> CoinCounter::count(const cv::Mat &image) {
#ifdef GPU
if (cv::gpu::getCudaEnabledDeviceCount() > 0) return countGpu(image);
#endif
return countCpu(image);
}
<|endoftext|> |
<commit_before><commit_msg>[assembler.gridwalker] added add() for codim 0 lambda<commit_after><|endoftext|> |
<commit_before><commit_msg>[la.container.eigen] added copy constructors<commit_after><|endoftext|> |
<commit_before><commit_msg>cppcheck: size() == 0 -> empty()<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix pingpong server OnMessage bug<commit_after><|endoftext|> |
<commit_before>#ifndef GNR_DISPATCH_HPP
# define GNR_DISPATCH_HPP
# pragma once
#include <type_traits>
#include <utility>
#include "invoke.hpp"
namespace gnr
{
namespace detail
{
template <std::size_t I, typename ...T>
using at_t = std::tuple_element_t<I, std::tuple<T...>>;
template <typename R>
using result_t = std::conditional_t<
std::is_array_v<std::remove_reference_t<R>> &&
(1 == std::rank_v<std::remove_reference_t<R>>) &&
std::is_same_v<
char,
std::remove_const_t<std::remove_extent_t<std::remove_reference_t<R>>>
>,
std::remove_extent_t<std::remove_reference_t<R>>(*)[],
std::conditional_t<
std::is_reference_v<R>,
std::remove_reference_t<R>*,
R
>
>;
template <typename F>
constexpr auto is_noexcept_dispatchable() noexcept
{
auto const f(static_cast<std::remove_reference_t<F>*>(nullptr));
if constexpr(std::is_void_v<decltype(F(*f)())> ||
std::is_reference_v<decltype(F(*f)())>)
{
return noexcept(F(*f)());
}
else
{
return noexcept(std::declval<decltype(F(*f)())&>() = F(*f)());
}
}
}
constexpr decltype(auto) dispatch(auto const i, auto&& ...f)
noexcept((detail::is_noexcept_dispatchable<decltype(f)>() && ...))
requires(
std::is_enum_v<std::remove_const_t<decltype(i)>> &&
std::conjunction_v<
std::is_same<
std::decay_t<
decltype(std::declval<detail::at_t<0, decltype(f)...>>()())
>,
std::decay_t<decltype(std::declval<decltype(f)>()())>
>...
>
)
{
using int_t = std::underlying_type_t<std::remove_const_t<decltype(i)>>;
using R = decltype(std::declval<detail::at_t<0, decltype(f)...>>()());
return [&]<auto ...I>(std::integer_sequence<int_t, I...>)
noexcept((detail::is_noexcept_dispatchable<decltype(f)>() && ...)) ->
decltype(auto)
{
if constexpr(std::is_void_v<R>)
{
((I == int_t(i) ? (f(), 0) : 0), ...);
}
else if constexpr(
(
std::is_array_v<std::remove_reference_t<R>> &&
(1 == std::rank_v<std::remove_reference_t<R>>) &&
std::is_same_v<
char,
std::remove_const_t<std::remove_extent_t<std::remove_reference_t<R>>>
>
) ||
std::is_reference_v<R>
)
{
detail::result_t<R> r;
(
(
I == int_t(i) ?
r = reinterpret_cast<decltype(r)>(&f()) :
nullptr
),
...
);
return *r;
}
else
{
R r;
((I == int_t(i) ? (r = f(), 0) : 0), ...);
return r;
}
}(std::make_integer_sequence<int_t, sizeof...(f)>());
}
constexpr decltype(auto) dispatch2(auto const i, auto&& ...a)
#ifndef __clang__
noexcept(noexcept(
gnr::invoke_split<2>(
[](auto&&, auto&& f)
{
detail::is_noexcept_dispatchable<decltype(f)>();
},
std::forward<decltype(a)>(a)...
)
)
)
#endif // __clang__
{
using R = decltype(std::declval<detail::at_t<1, decltype(a)...>>()());
if constexpr(std::is_void_v<R>)
{
gnr::invoke_split<2>(
[&](auto&& e, auto&& f) noexcept(noexcept(f()))
{
if (e == i)
{
f();
}
},
std::forward<decltype(a)>(a)...
);
}
else if constexpr(
(
std::is_array_v<std::remove_reference_t<R>> &&
(1 == std::rank_v<std::remove_reference_t<R>>) &&
std::is_same_v<
char,
std::remove_const_t<std::remove_extent_t<std::remove_reference_t<R>>>
>
) ||
std::is_reference_v<R>
)
{
detail::result_t<R> r;
gnr::invoke_split<2>(
[&](auto&& e, auto&& f) noexcept(noexcept(f()))
{
if (e == i)
{
r = reinterpret_cast<decltype(r)>(&f());
}
},
std::forward<decltype(a)>(a)...
);
return *r;
}
else
{
R r;
gnr::invoke_split<2>(
[&](auto&& e, auto&& f)
noexcept(noexcept(std::declval<R&>() = f()))
{
if (e == i)
{
r = f();
}
},
std::forward<decltype(a)>(a)...
);
return r;
}
}
constexpr decltype(auto) select(auto const i, auto&& ...v) noexcept
requires(
std::conjunction_v<
std::is_same<
std::decay_t<
decltype(std::declval<detail::at_t<0, decltype(v)...>>())
>,
std::decay_t<decltype(std::declval<decltype(v)>())>
>...
>
)
{
return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> decltype(auto)
{
detail::result_t<detail::at_t<0, decltype(v)...>> r;
(void)(((I == i) && (r = reinterpret_cast<decltype(r)>(&v))) || ...);
return *r;
}(std::make_index_sequence<sizeof...(v)>());
}
constexpr decltype(auto) select2(auto const i, auto&& ...a) noexcept
{
using R = decltype(std::declval<detail::at_t<1, decltype(a)...>>());
detail::result_t<R> r;
gnr::invoke_split_cond<2>(
[&](auto&& e, auto&& v) noexcept
{
if (e == i)
{
r = reinterpret_cast<decltype(r)>(&v);
return true;
}
else
{
return false;
}
},
std::forward<decltype(a)>(a)...
);
return *r;
}
}
#endif // GNR_DISPATCH_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_DISPATCH_HPP
# define GNR_DISPATCH_HPP
# pragma once
#include <type_traits>
#include <utility>
#include "invoke.hpp"
namespace gnr
{
namespace detail
{
template <std::size_t I, typename ...T>
using at_t = std::tuple_element_t<I, std::tuple<T...>>;
template <typename R>
using result_t = std::conditional_t<
std::is_array_v<std::remove_reference_t<R>> &&
(1 == std::rank_v<std::remove_reference_t<R>>) &&
std::is_same_v<
char,
std::remove_const_t<std::remove_extent_t<std::remove_reference_t<R>>>
>,
std::remove_extent_t<std::remove_reference_t<R>>(*)[],
std::conditional_t<
std::is_reference_v<R>,
std::remove_reference_t<R>*,
R
>
>;
template <typename F>
constexpr auto is_noexcept_dispatchable() noexcept
{
auto const f(static_cast<std::remove_reference_t<F>*>(nullptr));
if constexpr(std::is_void_v<decltype(F(*f)())> ||
std::is_reference_v<decltype(F(*f)())>)
{
return noexcept(F(*f)());
}
else
{
return noexcept(std::declval<decltype(F(*f)())&>() = F(*f)());
}
}
}
constexpr decltype(auto) dispatch(auto const i, auto&& ...f)
noexcept((detail::is_noexcept_dispatchable<decltype(f)>() && ...))
requires(
std::is_enum_v<std::remove_const_t<decltype(i)>> &&
std::conjunction_v<
std::is_same<
std::decay_t<
decltype(std::declval<detail::at_t<0, decltype(f)...>>()())
>,
std::decay_t<decltype(std::declval<decltype(f)>()())>
>...
>
)
{
using int_t = std::underlying_type_t<std::remove_const_t<decltype(i)>>;
using R = decltype(std::declval<detail::at_t<0, decltype(f)...>>()());
return [&]<auto ...I>(std::integer_sequence<int_t, I...>)
noexcept((detail::is_noexcept_dispatchable<decltype(f)>() && ...)) ->
decltype(auto)
{
if constexpr(std::is_void_v<R>)
{
((I == int_t(i) ? (f(), 0) : 0), ...);
}
else if constexpr(
(
std::is_array_v<std::remove_reference_t<R>> &&
(1 == std::rank_v<std::remove_reference_t<R>>) &&
std::is_same_v<
char,
std::remove_const_t<std::remove_extent_t<std::remove_reference_t<R>>>
>
) ||
std::is_reference_v<R>
)
{
detail::result_t<R> r;
(
(
I == int_t(i) ?
r = reinterpret_cast<decltype(r)>(&f()) :
nullptr
),
...
);
return *r;
}
else
{
R r;
((I == int_t(i) ? (r = f(), 0) : 0), ...);
return r;
}
}(std::make_integer_sequence<int_t, sizeof...(f)>());
}
constexpr decltype(auto) dispatch2(auto const i, auto&& ...a)
#ifndef __clang__
noexcept(noexcept(
gnr::invoke_split<2>(
[](auto&&, auto&& f)
{
detail::is_noexcept_dispatchable<decltype(f)>();
},
std::forward<decltype(a)>(a)...
)
)
)
#endif // __clang__
{
using R = decltype(std::declval<detail::at_t<1, decltype(a)...>>()());
if constexpr(std::is_void_v<R>)
{
gnr::invoke_split<2>(
[&](auto&& e, auto&& f) noexcept(noexcept(f()))
{
if (e == i)
{
f();
}
},
std::forward<decltype(a)>(a)...
);
}
else if constexpr(
(
std::is_array_v<std::remove_reference_t<R>> &&
(1 == std::rank_v<std::remove_reference_t<R>>) &&
std::is_same_v<
char,
std::remove_const_t<std::remove_extent_t<std::remove_reference_t<R>>>
>
) ||
std::is_reference_v<R>
)
{
detail::result_t<R> r;
gnr::invoke_split<2>(
[&](auto&& e, auto&& f) noexcept(noexcept(f()))
{
if (e == i)
{
r = reinterpret_cast<decltype(r)>(&f());
}
},
std::forward<decltype(a)>(a)...
);
return *r;
}
else
{
R r;
gnr::invoke_split<2>(
[&](auto&& e, auto&& f)
noexcept(noexcept(std::declval<R&>() = f()))
{
if (e == i)
{
r = f();
}
},
std::forward<decltype(a)>(a)...
);
return r;
}
}
constexpr decltype(auto) select(auto const i, auto&& ...v) noexcept
requires(
std::conjunction_v<
std::is_same<
std::decay_t<
decltype(std::declval<detail::at_t<0, decltype(v)...>>())
>,
std::decay_t<decltype(std::declval<decltype(v)>())>
>...
>
)
{
return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> decltype(auto)
{
detail::result_t<detail::at_t<0, decltype(v)...>> r;
(void)(((I == i) && (r = reinterpret_cast<decltype(r)>(&v))) || ...);
return *r;
}(std::make_index_sequence<sizeof...(v)>());
}
constexpr decltype(auto) select2(auto const i, auto&& ...a) noexcept
{
using R = decltype(std::declval<detail::at_t<1, decltype(a)...>>());
detail::result_t<R> r;
gnr::invoke_split_cond<2>(
[&](auto&& e, auto&& v) noexcept -> bool
{
return e == i ?
bool(r = reinterpret_cast<decltype(r)>(&v)) :
false;
},
std::forward<decltype(a)>(a)...
);
return *r;
}
}
#endif // GNR_DISPATCH_HPP
<|endoftext|> |
<commit_before><commit_msg>testFdo52989 kept failing for my Mac build at least<commit_after><|endoftext|> |
<commit_before><commit_msg>sw: Fix cursor accessibility API (fdo#43390)<commit_after><|endoftext|> |
<commit_before>#include "BTU/btu_PID_lite.cpp"
#include "mbed.h"
#define NUM_FLOATS 5
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.3
#define MIN_MISSION_DEPTH 0.2
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.075
#define SUCCESS_TIME 8.0
#define DEBRIEF_TIME_LIMIT 20.0
#define UNWOUND_POS 91.0
#include "MODSERIAL.h"
#include "SerialComm.h"
MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);
LocalFileSystem local("local");
// bool clk = true;
BTU btu = BTU();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float floorVal;
float jumpVal;
float missionFloor;
float missionStep;
float setVal = 0.0; // meters
Ticker Mission;
float timeout = 0.0;
float missionTime = 0.0;
float successTime = 0.0;
float missionDepth = 0.0;
bool missionStarted = false;
float debriefTime = 0.0;
bool debriefMode = false;
FILE *fp;
void terminateMission() {
Mission.detach();
fclose(fp);
counter = 0;
TestLED = 0;
inMission = 0;
timeout = 0.0;
successTime = 0.0;
missionTime = 0.0;
missionStarted = false;
debriefMode = false;
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}
bool checkThreshold() {
float error = btu.getDepth() - missionDepth;
// float error = btu.getServoPos() - missionDepth;
float absError = (error > 0) ? error : (-1 * error);
return (absError <= ERROR_THRESHOLD);
}
void runMission() {
if(debriefMode) {
inMission = 0;
missionDepth = 0;
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
if(debriefTime >= DEBRIEF_TIME_LIMIT) {
terminateMission();
}
debriefTime += TIMESTEP;
return;
}
counter = (counter + 1) % 20;
if(!counter) {
TestLED = !TestLED;
}
if(btu.getDepth() >= DEPTH_THRESHOLD) {
inMission = 1;
missionStarted = true;
btu.updateMode(DEPTH_CTRL_MODE);
}
if(!missionStarted) {
return;
}
btu.runCycle(missionDepth);
if(checkThreshold()) {
successTime += TIMESTEP;
} else {
successTime = 0.0;
}
if (successTime >= SUCCESS_TIME) {
if(missionDepth == missionFloor) {
missionSuccess = 1;
debriefMode = true;
return;
} else {
successTime = 0.0;
missionDepth = clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);
timeout = 0.0;
}
}
if (timeout >= MISSION_TIMEOUT) {
missionSuccess = 0;
debriefMode = true;
return;
}
missionTime += TIMESTEP;
timeout += TIMESTEP;
}
void startMission(float kc, float taui, float taud, float setDepth, float stepDist) {
terminateMission();
fp = fopen("/local/log", "w");
fprintf(fp, "MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\r\n", setDepth, stepDist);
missionSuccess = 0;
missionFloor = setDepth;
missionDepth = clip(stepDist, MIN_MISSION_DEPTH, missionFloor);
missionStep = stepDist;
btu.update(DEPTH_CTRL_MODE, kc, taui, taud);
// btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
Mission.attach(&runMission, TIMESTEP);
}
int main() {
pcSerial.printf("Start!\n");
SerialComm serialComm(&pcSerial);
btu.init();
pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
TestLED = 0;
float valueFloats[NUM_FLOATS];
while(1) {
// depth = btu.getDepth();
// if (mode == DEPTH_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth);
// } else if (mode == SPEC_POSITION_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, pos_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - btu.getServoPos());
// } else {
// pcSerial.printf("m:%d, s:%.2f, cu:%.2f, de:%.2f\r\n", btu.getMode(), setVal, btu.getServoPos(), depth);
// }
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, pos_er:%.4f, th:%d, to:%.2f, st:%.2f\r\n", btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), setVal - btu.getServoPos(), checkThreshold(), timeout, successTime);
if(inMission || debriefMode) {
float depth = btu.getDepth();
fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f\r\n",
btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), missionDepth, btu.getServoPos(), depth, missionDepth - depth, missionTime, timeout);
} else {
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}
//float depth = btu.getDepth();
//pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), missionDepth, btu.getServoPos(), depth, missionDepth - depth, missionTime, timeout);
if(serialComm.checkIfNewMessage()) {
serialComm.getFloats(valueFloats, NUM_FLOATS);
// mode = (int) valueFloats[0];
Kc = valueFloats[0];
TauI = valueFloats[1];
TauD = valueFloats[2];
jumpVal = valueFloats[3];
floorVal = valueFloats[4];
startMission(Kc, TauI, TauD, floorVal, jumpVal);
}
wait_ms(500);
TestLED2 = !TestLED2;
}
}
<commit_msg>fixed bug where in missions after the first, debriefs wouldn't log<commit_after>#include "BTU/btu_PID_lite.cpp"
#include "mbed.h"
#define NUM_FLOATS 5
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.3
#define MIN_MISSION_DEPTH 0.2
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.125
#define SUCCESS_TIME 8.0
#define DEBRIEF_TIME_LIMIT 20.0
#define UNWOUND_POS 91.0
#include "MODSERIAL.h"
#include "SerialComm.h"
MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);
LocalFileSystem local("local");
// bool clk = true;
BTU btu = BTU();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float floorVal;
float jumpVal;
float missionFloor;
float missionStep;
float setVal = 0.0; // meters
Ticker Mission;
float timeout = 0.0;
float missionTime = 0.0;
float successTime = 0.0;
float missionDepth = 0.0;
bool missionStarted = false;
float debriefTime = 0.0;
bool debriefMode = false;
FILE *fp;
void terminateMission() {
Mission.detach();
fclose(fp);
counter = 0;
TestLED = 0;
inMission = 0;
timeout = 0.0;
successTime = 0.0;
missionTime = 0.0;
missionStarted = false;
debriefMode = false;
debriefTime = 0.0;
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}
bool checkThreshold() {
float error = btu.getDepth() - missionDepth;
// float error = btu.getServoPos() - missionDepth;
float absError = (error > 0) ? error : (-1 * error);
return (absError <= ERROR_THRESHOLD);
}
void runMission() {
if(debriefMode) {
inMission = 0;
missionDepth = 0;
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
if(debriefTime >= DEBRIEF_TIME_LIMIT) {
terminateMission();
}
debriefTime += TIMESTEP;
return;
}
counter = (counter + 1) % 20;
if(!counter) {
TestLED = !TestLED;
}
if(btu.getDepth() >= DEPTH_THRESHOLD) {
inMission = 1;
missionStarted = true;
btu.updateMode(DEPTH_CTRL_MODE);
}
if(!missionStarted) {
return;
}
btu.runCycle(missionDepth);
if(checkThreshold()) {
successTime += TIMESTEP;
} else {
successTime = 0.0;
}
if (successTime >= SUCCESS_TIME) {
if(missionDepth == missionFloor) {
missionSuccess = 1;
debriefMode = true;
return;
} else {
successTime = 0.0;
missionDepth = clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);
timeout = 0.0;
}
}
if (timeout >= MISSION_TIMEOUT) {
missionSuccess = 0;
debriefMode = true;
return;
}
missionTime += TIMESTEP;
timeout += TIMESTEP;
}
void startMission(float kc, float taui, float taud, float setDepth, float stepDist) {
terminateMission();
fp = fopen("/local/log", "w");
fprintf(fp, "MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\r\n", setDepth, stepDist);
missionSuccess = 0;
missionFloor = setDepth;
missionDepth = clip(stepDist, MIN_MISSION_DEPTH, missionFloor);
missionStep = stepDist;
btu.update(DEPTH_CTRL_MODE, kc, taui, taud);
// btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
Mission.attach(&runMission, TIMESTEP);
}
int main() {
pcSerial.printf("Start!\n");
SerialComm serialComm(&pcSerial);
btu.init();
pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
TestLED = 0;
float valueFloats[NUM_FLOATS];
while(1) {
// depth = btu.getDepth();
// if (mode == DEPTH_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth);
// } else if (mode == SPEC_POSITION_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, pos_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - btu.getServoPos());
// } else {
// pcSerial.printf("m:%d, s:%.2f, cu:%.2f, de:%.2f\r\n", btu.getMode(), setVal, btu.getServoPos(), depth);
// }
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, pos_er:%.4f, th:%d, to:%.2f, st:%.2f\r\n", btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), setVal - btu.getServoPos(), checkThreshold(), timeout, successTime);
if(inMission || debriefMode) {
float depth = btu.getDepth();
fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f\r\n",
btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), missionDepth, btu.getServoPos(), depth, missionDepth - depth, missionTime, timeout);
} else {
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}
//float depth = btu.getDepth();
//pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), missionDepth, btu.getServoPos(), depth, missionDepth - depth, missionTime, timeout);
if(serialComm.checkIfNewMessage()) {
serialComm.getFloats(valueFloats, NUM_FLOATS);
// mode = (int) valueFloats[0];
Kc = valueFloats[0];
TauI = valueFloats[1];
TauD = valueFloats[2];
jumpVal = valueFloats[3];
floorVal = valueFloats[4];
startMission(Kc, TauI, TauD, floorVal, jumpVal);
}
wait_ms(500);
TestLED2 = !TestLED2;
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// expression_test.cpp
//
// Identification: tests/expression/expression_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include <sstream>
#include <queue>
#include "gtest/gtest.h"
#include "harness.h"
#include "backend/expression/abstract_expression.h"
#include "backend/common/types.h"
#include "backend/common/value_peeker.h"
#include "backend/storage/tuple.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/conjunction_expression.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Expression Tests
//===--------------------------------------------------------------------===//
/*
Description of test:
1. This test defines a data structure for each expression type with
unique fields.
2. The test includes a helper to convert a std::queue of these structures
into a tree of AbstractExpressions, using the expression factory via a
json serialization.
3. Using this utilities, the test defines several expressions (in
std::queue) formats and asserts on the expected result.
TODO: Unfortunately, the json_spirit serialization asserts when trying
to read an int field from a value serialized as a string; need to figure
out what's going on here .. and what the proper serialization method is.
*/
/*
* Abstract expression mock object
*/
class AE {
public:
AE(ExpressionType et, ValueType vt, int vs)
: m_type(et),
m_valueType(vt),
m_valueSize(vs),
left(nullptr),
right(nullptr) {}
virtual ~AE() {
delete left;
delete right;
}
virtual json_spirit::Object SerializeValue() {
json_spirit::Object json;
Serialize(json);
return json;
}
// this is how java serializes..
// note derived class data follows the serialization of children
virtual void Serialize(json_spirit::Object &json) {
json.push_back(json_spirit::Pair(
"TYPE", json_spirit::Value(ExpressionTypeToString(m_type))));
json.push_back(json_spirit::Pair(
"VALUE_TYPE", json_spirit::Value(ValueTypeToString(m_valueType))));
json.push_back(
json_spirit::Pair("VALUE_SIZE", json_spirit::Value(m_valueSize)));
if (left) json.push_back(json_spirit::Pair("LEFT", left->SerializeValue()));
if (right)
json.push_back(json_spirit::Pair("RIGHT", right->SerializeValue()));
}
ExpressionType m_type; // TYPE
ValueType m_valueType; // VALUE_TYPE
int m_valueSize; // VALUE_SIZE
// to build a tree
AE *left;
AE *right;
};
/*
* constant value expression mock object
*/
class CV : public AE {
public:
CV(ExpressionType et, ValueType vt, int vs, int64_t v)
: AE(et, vt, vs), m_jsontype(1), m_intValue(v) {
m_stringValue = nullptr;
m_doubleValue = 0.0;
}
CV(ExpressionType et, ValueType vt, int vs, char *v)
: AE(et, vt, vs), m_jsontype(1), m_stringValue(strdup(v)) {
m_intValue = 0;
m_doubleValue = 0.0;
}
CV(ExpressionType et, ValueType vt, int vs, double v)
: AE(et, vt, vs), m_jsontype(1), m_doubleValue(v) {
m_stringValue = nullptr;
m_intValue = 0;
}
~CV() {}
virtual void Serialize(json_spirit::Object &json) {
AE::Serialize(json);
if (m_jsontype == 0)
json.push_back(
json_spirit::Pair("VALUE", json_spirit::Value(m_stringValue)));
else if (m_jsontype == 1)
json.push_back(
json_spirit::Pair("VALUE", json_spirit::Value(m_intValue)));
else if (m_jsontype == 2)
json.push_back(
json_spirit::Pair("VALUE", json_spirit::Value(m_doubleValue)));
}
int m_jsontype; // 0 = string, 1 = int64_t, 2 = double
int64_t m_intValue; // VALUE
char *m_stringValue; // VALUE
double m_doubleValue; // VALUE
};
/*
* parameter value expression mock object
*/
class PV : public AE {
public:
PV(ExpressionType et, ValueType vt, int vs, int pi)
: AE(et, vt, vs), m_paramIdx(pi) {}
virtual void Serialize(json_spirit::Object &json) {
AE::Serialize(json);
json.push_back(
json_spirit::Pair("PARAM_IDX", json_spirit::Value(m_paramIdx)));
}
int m_paramIdx; // PARAM_IDX
};
/*
* tuple value expression mock object
*/
class TV : public AE {
public:
TV(ExpressionType et, ValueType vt, int vs, int ci, const char *tn,
const char *cn, const char *ca)
: AE(et, vt, vs),
m_columnIdx(ci),
m_tableName(strdup(tn)),
m_colName(strdup(cn)),
m_colAlias(strdup(ca)) {}
~TV() {
delete m_tableName;
delete m_colName;
delete m_colAlias;
}
virtual void Serialize(json_spirit::Object &json) {
AE::Serialize(json);
json.push_back(
json_spirit::Pair("COLUMN_IDX", json_spirit::Value(m_columnIdx)));
json.push_back(
json_spirit::Pair("TABLE_NAME", json_spirit::Value(m_tableName)));
json.push_back(
json_spirit::Pair("COLUMN_NAME", json_spirit::Value(m_colName)));
json.push_back(
json_spirit::Pair("COLUMN_ALIAS", json_spirit::Value(m_colAlias)));
}
int m_columnIdx; // COLUMN_IDX
char *m_tableName; // TABLE_NAME
char *m_colName; // COLUMN_NAME
char *m_colAlias; // COLUMN_ALIAS
};
/*
helpers to build trivial left-associative trees
that is (a, *, b, +, c) returns (a * b) + c
and (a, +, b, * c) returns (a + b) * c
*/
AE *Join(AE *op, AE *left, AE *right) {
op->left = left;
op->right = right;
return op;
}
AE *MakeTree(AE *tree, std::queue<AE *> &q) {
if (!q.empty()) {
AE *left, *right, *op;
if (tree) {
left = tree;
} else {
left = q.front();
q.pop();
}
op = q.front();
q.pop();
right = q.front();
q.pop();
tree = MakeTree(Join(op, left, right), q);
}
return tree;
}
// boilerplate to turn the queue into a real AbstractExpression tree;
// return the generated AE tree by reference to allow deletion (the queue
// is emptied by the tree building process)
expression::AbstractExpression *ConvertToExpression(std::queue<AE *> &e) {
AE *tree = MakeTree(nullptr, e);
json_spirit::Object json = tree->SerializeValue();
expression::AbstractExpression *exp =
expression::AbstractExpression::CreateExpressionTree(json);
delete tree;
return exp;
}
/*
* Show that simple addition works with the framework
*/
TEST(ExpressionTest, SimpleAddition) {
std::queue<AE *> e;
storage::Tuple junk;
// 1 + 4
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)1));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)4));
std::unique_ptr<expression::AbstractExpression> testexp(
ConvertToExpression(e));
Value result = testexp->Evaluate(&junk, nullptr, nullptr);
std::cout << (*testexp);
EXPECT_EQ(ValuePeeker::PeekAsBigInt(result), 5LL);
}
/*
* Show that the associative property is as expected
*/
TEST(ExpressionTest, SimpleMultiplication) {
std::queue<AE *> e;
storage::Tuple junk;
// (1 + 4) * 5
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)1));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)4));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)5));
std::unique_ptr<expression::AbstractExpression> e1(ConvertToExpression(e));
Value r1 = e1->Evaluate(&junk, nullptr, nullptr);
std::cout << (*e1);
EXPECT_EQ(ValuePeeker::PeekAsBigInt(r1), 25LL);
// (2 * 5) + 3
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)2));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)5));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)3));
std::unique_ptr<expression::AbstractExpression> e2(ConvertToExpression(e));
Value r2 = e2->Evaluate(&junk, nullptr, nullptr);
std::cout << (*e2);
EXPECT_EQ(ValuePeeker::PeekAsBigInt(r2), 13LL);
}
TEST(ExpressionTest, SimpleFilter) {
// WHERE id = 20
// EXPRESSION
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(20));
expression::ComparisonExpression<expression::CmpEq> *equal =
new expression::ComparisonExpression<expression::CmpEq>(
EXPRESSION_TYPE_COMPARE_EQUAL, tup_val_exp, const_val_exp);
// TUPLE
std::vector<catalog::Column> columns;
catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"A", true);
catalog::Column column2(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"B", true);
columns.push_back(column1);
columns.push_back(column2);
catalog::Schema *schema(new catalog::Schema(columns));
storage::Tuple *tuple(new storage::Tuple(schema, true));
tuple->SetValue(0, ValueFactory::GetIntegerValue(20));
tuple->SetValue(1, ValueFactory::GetIntegerValue(45));
std::cout << (*equal);
EXPECT_EQ(equal->Evaluate(tuple, NULL, NULL).IsTrue(), true);
tuple->SetValue(0, ValueFactory::GetIntegerValue(50));
EXPECT_EQ(equal->Evaluate(tuple, NULL, NULL).IsTrue(), false);
// delete the root to destroy the full tree.
delete equal;
delete schema;
delete tuple;
}
} // End test namespace
} // End peloton namespace
<commit_msg>TEST code in Expression_test.cpp<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// expression_test.cpp
//
// Identification: tests/expression/expression_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include <sstream>
#include <queue>
#include "gtest/gtest.h"
#include "harness.h"
#include "backend/expression/abstract_expression.h"
#include "backend/common/types.h"
#include "backend/common/value_peeker.h"
#include "backend/storage/tuple.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/conjunction_expression.h"
#include "backend/expression/vector_expression.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Expression Tests
//===--------------------------------------------------------------------===//
/*
Description of test:
1. This test defines a data structure for each expression type with
unique fields.
2. The test includes a helper to convert a std::queue of these structures
into a tree of AbstractExpressions, using the expression factory via a
json serialization.
3. Using this utilities, the test defines several expressions (in
std::queue) formats and asserts on the expected result.
TODO: Unfortunately, the json_spirit serialization asserts when trying
to read an int field from a value serialized as a string; need to figure
out what's going on here .. and what the proper serialization method is.
*/
/*
* Abstract expression mock object
*/
class AE {
public:
AE(ExpressionType et, ValueType vt, int vs)
: m_type(et),
m_valueType(vt),
m_valueSize(vs),
left(nullptr),
right(nullptr) {}
virtual ~AE() {
delete left;
delete right;
}
virtual json_spirit::Object SerializeValue() {
json_spirit::Object json;
Serialize(json);
return json;
}
// this is how java serializes..
// note derived class data follows the serialization of children
virtual void Serialize(json_spirit::Object &json) {
json.push_back(json_spirit::Pair(
"TYPE", json_spirit::Value(ExpressionTypeToString(m_type))));
json.push_back(json_spirit::Pair(
"VALUE_TYPE", json_spirit::Value(ValueTypeToString(m_valueType))));
json.push_back(
json_spirit::Pair("VALUE_SIZE", json_spirit::Value(m_valueSize)));
if (left) json.push_back(json_spirit::Pair("LEFT", left->SerializeValue()));
if (right)
json.push_back(json_spirit::Pair("RIGHT", right->SerializeValue()));
}
ExpressionType m_type; // TYPE
ValueType m_valueType; // VALUE_TYPE
int m_valueSize; // VALUE_SIZE
// to build a tree
AE *left;
AE *right;
};
/*
* constant value expression mock object
*/
class CV : public AE {
public:
CV(ExpressionType et, ValueType vt, int vs, int64_t v)
: AE(et, vt, vs), m_jsontype(1), m_intValue(v) {
m_stringValue = nullptr;
m_doubleValue = 0.0;
}
CV(ExpressionType et, ValueType vt, int vs, char *v)
: AE(et, vt, vs), m_jsontype(1), m_stringValue(strdup(v)) {
m_intValue = 0;
m_doubleValue = 0.0;
}
CV(ExpressionType et, ValueType vt, int vs, double v)
: AE(et, vt, vs), m_jsontype(1), m_doubleValue(v) {
m_stringValue = nullptr;
m_intValue = 0;
}
~CV() {}
virtual void Serialize(json_spirit::Object &json) {
AE::Serialize(json);
if (m_jsontype == 0)
json.push_back(
json_spirit::Pair("VALUE", json_spirit::Value(m_stringValue)));
else if (m_jsontype == 1)
json.push_back(
json_spirit::Pair("VALUE", json_spirit::Value(m_intValue)));
else if (m_jsontype == 2)
json.push_back(
json_spirit::Pair("VALUE", json_spirit::Value(m_doubleValue)));
}
int m_jsontype; // 0 = string, 1 = int64_t, 2 = double
int64_t m_intValue; // VALUE
char *m_stringValue; // VALUE
double m_doubleValue; // VALUE
};
/*
* parameter value expression mock object
*/
class PV : public AE {
public:
PV(ExpressionType et, ValueType vt, int vs, int pi)
: AE(et, vt, vs), m_paramIdx(pi) {}
virtual void Serialize(json_spirit::Object &json) {
AE::Serialize(json);
json.push_back(
json_spirit::Pair("PARAM_IDX", json_spirit::Value(m_paramIdx)));
}
int m_paramIdx; // PARAM_IDX
};
/*
* tuple value expression mock object
*/
class TV : public AE {
public:
TV(ExpressionType et, ValueType vt, int vs, int ci, const char *tn,
const char *cn, const char *ca)
: AE(et, vt, vs),
m_columnIdx(ci),
m_tableName(strdup(tn)),
m_colName(strdup(cn)),
m_colAlias(strdup(ca)) {}
~TV() {
delete m_tableName;
delete m_colName;
delete m_colAlias;
}
virtual void Serialize(json_spirit::Object &json) {
AE::Serialize(json);
json.push_back(
json_spirit::Pair("COLUMN_IDX", json_spirit::Value(m_columnIdx)));
json.push_back(
json_spirit::Pair("TABLE_NAME", json_spirit::Value(m_tableName)));
json.push_back(
json_spirit::Pair("COLUMN_NAME", json_spirit::Value(m_colName)));
json.push_back(
json_spirit::Pair("COLUMN_ALIAS", json_spirit::Value(m_colAlias)));
}
int m_columnIdx; // COLUMN_IDX
char *m_tableName; // TABLE_NAME
char *m_colName; // COLUMN_NAME
char *m_colAlias; // COLUMN_ALIAS
};
/*
helpers to build trivial left-associative trees
that is (a, *, b, +, c) returns (a * b) + c
and (a, +, b, * c) returns (a + b) * c
*/
AE *Join(AE *op, AE *left, AE *right) {
op->left = left;
op->right = right;
return op;
}
AE *MakeTree(AE *tree, std::queue<AE *> &q) {
if (!q.empty()) {
AE *left, *right, *op;
if (tree) {
left = tree;
} else {
left = q.front();
q.pop();
}
op = q.front();
q.pop();
right = q.front();
q.pop();
tree = MakeTree(Join(op, left, right), q);
}
return tree;
}
// boilerplate to turn the queue into a real AbstractExpression tree;
// return the generated AE tree by reference to allow deletion (the queue
// is emptied by the tree building process)
expression::AbstractExpression *ConvertToExpression(std::queue<AE *> &e) {
AE *tree = MakeTree(nullptr, e);
json_spirit::Object json = tree->SerializeValue();
expression::AbstractExpression *exp =
expression::AbstractExpression::CreateExpressionTree(json);
delete tree;
return exp;
}
/*
* Show that simple addition works with the framework
*/
TEST(ExpressionTest, SimpleAddition) {
std::queue<AE *> e;
storage::Tuple junk;
// 1 + 4
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)1));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)4));
std::unique_ptr<expression::AbstractExpression> testexp(
ConvertToExpression(e));
Value result = testexp->Evaluate(&junk, nullptr, nullptr);
std::cout << (*testexp);
EXPECT_EQ(ValuePeeker::PeekAsBigInt(result), 5LL);
}
/*
* Show that the associative property is as expected
*/
TEST(ExpressionTest, SimpleMultiplication) {
std::queue<AE *> e;
storage::Tuple junk;
// (1 + 4) * 5
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)1));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)4));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)5));
std::unique_ptr<expression::AbstractExpression> e1(ConvertToExpression(e));
Value r1 = e1->Evaluate(&junk, nullptr, nullptr);
std::cout << (*e1);
EXPECT_EQ(ValuePeeker::PeekAsBigInt(r1), 25LL);
// (2 * 5) + 3
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)2));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)5));
e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, VALUE_TYPE_TINYINT, 1));
e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, VALUE_TYPE_TINYINT, 1,
(int64_t)3));
std::unique_ptr<expression::AbstractExpression> e2(ConvertToExpression(e));
Value r2 = e2->Evaluate(&junk, nullptr, nullptr);
std::cout << (*e2);
EXPECT_EQ(ValuePeeker::PeekAsBigInt(r2), 13LL);
}
TEST(ExpressionTest, SimpleFilter) {
// WHERE id = 20
// EXPRESSION
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(20));
expression::ComparisonExpression<expression::CmpEq> *equal =
new expression::ComparisonExpression<expression::CmpEq>(
EXPRESSION_TYPE_COMPARE_EQUAL, tup_val_exp, const_val_exp);
// TUPLE
std::vector<catalog::Column> columns;
catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"A", true);
catalog::Column column2(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"B", true);
columns.push_back(column1);
columns.push_back(column2);
catalog::Schema *schema(new catalog::Schema(columns));
storage::Tuple *tuple(new storage::Tuple(schema, true));
tuple->SetValue(0, ValueFactory::GetIntegerValue(20));
tuple->SetValue(1, ValueFactory::GetIntegerValue(45));
std::cout << (*equal);
EXPECT_EQ(equal->Evaluate(tuple, NULL, NULL).IsTrue(), true);
tuple->SetValue(0, ValueFactory::GetIntegerValue(50));
EXPECT_EQ(equal->Evaluate(tuple, NULL, NULL).IsTrue(), false);
// delete the root to destroy the full tree.
delete equal;
delete schema;
delete tuple;
}
TEST(ExpressionTest, SimpleInFilter) {
// WHERE id in (15, 20)
// EXPRESSION
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp1 =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(15));
expression::ConstantValueExpression *const_val_exp2 =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(20));
std::vector<expression::AbstractExpression *> vec_const_exprs;
vec_const_exprs.push_back(const_val_exp1);
vec_const_exprs.push_back(const_val_exp2);
expression::VectorExpression *vec_exp =
new expression::VectorExpression(
VALUE_TYPE_ARRAY, vec_const_exprs);
expression::ComparisonExpression<expression::CmpIn> *equal =
new expression::ComparisonExpression<expression::CmpIn>(
EXPRESSION_TYPE_COMPARE_IN, tup_val_exp, vec_exp);
// TUPLE
std::vector<catalog::Column> columns;
catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"A", true);
catalog::Column column2(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"B", true);
columns.push_back(column1);
columns.push_back(column2);
catalog::Schema *schema(new catalog::Schema(columns));
storage::Tuple *tuple(new storage::Tuple(schema, true));
tuple->SetValue(0, ValueFactory::GetIntegerValue(20));
tuple->SetValue(1, ValueFactory::GetIntegerValue(45));
//std::cout << (*equal);
EXPECT_EQ(equal->Evaluate(tuple, NULL, NULL).IsTrue(), true);
tuple->SetValue(0, ValueFactory::GetIntegerValue(50));
EXPECT_EQ(equal->Evaluate(tuple, NULL, NULL).IsTrue(), false);
// delete the root to destroy the full tree.
delete tup_val_exp;
delete const_val_exp1;
delete const_val_exp2;
delete vec_exp;
delete equal;
delete schema;
delete tuple;
}
} // End test namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: uiconfigurationmanager.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: as $ $Date: 2004-12-07 13:18:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
#define __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <list>
#include <hash_map>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_IMAGEMANAGER_HXX_
#include <uiconfiguration/imagemanager.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATION_HPP_
#include <drafts/com/sun/star/ui/XUIConfiguration.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_
#include <drafts/com/sun/star/ui/XUIConfigurationPersistence.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONSTORGAE_HPP_
#include <drafts/com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_
#include <drafts/com/sun/star/ui/XUIConfigurationManager.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_CONFIGURATIONEVENT_HPP_
#include <drafts/com/sun/star/ui/ConfigurationEvent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <drafts/com/sun/star/ui/UIElementType.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class UIConfigurationManager : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public com::sun::star::lang::XComponent ,
public drafts::com::sun::star::ui::XUIConfiguration ,
public drafts::com::sun::star::ui::XUIConfigurationManager ,
public drafts::com::sun::star::ui::XUIConfigurationPersistence ,
public drafts::com::sun::star::ui::XUIConfigurationStorage ,
private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
UIConfigurationManager( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xServiceManager );
virtual ~UIConfigurationManager();
// XComponent
virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
// XUIConfiguration
virtual void SAL_CALL addConfigurationListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeConfigurationListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);
// XUIConfigurationManager
virtual void SAL_CALL reset() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getUIElementsInfo( sal_Int16 ElementType ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > SAL_CALL createSettings( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( const ::rtl::OUString& ResourceURL, sal_Bool bWriteable ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL replaceSettings( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertSettings( const ::rtl::OUString& NewResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getImageManager() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getShortCutManager() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getEventsManager() throw (::com::sun::star::uno::RuntimeException);
// XUIConfigurationPersistence
virtual void SAL_CALL reload() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL store() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL storeToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isModified() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly() throw (::com::sun::star::uno::RuntimeException);
// XUIConfigurationStorage
virtual void SAL_CALL setStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasStorage() throw (::com::sun::star::uno::RuntimeException);
private:
// private data types
enum NotifyOp
{
NotifyOp_Remove,
NotifyOp_Insert,
NotifyOp_Replace
};
struct UIElementInfo
{
UIElementInfo( const rtl::OUString& rResourceURL, const rtl::OUString& rUIName ) :
aResourceURL( rResourceURL), aUIName( rUIName ) {}
rtl::OUString aResourceURL;
rtl::OUString aUIName;
};
struct UIElementData
{
UIElementData() : bModified( false ), bDefault( true ) {};
rtl::OUString aResourceURL;
rtl::OUString aName;
bool bModified; // has been changed since last storing
bool bDefault; // default settings
com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > xSettings;
};
struct UIElementType;
friend struct UIElementType;
typedef ::std::hash_map< rtl::OUString, UIElementData, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementDataHashMap;
struct UIElementType
{
UIElementType() : nElementType( drafts::com::sun::star::ui::UIElementType::UNKNOWN ), bLoaded( false ), bModified( false ), bDefaultLayer( false ) {}
bool bModified;
bool bLoaded;
bool bDefaultLayer;
sal_Int16 nElementType;
UIElementDataHashMap aElementsHashMap;
com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage;
};
typedef ::std::vector< UIElementType > UIElementTypesVector;
typedef ::std::vector< drafts::com::sun::star::ui::ConfigurationEvent > ConfigEventNotifyContainer;
typedef ::std::hash_map< rtl::OUString, UIElementInfo, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementInfoHashMap;
// private methods
void impl_Initialize();
void implts_notifyContainerListener( const drafts::com::sun::star::ui::ConfigurationEvent& aEvent, NotifyOp eOp );
void impl_fillSequenceWithElementTypeInfo( UIElementInfoHashMap& aUIElementInfoCollection, sal_Int16 nElementType );
void impl_preloadUIElementTypeList( sal_Int16 nElementType );
UIElementData* impl_findUIElementData( const rtl::OUString& aResourceURL, sal_Int16 nElementType, bool bLoad = true );
void impl_requestUIElementData( sal_Int16 nElementType, UIElementData& aUIElementData );
void impl_storeElementTypeData( com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage, UIElementType& rElementType, bool bResetModifyState = true );
void impl_resetElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer );
void impl_reloadElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer );
UIElementTypesVector m_aUIElements;
com::sun::star::uno::Reference< com::sun::star::embed::XStorage > m_xDocConfigStorage;
bool m_bReadOnly;
bool m_bInitialized;
bool m_bModified;
bool m_bConfigRead;
bool m_bDisposed;
rtl::OUString m_aXMLPostfix;
rtl::OUString m_aPropUIName;
rtl::OUString m_aPropResourceURL;
rtl::OUString m_aModuleIdentifier;
com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener
com::sun::star::uno::Reference< com::sun::star::lang::XComponent > m_xImageManager;
com::sun::star::uno::Reference< com::sun::star::uno::XInterface > m_xAccConfig;
};
}
#endif // __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
<commit_msg>INTEGRATION: CWS removedrafts (1.5.58); FILE MERGED 2005/02/17 12:45:52 cd 1.5.58.1: #i42557# move UNOIDL types from drafts to com<commit_after>/*************************************************************************
*
* $RCSfile: uiconfigurationmanager.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2005-03-01 19:27:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
#define __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <list>
#include <hash_map>
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_IMAGEMANAGER_HXX_
#include <uiconfiguration/imagemanager.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATION_HPP_
#include <com/sun/star/ui/XUIConfiguration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_
#include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONSTORGAE_HPP_
#include <com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_
#include <com/sun/star/ui/XUIConfigurationManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_CONFIGURATIONEVENT_HPP_
#include <com/sun/star/ui/ConfigurationEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class UIConfigurationManager : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public com::sun::star::lang::XComponent ,
public ::com::sun::star::ui::XUIConfiguration ,
public ::com::sun::star::ui::XUIConfigurationManager ,
public ::com::sun::star::ui::XUIConfigurationPersistence ,
public ::com::sun::star::ui::XUIConfigurationStorage ,
private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
UIConfigurationManager( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xServiceManager );
virtual ~UIConfigurationManager();
// XComponent
virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
// XUIConfiguration
virtual void SAL_CALL addConfigurationListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeConfigurationListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);
// XUIConfigurationManager
virtual void SAL_CALL reset() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getUIElementsInfo( sal_Int16 ElementType ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > SAL_CALL createSettings( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( const ::rtl::OUString& ResourceURL, sal_Bool bWriteable ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL replaceSettings( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertSettings( const ::rtl::OUString& NewResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getImageManager() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getShortCutManager() throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getEventsManager() throw (::com::sun::star::uno::RuntimeException);
// XUIConfigurationPersistence
virtual void SAL_CALL reload() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL store() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL storeToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isModified() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly() throw (::com::sun::star::uno::RuntimeException);
// XUIConfigurationStorage
virtual void SAL_CALL setStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasStorage() throw (::com::sun::star::uno::RuntimeException);
private:
// private data types
enum NotifyOp
{
NotifyOp_Remove,
NotifyOp_Insert,
NotifyOp_Replace
};
struct UIElementInfo
{
UIElementInfo( const rtl::OUString& rResourceURL, const rtl::OUString& rUIName ) :
aResourceURL( rResourceURL), aUIName( rUIName ) {}
rtl::OUString aResourceURL;
rtl::OUString aUIName;
};
struct UIElementData
{
UIElementData() : bModified( false ), bDefault( true ) {};
rtl::OUString aResourceURL;
rtl::OUString aName;
bool bModified; // has been changed since last storing
bool bDefault; // default settings
com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > xSettings;
};
struct UIElementType;
friend struct UIElementType;
typedef ::std::hash_map< rtl::OUString, UIElementData, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementDataHashMap;
struct UIElementType
{
UIElementType() : nElementType( ::com::sun::star::ui::UIElementType::UNKNOWN ), bLoaded( false ), bModified( false ), bDefaultLayer( false ) {}
bool bModified;
bool bLoaded;
bool bDefaultLayer;
sal_Int16 nElementType;
UIElementDataHashMap aElementsHashMap;
com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage;
};
typedef ::std::vector< UIElementType > UIElementTypesVector;
typedef ::std::vector< ::com::sun::star::ui::ConfigurationEvent > ConfigEventNotifyContainer;
typedef ::std::hash_map< rtl::OUString, UIElementInfo, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementInfoHashMap;
// private methods
void impl_Initialize();
void implts_notifyContainerListener( const ::com::sun::star::ui::ConfigurationEvent& aEvent, NotifyOp eOp );
void impl_fillSequenceWithElementTypeInfo( UIElementInfoHashMap& aUIElementInfoCollection, sal_Int16 nElementType );
void impl_preloadUIElementTypeList( sal_Int16 nElementType );
UIElementData* impl_findUIElementData( const rtl::OUString& aResourceURL, sal_Int16 nElementType, bool bLoad = true );
void impl_requestUIElementData( sal_Int16 nElementType, UIElementData& aUIElementData );
void impl_storeElementTypeData( com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage, UIElementType& rElementType, bool bResetModifyState = true );
void impl_resetElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer );
void impl_reloadElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer );
UIElementTypesVector m_aUIElements;
com::sun::star::uno::Reference< com::sun::star::embed::XStorage > m_xDocConfigStorage;
bool m_bReadOnly;
bool m_bInitialized;
bool m_bModified;
bool m_bConfigRead;
bool m_bDisposed;
rtl::OUString m_aXMLPostfix;
rtl::OUString m_aPropUIName;
rtl::OUString m_aPropResourceURL;
rtl::OUString m_aModuleIdentifier;
com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener
com::sun::star::uno::Reference< com::sun::star::lang::XComponent > m_xImageManager;
com::sun::star::uno::Reference< com::sun::star::uno::XInterface > m_xAccConfig;
};
}
#endif // __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
<|endoftext|> |
<commit_before>#include <QtTest/QtTest>
#include "../qtest-platform.h"
#include "helpwidget.h"
#include "mainwindow.h"
class TestMainWindow : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void about_window();
void console_window();
void quit_simple();
void quit_tasks();
};
void TestMainWindow::initTestCase()
{
QCoreApplication::setOrganizationName(TEST_NAME);
IF_NOT_VISUAL
{
// Use a custom message handler to filter out unwanted messages
orig_message_handler = qInstallMessageHandler(offscreenMessageOutput);
}
}
static QAction *get_menubar_about(QMenuBar *menubar)
{
foreach(QAction *action, menubar->actions())
{
if(action->menu())
{
foreach(QAction *subaction, action->menu()->actions())
{
if(subaction->menuRole() == QAction::AboutRole)
{
return subaction;
}
}
}
}
return (nullptr);
}
void TestMainWindow::about_window()
{
MainWindow * mainwindow = new MainWindow();
HelpWidget * help = &mainwindow->_helpWidget;
Ui::MainWindow ui_main = mainwindow->_ui;
Ui::HelpWidget ui = help->_ui;
VISUAL_INIT(mainwindow);
// Starts off not visible and the button is not pushed down
ui_main.actionGoHelp->trigger();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by clicking the button again
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by closing the About window
help->_aboutWindow.close();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
// Test the "About Tarsnap" menubar item, if applicable.
if(mainwindow->_menuBar != nullptr)
{
// find "About Tarsnap" menu item
QAction *menuAction = get_menubar_about(mainwindow->_menuBar);
QVERIFY(menuAction != nullptr);
VISUAL_WAIT;
// Becomes visible using the menu bar action
menuAction->trigger();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Stay visible even when clicking the menu bar action again
menuAction->trigger();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by clicking the Help->About button
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
}
delete mainwindow;
}
void TestMainWindow::quit_simple()
{
MainWindow *mainwindow = new MainWindow();
QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo()));
VISUAL_INIT(mainwindow);
// If we try to close the window, we emit a getTaskInfo instead
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 1);
sig_getTaskInfo.clear();
// Fake getting a reply which says there's no tasks.
mainwindow->closeWithTaskInfo(false, 0, 0);
// After quitting, we don't respond to more events.
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 0);
delete mainwindow;
}
void TestMainWindow::quit_tasks()
{
MainWindow *mainwindow = new MainWindow();
QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo()));
VISUAL_INIT(mainwindow);
// Fake getting a response to a closeEvent (not sent in this test) which
// says that there's running tasks, but cancel the quitting.
QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo",
Qt::QueuedConnection, Q_ARG(bool, true),
Q_ARG(int, 1), Q_ARG(int, 1));
QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "close",
Qt::QueuedConnection);
VISUAL_WAIT;
// After cancelling the quit, we still respond to events
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 1);
sig_getTaskInfo.clear();
VISUAL_WAIT;
// Quit the app
// FIXME: sending an "accept" is a hack because the task-specific choices
// (e.g., stop tasks, run in background) are only added to the dialog box
// after MainWindow receives the closeWithTaskInfo, so we can't
// "queue up" sending a message to one of those objects.
QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo",
Qt::QueuedConnection, Q_ARG(bool, true),
Q_ARG(int, 1), Q_ARG(int, 1));
QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "accept",
Qt::QueuedConnection);
VISUAL_WAIT;
// After quitting, we don't respond to more events
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 0);
VISUAL_WAIT;
delete mainwindow;
}
void TestMainWindow::console_window()
{
MainWindow * mainwindow = new MainWindow();
HelpWidget * help = &mainwindow->_helpWidget;
Ui::MainWindow ui_main = mainwindow->_ui;
Ui::HelpWidget ui = help->_ui;
VISUAL_INIT(mainwindow);
// Starts off not visible and the button is not pushed down
ui_main.actionGoHelp->trigger();
QVERIFY(help->_consoleWindow.isVisible() == false);
QVERIFY(ui.consoleButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.consoleButton->click();
QVERIFY(help->_consoleWindow.isVisible() == true);
QVERIFY(ui.consoleButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by clicking the button again
ui.consoleButton->click();
QVERIFY(help->_consoleWindow.isVisible() == false);
QVERIFY(ui.consoleButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.consoleButton->click();
QVERIFY(help->_consoleWindow.isVisible() == true);
QVERIFY(ui.consoleButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by closing the Console window
help->_consoleWindow.close();
QVERIFY(help->_consoleWindow.isVisible() == false);
QVERIFY(ui.consoleButton->isChecked() == false);
VISUAL_WAIT;
delete mainwindow;
}
QTEST_MAIN(TestMainWindow)
#include "test-mainwindow.moc"
<commit_msg>tests/mainwindow: test navigation between tabs<commit_after>#include <QtTest/QtTest>
#include "../qtest-platform.h"
#include "helpwidget.h"
#include "mainwindow.h"
#include "archive.h"
class TestMainWindow : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void about_window();
void console_window();
void quit_simple();
void quit_tasks();
void tab_navigation();
};
void TestMainWindow::initTestCase()
{
QCoreApplication::setOrganizationName(TEST_NAME);
IF_NOT_VISUAL
{
// Use a custom message handler to filter out unwanted messages
orig_message_handler = qInstallMessageHandler(offscreenMessageOutput);
}
// Initialization normally done in init_shared.cpp's init_no_app()
qRegisterMetaType<QVector<File>>("QVector<File>");
}
static QAction *get_menubar_about(QMenuBar *menubar)
{
foreach(QAction *action, menubar->actions())
{
if(action->menu())
{
foreach(QAction *subaction, action->menu()->actions())
{
if(subaction->menuRole() == QAction::AboutRole)
{
return subaction;
}
}
}
}
return (nullptr);
}
void TestMainWindow::about_window()
{
MainWindow * mainwindow = new MainWindow();
HelpWidget * help = &mainwindow->_helpWidget;
Ui::MainWindow ui_main = mainwindow->_ui;
Ui::HelpWidget ui = help->_ui;
VISUAL_INIT(mainwindow);
// Starts off not visible and the button is not pushed down
ui_main.actionGoHelp->trigger();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by clicking the button again
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by closing the About window
help->_aboutWindow.close();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
// Test the "About Tarsnap" menubar item, if applicable.
if(mainwindow->_menuBar != nullptr)
{
// find "About Tarsnap" menu item
QAction *menuAction = get_menubar_about(mainwindow->_menuBar);
QVERIFY(menuAction != nullptr);
VISUAL_WAIT;
// Becomes visible using the menu bar action
menuAction->trigger();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Stay visible even when clicking the menu bar action again
menuAction->trigger();
QVERIFY(help->_aboutWindow.isVisible() == true);
QVERIFY(ui.aboutButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by clicking the Help->About button
ui.aboutButton->click();
QVERIFY(help->_aboutWindow.isVisible() == false);
QVERIFY(ui.aboutButton->isChecked() == false);
VISUAL_WAIT;
}
delete mainwindow;
}
void TestMainWindow::quit_simple()
{
MainWindow *mainwindow = new MainWindow();
QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo()));
VISUAL_INIT(mainwindow);
// If we try to close the window, we emit a getTaskInfo instead
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 1);
sig_getTaskInfo.clear();
// Fake getting a reply which says there's no tasks.
mainwindow->closeWithTaskInfo(false, 0, 0);
// After quitting, we don't respond to more events.
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 0);
delete mainwindow;
}
void TestMainWindow::quit_tasks()
{
MainWindow *mainwindow = new MainWindow();
QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo()));
VISUAL_INIT(mainwindow);
// Fake getting a response to a closeEvent (not sent in this test) which
// says that there's running tasks, but cancel the quitting.
QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo",
Qt::QueuedConnection, Q_ARG(bool, true),
Q_ARG(int, 1), Q_ARG(int, 1));
QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "close",
Qt::QueuedConnection);
VISUAL_WAIT;
// After cancelling the quit, we still respond to events
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 1);
sig_getTaskInfo.clear();
VISUAL_WAIT;
// Quit the app
// FIXME: sending an "accept" is a hack because the task-specific choices
// (e.g., stop tasks, run in background) are only added to the dialog box
// after MainWindow receives the closeWithTaskInfo, so we can't
// "queue up" sending a message to one of those objects.
QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo",
Qt::QueuedConnection, Q_ARG(bool, true),
Q_ARG(int, 1), Q_ARG(int, 1));
QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "accept",
Qt::QueuedConnection);
VISUAL_WAIT;
// After quitting, we don't respond to more events
mainwindow->closeEvent(new QCloseEvent());
QVERIFY(sig_getTaskInfo.count() == 0);
VISUAL_WAIT;
delete mainwindow;
}
void TestMainWindow::console_window()
{
MainWindow * mainwindow = new MainWindow();
HelpWidget * help = &mainwindow->_helpWidget;
Ui::MainWindow ui_main = mainwindow->_ui;
Ui::HelpWidget ui = help->_ui;
VISUAL_INIT(mainwindow);
// Starts off not visible and the button is not pushed down
ui_main.actionGoHelp->trigger();
QVERIFY(help->_consoleWindow.isVisible() == false);
QVERIFY(ui.consoleButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.consoleButton->click();
QVERIFY(help->_consoleWindow.isVisible() == true);
QVERIFY(ui.consoleButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by clicking the button again
ui.consoleButton->click();
QVERIFY(help->_consoleWindow.isVisible() == false);
QVERIFY(ui.consoleButton->isChecked() == false);
VISUAL_WAIT;
// Becomes visible
ui.consoleButton->click();
QVERIFY(help->_consoleWindow.isVisible() == true);
QVERIFY(ui.consoleButton->isChecked() == true);
VISUAL_WAIT;
// Becomes invisible by closing the Console window
help->_consoleWindow.close();
QVERIFY(help->_consoleWindow.isVisible() == false);
QVERIFY(ui.consoleButton->isChecked() == false);
VISUAL_WAIT;
delete mainwindow;
}
void TestMainWindow::tab_navigation()
{
MainWindow * mainwindow = new MainWindow();
Ui::MainWindow ui = mainwindow->_ui;
VISUAL_INIT(mainwindow);
// Switch between tabs
// Unfortunately we can't test the Ctrl+X keyboard shortcuts, because
// QTest::keyClick() doesn't work with -platform offscreen.
mainwindow->displayTab(ui.archivesTab);
QVERIFY(ui.mainTabWidget->currentWidget() == ui.archivesTab);
VISUAL_WAIT;
mainwindow->displayTab(ui.helpTab);
QVERIFY(ui.mainTabWidget->currentWidget() == ui.helpTab);
VISUAL_WAIT;
// Switch tabs via other methods.
// The previous test should not end on the backup tab.
QVERIFY(ui.mainTabWidget->currentWidget() != ui.backupTab);
QMetaObject::invokeMethod(mainwindow, "browseForBackupItems",
Qt::QueuedConnection);
QMetaObject::invokeMethod(&mainwindow->_filePickerDialog, "close",
Qt::QueuedConnection);
QTest::qWait(100);
VISUAL_WAIT;
QVERIFY(ui.mainTabWidget->currentWidget() == ui.backupTab);
// Add a Job
mainwindow->displayTab(ui.jobsTab);
ui.backupNameLineEdit->setText("test-job");
ui.backupListWidget->setItemsWithUrls(
QList<QUrl>() << QUrl("file:///tmp/tarsnap-gui-test"));
mainwindow->createJobClicked();
mainwindow->addJobClicked();
JobPtr job = ((JobListWidgetItem *)ui.jobListWidget->currentItem())->job();
VISUAL_WAIT;
// Add an Archive
mainwindow->displayTab(ui.archivesTab);
ArchivePtr archive(new Archive);
archive->setName("Job_test-job_archive1");
mainwindow->addArchive(archive);
archive->setJobRef("test-job");
VISUAL_WAIT;
// Link them
job->setArchives(QList<ArchivePtr>() << archive);
// Switch back and forth between the job and archive.
mainwindow->displayTab(ui.backupTab);
QVERIFY(ui.mainTabWidget->currentWidget() == ui.backupTab);
VISUAL_WAIT;
mainwindow->displayInspectArchive(archive);
QVERIFY(ui.mainTabWidget->currentWidget() == ui.archivesTab);
VISUAL_WAIT;
mainwindow->displayJobDetails(job);
QVERIFY(ui.mainTabWidget->currentWidget() == ui.jobsTab);
VISUAL_WAIT;
delete mainwindow;
}
QTEST_MAIN(TestMainWindow)
#include "test-mainwindow.moc"
<|endoftext|> |
<commit_before><commit_msg>fix recycling heap bug<commit_after><|endoftext|> |
<commit_before><commit_msg>Added missed include in exceptions<commit_after><|endoftext|> |
<commit_before><commit_msg>added two comments<commit_after><|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_DISCONTINUOUSLAGRANGE_PDELAB_HH
#define DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_PDELAB_HH
#include <memory>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/geometry/genericgeometry/topologytypes.hh>
#if HAVE_DUNE_PDELAB
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/pdelab/finiteelementmap/qkdg.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/constraints/conforming.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#endif // HAVE_DUNE_PDELAB
#include <dune/stuff/la/container/istl.hh>
#include <dune/gdt/spaces/parallel.hh>
#include "../../../mapper/pdelab.hh"
#include "../../../basefunctionset/pdelab.hh"
#include "../../../spaces/interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
namespace DiscontinuousLagrange {
#if HAVE_DUNE_PDELAB
// forward, to be used in the traits and to allow for specialization
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "Untested for this combination of dimensions!");
}; // class PdelabBased
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBasedTraits
{
public:
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
typedef GridViewImp GridViewType;
static const int polOrder = polynomialOrder;
static_assert(polOrder >= 1, "Wrong polOrder given!");
private:
typedef typename GridViewType::ctype DomainFieldType;
public:
static const unsigned int dimDomain = GridViewType::dimension;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = rangeDimCols;
private:
template <class G, bool single_geom, bool is_simplex, bool is_cube>
struct FeMap
{
static_assert(Dune::AlwaysFalse<G>::value,
"This space is only implemented for either fully simplicial or fully cubic grids!");
};
template <class G>
struct FeMap<G, true, true, false>
{
static_assert(Dune::AlwaysFalse<G>::value, "Not yet implemented for simplicial grids!");
};
template <class G>
struct FeMap<G, true, false, true>
{
typedef PDELab::QkDGLocalFiniteElementMap<DomainFieldType, RangeFieldType, polOrder, dimDomain> Type;
};
typedef typename GridViewType::Grid GridType;
static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;
static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::SimplexTopology<dimDomain>::type::id);
static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::CubeTopology<dimDomain>::type::id);
typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;
public:
typedef PDELab::GridFunctionSpace<GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints>
BackendType;
typedef Mapper::SimplePdelabWrapper<BackendType> MapperType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange,
dimRangeCols> BaseFunctionSetType;
static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;
static const bool needs_grid_view = true;
typedef CommunicationChooser<GridViewType> CommunicationChooserType;
typedef typename CommunicationChooserType::Type CommunicatorType;
private:
friend class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;
}; // class PdelabBasedTraits
template <class GridViewImp, int polynomialOrder, class RangeFieldImp>
class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>
: public SpaceInterface<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>>
{
typedef SpaceInterface<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>> BaseType;
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;
public:
typedef PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
static const int polOrder = Traits::polOrder;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef FieldVector<DomainFieldType, dimDomain> DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
static const unsigned int dimRange = Traits::dimRange;
static const unsigned int dimRangeCols = Traits::dimRangeCols;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::MapperType MapperType;
typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
typedef typename Traits::CommunicationChooserType CommunicationChooserType;
typedef typename Traits::CommunicatorType CommunicatorType;
private:
typedef typename Traits::FEMapType FEMapType;
public:
typedef typename BaseType::IntersectionType IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::PatternType PatternType;
typedef typename BaseType::BoundaryInfoType BoundaryInfoType;
PdelabBased(const std::shared_ptr<const GridViewType>& gV)
: gridView_(gV)
, fe_map_(std::make_shared<FEMapType>())
, backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *fe_map_))
, mapper_(std::make_shared<MapperType>(*backend_))
, communicator_(CommunicationChooser<GridViewImp>::create(*gridView_))
, communicator_prepared_(false)
{
}
/**
* \brief Copy ctor.
* \note Manually implemented bc of the std::mutex.
*/
PdelabBased(const ThisType& other)
: gridView_(other.gridView_)
, fe_map_(other.fe_map_)
, backend_(other.backend_)
, mapper_(other.mapper_)
, communicator_(other.communicator_)
, communicator_prepared_(other.communicator_prepared_)
{
}
/**
* \brief Move ctor.
* \note Manually implemented bc of the std::mutex.
*/
PdelabBased(ThisType&& source)
: gridView_(source.gridView_)
, fe_map_(source.fe_map_)
, backend_(source.backend_)
, mapper_(source.mapper_)
, communicator_(source.communicator_)
, communicator_prepared_(source.communicator_prepared_)
{
}
ThisType& operator=(const ThisType& other) = delete;
ThisType& operator=(ThisType&& source) = delete;
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_face_and_volume_pattern(local_grid_view, ansatz_space);
}
const std::shared_ptr<const GridViewType>& grid_view() const
{
return gridView_;
}
const BackendType& backend() const
{
return *backend_;
}
const MapperType& mapper() const
{
return *mapper_;
}
BaseFunctionSetType base_function_set(const EntityType& entity) const
{
return BaseFunctionSetType(*backend_, entity);
}
CommunicatorType& communicator() const
{
std::lock_guard<std::mutex> DUNE_UNUSED(gg)(communicator_mutex_);
if (!communicator_prepared_)
communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);
return *communicator_;
} // ... communicator(...)
private:
const std::shared_ptr<const GridViewType> gridView_;
const std::shared_ptr<const FEMapType> fe_map_;
const std::shared_ptr<const BackendType> backend_;
const std::shared_ptr<const MapperType> mapper_;
mutable std::shared_ptr<CommunicatorType> communicator_;
mutable bool communicator_prepared_;
mutable std::mutex communicator_mutex_;
}; // class PdelabBased< ..., 1 >
#else // HAVE_DUNE_PDELAB
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "You are missing dune-pdelab!");
};
#endif // HAVE_DUNE_PDELAB
} // namespace DiscontinuousLagrange
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_PDELAB_HH
<commit_msg>[spaces.dg.pdelab] restrict to polorder 1<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_DISCONTINUOUSLAGRANGE_PDELAB_HH
#define DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_PDELAB_HH
#include <memory>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/geometry/genericgeometry/topologytypes.hh>
#if HAVE_DUNE_PDELAB
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/pdelab/finiteelementmap/qkdg.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/constraints/conforming.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#endif // HAVE_DUNE_PDELAB
#include <dune/stuff/la/container/istl.hh>
#include <dune/gdt/spaces/parallel.hh>
#include "../../../mapper/pdelab.hh"
#include "../../../basefunctionset/pdelab.hh"
#include "../../../spaces/interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
namespace DiscontinuousLagrange {
#if HAVE_DUNE_PDELAB
// forward, to be used in the traits and to allow for specialization
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "Untested for this combination of dimensions!");
}; // class PdelabBased
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBasedTraits
{
public:
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
typedef GridViewImp GridViewType;
static const int polOrder = polynomialOrder;
// using this space for the QuadraticSpaces in test/products_l2weighted.cc results in a test failure
static_assert(polOrder == 1, "This space is known to fail for higher polynomial orders!");
private:
typedef typename GridViewType::ctype DomainFieldType;
public:
static const unsigned int dimDomain = GridViewType::dimension;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = rangeDimCols;
private:
template <class G, bool single_geom, bool is_simplex, bool is_cube>
struct FeMap
{
static_assert(Dune::AlwaysFalse<G>::value,
"This space is only implemented for either fully simplicial or fully cubic grids!");
};
template <class G>
struct FeMap<G, true, true, false>
{
static_assert(Dune::AlwaysFalse<G>::value, "Not yet implemented for simplicial grids!");
};
template <class G>
struct FeMap<G, true, false, true>
{
typedef PDELab::QkDGLocalFiniteElementMap<DomainFieldType, RangeFieldType, polOrder, dimDomain> Type;
};
typedef typename GridViewType::Grid GridType;
static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;
static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::SimplexTopology<dimDomain>::type::id);
static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::CubeTopology<dimDomain>::type::id);
typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;
public:
typedef PDELab::GridFunctionSpace<GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints>
BackendType;
typedef Mapper::SimplePdelabWrapper<BackendType> MapperType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange,
dimRangeCols> BaseFunctionSetType;
static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;
static const bool needs_grid_view = true;
typedef CommunicationChooser<GridViewType> CommunicationChooserType;
typedef typename CommunicationChooserType::Type CommunicatorType;
private:
friend class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;
}; // class PdelabBasedTraits
template <class GridViewImp, int polynomialOrder, class RangeFieldImp>
class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>
: public SpaceInterface<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>>
{
typedef SpaceInterface<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>> BaseType;
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;
public:
typedef PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
static const int polOrder = Traits::polOrder;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef FieldVector<DomainFieldType, dimDomain> DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
static const unsigned int dimRange = Traits::dimRange;
static const unsigned int dimRangeCols = Traits::dimRangeCols;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::MapperType MapperType;
typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
typedef typename Traits::CommunicationChooserType CommunicationChooserType;
typedef typename Traits::CommunicatorType CommunicatorType;
private:
typedef typename Traits::FEMapType FEMapType;
public:
typedef typename BaseType::IntersectionType IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::PatternType PatternType;
typedef typename BaseType::BoundaryInfoType BoundaryInfoType;
PdelabBased(const std::shared_ptr<const GridViewType>& gV)
: gridView_(gV)
, fe_map_(std::make_shared<FEMapType>())
, backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *fe_map_))
, mapper_(std::make_shared<MapperType>(*backend_))
, communicator_(CommunicationChooser<GridViewImp>::create(*gridView_))
, communicator_prepared_(false)
{
}
/**
* \brief Copy ctor.
* \note Manually implemented bc of the std::mutex.
*/
PdelabBased(const ThisType& other)
: gridView_(other.gridView_)
, fe_map_(other.fe_map_)
, backend_(other.backend_)
, mapper_(other.mapper_)
, communicator_(other.communicator_)
, communicator_prepared_(other.communicator_prepared_)
{
}
/**
* \brief Move ctor.
* \note Manually implemented bc of the std::mutex.
*/
PdelabBased(ThisType&& source)
: gridView_(source.gridView_)
, fe_map_(source.fe_map_)
, backend_(source.backend_)
, mapper_(source.mapper_)
, communicator_(source.communicator_)
, communicator_prepared_(source.communicator_prepared_)
{
}
ThisType& operator=(const ThisType& other) = delete;
ThisType& operator=(ThisType&& source) = delete;
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_face_and_volume_pattern(local_grid_view, ansatz_space);
}
const std::shared_ptr<const GridViewType>& grid_view() const
{
return gridView_;
}
const BackendType& backend() const
{
return *backend_;
}
const MapperType& mapper() const
{
return *mapper_;
}
BaseFunctionSetType base_function_set(const EntityType& entity) const
{
return BaseFunctionSetType(*backend_, entity);
}
CommunicatorType& communicator() const
{
std::lock_guard<std::mutex> DUNE_UNUSED(gg)(communicator_mutex_);
if (!communicator_prepared_)
communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);
return *communicator_;
} // ... communicator(...)
private:
const std::shared_ptr<const GridViewType> gridView_;
const std::shared_ptr<const FEMapType> fe_map_;
const std::shared_ptr<const BackendType> backend_;
const std::shared_ptr<const MapperType> mapper_;
mutable std::shared_ptr<CommunicatorType> communicator_;
mutable bool communicator_prepared_;
mutable std::mutex communicator_mutex_;
}; // class PdelabBased< ..., 1 >
#else // HAVE_DUNE_PDELAB
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "You are missing dune-pdelab!");
};
#endif // HAVE_DUNE_PDELAB
} // namespace DiscontinuousLagrange
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_PDELAB_HH
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "chrome/browser/bookmarks/bookmark_context_menu_controller.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
BookmarkContextMenuController::BookmarkContextMenuController(
gfx::NativeWindow parent_window,
BookmarkContextMenuControllerDelegate* delegate,
Profile* profile,
PageNavigator* navigator,
const BookmarkNode* parent,
const std::vector<const BookmarkNode*>& selection)
: parent_window_(parent_window),
delegate_(delegate),
profile_(profile),
navigator_(navigator),
parent_(parent),
selection_(selection),
model_(profile->GetBookmarkModel()) {
DCHECK(profile_);
DCHECK(model_->IsLoaded());
menu_model_.reset(new ui::SimpleMenuModel(this));
model_->AddObserver(this);
BuildMenu();
}
BookmarkContextMenuController::~BookmarkContextMenuController() {
if (model_)
model_->RemoveObserver(this);
}
void BookmarkContextMenuController::BuildMenu() {
if (selection_.size() == 1 && selection_[0]->is_url()) {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_INCOGNITO);
} else {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
}
AddSeparator();
if (selection_.size() == 1 && selection_[0]->is_folder()) {
AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
} else {
AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
}
AddSeparator();
AddItem(IDC_CUT, IDS_CUT);
AddItem(IDC_COPY, IDS_COPY);
AddItem(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);
AddSeparator();
AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}
void BookmarkContextMenuController::AddItem(int id, int localization_id) {
menu_model_->AddItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::AddSeparator() {
menu_model_->AddSeparator();
}
void BookmarkContextMenuController::AddCheckboxItem(int id,
int localization_id) {
menu_model_->AddCheckItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::ExecuteCommand(int id) {
if (delegate_)
delegate_->WillExecuteCommand();
switch (id) {
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
WindowOpenDisposition initial_disposition;
if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
initial_disposition = NEW_FOREGROUND_TAB;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
profile_);
} else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
initial_disposition = NEW_WINDOW;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
profile_);
} else {
initial_disposition = OFF_THE_RECORD;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
profile_);
}
bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
initial_disposition);
break;
}
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
profile_);
if (selection_.size() != 1) {
NOTREACHED();
break;
}
if (selection_[0]->is_url()) {
BookmarkEditor::Show(parent_window_, profile_, parent_,
BookmarkEditor::EditDetails(selection_[0]),
BookmarkEditor::SHOW_TREE);
} else {
BookmarkFolderEditorController::Show(profile_, parent_window_,
selection_[0], -1,
BookmarkFolderEditorController::EXISTING_BOOKMARK);
}
break;
case IDC_BOOKMARK_BAR_REMOVE: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
profile_);
for (size_t i = 0; i < selection_.size(); ++i) {
model_->Remove(selection_[i]->GetParent(),
selection_[i]->GetParent()->IndexOfChild(selection_[i]));
}
selection_.clear();
break;
}
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Add"),
profile_);
// TODO: this should honor the index from GetParentForNewNodes.
BookmarkEditor::Show(
parent_window_, profile_,
bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
break;
}
case IDC_BOOKMARK_BAR_NEW_FOLDER: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
profile_);
int index;
const BookmarkNode* parent =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
index, BookmarkFolderEditorController::NEW_BOOKMARK);
break;
}
case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
bookmark_utils::ToggleWhenVisible(profile_);
break;
case IDC_BOOKMARK_MANAGER:
UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
profile_);
{
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser)
browser->OpenBookmarkManager();
else
NOTREACHED();
}
break;
case IDC_CUT:
bookmark_utils::CopyToClipboard(model_, selection_, true);
break;
case IDC_COPY:
bookmark_utils::CopyToClipboard(model_, selection_, false);
break;
case IDC_PASTE: {
int index;
const BookmarkNode* paste_target =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
if (!paste_target)
return;
bookmark_utils::PasteFromClipboard(model_, paste_target, index);
break;
}
default:
NOTREACHED();
}
if (delegate_)
delegate_->DidExecuteCommand();
}
bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}
bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
bool is_root_node =
(selection_.size() == 1 &&
selection_[0]->GetParent() == model_->root_node());
switch (command_id) {
case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
return !profile_->IsOffTheRecord();
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
return HasURLs() && !profile_->IsOffTheRecord();
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
return HasURLs();
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
return selection_.size() == 1 && !is_root_node;
case IDC_BOOKMARK_BAR_REMOVE:
return !selection_.empty() && !is_root_node;
case IDC_BOOKMARK_BAR_NEW_FOLDER:
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
return bookmark_utils::GetParentForNewNodes(
parent_, selection_, NULL) != NULL;
case IDC_COPY:
case IDC_CUT:
return selection_.size() > 0 && !is_root_node;
case IDC_PASTE:
// Paste to selection from the Bookmark Bar, to parent_ everywhere else
return (!selection_.empty() &&
bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
bookmark_utils::CanPasteFromClipboard(parent_);
}
return true;
}
bool BookmarkContextMenuController::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void BookmarkContextMenuController::BookmarkModelChanged() {
if (delegate_)
delegate_->CloseMenu();
}
bool BookmarkContextMenuController::HasURLs() const {
for (size_t i = 0; i < selection_.size(); ++i) {
if (bookmark_utils::NodeHasURLs(selection_[i]))
return true;
}
return false;
}
<commit_msg>GTK uses a different controller for the bookmark bar view context menu than toolkit_views and this adds the same check for incognito pref that I added for views.<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 "chrome/browser/bookmarks/bookmark_context_menu_controller.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
BookmarkContextMenuController::BookmarkContextMenuController(
gfx::NativeWindow parent_window,
BookmarkContextMenuControllerDelegate* delegate,
Profile* profile,
PageNavigator* navigator,
const BookmarkNode* parent,
const std::vector<const BookmarkNode*>& selection)
: parent_window_(parent_window),
delegate_(delegate),
profile_(profile),
navigator_(navigator),
parent_(parent),
selection_(selection),
model_(profile->GetBookmarkModel()) {
DCHECK(profile_);
DCHECK(model_->IsLoaded());
menu_model_.reset(new ui::SimpleMenuModel(this));
model_->AddObserver(this);
BuildMenu();
}
BookmarkContextMenuController::~BookmarkContextMenuController() {
if (model_)
model_->RemoveObserver(this);
}
void BookmarkContextMenuController::BuildMenu() {
if (selection_.size() == 1 && selection_[0]->is_url()) {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_INCOGNITO);
} else {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
}
AddSeparator();
if (selection_.size() == 1 && selection_[0]->is_folder()) {
AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
} else {
AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
}
AddSeparator();
AddItem(IDC_CUT, IDS_CUT);
AddItem(IDC_COPY, IDS_COPY);
AddItem(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);
AddSeparator();
AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}
void BookmarkContextMenuController::AddItem(int id, int localization_id) {
menu_model_->AddItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::AddSeparator() {
menu_model_->AddSeparator();
}
void BookmarkContextMenuController::AddCheckboxItem(int id,
int localization_id) {
menu_model_->AddCheckItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::ExecuteCommand(int id) {
if (delegate_)
delegate_->WillExecuteCommand();
switch (id) {
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
WindowOpenDisposition initial_disposition;
if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
initial_disposition = NEW_FOREGROUND_TAB;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
profile_);
} else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
initial_disposition = NEW_WINDOW;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
profile_);
} else {
initial_disposition = OFF_THE_RECORD;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
profile_);
}
bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
initial_disposition);
break;
}
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
profile_);
if (selection_.size() != 1) {
NOTREACHED();
break;
}
if (selection_[0]->is_url()) {
BookmarkEditor::Show(parent_window_, profile_, parent_,
BookmarkEditor::EditDetails(selection_[0]),
BookmarkEditor::SHOW_TREE);
} else {
BookmarkFolderEditorController::Show(profile_, parent_window_,
selection_[0], -1,
BookmarkFolderEditorController::EXISTING_BOOKMARK);
}
break;
case IDC_BOOKMARK_BAR_REMOVE: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
profile_);
for (size_t i = 0; i < selection_.size(); ++i) {
model_->Remove(selection_[i]->GetParent(),
selection_[i]->GetParent()->IndexOfChild(selection_[i]));
}
selection_.clear();
break;
}
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Add"),
profile_);
// TODO: this should honor the index from GetParentForNewNodes.
BookmarkEditor::Show(
parent_window_, profile_,
bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
break;
}
case IDC_BOOKMARK_BAR_NEW_FOLDER: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
profile_);
int index;
const BookmarkNode* parent =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
index, BookmarkFolderEditorController::NEW_BOOKMARK);
break;
}
case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
bookmark_utils::ToggleWhenVisible(profile_);
break;
case IDC_BOOKMARK_MANAGER:
UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
profile_);
{
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser)
browser->OpenBookmarkManager();
else
NOTREACHED();
}
break;
case IDC_CUT:
bookmark_utils::CopyToClipboard(model_, selection_, true);
break;
case IDC_COPY:
bookmark_utils::CopyToClipboard(model_, selection_, false);
break;
case IDC_PASTE: {
int index;
const BookmarkNode* paste_target =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
if (!paste_target)
return;
bookmark_utils::PasteFromClipboard(model_, paste_target, index);
break;
}
default:
NOTREACHED();
}
if (delegate_)
delegate_->DidExecuteCommand();
}
bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}
bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
bool is_root_node =
(selection_.size() == 1 &&
selection_[0]->GetParent() == model_->root_node());
switch (command_id) {
case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
return !profile_->IsOffTheRecord() &&
profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
return HasURLs() && !profile_->IsOffTheRecord() &&
profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
return HasURLs();
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
return selection_.size() == 1 && !is_root_node;
case IDC_BOOKMARK_BAR_REMOVE:
return !selection_.empty() && !is_root_node;
case IDC_BOOKMARK_BAR_NEW_FOLDER:
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
return bookmark_utils::GetParentForNewNodes(
parent_, selection_, NULL) != NULL;
case IDC_COPY:
case IDC_CUT:
return selection_.size() > 0 && !is_root_node;
case IDC_PASTE:
// Paste to selection from the Bookmark Bar, to parent_ everywhere else
return (!selection_.empty() &&
bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
bookmark_utils::CanPasteFromClipboard(parent_);
}
return true;
}
bool BookmarkContextMenuController::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void BookmarkContextMenuController::BookmarkModelChanged() {
if (delegate_)
delegate_->CloseMenu();
}
bool BookmarkContextMenuController::HasURLs() const {
for (size_t i = 0; i < selection_.size(); ++i) {
if (bookmark_utils::NodeHasURLs(selection_[i]))
return true;
}
return false;
}
<|endoftext|> |
<commit_before>void P010_TDataProgressDialog()
{
gPluginMgr->AddHandler("TDataProgressDialog", "*", "TDataProgressDialog",
"PeacGui", "TDataProgressDialog(TProof*,const char*,Int_t,Long64_t)");
}
<commit_msg>Remove obsolete plugin definition libPeac was removed in version 5.34.01<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Add) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> expected;
GetLogins(GetVerifierPasswordStore(), form, expected);
ASSERT_EQ(1U, expected.size());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_zero));
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Race) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
PasswordForm form_zero;
form_zero.origin = GURL("http://www.google.com/");
form_zero.username_value = ASCIIToUTF16("username");
form_zero.password_value = ASCIIToUTF16("zero");
AddLogin(GetPasswordStore(0), form_zero);
PasswordForm form_one;
form_one.origin = GURL("http://www.google.com/");
form_one.username_value = ASCIIToUTF16("username");
form_one.password_value = ASCIIToUTF16("one");
AddLogin(GetPasswordStore(1), form_one);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_EQ(1U, actual_zero.size());
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_EQ(1U, actual_one.size());
ASSERT_TRUE(ContainsSamePasswordForms(actual_zero, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_SetPassphrase) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndAddPassword) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetPasswordStore(0), form);
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
ASSERT_EQ(1, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->AwaitSyncCycleCompletion("Accept passphrase and decrypt.");
ASSERT_EQ(0, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndThenSetupSync) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndThenSetupSync) {
#endif
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitSyncCycleCompletion("Initial sync.");
ASSERT_TRUE(GetClient(1)->SetupSync());
ASSERT_TRUE(AwaitQuiescence());
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseTwice) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseTwice) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
<commit_msg>Disabling a couple of failing passphrase sync tests.<commit_after>// Copyright (c) 2010 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 "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Add) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> expected;
GetLogins(GetVerifierPasswordStore(), form, expected);
ASSERT_EQ(1U, expected.size());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_zero));
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Race) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
PasswordForm form_zero;
form_zero.origin = GURL("http://www.google.com/");
form_zero.username_value = ASCIIToUTF16("username");
form_zero.password_value = ASCIIToUTF16("zero");
AddLogin(GetPasswordStore(0), form_zero);
PasswordForm form_one;
form_one.origin = GURL("http://www.google.com/");
form_one.username_value = ASCIIToUTF16("username");
form_one.password_value = ASCIIToUTF16("one");
AddLogin(GetPasswordStore(1), form_one);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_EQ(1U, actual_zero.size());
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_EQ(1U, actual_one.size());
ASSERT_TRUE(ContainsSamePasswordForms(actual_zero, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_SetPassphrase) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndAddPassword) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetPasswordStore(0), form);
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
ASSERT_EQ(1, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->AwaitSyncCycleCompletion("Accept passphrase and decrypt.");
ASSERT_EQ(0, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
}
// TODO(sync): Remove DISABLED_ annotation after http://crbug.com/59867 and
// http://crbug.com/67862 are fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
DISABLED_SetPassphraseAndThenSetupSync) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitSyncCycleCompletion("Initial sync.");
ASSERT_TRUE(GetClient(1)->SetupSync());
ASSERT_TRUE(AwaitQuiescence());
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove DISABLED_ annotation after http://crbug.com/59867 and
// http://crbug.com/67862 are fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
DISABLED_SetPassphraseTwice) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
<|endoftext|> |
<commit_before>namespace foo {
int x;
void bar(int z);
}
namespace bar {
typedef int QType;
void bar(QType z);
}
class ClsA {
public:
int a, b;
ClsA(int A, int B) : a(A), b(B) {}
};
namespace foo {
class ClsB : public ClsA {
public:
ClsB() : ClsA(1, 2) {}
int result() const;
};
}
int foo::ClsB::result() const {
return a + b;
}
namespace {
class ClsC : public foo::ClsB {};
int w;
}
int z;
namespace foo { namespace taz {
int x;
static inline int add(int a, int b) { return a + b; }
void sub(int a, int b);
}
}
// RUN: c-index-test -test-load-source-usrs all %s | FileCheck %s
// CHECK: usrs.cpp c:@N@foo Extent=[1:11 - 4:2]
// CHECK: usrs.cpp c:@N@foo@x Extent=[2:3 - 2:8]
// CHECK: usrs.cpp c:@N@foo@F@bar Extent=[3:8 - 3:18]
// CHECK: usrs.cpp c:usrs.cpp@3:12@N@foo@F@bar@z Extent=[3:12 - 3:17]
// CHECK: usrs.cpp c:@N@bar Extent=[5:11 - 8:2]
// CHECK: usrs.cpp c:usrs.cpp@6:15@N@bar@T@QType Extent=[6:15 - 6:20]
// CHECK: usrs.cpp c:@N@bar@F@bar Extent=[7:8 - 7:20]
// CHECK: usrs.cpp c:usrs.cpp@7:12@N@bar@F@bar@z Extent=[7:12 - 7:19]
// CHECK: usrs.cpp c:@C@ClsA Extent=[10:1 - 14:2]
// CHECK: usrs.cpp c:@C@ClsA@FI@a Extent=[12:7 - 12:8]
// CHECK: usrs.cpp c:@C@ClsA@FI@b Extent=[12:10 - 12:11]
// CHECK: usrs.cpp c:@C@ClsA@F@ClsA Extent=[13:3 - 13:37]
// CHECK: usrs.cpp c:usrs.cpp@13:8@C@ClsA@F@ClsA@A Extent=[13:8 - 13:13]
// CHECK: usrs.cpp c:usrs.cpp@13:15@C@ClsA@F@ClsA@B Extent=[13:15 - 13:20]
// CHECK: usrs.cpp c:@N@foo Extent=[16:11 - 22:2]
// CHECK: usrs.cpp c:@N@foo@C@ClsB Extent=[17:3 - 21:4]
// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@ClsB Extent=[19:5 - 19:27]
// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result Extent=[20:9 - 20:17]
// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result Extent=[24:16 - 26:2]
// CHECK: usrs.cpp c:@aN@C@ClsC Extent=[29:3 - 29:35]
// CHECK: usrs.cpp c:@aN@w Extent=[30:3 - 30:8]
// CHECK: usrs.cpp c:@z Extent=[33:1 - 33:6]
// CHECK: usrs.cpp c:@N@foo Extent=[35:11 - 40:2]
// CHECK: usrs.cpp c:@N@foo@N@taz Extent=[35:27 - 39:2]
// CHECK: usrs.cpp c:@N@foo@N@taz@x Extent=[36:3 - 36:8]
// CHECK: usrs.cpp c:usrs.cpp@37:21@N@foo@N@taz@F@add Extent=[37:21 - 37:56]
// CHECK: usrs.cpp c:usrs.cpp@37:25@N@foo@N@taz@F@add@a Extent=[37:25 - 37:30]
// CHECK: usrs.cpp c:usrs.cpp@37:32@N@foo@N@taz@F@add@b Extent=[37:32 - 37:37]
// CHECK: usrs.cpp c:@N@foo@N@taz@F@sub Extent=[38:8 - 38:25]
// CHECK: usrs.cpp c:usrs.cpp@38:12@N@foo@N@taz@F@sub@a Extent=[38:12 - 38:17]
// CHECK: usrs.cpp c:usrs.cpp@38:19@N@foo@N@taz@F@sub@b Extent=[38:19 - 38:24]
<commit_msg>Add USR test case for C++ operator methods.<commit_after>namespace foo {
int x;
void bar(int z);
}
namespace bar {
typedef int QType;
void bar(QType z);
}
class ClsA {
public:
int a, b;
ClsA(int A, int B) : a(A), b(B) {}
};
namespace foo {
class ClsB : public ClsA {
public:
ClsB() : ClsA(1, 2) {}
int result() const;
};
}
int foo::ClsB::result() const {
return a + b;
}
namespace {
class ClsC : public foo::ClsB {};
int w;
}
int z;
namespace foo { namespace taz {
int x;
static inline int add(int a, int b) { return a + b; }
void sub(int a, int b);
}
}
namespace foo { namespace taz {
class ClsD : public foo::ClsB {
public:
ClsD& operator=(int x) { a = x; return *this; }
ClsD& operator=(double x) { a = (int) x; return *this; }
};
}}
// RUN: c-index-test -test-load-source-usrs all %s | FileCheck %s
// CHECK: usrs.cpp c:@N@foo Extent=[1:11 - 4:2]
// CHECK: usrs.cpp c:@N@foo@x Extent=[2:3 - 2:8]
// CHECK: usrs.cpp c:@N@foo@F@bar Extent=[3:8 - 3:18]
// CHECK: usrs.cpp c:usrs.cpp@3:12@N@foo@F@bar@z Extent=[3:12 - 3:17]
// CHECK: usrs.cpp c:@N@bar Extent=[5:11 - 8:2]
// CHECK: usrs.cpp c:usrs.cpp@6:15@N@bar@T@QType Extent=[6:15 - 6:20]
// CHECK: usrs.cpp c:@N@bar@F@bar Extent=[7:8 - 7:20]
// CHECK: usrs.cpp c:usrs.cpp@7:12@N@bar@F@bar@z Extent=[7:12 - 7:19]
// CHECK: usrs.cpp c:@C@ClsA Extent=[10:1 - 14:2]
// CHECK: usrs.cpp c:@C@ClsA@FI@a Extent=[12:7 - 12:8]
// CHECK: usrs.cpp c:@C@ClsA@FI@b Extent=[12:10 - 12:11]
// CHECK: usrs.cpp c:@C@ClsA@F@ClsA Extent=[13:3 - 13:37]
// CHECK: usrs.cpp c:usrs.cpp@13:8@C@ClsA@F@ClsA@A Extent=[13:8 - 13:13]
// CHECK: usrs.cpp c:usrs.cpp@13:15@C@ClsA@F@ClsA@B Extent=[13:15 - 13:20]
// CHECK: usrs.cpp c:@N@foo Extent=[16:11 - 22:2]
// CHECK: usrs.cpp c:@N@foo@C@ClsB Extent=[17:3 - 21:4]
// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@ClsB Extent=[19:5 - 19:27]
// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result Extent=[20:9 - 20:17]
// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result Extent=[24:16 - 26:2]
// CHECK: usrs.cpp c:@aN@C@ClsC Extent=[29:3 - 29:35]
// CHECK: usrs.cpp c:@aN@w Extent=[30:3 - 30:8]
// CHECK: usrs.cpp c:@z Extent=[33:1 - 33:6]
// CHECK: usrs.cpp c:@N@foo Extent=[35:11 - 40:2]
// CHECK: usrs.cpp c:@N@foo@N@taz Extent=[35:27 - 39:2]
// CHECK: usrs.cpp c:@N@foo@N@taz@x Extent=[36:3 - 36:8]
// CHECK: usrs.cpp c:usrs.cpp@37:21@N@foo@N@taz@F@add Extent=[37:21 - 37:56]
// CHECK: usrs.cpp c:usrs.cpp@37:25@N@foo@N@taz@F@add@a Extent=[37:25 - 37:30]
// CHECK: usrs.cpp c:usrs.cpp@37:32@N@foo@N@taz@F@add@b Extent=[37:32 - 37:37]
// CHECK: usrs.cpp c:@N@foo@N@taz@F@sub Extent=[38:8 - 38:25]
// CHECK: usrs.cpp c:usrs.cpp@38:12@N@foo@N@taz@F@sub@a Extent=[38:12 - 38:17]
// CHECK: usrs.cpp c:usrs.cpp@38:19@N@foo@N@taz@F@sub@b Extent=[38:19 - 38:24]
// CHECK: usrs.cpp c:@N@foo Extent=[42:11 - 48:3]
// CHECK: usrs.cpp c:@N@foo@N@taz Extent=[42:27 - 48:2]
// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD Extent=[43:3 - 47:4]
// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator= Extent=[45:11 - 45:52]
// CHECK: usrs.cpp c:usrs.cpp@45:21@N@foo@N@taz@C@ClsD@F@operator=@x Extent=[45:21 - 45:26]
// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator= Extent=[46:11 - 46:61]
// CHECK: usrs.cpp c:usrs.cpp@46:21@N@foo@N@taz@C@ClsD@F@operator=@x Extent=[46:21 - 46:29]
<|endoftext|> |
<commit_before>/*
*
*/
#include <stdio.h>
#include "sync.h"
#include "topo.h"
#include "mp.h"
#include "measurement_framework.h"
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include "model_defs.h"
#ifdef PARLIB
#include "mcs.h"
#endif
//#define SEND7
#ifdef BARRELFISH
#include <barrelfish/barrelfish.h>
#include <posixcompat.h>
#endif
__thread struct sk_measurement m;
__thread struct sk_measurement m2;
unsigned num_threads;
#define NUM_RUNS 1000000 //50 // 10000 // Tested up to 1.000.000
#define NUM_RESULTS 1000
pthread_barrier_t ab_barrier;
#define TOPO_NAME(x,y) sprintf(x, "%s_%s", y, topo_get_name());
mcs_barrier_t mcs_b;
static void* mcs_barrier(void* a)
{
coreid_t tid = *((int*) a);
__thread_init(tid, num_threads); // will bind threads
cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
char outname[1024];
TOPO_NAME(outname, "mcs-barrier");
sk_m_init(&m, NUM_RESULTS, outname, buf);
sk_m_restart_tsc(&m);
for (unsigned i=0; i<NUM_RUNS; i++) {
mcs_barrier_wait(&mcs_b, tid);
}
sk_m_add(&m);
if (get_thread_id() == get_sequentializer()) {
sk_m_print(&m);
}
return NULL;
}
static void* barrier(void* a)
{
coreid_t tid = *((int*) a);
__thread_init(tid, num_threads);
cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
char outname[1024];
TOPO_NAME(outname, "syc-barrier");
sk_m_init(&m, NUM_RESULTS, outname, buf);
sk_m_restart_tsc(&m);
for (int epoch=0; epoch<NUM_RUNS; epoch++) {
mp_barrier(NULL);
}
sk_m_add(&m);
if (get_thread_id() == get_sequentializer()) {
sk_m_print(&m);
}
__thread_end();
return NULL;
}
static void* barrier0(void* a)
{
coreid_t tid = *((int*) a);
__thread_init(tid, num_threads);
cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
char outname[1024];
TOPO_NAME(outname, "syc-barrier");
sk_m_init(&m, NUM_RESULTS, outname, buf);
sk_m_restart_tsc(&m);
for (int epoch=0; epoch<NUM_RUNS; epoch++) {
mp_barrier0();
}
sk_m_add(&m);
if (get_thread_id() == get_sequentializer()) {
sk_m_print(&m);
}
__thread_end();
return NULL;
}
#define NUM_EXP 3
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
int main(int argc, char **argv)
{
unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);
__sync_init(nthreads, true);
num_threads = get_num_threads();
mcs_barrier_init(&mcs_b, num_threads);
pthread_barrier_init(&ab_barrier, NULL, num_threads);
typedef void* (worker_func_t)(void*);
worker_func_t* workers[NUM_EXP] = {
&mcs_barrier,
&barrier,
&barrier0,
};
const char *labels[NUM_EXP] = {
"MCS barrier",
"libsync barrier",
"libsync barrier0"
};
pthread_t ptds[num_threads];
int tids[num_threads];
printf("%d models\n", max(1U, (topo_num_topos()-1)));
for (unsigned e=0; e<max(1U, (topo_num_topos()-1)); e++) {
for (int j=0; j<NUM_EXP; j++) {
printf("----------------------------------------\n");
printf("Executing experiment %d - %s\n", (j+1), labels[j]);
printf("----------------------------------------\n");
// Yield to reduce the risk of getting de-scheduled later
sched_yield();
// Create
for (unsigned i=1; i<num_threads; i++) {
tids[i] = i;
pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));
}
// Master thread executes work for node 0
tids[0] = 0;
workers[j]((void*) (tids+0));
// Join
for (unsigned i=1; i<num_threads; i++) {
pthread_join(ptds[i], NULL);
}
}
if( e<topo_num_topos()-1) switch_topo();
}
pthread_barrier_destroy(&ab_barrier);
}
<commit_msg>some modifications in the ab-thorughput<commit_after>/*
*
*/
#include <stdio.h>
#include "sync.h"
#include "topo.h"
#include "mp.h"
#include "measurement_framework.h"
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include "model_defs.h"
#ifdef PARLIB
#include "mcs.h"
#endif
//#define SEND7
#ifdef BARRELFISH
#include <barrelfish/barrelfish.h>
#include <posixcompat.h>
#endif
__thread struct sk_measurement m;
__thread struct sk_measurement m2;
unsigned num_threads;
#define NUM_RUNS 10000000 //50 // 10000 // Tested up to 1.000.000
#define NUM_RESULTS 1000
pthread_barrier_t ab_barrier;
#define TOPO_NAME(x,y) sprintf(x, "%s_%s", y, topo_get_name());
mcs_barrier_t mcs_b;
static void* mcs_barrier(void* a)
{
coreid_t tid = *((int*) a);
__thread_init(tid, num_threads); // will bind threads
cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
char outname[1024];
TOPO_NAME(outname, "mcs-barrier");
sk_m_init(&m, NUM_RESULTS, outname, buf);
sk_m_restart_tsc(&m);
for (unsigned i=0; i<NUM_RUNS; i++) {
mcs_barrier_wait(&mcs_b, tid);
}
sk_m_add(&m);
if (get_thread_id() == get_sequentializer()) {
sk_m_print(&m);
}
return NULL;
}
static void* barrier(void* a)
{
coreid_t tid = *((int*) a);
__thread_init(tid, num_threads);
cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
char outname[1024];
TOPO_NAME(outname, "syc-barrier");
sk_m_init(&m, NUM_RESULTS, outname, buf);
sk_m_restart_tsc(&m);
for (int epoch=0; epoch<NUM_RUNS; epoch++) {
mp_barrier(NULL);
}
sk_m_add(&m);
if (get_thread_id() == get_sequentializer()) {
sk_m_print(&m);
}
__thread_end();
return NULL;
}
static void* barrier0(void* a)
{
coreid_t tid = *((int*) a);
__thread_init(tid, num_threads);
cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);
char outname[1024];
TOPO_NAME(outname, "syc-barrier0");
sk_m_init(&m, NUM_RESULTS, outname, buf);
sk_m_restart_tsc(&m);
for (int epoch=0; epoch<NUM_RUNS; epoch++) {
mp_barrier0();
}
sk_m_add(&m);
if (get_thread_id() == get_sequentializer()) {
sk_m_print(&m);
}
__thread_end();
return NULL;
}
#define NUM_EXP 3
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
int main(int argc, char **argv)
{
unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);
__sync_init(nthreads, true);
num_threads = get_num_threads();
mcs_barrier_init(&mcs_b, num_threads);
pthread_barrier_init(&ab_barrier, NULL, num_threads);
typedef void* (worker_func_t)(void*);
worker_func_t* workers[NUM_EXP] = {
&mcs_barrier,
&barrier,
&barrier0,
};
const char *labels[NUM_EXP] = {
"MCS barrier",
"libsync barrier",
"libsync barrier0"
};
pthread_t ptds[num_threads];
int tids[num_threads];
printf("%d models\n", max(1U, (topo_num_topos()-1)));
for (unsigned e=0; e<max(1U, (topo_num_topos()-1)); e++) {
for (int j=0; j<NUM_EXP; j++) {
printf("----------------------------------------\n");
printf("Executing experiment %d - %s\n", (j+1), labels[j]);
printf("----------------------------------------\n");
// Yield to reduce the risk of getting de-scheduled later
sched_yield();
// Create
for (unsigned i=1; i<num_threads; i++) {
tids[i] = i;
pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));
}
// Master thread executes work for node 0
tids[0] = 0;
workers[j]((void*) (tids+0));
// Join
for (unsigned i=1; i<num_threads; i++) {
pthread_join(ptds[i], NULL);
}
}
if( e<topo_num_topos()-1) switch_topo();
}
pthread_barrier_destroy(&ab_barrier);
}
<|endoftext|> |
<commit_before><commit_msg>Fix DemoApplication memory leak<commit_after><|endoftext|> |
<commit_before>/**
* A camera component that generates view and projection matrices.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
* - Dan Printzell
*/
#pragma once
#include <hydra/ext/api.hpp>
#include <hydra/world/world.hpp>
#include <hydra/renderer/renderer.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/transform.hpp>
#include <hydra/component/transformcomponent.hpp>
#include <SDL2/SDL.h>
using namespace Hydra::World;
namespace Hydra::Component {
struct HYDRA_GRAPHICS_API CameraComponent final : public IComponent<CameraComponent, ComponentBits::Camera> {
Hydra::Renderer::IRenderTarget* renderTarget = nullptr;
glm::vec3 position = glm::vec3{0, 0, 0};
glm::quat orientation = glm::quat();
float fov = 90.0f;
float zNear = 0.1f;
float zFar = 75.0f;
float aspect = 1920.0f/1080.0f;
float sensitivity = 0.003f;
float cameraYaw = 0.0f;
float cameraPitch = 0.0f;
bool mouseControl = true;
~CameraComponent() final;
inline const std::string type() const final { return "CameraComponent"; }
void serialize(nlohmann::json& json) const final;
void deserialize(nlohmann::json& json) final;
void registerUI() final;
// TODO: Cache these?
inline glm::mat4 getViewMatrix() const { return glm::translate(glm::mat4_cast(orientation), -position); }
inline glm::mat4 getProjectionMatrix() const { return glm::perspective(glm::radians(fov), aspect, zNear, zFar); }
};
};
<commit_msg>Started wokring on VFC<commit_after>/**
* A camera component that generates view and projection matrices.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
* - Dan Printzell
*/
#pragma once
#include <hydra/ext/api.hpp>
#include <hydra/world/world.hpp>
#include <hydra/renderer/renderer.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/transform.hpp>
#include <hydra/component/transformcomponent.hpp>
#include <SDL2/SDL.h>
using namespace Hydra::World;
namespace Hydra::Component {
struct HYDRA_GRAPHICS_API CameraComponent final : public IComponent<CameraComponent, ComponentBits::Camera> {
Hydra::Renderer::IRenderTarget* renderTarget = nullptr;
glm::vec3 position = glm::vec3{0, 0, 0};
glm::quat orientation = glm::quat();
float fov = 90.0f;
float zNear = 0.1f;
float zFar = 75.0f;
float aspect = 1920.0f/1080.0f;
float sensitivity = 0.003f;
float cameraYaw = 0.0f;
float cameraPitch = 0.0f;
bool mouseControl = true;
enum {
TOP = 0, BOTTOM, LEFT,
RIGHT, NEAR, FAR
};
~CameraComponent() final;
inline const std::string type() const final { return "CameraComponent"; }
void serialize(nlohmann::json& json) const final;
void deserialize(nlohmann::json& json) final;
void registerUI() final;
// TODO: Cache these?
inline glm::mat4 getViewMatrix() const { return glm::translate(glm::mat4_cast(orientation), -position); }
inline glm::mat4 getProjectionMatrix() const { return glm::perspective(glm::radians(fov), aspect, zNear, zFar); }
};
};
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/time.h"
#include "content/browser/geolocation/arbitrator_dependency_factory.h"
#include "content/browser/geolocation/fake_access_token_store.h"
#include "content/browser/geolocation/geolocation_observer.h"
#include "content/browser/geolocation/geolocation_provider.h"
#include "content/browser/geolocation/location_arbitrator.h"
#include "content/browser/geolocation/mock_location_provider.h"
#include "content/public/browser/browser_thread.h"
#include "content/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::Geoposition;
using testing::_;
using testing::DoAll;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::MakeMatcher;
using testing::Matcher;
using testing::MatcherInterface;
using testing::MatchResultListener;
namespace {
class NonSingletonGeolocationProvider : public GeolocationProvider {
public:
NonSingletonGeolocationProvider() {}
virtual ~NonSingletonGeolocationProvider() {}
};
class StartStopMockLocationProvider : public MockLocationProvider {
public:
explicit StartStopMockLocationProvider() : MockLocationProvider(&instance_) {
}
virtual ~StartStopMockLocationProvider() {
Die();
}
MOCK_METHOD0(Die, void());
};
class TestingDependencyFactory
: public DefaultGeolocationArbitratorDependencyFactory {
public:
TestingDependencyFactory(base::WaitableEvent* event) : event_(event) {
}
virtual content::AccessTokenStore* NewAccessTokenStore() OVERRIDE {
content::FakeAccessTokenStore* store = new content::FakeAccessTokenStore();
EXPECT_CALL(*store, LoadAccessTokens(_))
.WillRepeatedly(DoAll(
Invoke(store,
&content::FakeAccessTokenStore::DefaultLoadAccessTokens),
InvokeWithoutArgs(store,
&content::FakeAccessTokenStore::
NotifyDelegateTokensLoaded),
InvokeWithoutArgs(event_, &base::WaitableEvent::Signal)));
return store;
}
virtual LocationProviderBase* NewNetworkLocationProvider(
content::AccessTokenStore* access_token_store,
net::URLRequestContextGetter* context,
const GURL& url,
const string16& access_token) OVERRIDE {
StartStopMockLocationProvider* provider =
new StartStopMockLocationProvider();
EXPECT_CALL(*provider, Die())
.Times(1)
.WillOnce(InvokeWithoutArgs(event_, &base::WaitableEvent::Signal));
return provider;
}
virtual LocationProviderBase* NewSystemLocationProvider() OVERRIDE {
return NULL;
}
private:
base::WaitableEvent* event_;
};
class NullGeolocationObserver : public GeolocationObserver {
public:
// GeolocationObserver
virtual void OnLocationUpdate(const content::Geoposition& position) {}
};
class MockGeolocationObserver : public GeolocationObserver {
public:
// GeolocationObserver
MOCK_METHOD1(OnLocationUpdate, void(const content::Geoposition& position));
};
class MockGeolocationCallbackWrapper {
public:
MOCK_METHOD1(Callback, void(const content::Geoposition& position));
};
class GeopositionEqMatcher
: public MatcherInterface<const content::Geoposition&> {
public:
explicit GeopositionEqMatcher(const content::Geoposition& expected)
: expected_(expected) {}
virtual bool MatchAndExplain(const content::Geoposition& actual,
MatchResultListener* listener) const OVERRIDE {
return actual.latitude == expected_.latitude &&
actual.longitude == expected_.longitude &&
actual.altitude == expected_.altitude &&
actual.accuracy == expected_.accuracy &&
actual.altitude_accuracy == expected_.altitude_accuracy &&
actual.heading == expected_.heading &&
actual.speed == expected_.speed &&
actual.timestamp == expected_.timestamp &&
actual.error_code == expected_.error_code &&
actual.error_message == expected_.error_message;
}
virtual void DescribeTo(::std::ostream* os) const OVERRIDE {
*os << "which matches the expected position";
}
virtual void DescribeNegationTo(::std::ostream* os) const OVERRIDE{
*os << "which does not match the expected position";
}
private:
content::Geoposition expected_;
DISALLOW_COPY_AND_ASSIGN(GeopositionEqMatcher);
};
Matcher<const content::Geoposition&> GeopositionEq(
const content::Geoposition& expected) {
return MakeMatcher(new GeopositionEqMatcher(expected));
}
class GeolocationProviderTest : public testing::Test {
protected:
GeolocationProviderTest()
: message_loop_(),
io_thread_(content::BrowserThread::IO, &message_loop_),
event_(false, false),
dependency_factory_(new TestingDependencyFactory(&event_)),
provider_(new NonSingletonGeolocationProvider) {
GeolocationArbitrator::SetDependencyFactoryForTest(
dependency_factory_.get());
}
~GeolocationProviderTest() {
GeolocationArbitrator::SetDependencyFactoryForTest(NULL);
}
MessageLoop message_loop_;
content::TestBrowserThread io_thread_;
base::WaitableEvent event_;
scoped_refptr<TestingDependencyFactory> dependency_factory_;
scoped_ptr<NonSingletonGeolocationProvider> provider_;
};
// Regression test for http://crbug.com/59377
TEST_F(GeolocationProviderTest, OnPermissionGrantedWithoutObservers) {
EXPECT_FALSE(provider_->HasPermissionBeenGranted());
provider_->OnPermissionGranted();
EXPECT_TRUE(provider_->HasPermissionBeenGranted());
}
TEST_F(GeolocationProviderTest, StartStop) {
EXPECT_FALSE(provider_->IsRunning());
NullGeolocationObserver null_observer;
GeolocationObserverOptions options;
provider_->AddObserver(&null_observer, options);
EXPECT_TRUE(provider_->IsRunning());
// Wait for token load request from the arbitrator to come through.
event_.Wait();
event_.Reset();
EXPECT_EQ(MockLocationProvider::instance_->state_,
MockLocationProvider::LOW_ACCURACY);
provider_->RemoveObserver(&null_observer);
// Wait for the providers to be stopped.
event_.Wait();
EXPECT_TRUE(provider_->IsRunning());
}
TEST_F(GeolocationProviderTest, OverrideLocationForTesting) {
content::Geoposition position;
position.error_code = content::Geoposition::ERROR_CODE_POSITION_UNAVAILABLE;
provider_->OverrideLocationForTesting(position);
// Adding an observer when the location is overridden should synchronously
// update the observer with our overridden position.
MockGeolocationObserver mock_observer;
EXPECT_CALL(mock_observer, OnLocationUpdate(GeopositionEq(position)));
provider_->AddObserver(&mock_observer, GeolocationObserverOptions());
provider_->RemoveObserver(&mock_observer);
}
TEST_F(GeolocationProviderTest, Callback) {
MockGeolocationCallbackWrapper callback_wrapper;
provider_->RequestCallback(
base::Bind(&MockGeolocationCallbackWrapper::Callback,
base::Unretained(&callback_wrapper)));
content::Geoposition position;
position.latitude = 12;
position.longitude = 34;
position.accuracy = 56;
position.timestamp = base::Time::Now();
EXPECT_CALL(callback_wrapper, Callback(GeopositionEq(position)));
provider_->OverrideLocationForTesting(position);
}
} // namespace
<commit_msg>Try to fix GeolocationProviderTest flakiness<commit_after>// Copyright (c) 2012 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 "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/time.h"
#include "content/browser/geolocation/arbitrator_dependency_factory.h"
#include "content/browser/geolocation/fake_access_token_store.h"
#include "content/browser/geolocation/geolocation_observer.h"
#include "content/browser/geolocation/geolocation_provider.h"
#include "content/browser/geolocation/location_arbitrator.h"
#include "content/browser/geolocation/mock_location_provider.h"
#include "content/public/browser/browser_thread.h"
#include "content/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::Geoposition;
using testing::_;
using testing::DoAll;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::MakeMatcher;
using testing::Matcher;
using testing::MatcherInterface;
using testing::MatchResultListener;
namespace {
class NonSingletonGeolocationProvider : public GeolocationProvider {
public:
NonSingletonGeolocationProvider() {}
virtual ~NonSingletonGeolocationProvider() {}
};
class StartStopMockLocationProvider : public MockLocationProvider {
public:
explicit StartStopMockLocationProvider() : MockLocationProvider(&instance_) {
}
virtual ~StartStopMockLocationProvider() {
Die();
}
MOCK_METHOD0(Die, void());
};
class TestingDependencyFactory
: public DefaultGeolocationArbitratorDependencyFactory {
public:
TestingDependencyFactory(base::WaitableEvent* event) : event_(event) {
}
virtual content::AccessTokenStore* NewAccessTokenStore() OVERRIDE {
content::FakeAccessTokenStore* store = new content::FakeAccessTokenStore();
EXPECT_CALL(*store, LoadAccessTokens(_))
.WillRepeatedly(DoAll(
Invoke(store,
&content::FakeAccessTokenStore::DefaultLoadAccessTokens),
InvokeWithoutArgs(store,
&content::FakeAccessTokenStore::
NotifyDelegateTokensLoaded),
InvokeWithoutArgs(event_, &base::WaitableEvent::Signal)));
return store;
}
virtual LocationProviderBase* NewNetworkLocationProvider(
content::AccessTokenStore* access_token_store,
net::URLRequestContextGetter* context,
const GURL& url,
const string16& access_token) OVERRIDE {
StartStopMockLocationProvider* provider =
new StartStopMockLocationProvider();
EXPECT_CALL(*provider, Die())
.Times(1)
.WillOnce(InvokeWithoutArgs(event_, &base::WaitableEvent::Signal));
return provider;
}
virtual LocationProviderBase* NewSystemLocationProvider() OVERRIDE {
return NULL;
}
private:
base::WaitableEvent* event_;
};
class NullGeolocationObserver : public GeolocationObserver {
public:
// GeolocationObserver
virtual void OnLocationUpdate(const content::Geoposition& position) {}
};
class MockGeolocationObserver : public GeolocationObserver {
public:
// GeolocationObserver
MOCK_METHOD1(OnLocationUpdate, void(const content::Geoposition& position));
};
class MockGeolocationCallbackWrapper {
public:
MOCK_METHOD1(Callback, void(const content::Geoposition& position));
};
class GeopositionEqMatcher
: public MatcherInterface<const content::Geoposition&> {
public:
explicit GeopositionEqMatcher(const content::Geoposition& expected)
: expected_(expected) {}
virtual bool MatchAndExplain(const content::Geoposition& actual,
MatchResultListener* listener) const OVERRIDE {
return actual.latitude == expected_.latitude &&
actual.longitude == expected_.longitude &&
actual.altitude == expected_.altitude &&
actual.accuracy == expected_.accuracy &&
actual.altitude_accuracy == expected_.altitude_accuracy &&
actual.heading == expected_.heading &&
actual.speed == expected_.speed &&
actual.timestamp == expected_.timestamp &&
actual.error_code == expected_.error_code &&
actual.error_message == expected_.error_message;
}
virtual void DescribeTo(::std::ostream* os) const OVERRIDE {
*os << "which matches the expected position";
}
virtual void DescribeNegationTo(::std::ostream* os) const OVERRIDE{
*os << "which does not match the expected position";
}
private:
content::Geoposition expected_;
DISALLOW_COPY_AND_ASSIGN(GeopositionEqMatcher);
};
Matcher<const content::Geoposition&> GeopositionEq(
const content::Geoposition& expected) {
return MakeMatcher(new GeopositionEqMatcher(expected));
}
class GeolocationProviderTest : public testing::Test {
protected:
GeolocationProviderTest()
: message_loop_(),
io_thread_(content::BrowserThread::IO, &message_loop_),
event_(false, false),
dependency_factory_(new TestingDependencyFactory(&event_)),
provider_(new NonSingletonGeolocationProvider) {
GeolocationArbitrator::SetDependencyFactoryForTest(
dependency_factory_.get());
}
~GeolocationProviderTest() {
GeolocationArbitrator::SetDependencyFactoryForTest(NULL);
}
void WaitAndReset() {
event_.Wait();
event_.Reset();
}
MessageLoop message_loop_;
content::TestBrowserThread io_thread_;
base::WaitableEvent event_;
scoped_refptr<TestingDependencyFactory> dependency_factory_;
scoped_ptr<NonSingletonGeolocationProvider> provider_;
};
// Regression test for http://crbug.com/59377
TEST_F(GeolocationProviderTest, OnPermissionGrantedWithoutObservers) {
EXPECT_FALSE(provider_->HasPermissionBeenGranted());
provider_->OnPermissionGranted();
EXPECT_TRUE(provider_->HasPermissionBeenGranted());
}
TEST_F(GeolocationProviderTest, StartStop) {
EXPECT_FALSE(provider_->IsRunning());
NullGeolocationObserver null_observer;
GeolocationObserverOptions options;
provider_->AddObserver(&null_observer, options);
EXPECT_TRUE(provider_->IsRunning());
// Wait for token load request from the arbitrator to come through.
WaitAndReset();
EXPECT_EQ(MockLocationProvider::instance_->state_,
MockLocationProvider::LOW_ACCURACY);
provider_->RemoveObserver(&null_observer);
// Wait for the providers to be stopped now that all clients are gone.
WaitAndReset();
EXPECT_TRUE(provider_->IsRunning());
}
TEST_F(GeolocationProviderTest, OverrideLocationForTesting) {
content::Geoposition position;
position.error_code = content::Geoposition::ERROR_CODE_POSITION_UNAVAILABLE;
provider_->OverrideLocationForTesting(position);
// Adding an observer when the location is overridden should synchronously
// update the observer with our overridden position.
MockGeolocationObserver mock_observer;
EXPECT_CALL(mock_observer, OnLocationUpdate(GeopositionEq(position)));
provider_->AddObserver(&mock_observer, GeolocationObserverOptions());
// Wait for token load request from the arbitrator to come through.
WaitAndReset();
provider_->RemoveObserver(&mock_observer);
// Wait for the providers to be stopped now that all clients are gone.
WaitAndReset();
}
TEST_F(GeolocationProviderTest, Callback) {
MockGeolocationCallbackWrapper callback_wrapper;
provider_->RequestCallback(
base::Bind(&MockGeolocationCallbackWrapper::Callback,
base::Unretained(&callback_wrapper)));
// Wait for token load request from the arbitrator to come through.
WaitAndReset();
content::Geoposition position;
position.latitude = 12;
position.longitude = 34;
position.accuracy = 56;
position.timestamp = base::Time::Now();
EXPECT_CALL(callback_wrapper, Callback(GeopositionEq(position)));
provider_->OverrideLocationForTesting(position);
// Wait for the providers to be stopped now that all clients are gone.
WaitAndReset();
}
} // namespace
<|endoftext|> |
<commit_before>// test: indent_only
if (foo)
return;
if (foo +
bar)
return;
if (foo) {
#if DIRECTIVES_IGNORED
DropEverything();
}
if (a->ba(
baz)) {}
LOG(FOO) << "foo"
<< "bar";
while (foo +
bar) {
} // aligning to parens
namespace mynamespace {
}
const Foo& foo =
bar.baz().quux(X);
const Foo& foo =
bar.baz().quux(
X);
ReturnType
LongClassName::Meth(
Type1 par1) {
}
ReturnType LongClassName::Meth(
Type1 par1) {
}
method([&](int a, int b) {
});
O C::M(T a,
T b) {
}
O C::M(T a,
T b) {
}
void foo(int my_arg) {
int abc =
MyFunction(
my_arg);
}
class A
:
public B {
}
class A
: public B {
}
class A
: public B<
X, Y> {
}
class Foo {
public:
}
Type m{a,
b};
Type m(
a,
b);
Type m = {
};
Type m =
(
);
MyClass::MyClass(
int var)
: some_var_(var) {
}
MyClass::MyClass(
int var)
: some_var_(var) {
}
MyClass::MyClass(
int var)
: some_var_(var),
some_other_var_(var + 1) {
}
<commit_msg>Fix indentation test<commit_after>// test: indent_only
if (foo)
return;
if (foo +
bar)
return;
if (foo) {
#if DIRECTIVES_IGNORED
DropEverything();
}
if (a->ba(
baz)) {}
LOG(FOO) << "foo"
<< "bar";
while (foo +
bar) {
} // aligning to parens
namespace mynamespace {
}
const Foo& foo =
bar.baz().quux(X);
const Foo& foo =
bar.baz().quux(
X);
ReturnType
LongClassName::Meth(
Type1 par1) {
}
ReturnType LongClassName::Meth(
Type1 par1) {
}
method([&](int a, int b) {
});
O C::M(T a,
T b) {
}
O C::M(T a,
T b) {
}
void foo(int my_arg) {
int abc =
MyFunction(
my_arg);
}
class A
:
public B {
}
class A
: public B {
}
class A
: public B<
X, Y> {
}
class Foo {
public:
}
Type m{a,
b};
Type m(
a,
b);
Type m = {
};
Type m = (
);
Type m =
();
MyClass::MyClass(
int var)
: some_var_(var) {
}
MyClass::MyClass(
int var)
: some_var_(var) {
}
MyClass::MyClass(
int var)
: some_var_(var),
some_other_var_(var + 1) {
}
<|endoftext|> |
<commit_before>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rob McDonald - initial code and implementation
********************************************************************************/
#ifndef eli_geom_intersect_intersect_surface_surface_hpp
#define eli_geom_intersect_intersect_surface_surface_hpp
#include <cmath>
#include <vector>
#include <list>
#include <algorithm>
#include "eli/code_eli.hpp"
#include "eli/mutil/nls/newton_raphson_method.hpp"
#include "eli/geom/point/distance.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/intersect/minimum_distance_bounding_box.hpp"
namespace eli
{
namespace geom
{
namespace intersect
{
namespace internal
{
template <typename surface__>
struct surf_surf_g_functor
{
const surface__ *s1;
const surface__ *s2;
typename surface__::point_type pt;
typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec;
vec operator()(const vec &x) const
{
typename surface__::data_type u1(x[0]), v1(x[1]);
typename surface__::data_type u2(x[2]), v2(x[3]);
vec rtn;
typename surface__::data_type u1min, u1max, v1min, v1max;
typename surface__::data_type u2min, u2max, v2min, v2max;
s1->get_parameter_min(u1min,v1min);
s1->get_parameter_max(u1max,v1max);
s2->get_parameter_min(u2min,v2min);
s2->get_parameter_max(u2max,v2max);
u1=std::min(std::max(u1, u1min), u1max);
v1=std::min(std::max(v1, v1min), v1max);
u2=std::min(std::max(u2, u2min), u2max);
v2=std::min(std::max(v2, v2min), v2max);
typename surface__::point_type p1, p2, pave, disp, tvec;
p1=s1->f(u1,v1);
p2=s2->f(u2,v2);
pave=(p1+p2)*0.5;
disp=p2-p1;
tvec=(s1->f_u(u1,v1).cross(s1->f_v(u1,v1))).cross(s2->f_u(u2,v2).cross(s2->f_v(u2,v2)));
rtn(0)=disp(0);
rtn(1)=disp(1);
rtn(2)=disp(2);
rtn(3)=tvec.dot(pave-pt);
return rtn;
}
};
template <typename surface__>
struct surf_surf_gp_functor
{
const surface__ *s1;
const surface__ *s2;
typename surface__::point_type pt;
typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec;
typedef typename Eigen::Matrix<typename surface__::data_type, 4, 4> mat;
mat operator()(const vec &x) const
{
typename surface__::data_type u1(x[0]), v1(x[1]);
typename surface__::data_type u2(x[2]), v2(x[3]);
mat rtn;
typename surface__::data_type u1min, u1max, v1min, v1max;
typename surface__::data_type u2min, u2max, v2min, v2max;
s1->get_parameter_min(u1min,v1min);
s1->get_parameter_max(u1max,v1max);
s2->get_parameter_min(u2min,v2min);
s2->get_parameter_max(u2max,v2max);
u1=std::min(std::max(u1, u1min), u1max);
v1=std::min(std::max(v1, v1min), v1max);
u2=std::min(std::max(u2, u2min), u2max);
v2=std::min(std::max(v2, v2min), v2max);
typename surface__::point_type S1u, S1v, S1uu, S1uv, S1vv;
typename surface__::point_type S2u, S2v, S2uu, S2uv, S2vv;
typename surface__::point_type p1, p2, pave, tvec, dist;
p1=s1->f(u1,v1);
p2=s2->f(u2,v2);
pave=(p1+p2)*0.5;
dist=pave-pt;
S1u=s1->f_u(u1, v1);
S1v=s1->f_v(u1, v1);
S1uu=s1->f_uu(u1, v1);
S1uv=s1->f_uv(u1, v1);
S1vv=s1->f_vv(u1, v1);
S2u=s2->f_u(u2, v2);
S2v=s2->f_v(u2, v2);
S2uu=s2->f_uu(u2, v2);
S2uv=s2->f_uv(u2, v2);
S2vv=s2->f_vv(u2, v2);
tvec=(S1u.cross(S1v)).cross(S2u.cross(S2v));
rtn(0,0)=-S1u(0);
rtn(0,1)=-S1v(0);
rtn(0,2)=S2u(0);
rtn(0,3)=S2v(0);
rtn(1,0)=-S1u(1);
rtn(1,1)=-S1v(1);
rtn(1,2)=S2u(1);
rtn(1,3)=S2v(1);
rtn(2,0)=-S1u(2);
rtn(2,1)=-S1v(2);
rtn(2,2)=S2u(2);
rtn(2,3)=S2v(2);
// tvec.dot(dist);
rtn(3,0)= dist.dot( ( S1uu.cross(S1v)+S1u.cross(S1uv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1u * 0.5 );
rtn(3,1)= dist.dot( ( S1uv.cross(S1v)+S1u.cross(S1vv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1v * 0.5 );
rtn(3,2)= dist.dot( (S1u.cross(S1v)).cross( S2uu.cross(S2v)+S2u.cross(S2uv) ) ) + tvec.dot( S2u * 0.5 );
rtn(3,3)= dist.dot( (S1u.cross(S1v)).cross( S2uv.cross(S2v)+S2u.cross(S2vv) ) ) + tvec.dot( S2v * 0.5 );
// TODO: What to do if matrix becomes singular?
return rtn;
}
};
}
template<typename surface__>
typename surface__::data_type intersect(typename surface__::data_type &u1, typename surface__::data_type &v1,
typename surface__::data_type &u2, typename surface__::data_type &v2,
const surface__ &s1, const surface__ &s2, const typename surface__::point_type &pt,
const typename surface__::data_type &u01, const typename surface__::data_type &v01,
const typename surface__::data_type &u02, const typename surface__::data_type &v02 )
{
typedef eli::mutil::nls::newton_raphson_system_method<typename surface__::data_type, 4, 1> nonlinear_solver_type;
nonlinear_solver_type nrm;
internal::surf_surf_g_functor<surface__> g;
internal::surf_surf_gp_functor<surface__> gp;
typename surface__::data_type dist0, dist;
typename surface__::tolerance_type tol;
typename surface__::data_type u1min, u1max, v1min, v1max;
typename surface__::data_type u2min, u2max, v2min, v2max;
s1.get_parameter_min(u1min,v1min);
s1.get_parameter_max(u1max,v1max);
s2.get_parameter_min(u2min,v2min);
s2.get_parameter_max(u2max,v2max);
typename surface__::point_type p1, p2;
p1=s1.f(u01,v01);
p2=s2.f(u02,v02);
// setup the functors
g.s1=&s1;
g.s2=&s2;
g.pt=pt;
gp.s1=&s1;
gp.s2=&s2;
gp.pt=pt;
// setup the solver
nrm.set_absolute_f_tolerance(tol.get_absolute_tolerance());
nrm.set_max_iteration(20);
nrm.set_norm_type(nonlinear_solver_type::max_norm);
if (s1.open_u())
{
nrm.set_lower_condition(0, u1min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(0, u1max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(0, u1min, u1max);
}
if (s1.open_v())
{
nrm.set_lower_condition(1, v1min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(1, v1max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(1, v1min, v1max);
}
if (s2.open_u())
{
nrm.set_lower_condition(2, u2min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(2, u2max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(2, u2min, u2max);
}
if (s2.open_v())
{
nrm.set_lower_condition(3, v2min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(3, v2max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(3, v2min, v2max);
}
// set the initial guess
typename nonlinear_solver_type::solution_matrix xinit, rhs, ans;
xinit(0)=u01;
xinit(1)=v01;
xinit(2)=u02;
xinit(3)=v02;
nrm.set_initial_guess(xinit);
rhs.setZero();
dist0=eli::geom::point::distance(p1, p2);
// find the root
nrm.find_root(ans, g, gp, rhs);
u1=ans(0);
v1=ans(1);
u2=ans(2);
v2=ans(3);
dist = eli::geom::point::distance(s1.f(u1, v1), s2.f(u2,v2));
// if( dist > 1e-6 )
// {
// printf("d0: %g d: %g\n", dist0, dist );
// printf(" u01: %f u1: %f\n", u01, u1 );
// printf(" v01: %f v1: %f\n", v01, v1 );
// printf(" u02: %f u2: %f\n", u02, u2 );
// printf(" v02: %f v2: %f\n", v02, v2 );
// }
if (dist<=dist0)
{
return dist;
}
// couldn't find better answer so return initial guess
u1=u01;
v1=v01;
u2=u02;
v2=v02;
return dist0;
}
}
}
}
#endif
<commit_msg>Update surface-surface intersection to return error code<commit_after>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rob McDonald - initial code and implementation
********************************************************************************/
#ifndef eli_geom_intersect_intersect_surface_surface_hpp
#define eli_geom_intersect_intersect_surface_surface_hpp
#include <cmath>
#include <vector>
#include <list>
#include <algorithm>
#include "eli/code_eli.hpp"
#include "eli/mutil/nls/newton_raphson_method.hpp"
#include "eli/geom/point/distance.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/intersect/minimum_distance_bounding_box.hpp"
namespace eli
{
namespace geom
{
namespace intersect
{
namespace internal
{
template <typename surface__>
struct surf_surf_g_functor
{
const surface__ *s1;
const surface__ *s2;
typename surface__::point_type pt;
typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec;
vec operator()(const vec &x) const
{
typename surface__::data_type u1(x[0]), v1(x[1]);
typename surface__::data_type u2(x[2]), v2(x[3]);
vec rtn;
typename surface__::data_type u1min, u1max, v1min, v1max;
typename surface__::data_type u2min, u2max, v2min, v2max;
s1->get_parameter_min(u1min,v1min);
s1->get_parameter_max(u1max,v1max);
s2->get_parameter_min(u2min,v2min);
s2->get_parameter_max(u2max,v2max);
u1=std::min(std::max(u1, u1min), u1max);
v1=std::min(std::max(v1, v1min), v1max);
u2=std::min(std::max(u2, u2min), u2max);
v2=std::min(std::max(v2, v2min), v2max);
typename surface__::point_type p1, p2, pave, disp, tvec;
p1=s1->f(u1,v1);
p2=s2->f(u2,v2);
pave=(p1+p2)*0.5;
disp=p2-p1;
tvec=(s1->f_u(u1,v1).cross(s1->f_v(u1,v1))).cross(s2->f_u(u2,v2).cross(s2->f_v(u2,v2)));
rtn(0)=disp(0);
rtn(1)=disp(1);
rtn(2)=disp(2);
rtn(3)=tvec.dot(pave-pt);
return rtn;
}
};
template <typename surface__>
struct surf_surf_gp_functor
{
const surface__ *s1;
const surface__ *s2;
typename surface__::point_type pt;
typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec;
typedef typename Eigen::Matrix<typename surface__::data_type, 4, 4> mat;
mat operator()(const vec &x) const
{
typename surface__::data_type u1(x[0]), v1(x[1]);
typename surface__::data_type u2(x[2]), v2(x[3]);
mat rtn;
typename surface__::data_type u1min, u1max, v1min, v1max;
typename surface__::data_type u2min, u2max, v2min, v2max;
s1->get_parameter_min(u1min,v1min);
s1->get_parameter_max(u1max,v1max);
s2->get_parameter_min(u2min,v2min);
s2->get_parameter_max(u2max,v2max);
u1=std::min(std::max(u1, u1min), u1max);
v1=std::min(std::max(v1, v1min), v1max);
u2=std::min(std::max(u2, u2min), u2max);
v2=std::min(std::max(v2, v2min), v2max);
typename surface__::point_type S1u, S1v, S1uu, S1uv, S1vv;
typename surface__::point_type S2u, S2v, S2uu, S2uv, S2vv;
typename surface__::point_type p1, p2, pave, tvec, dist;
p1=s1->f(u1,v1);
p2=s2->f(u2,v2);
pave=(p1+p2)*0.5;
dist=pave-pt;
S1u=s1->f_u(u1, v1);
S1v=s1->f_v(u1, v1);
S1uu=s1->f_uu(u1, v1);
S1uv=s1->f_uv(u1, v1);
S1vv=s1->f_vv(u1, v1);
S2u=s2->f_u(u2, v2);
S2v=s2->f_v(u2, v2);
S2uu=s2->f_uu(u2, v2);
S2uv=s2->f_uv(u2, v2);
S2vv=s2->f_vv(u2, v2);
tvec=(S1u.cross(S1v)).cross(S2u.cross(S2v));
rtn(0,0)=-S1u(0);
rtn(0,1)=-S1v(0);
rtn(0,2)=S2u(0);
rtn(0,3)=S2v(0);
rtn(1,0)=-S1u(1);
rtn(1,1)=-S1v(1);
rtn(1,2)=S2u(1);
rtn(1,3)=S2v(1);
rtn(2,0)=-S1u(2);
rtn(2,1)=-S1v(2);
rtn(2,2)=S2u(2);
rtn(2,3)=S2v(2);
// tvec.dot(dist);
rtn(3,0)= dist.dot( ( S1uu.cross(S1v)+S1u.cross(S1uv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1u * 0.5 );
rtn(3,1)= dist.dot( ( S1uv.cross(S1v)+S1u.cross(S1vv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1v * 0.5 );
rtn(3,2)= dist.dot( (S1u.cross(S1v)).cross( S2uu.cross(S2v)+S2u.cross(S2uv) ) ) + tvec.dot( S2u * 0.5 );
rtn(3,3)= dist.dot( (S1u.cross(S1v)).cross( S2uv.cross(S2v)+S2u.cross(S2vv) ) ) + tvec.dot( S2v * 0.5 );
// TODO: What to do if matrix becomes singular?
return rtn;
}
};
}
template<typename surface__>
typename surface__::index_type intersect(typename surface__::data_type &u1, typename surface__::data_type &v1,
typename surface__::data_type &u2, typename surface__::data_type &v2,
typename surface__::data_type &dist,
const surface__ &s1, const surface__ &s2, const typename surface__::point_type &pt,
const typename surface__::data_type &u01, const typename surface__::data_type &v01,
const typename surface__::data_type &u02, const typename surface__::data_type &v02 )
{
typedef eli::mutil::nls::newton_raphson_system_method<typename surface__::data_type, 4, 1> nonlinear_solver_type;
nonlinear_solver_type nrm;
internal::surf_surf_g_functor<surface__> g;
internal::surf_surf_gp_functor<surface__> gp;
typename surface__::data_type dist0;
typename surface__::tolerance_type tol;
typename surface__::data_type u1min, u1max, v1min, v1max;
typename surface__::data_type u2min, u2max, v2min, v2max;
s1.get_parameter_min(u1min,v1min);
s1.get_parameter_max(u1max,v1max);
s2.get_parameter_min(u2min,v2min);
s2.get_parameter_max(u2max,v2max);
typename surface__::point_type p1, p2;
p1=s1.f(u01,v01);
p2=s2.f(u02,v02);
// setup the functors
g.s1=&s1;
g.s2=&s2;
g.pt=pt;
gp.s1=&s1;
gp.s2=&s2;
gp.pt=pt;
// setup the solver
nrm.set_absolute_f_tolerance(tol.get_absolute_tolerance());
nrm.set_max_iteration(20);
nrm.set_norm_type(nonlinear_solver_type::max_norm);
if (s1.open_u())
{
nrm.set_lower_condition(0, u1min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(0, u1max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(0, u1min, u1max);
}
if (s1.open_v())
{
nrm.set_lower_condition(1, v1min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(1, v1max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(1, v1min, v1max);
}
if (s2.open_u())
{
nrm.set_lower_condition(2, u2min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(2, u2max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(2, u2min, u2max);
}
if (s2.open_v())
{
nrm.set_lower_condition(3, v2min, nonlinear_solver_type::IRC_EXCLUSIVE);
nrm.set_upper_condition(3, v2max, nonlinear_solver_type::IRC_EXCLUSIVE);
}
else
{
nrm.set_periodic_condition(3, v2min, v2max);
}
// set the initial guess
typename nonlinear_solver_type::solution_matrix xinit, rhs, ans;
xinit(0)=u01;
xinit(1)=v01;
xinit(2)=u02;
xinit(3)=v02;
nrm.set_initial_guess(xinit);
rhs.setZero();
dist0=eli::geom::point::distance(p1, p2);
// find the root
typename surface__::index_type ret = nrm.find_root(ans, g, gp, rhs);
if ( ret == nrm.converged )
{
u1=ans(0);
v1=ans(1);
u2=ans(2);
v2=ans(3);
dist = eli::geom::point::distance(s1.f(u1, v1), s2.f(u2,v2));
// if( dist > 1e-6 )
// {
// printf("d0: %g d: %g\n", dist0, dist );
// printf(" u01: %f u1: %f\n", u01, u1 );
// printf(" v01: %f v1: %f\n", v01, v1 );
// printf(" u02: %f u2: %f\n", u02, u2 );
// printf(" v02: %f v2: %f\n", v02, v2 );
// }
if (dist<=dist0)
{
return ret;
}
ret = 3; // Converged, but worse answer than initial guess.
}
// couldn't find better answer so return initial guess
u1=u01;
v1=v01;
u2=u02;
v2=v02;
dist=dist0;
return ret;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>#define EIGEN_ENABLE_EVALUATORS
#include "main.h"
using internal::copy_using_evaluator;
using namespace std;
#define VERIFY_IS_APPROX_EVALUATOR(DEST,EXPR) VERIFY_IS_APPROX(copy_using_evaluator(DEST,(EXPR)), (EXPR).eval());
#define VERIFY_IS_APPROX_EVALUATOR2(DEST,EXPR,REF) VERIFY_IS_APPROX(copy_using_evaluator(DEST,(EXPR)), (REF).eval());
void test_evaluators()
{
// Testing Matrix evaluator and Transpose
Vector2d v = Vector2d::Random();
const Vector2d v_const(v);
Vector2d v2;
RowVector2d w;
VERIFY_IS_APPROX_EVALUATOR(v2, v);
VERIFY_IS_APPROX_EVALUATOR(v2, v_const);
// Testing Transpose
VERIFY_IS_APPROX_EVALUATOR(w, v.transpose()); // Transpose as rvalue
VERIFY_IS_APPROX_EVALUATOR(w, v_const.transpose());
copy_using_evaluator(w.transpose(), v); // Transpose as lvalue
VERIFY_IS_APPROX(w,v.transpose().eval());
copy_using_evaluator(w.transpose(), v_const);
VERIFY_IS_APPROX(w,v_const.transpose().eval());
// Testing Array evaluator
ArrayXXf a(2,3);
ArrayXXf b(3,2);
a << 1,2,3, 4,5,6;
const ArrayXXf a_const(a);
VERIFY_IS_APPROX_EVALUATOR(b, a.transpose());
VERIFY_IS_APPROX_EVALUATOR(b, a_const.transpose());
// Testing CwiseNullaryOp evaluator
copy_using_evaluator(w, RowVector2d::Random());
VERIFY((w.array() >= -1).all() && (w.array() <= 1).all()); // not easy to test ...
VERIFY_IS_APPROX_EVALUATOR(w, RowVector2d::Zero());
VERIFY_IS_APPROX_EVALUATOR(w, RowVector2d::Constant(3));
// mix CwiseNullaryOp and transpose
VERIFY_IS_APPROX_EVALUATOR(w, Vector2d::Zero().transpose());
{
int s = internal::random<int>(1,100);
MatrixXf a(s,s), b(s,s), c(s,s), d(s,s);
a.setRandom();
b.setRandom();
c.setRandom();
d.setRandom();
VERIFY_IS_APPROX_EVALUATOR(d, (a + b));
VERIFY_IS_APPROX_EVALUATOR(d, (a + b).transpose());
VERIFY_IS_APPROX_EVALUATOR2(d, prod(a,b).transpose(), (a*b).transpose());
VERIFY_IS_APPROX_EVALUATOR2(d, prod(a,b) + prod(b,c), a*b + b*c);
// copy_using_evaluator(d, a.transpose() + (a.transpose() * (b+b)));
// cout << d << endl;
}
// this does not work because Random is eval-before-nested:
// copy_using_evaluator(w, Vector2d::Random().transpose());
// test CwiseUnaryOp
VERIFY_IS_APPROX_EVALUATOR(v2, 3 * v);
VERIFY_IS_APPROX_EVALUATOR(w, (3 * v).transpose());
VERIFY_IS_APPROX_EVALUATOR(b, (a + 3).transpose());
VERIFY_IS_APPROX_EVALUATOR(b, (2 * a_const + 3).transpose());
// test CwiseBinaryOp
VERIFY_IS_APPROX_EVALUATOR(v2, v + Vector2d::Ones());
VERIFY_IS_APPROX_EVALUATOR(w, (v + Vector2d::Ones()).transpose().cwiseProduct(RowVector2d::Constant(3)));
// dynamic matrices and arrays
MatrixXd mat1(6,6), mat2(6,6);
VERIFY_IS_APPROX_EVALUATOR(mat1, MatrixXd::Identity(6,6));
VERIFY_IS_APPROX_EVALUATOR(mat2, mat1);
copy_using_evaluator(mat2.transpose(), mat1);
VERIFY_IS_APPROX(mat2.transpose(), mat1);
ArrayXXd arr1(6,6), arr2(6,6);
VERIFY_IS_APPROX_EVALUATOR(arr1, ArrayXXd::Constant(6,6, 3.0));
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1);
// test direct traversal
Matrix3f m3;
Array33f a3;
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Identity()); // matrix, nullary
// TODO: find a way to test direct traversal with array
VERIFY_IS_APPROX_EVALUATOR(m3.transpose(), Matrix3f::Identity().transpose()); // transpose
VERIFY_IS_APPROX_EVALUATOR(m3, 2 * Matrix3f::Identity()); // unary
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Identity() + m3); // binary
VERIFY_IS_APPROX_EVALUATOR(m3.block(0,0,2,2), Matrix3f::Identity().block(1,1,2,2)); // block
// test linear traversal
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Zero()); // matrix, nullary
VERIFY_IS_APPROX_EVALUATOR(a3, Array33f::Zero()); // array
VERIFY_IS_APPROX_EVALUATOR(m3.transpose(), Matrix3f::Zero().transpose()); // transpose
VERIFY_IS_APPROX_EVALUATOR(m3, 2 * Matrix3f::Zero()); // unary
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Zero() + m3); // binary
// test inner vectorization
Matrix4f m4, m4src = Matrix4f::Random();
Array44f a4, a4src = Matrix4f::Random();
VERIFY_IS_APPROX_EVALUATOR(m4, m4src); // matrix
VERIFY_IS_APPROX_EVALUATOR(a4, a4src); // array
VERIFY_IS_APPROX_EVALUATOR(m4.transpose(), m4src.transpose()); // transpose
// TODO: find out why Matrix4f::Zero() does not allow inner vectorization
VERIFY_IS_APPROX_EVALUATOR(m4, 2 * m4src); // unary
VERIFY_IS_APPROX_EVALUATOR(m4, m4src + m4src); // binary
// test linear vectorization
MatrixXf mX(6,6), mXsrc = MatrixXf::Random(6,6);
ArrayXXf aX(6,6), aXsrc = ArrayXXf::Random(6,6);
VERIFY_IS_APPROX_EVALUATOR(mX, mXsrc); // matrix
VERIFY_IS_APPROX_EVALUATOR(aX, aXsrc); // array
VERIFY_IS_APPROX_EVALUATOR(mX.transpose(), mXsrc.transpose()); // transpose
VERIFY_IS_APPROX_EVALUATOR(mX, MatrixXf::Zero(6,6)); // nullary
VERIFY_IS_APPROX_EVALUATOR(mX, 2 * mXsrc); // unary
VERIFY_IS_APPROX_EVALUATOR(mX, mXsrc + mXsrc); // binary
// test blocks and slice vectorization
VERIFY_IS_APPROX_EVALUATOR(m4, (mXsrc.block<4,4>(1,0)));
VERIFY_IS_APPROX_EVALUATOR(aX, ArrayXXf::Constant(10, 10, 3.0).block(2, 3, 6, 6));
Matrix4f m4ref = m4;
copy_using_evaluator(m4.block(1, 1, 2, 3), m3.bottomRows(2));
m4ref.block(1, 1, 2, 3) = m3.bottomRows(2);
VERIFY_IS_APPROX(m4, m4ref);
mX.setIdentity(20,20);
MatrixXf mXref = MatrixXf::Identity(20,20);
mXsrc = MatrixXf::Random(9,12);
copy_using_evaluator(mX.block(4, 4, 9, 12), mXsrc);
mXref.block(4, 4, 9, 12) = mXsrc;
VERIFY_IS_APPROX(mX, mXref);
// test Map
const float raw[3] = {1,2,3};
float buffer[3] = {0,0,0};
Vector3f v3;
Array3f a3f;
VERIFY_IS_APPROX_EVALUATOR(v3, Map<const Vector3f>(raw));
VERIFY_IS_APPROX_EVALUATOR(a3f, Map<const Array3f>(raw));
Vector3f::Map(buffer) = 2*v3;
VERIFY(buffer[0] == 2);
VERIFY(buffer[1] == 4);
VERIFY(buffer[2] == 6);
// test CwiseUnaryView
mat1.setRandom();
mat2.setIdentity();
MatrixXcd matXcd(6,6), matXcd_ref(6,6);
copy_using_evaluator(matXcd.real(), mat1);
copy_using_evaluator(matXcd.imag(), mat2);
matXcd_ref.real() = mat1;
matXcd_ref.imag() = mat2;
VERIFY_IS_APPROX(matXcd, matXcd_ref);
// test Select
VERIFY_IS_APPROX_EVALUATOR(aX, (aXsrc > 0).select(aXsrc, -aXsrc));
// test Replicate
mXsrc = MatrixXf::Random(6, 6);
VectorXf vX = VectorXf::Random(6);
mX.resize(6, 6);
VERIFY_IS_APPROX_EVALUATOR(mX, mXsrc.colwise() + vX);
matXcd.resize(12, 12);
VERIFY_IS_APPROX_EVALUATOR(matXcd, matXcd_ref.replicate(2,2));
VERIFY_IS_APPROX_EVALUATOR(matXcd, (matXcd_ref.replicate<2,2>()));
// test partial reductions
VectorXd vec1(6);
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.rowwise().sum());
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.colwise().sum().transpose());
// test MatrixWrapper and ArrayWrapper
mat1.setRandom(6,6);
arr1.setRandom(6,6);
VERIFY_IS_APPROX_EVALUATOR(mat2, arr1.matrix());
VERIFY_IS_APPROX_EVALUATOR(arr2, mat1.array());
VERIFY_IS_APPROX_EVALUATOR(mat2, (arr1 + 2).matrix());
VERIFY_IS_APPROX_EVALUATOR(arr2, mat1.array() + 2);
mat2.array() = arr1 * arr1;
VERIFY_IS_APPROX(mat2, (arr1 * arr1).matrix());
arr2.matrix() = MatrixXd::Identity(6,6);
VERIFY_IS_APPROX(arr2, MatrixXd::Identity(6,6).array());
// test Reverse
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1.reverse());
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1.colwise().reverse());
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1.rowwise().reverse());
arr2.reverse() = arr1;
VERIFY_IS_APPROX(arr2, arr1.reverse());
// test Diagonal
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.diagonal());
vec1.resize(5);
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.diagonal(1));
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.diagonal<-1>());
vec1.setRandom();
mat2 = mat1;
copy_using_evaluator(mat1.diagonal(1), vec1);
mat2.diagonal(1) = vec1;
VERIFY_IS_APPROX(mat1, mat2);
copy_using_evaluator(mat1.diagonal<-1>(), mat1.diagonal(1));
mat2.diagonal<-1>() = mat2.diagonal(1);
VERIFY_IS_APPROX(mat1, mat2);
{
// test swapping
MatrixXd mat1, mat2, mat1ref, mat2ref;
mat1ref = mat1 = MatrixXd::Random(6, 6);
mat2ref = mat2 = 2 * mat1 + MatrixXd::Identity(6, 6);
swap_using_evaluator(mat1, mat2);
mat1ref.swap(mat2ref);
VERIFY_IS_APPROX(mat1, mat1ref);
VERIFY_IS_APPROX(mat2, mat2ref);
swap_using_evaluator(mat1.block(0, 0, 3, 3), mat2.block(3, 3, 3, 3));
mat1ref.block(0, 0, 3, 3).swap(mat2ref.block(3, 3, 3, 3));
VERIFY_IS_APPROX(mat1, mat1ref);
VERIFY_IS_APPROX(mat2, mat2ref);
swap_using_evaluator(mat1.row(2), mat2.col(3).transpose());
mat1.row(2).swap(mat2.col(3).transpose());
VERIFY_IS_APPROX(mat1, mat1ref);
VERIFY_IS_APPROX(mat2, mat2ref);
}
{
// test compound assignment
const Matrix4d mat_const = Matrix4d::Random();
Matrix4d mat, mat_ref;
mat = mat_ref = Matrix4d::Identity();
add_assign_using_evaluator(mat, mat_const);
mat_ref += mat_const;
VERIFY_IS_APPROX(mat, mat_ref);
subtract_assign_using_evaluator(mat.row(1), 2*mat.row(2));
mat_ref.row(1) -= 2*mat_ref.row(2);
VERIFY_IS_APPROX(mat, mat_ref);
const ArrayXXf arr_const = ArrayXXf::Random(5,3);
ArrayXXf arr, arr_ref;
arr = arr_ref = ArrayXXf::Constant(5, 3, 0.5);
multiply_assign_using_evaluator(arr, arr_const);
arr_ref *= arr_const;
VERIFY_IS_APPROX(arr, arr_ref);
divide_assign_using_evaluator(arr.row(1), arr.row(2) + 1);
arr_ref.row(1) /= (arr_ref.row(2) + 1);
VERIFY_IS_APPROX(arr, arr_ref);
}
}
<commit_msg>Fix an evaluator test which was wrong and failed in debug builds.<commit_after>#define EIGEN_ENABLE_EVALUATORS
#include "main.h"
using internal::copy_using_evaluator;
using namespace std;
#define VERIFY_IS_APPROX_EVALUATOR(DEST,EXPR) VERIFY_IS_APPROX(copy_using_evaluator(DEST,(EXPR)), (EXPR).eval());
#define VERIFY_IS_APPROX_EVALUATOR2(DEST,EXPR,REF) VERIFY_IS_APPROX(copy_using_evaluator(DEST,(EXPR)), (REF).eval());
void test_evaluators()
{
// Testing Matrix evaluator and Transpose
Vector2d v = Vector2d::Random();
const Vector2d v_const(v);
Vector2d v2;
RowVector2d w;
VERIFY_IS_APPROX_EVALUATOR(v2, v);
VERIFY_IS_APPROX_EVALUATOR(v2, v_const);
// Testing Transpose
VERIFY_IS_APPROX_EVALUATOR(w, v.transpose()); // Transpose as rvalue
VERIFY_IS_APPROX_EVALUATOR(w, v_const.transpose());
copy_using_evaluator(w.transpose(), v); // Transpose as lvalue
VERIFY_IS_APPROX(w,v.transpose().eval());
copy_using_evaluator(w.transpose(), v_const);
VERIFY_IS_APPROX(w,v_const.transpose().eval());
// Testing Array evaluator
ArrayXXf a(2,3);
ArrayXXf b(3,2);
a << 1,2,3, 4,5,6;
const ArrayXXf a_const(a);
VERIFY_IS_APPROX_EVALUATOR(b, a.transpose());
VERIFY_IS_APPROX_EVALUATOR(b, a_const.transpose());
// Testing CwiseNullaryOp evaluator
copy_using_evaluator(w, RowVector2d::Random());
VERIFY((w.array() >= -1).all() && (w.array() <= 1).all()); // not easy to test ...
VERIFY_IS_APPROX_EVALUATOR(w, RowVector2d::Zero());
VERIFY_IS_APPROX_EVALUATOR(w, RowVector2d::Constant(3));
// mix CwiseNullaryOp and transpose
VERIFY_IS_APPROX_EVALUATOR(w, Vector2d::Zero().transpose());
{
int s = internal::random<int>(1,100);
MatrixXf a(s,s), b(s,s), c(s,s), d(s,s);
a.setRandom();
b.setRandom();
c.setRandom();
d.setRandom();
VERIFY_IS_APPROX_EVALUATOR(d, (a + b));
VERIFY_IS_APPROX_EVALUATOR(d, (a + b).transpose());
VERIFY_IS_APPROX_EVALUATOR2(d, prod(a,b).transpose(), (a*b).transpose());
VERIFY_IS_APPROX_EVALUATOR2(d, prod(a,b) + prod(b,c), a*b + b*c);
// copy_using_evaluator(d, a.transpose() + (a.transpose() * (b+b)));
// cout << d << endl;
}
// this does not work because Random is eval-before-nested:
// copy_using_evaluator(w, Vector2d::Random().transpose());
// test CwiseUnaryOp
VERIFY_IS_APPROX_EVALUATOR(v2, 3 * v);
VERIFY_IS_APPROX_EVALUATOR(w, (3 * v).transpose());
VERIFY_IS_APPROX_EVALUATOR(b, (a + 3).transpose());
VERIFY_IS_APPROX_EVALUATOR(b, (2 * a_const + 3).transpose());
// test CwiseBinaryOp
VERIFY_IS_APPROX_EVALUATOR(v2, v + Vector2d::Ones());
VERIFY_IS_APPROX_EVALUATOR(w, (v + Vector2d::Ones()).transpose().cwiseProduct(RowVector2d::Constant(3)));
// dynamic matrices and arrays
MatrixXd mat1(6,6), mat2(6,6);
VERIFY_IS_APPROX_EVALUATOR(mat1, MatrixXd::Identity(6,6));
VERIFY_IS_APPROX_EVALUATOR(mat2, mat1);
copy_using_evaluator(mat2.transpose(), mat1);
VERIFY_IS_APPROX(mat2.transpose(), mat1);
ArrayXXd arr1(6,6), arr2(6,6);
VERIFY_IS_APPROX_EVALUATOR(arr1, ArrayXXd::Constant(6,6, 3.0));
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1);
// test direct traversal
Matrix3f m3;
Array33f a3;
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Identity()); // matrix, nullary
// TODO: find a way to test direct traversal with array
VERIFY_IS_APPROX_EVALUATOR(m3.transpose(), Matrix3f::Identity().transpose()); // transpose
VERIFY_IS_APPROX_EVALUATOR(m3, 2 * Matrix3f::Identity()); // unary
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Identity() + Matrix3f::Zero()); // binary
VERIFY_IS_APPROX_EVALUATOR(m3.block(0,0,2,2), Matrix3f::Identity().block(1,1,2,2)); // block
// test linear traversal
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Zero()); // matrix, nullary
VERIFY_IS_APPROX_EVALUATOR(a3, Array33f::Zero()); // array
VERIFY_IS_APPROX_EVALUATOR(m3.transpose(), Matrix3f::Zero().transpose()); // transpose
VERIFY_IS_APPROX_EVALUATOR(m3, 2 * Matrix3f::Zero()); // unary
VERIFY_IS_APPROX_EVALUATOR(m3, Matrix3f::Zero() + m3); // binary
// test inner vectorization
Matrix4f m4, m4src = Matrix4f::Random();
Array44f a4, a4src = Matrix4f::Random();
VERIFY_IS_APPROX_EVALUATOR(m4, m4src); // matrix
VERIFY_IS_APPROX_EVALUATOR(a4, a4src); // array
VERIFY_IS_APPROX_EVALUATOR(m4.transpose(), m4src.transpose()); // transpose
// TODO: find out why Matrix4f::Zero() does not allow inner vectorization
VERIFY_IS_APPROX_EVALUATOR(m4, 2 * m4src); // unary
VERIFY_IS_APPROX_EVALUATOR(m4, m4src + m4src); // binary
// test linear vectorization
MatrixXf mX(6,6), mXsrc = MatrixXf::Random(6,6);
ArrayXXf aX(6,6), aXsrc = ArrayXXf::Random(6,6);
VERIFY_IS_APPROX_EVALUATOR(mX, mXsrc); // matrix
VERIFY_IS_APPROX_EVALUATOR(aX, aXsrc); // array
VERIFY_IS_APPROX_EVALUATOR(mX.transpose(), mXsrc.transpose()); // transpose
VERIFY_IS_APPROX_EVALUATOR(mX, MatrixXf::Zero(6,6)); // nullary
VERIFY_IS_APPROX_EVALUATOR(mX, 2 * mXsrc); // unary
VERIFY_IS_APPROX_EVALUATOR(mX, mXsrc + mXsrc); // binary
// test blocks and slice vectorization
VERIFY_IS_APPROX_EVALUATOR(m4, (mXsrc.block<4,4>(1,0)));
VERIFY_IS_APPROX_EVALUATOR(aX, ArrayXXf::Constant(10, 10, 3.0).block(2, 3, 6, 6));
Matrix4f m4ref = m4;
copy_using_evaluator(m4.block(1, 1, 2, 3), m3.bottomRows(2));
m4ref.block(1, 1, 2, 3) = m3.bottomRows(2);
VERIFY_IS_APPROX(m4, m4ref);
mX.setIdentity(20,20);
MatrixXf mXref = MatrixXf::Identity(20,20);
mXsrc = MatrixXf::Random(9,12);
copy_using_evaluator(mX.block(4, 4, 9, 12), mXsrc);
mXref.block(4, 4, 9, 12) = mXsrc;
VERIFY_IS_APPROX(mX, mXref);
// test Map
const float raw[3] = {1,2,3};
float buffer[3] = {0,0,0};
Vector3f v3;
Array3f a3f;
VERIFY_IS_APPROX_EVALUATOR(v3, Map<const Vector3f>(raw));
VERIFY_IS_APPROX_EVALUATOR(a3f, Map<const Array3f>(raw));
Vector3f::Map(buffer) = 2*v3;
VERIFY(buffer[0] == 2);
VERIFY(buffer[1] == 4);
VERIFY(buffer[2] == 6);
// test CwiseUnaryView
mat1.setRandom();
mat2.setIdentity();
MatrixXcd matXcd(6,6), matXcd_ref(6,6);
copy_using_evaluator(matXcd.real(), mat1);
copy_using_evaluator(matXcd.imag(), mat2);
matXcd_ref.real() = mat1;
matXcd_ref.imag() = mat2;
VERIFY_IS_APPROX(matXcd, matXcd_ref);
// test Select
VERIFY_IS_APPROX_EVALUATOR(aX, (aXsrc > 0).select(aXsrc, -aXsrc));
// test Replicate
mXsrc = MatrixXf::Random(6, 6);
VectorXf vX = VectorXf::Random(6);
mX.resize(6, 6);
VERIFY_IS_APPROX_EVALUATOR(mX, mXsrc.colwise() + vX);
matXcd.resize(12, 12);
VERIFY_IS_APPROX_EVALUATOR(matXcd, matXcd_ref.replicate(2,2));
VERIFY_IS_APPROX_EVALUATOR(matXcd, (matXcd_ref.replicate<2,2>()));
// test partial reductions
VectorXd vec1(6);
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.rowwise().sum());
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.colwise().sum().transpose());
// test MatrixWrapper and ArrayWrapper
mat1.setRandom(6,6);
arr1.setRandom(6,6);
VERIFY_IS_APPROX_EVALUATOR(mat2, arr1.matrix());
VERIFY_IS_APPROX_EVALUATOR(arr2, mat1.array());
VERIFY_IS_APPROX_EVALUATOR(mat2, (arr1 + 2).matrix());
VERIFY_IS_APPROX_EVALUATOR(arr2, mat1.array() + 2);
mat2.array() = arr1 * arr1;
VERIFY_IS_APPROX(mat2, (arr1 * arr1).matrix());
arr2.matrix() = MatrixXd::Identity(6,6);
VERIFY_IS_APPROX(arr2, MatrixXd::Identity(6,6).array());
// test Reverse
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1.reverse());
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1.colwise().reverse());
VERIFY_IS_APPROX_EVALUATOR(arr2, arr1.rowwise().reverse());
arr2.reverse() = arr1;
VERIFY_IS_APPROX(arr2, arr1.reverse());
// test Diagonal
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.diagonal());
vec1.resize(5);
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.diagonal(1));
VERIFY_IS_APPROX_EVALUATOR(vec1, mat1.diagonal<-1>());
vec1.setRandom();
mat2 = mat1;
copy_using_evaluator(mat1.diagonal(1), vec1);
mat2.diagonal(1) = vec1;
VERIFY_IS_APPROX(mat1, mat2);
copy_using_evaluator(mat1.diagonal<-1>(), mat1.diagonal(1));
mat2.diagonal<-1>() = mat2.diagonal(1);
VERIFY_IS_APPROX(mat1, mat2);
{
// test swapping
MatrixXd mat1, mat2, mat1ref, mat2ref;
mat1ref = mat1 = MatrixXd::Random(6, 6);
mat2ref = mat2 = 2 * mat1 + MatrixXd::Identity(6, 6);
swap_using_evaluator(mat1, mat2);
mat1ref.swap(mat2ref);
VERIFY_IS_APPROX(mat1, mat1ref);
VERIFY_IS_APPROX(mat2, mat2ref);
swap_using_evaluator(mat1.block(0, 0, 3, 3), mat2.block(3, 3, 3, 3));
mat1ref.block(0, 0, 3, 3).swap(mat2ref.block(3, 3, 3, 3));
VERIFY_IS_APPROX(mat1, mat1ref);
VERIFY_IS_APPROX(mat2, mat2ref);
swap_using_evaluator(mat1.row(2), mat2.col(3).transpose());
mat1.row(2).swap(mat2.col(3).transpose());
VERIFY_IS_APPROX(mat1, mat1ref);
VERIFY_IS_APPROX(mat2, mat2ref);
}
{
// test compound assignment
const Matrix4d mat_const = Matrix4d::Random();
Matrix4d mat, mat_ref;
mat = mat_ref = Matrix4d::Identity();
add_assign_using_evaluator(mat, mat_const);
mat_ref += mat_const;
VERIFY_IS_APPROX(mat, mat_ref);
subtract_assign_using_evaluator(mat.row(1), 2*mat.row(2));
mat_ref.row(1) -= 2*mat_ref.row(2);
VERIFY_IS_APPROX(mat, mat_ref);
const ArrayXXf arr_const = ArrayXXf::Random(5,3);
ArrayXXf arr, arr_ref;
arr = arr_ref = ArrayXXf::Constant(5, 3, 0.5);
multiply_assign_using_evaluator(arr, arr_const);
arr_ref *= arr_const;
VERIFY_IS_APPROX(arr, arr_ref);
divide_assign_using_evaluator(arr.row(1), arr.row(2) + 1);
arr_ref.row(1) /= (arr_ref.row(2) + 1);
VERIFY_IS_APPROX(arr, arr_ref);
}
}
<|endoftext|> |
<commit_before>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <[email protected]>
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <qstring.h>
#include <qtoolbutton.h>
#include <qtooltip.h>
#include <kaccelmanager.h>
#include <kconfig.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include "emaileditwidget.h"
class EmailValidator : public QRegExpValidator
{
public:
EmailValidator()
: QRegExpValidator( 0, "EmailValidator" )
{
QRegExp rx( "[A-Za-z\\-\\.\\_0-9]+@[A-Za-z\\-\\.\\_0-9]+\\.[A-Za-z]+" );
setRegExp( rx );
}
};
class EmailItem : public QListBoxText
{
public:
EmailItem( QListBox *parent, const QString &text, bool preferred )
: QListBoxText( parent, text ), mPreferred( preferred )
{}
void setPreferred( bool preferred ) { mPreferred = preferred; }
bool preferred() const { return mPreferred; }
void setText( const QString &text )
{
QListBoxText::setText( text );
}
protected:
virtual void paint( QPainter *p )
{
if ( mPreferred ) {
QFont font = p->font();
font.setBold( true );
p->setFont( font );
}
QListBoxText::paint( p );
}
private:
bool mPreferred;
};
EmailEditWidget::EmailEditWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *topLayout = new QGridLayout( this, 2, 2, KDialog::marginHint(),
KDialog::spacingHint() );
QLabel *label = new QLabel( i18n( "Email:" ), this );
topLayout->addWidget( label, 0, 0 );
mEmailEdit = new KLineEdit( this );
mEmailEdit->setValidator( new EmailValidator );
connect( mEmailEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( textChanged( const QString& ) ) );
connect( mEmailEdit, SIGNAL( textChanged( const QString& ) ),
SIGNAL( modified() ) );
label->setBuddy( mEmailEdit );
topLayout->addWidget( mEmailEdit, 0, 1 );
mEditButton = new QPushButton( i18n( "Edit Email Addresses..." ), this);
connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) );
topLayout->addMultiCellWidget( mEditButton, 1, 1, 0, 1 );
topLayout->activate();
}
EmailEditWidget::~EmailEditWidget()
{
}
void EmailEditWidget::setReadOnly( bool readOnly )
{
mEmailEdit->setReadOnly( readOnly );
mEditButton->setEnabled( !readOnly );
}
void EmailEditWidget::setEmails( const QStringList &list )
{
mEmailList = list;
bool blocked = mEmailEdit->signalsBlocked();
mEmailEdit->blockSignals( true );
if ( list.count() > 0 )
mEmailEdit->setText( list[ 0 ] );
else
mEmailEdit->setText( "" );
mEmailEdit->blockSignals( blocked );
}
QStringList EmailEditWidget::emails()
{
if ( mEmailEdit->text().isEmpty() ) {
if ( mEmailList.count() > 0 )
mEmailList.remove( mEmailList.begin() );
} else {
if ( mEmailList.count() > 0 )
mEmailList.remove( mEmailList.begin() );
mEmailList.prepend( mEmailEdit->text() );
}
return mEmailList;
}
void EmailEditWidget::edit()
{
EmailEditDialog dlg( mEmailList, this );
if ( dlg.exec() ) {
if ( dlg.changed() ) {
mEmailList = dlg.emails();
mEmailEdit->setText( mEmailList[ 0 ] );
emit modified();
}
}
}
void EmailEditWidget::textChanged( const QString &text )
{
if ( mEmailList.count() > 0 )
mEmailList.remove( mEmailList.begin() );
mEmailList.prepend( text );
}
EmailEditDialog::EmailEditDialog( const QStringList &list, QWidget *parent,
const char *name )
: KDialogBase( KDialogBase::Plain, i18n( "Edit Email Addresses" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Help,
parent, name, true )
{
QWidget *page = plainPage();
QGridLayout *topLayout = new QGridLayout( page, 4, 3, 0, spacingHint() );
mEmailListBox = new QListBox( page );
// Make sure there is room for the scrollbar
mEmailListBox->setMinimumHeight( mEmailListBox->sizeHint().height() + 30 );
connect( mEmailListBox, SIGNAL( highlighted( int ) ),
SLOT( selectionChanged( int ) ) );
connect( mEmailListBox, SIGNAL( selected( int ) ),
SLOT( edit() ) );
topLayout->addMultiCellWidget( mEmailListBox, 0, 3, 0, 1 );
mAddButton = new QPushButton( i18n( "Add..." ), page );
connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) );
topLayout->addWidget( mAddButton, 0, 2 );
mEditButton = new QPushButton( i18n( "Edit..." ), page );
connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) );
topLayout->addWidget( mEditButton, 1, 2 );
mRemoveButton = new QPushButton( i18n( "Remove" ), page );
connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) );
topLayout->addWidget( mRemoveButton, 2, 2 );
mStandardButton = new QPushButton( i18n( "Set Standard" ), page );
connect( mStandardButton, SIGNAL( clicked() ), SLOT( standard() ) );
topLayout->addWidget( mStandardButton, 3, 2 );
topLayout->activate();
QStringList items = list;
if ( items.remove( "" ) > 0 )
mChanged = true;
else
mChanged = false;
QStringList::Iterator it;
bool preferred = true;
for ( it = items.begin(); it != items.end(); ++it ) {
new EmailItem( mEmailListBox, *it, preferred );
preferred = false;
}
// set default state
selectionChanged( -1 );
KAcceleratorManager::manage( this );
setInitialSize( QSize( 400, 200 ) );
}
EmailEditDialog::~EmailEditDialog()
{
}
QStringList EmailEditDialog::emails() const
{
QStringList emails;
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( i ) );
if ( item->preferred() )
emails.prepend( item->text() );
else
emails.append( item->text() );
}
return emails;
}
void EmailEditDialog::add()
{
EmailValidator *validator = new EmailValidator;
bool ok = false;
QString email = KInputDialog::getText( i18n( "Add Email" ), i18n( "New Email:" ),
QString::null, &ok, this, "EmailEditDialog",
validator );
if ( !ok )
return;
// check if item already available, ignore if so...
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
if ( mEmailListBox->text( i ) == email )
return;
}
new EmailItem( mEmailListBox, email, (mEmailListBox->count() == 0) );
mChanged = true;
}
void EmailEditDialog::edit()
{
EmailValidator *validator = new EmailValidator;
bool ok = false;
int editPos = mEmailListBox->currentItem();
QString email = KInputDialog::getText( i18n( "Edit Email" ), i18n( "Email:" ),
mEmailListBox->text( editPos ), &ok, this,
"EmailEditDialog", validator );
if ( !ok )
return;
// check if item already available, ignore if so...
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
if ( mEmailListBox->text( i ) == email )
return;
}
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( editPos ) );
item->setText( email );
mEmailListBox->triggerUpdate( true );
mChanged = true;
}
void EmailEditDialog::remove()
{
QString address = mEmailListBox->currentText();
QString text = i18n( "<qt>Are you sure that you want to remove the email address <b>%1</b>?</qt>" ).arg( address );
QString caption = i18n( "Confirm Remove" );
if ( KMessageBox::warningContinueCancel( this, text, caption, KGuiItem( i18n("&Delete"), "editdelete") ) == KMessageBox::Continue) {
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( mEmailListBox->currentItem() ) );
bool preferred = item->preferred();
mEmailListBox->removeItem( mEmailListBox->currentItem() );
if ( preferred ) {
item = dynamic_cast<EmailItem*>( mEmailListBox->item( 0 ) );
if ( item )
item->setPreferred( true );
}
mChanged = true;
}
}
bool EmailEditDialog::changed() const
{
return mChanged;
}
void EmailEditDialog::standard()
{
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( i ) );
if ( (int)i == mEmailListBox->currentItem() )
item->setPreferred( true );
else
item->setPreferred( false );
}
mEmailListBox->triggerUpdate( true );
mChanged = true;
}
void EmailEditDialog::selectionChanged( int index )
{
bool value = ( index >= 0 ); // An item is selected
mRemoveButton->setEnabled( value );
mEditButton->setEnabled( value );
mStandardButton->setEnabled( value );
}
#include "emaileditwidget.moc"
<commit_msg>Changed the mail validation regexp to allow also domain names with non-latin1 characters.<commit_after>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <[email protected]>
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <qstring.h>
#include <qtoolbutton.h>
#include <qtooltip.h>
#include <kaccelmanager.h>
#include <kconfig.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include "emaileditwidget.h"
class EmailValidator : public QRegExpValidator
{
public:
EmailValidator()
: QRegExpValidator( 0, "EmailValidator" )
{
QRegExp rx( ".*@.*\\.[A-Za-z]+" );
setRegExp( rx );
}
};
class EmailItem : public QListBoxText
{
public:
EmailItem( QListBox *parent, const QString &text, bool preferred )
: QListBoxText( parent, text ), mPreferred( preferred )
{}
void setPreferred( bool preferred ) { mPreferred = preferred; }
bool preferred() const { return mPreferred; }
void setText( const QString &text )
{
QListBoxText::setText( text );
}
protected:
virtual void paint( QPainter *p )
{
if ( mPreferred ) {
QFont font = p->font();
font.setBold( true );
p->setFont( font );
}
QListBoxText::paint( p );
}
private:
bool mPreferred;
};
EmailEditWidget::EmailEditWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *topLayout = new QGridLayout( this, 2, 2, KDialog::marginHint(),
KDialog::spacingHint() );
QLabel *label = new QLabel( i18n( "Email:" ), this );
topLayout->addWidget( label, 0, 0 );
mEmailEdit = new KLineEdit( this );
mEmailEdit->setValidator( new EmailValidator );
connect( mEmailEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( textChanged( const QString& ) ) );
connect( mEmailEdit, SIGNAL( textChanged( const QString& ) ),
SIGNAL( modified() ) );
label->setBuddy( mEmailEdit );
topLayout->addWidget( mEmailEdit, 0, 1 );
mEditButton = new QPushButton( i18n( "Edit Email Addresses..." ), this);
connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) );
topLayout->addMultiCellWidget( mEditButton, 1, 1, 0, 1 );
topLayout->activate();
}
EmailEditWidget::~EmailEditWidget()
{
}
void EmailEditWidget::setReadOnly( bool readOnly )
{
mEmailEdit->setReadOnly( readOnly );
mEditButton->setEnabled( !readOnly );
}
void EmailEditWidget::setEmails( const QStringList &list )
{
mEmailList = list;
bool blocked = mEmailEdit->signalsBlocked();
mEmailEdit->blockSignals( true );
if ( list.count() > 0 )
mEmailEdit->setText( list[ 0 ] );
else
mEmailEdit->setText( "" );
mEmailEdit->blockSignals( blocked );
}
QStringList EmailEditWidget::emails()
{
if ( mEmailEdit->text().isEmpty() ) {
if ( mEmailList.count() > 0 )
mEmailList.remove( mEmailList.begin() );
} else {
if ( mEmailList.count() > 0 )
mEmailList.remove( mEmailList.begin() );
mEmailList.prepend( mEmailEdit->text() );
}
return mEmailList;
}
void EmailEditWidget::edit()
{
EmailEditDialog dlg( mEmailList, this );
if ( dlg.exec() ) {
if ( dlg.changed() ) {
mEmailList = dlg.emails();
mEmailEdit->setText( mEmailList[ 0 ] );
emit modified();
}
}
}
void EmailEditWidget::textChanged( const QString &text )
{
if ( mEmailList.count() > 0 )
mEmailList.remove( mEmailList.begin() );
mEmailList.prepend( text );
}
EmailEditDialog::EmailEditDialog( const QStringList &list, QWidget *parent,
const char *name )
: KDialogBase( KDialogBase::Plain, i18n( "Edit Email Addresses" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Help,
parent, name, true )
{
QWidget *page = plainPage();
QGridLayout *topLayout = new QGridLayout( page, 4, 3, 0, spacingHint() );
mEmailListBox = new QListBox( page );
// Make sure there is room for the scrollbar
mEmailListBox->setMinimumHeight( mEmailListBox->sizeHint().height() + 30 );
connect( mEmailListBox, SIGNAL( highlighted( int ) ),
SLOT( selectionChanged( int ) ) );
connect( mEmailListBox, SIGNAL( selected( int ) ),
SLOT( edit() ) );
topLayout->addMultiCellWidget( mEmailListBox, 0, 3, 0, 1 );
mAddButton = new QPushButton( i18n( "Add..." ), page );
connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) );
topLayout->addWidget( mAddButton, 0, 2 );
mEditButton = new QPushButton( i18n( "Edit..." ), page );
connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) );
topLayout->addWidget( mEditButton, 1, 2 );
mRemoveButton = new QPushButton( i18n( "Remove" ), page );
connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) );
topLayout->addWidget( mRemoveButton, 2, 2 );
mStandardButton = new QPushButton( i18n( "Set Standard" ), page );
connect( mStandardButton, SIGNAL( clicked() ), SLOT( standard() ) );
topLayout->addWidget( mStandardButton, 3, 2 );
topLayout->activate();
QStringList items = list;
if ( items.remove( "" ) > 0 )
mChanged = true;
else
mChanged = false;
QStringList::Iterator it;
bool preferred = true;
for ( it = items.begin(); it != items.end(); ++it ) {
new EmailItem( mEmailListBox, *it, preferred );
preferred = false;
}
// set default state
selectionChanged( -1 );
KAcceleratorManager::manage( this );
setInitialSize( QSize( 400, 200 ) );
}
EmailEditDialog::~EmailEditDialog()
{
}
QStringList EmailEditDialog::emails() const
{
QStringList emails;
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( i ) );
if ( item->preferred() )
emails.prepend( item->text() );
else
emails.append( item->text() );
}
return emails;
}
void EmailEditDialog::add()
{
EmailValidator *validator = new EmailValidator;
bool ok = false;
QString email = KInputDialog::getText( i18n( "Add Email" ), i18n( "New Email:" ),
QString::null, &ok, this, "EmailEditDialog",
validator );
if ( !ok )
return;
// check if item already available, ignore if so...
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
if ( mEmailListBox->text( i ) == email )
return;
}
new EmailItem( mEmailListBox, email, (mEmailListBox->count() == 0) );
mChanged = true;
}
void EmailEditDialog::edit()
{
EmailValidator *validator = new EmailValidator;
bool ok = false;
int editPos = mEmailListBox->currentItem();
QString email = KInputDialog::getText( i18n( "Edit Email" ), i18n( "Email:" ),
mEmailListBox->text( editPos ), &ok, this,
"EmailEditDialog", validator );
if ( !ok )
return;
// check if item already available, ignore if so...
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
if ( mEmailListBox->text( i ) == email )
return;
}
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( editPos ) );
item->setText( email );
mEmailListBox->triggerUpdate( true );
mChanged = true;
}
void EmailEditDialog::remove()
{
QString address = mEmailListBox->currentText();
QString text = i18n( "<qt>Are you sure that you want to remove the email address <b>%1</b>?</qt>" ).arg( address );
QString caption = i18n( "Confirm Remove" );
if ( KMessageBox::warningContinueCancel( this, text, caption, KGuiItem( i18n("&Delete"), "editdelete") ) == KMessageBox::Continue) {
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( mEmailListBox->currentItem() ) );
bool preferred = item->preferred();
mEmailListBox->removeItem( mEmailListBox->currentItem() );
if ( preferred ) {
item = dynamic_cast<EmailItem*>( mEmailListBox->item( 0 ) );
if ( item )
item->setPreferred( true );
}
mChanged = true;
}
}
bool EmailEditDialog::changed() const
{
return mChanged;
}
void EmailEditDialog::standard()
{
for ( uint i = 0; i < mEmailListBox->count(); ++i ) {
EmailItem *item = static_cast<EmailItem*>( mEmailListBox->item( i ) );
if ( (int)i == mEmailListBox->currentItem() )
item->setPreferred( true );
else
item->setPreferred( false );
}
mEmailListBox->triggerUpdate( true );
mChanged = true;
}
void EmailEditDialog::selectionChanged( int index )
{
bool value = ( index >= 0 ); // An item is selected
mRemoveButton->setEnabled( value );
mEditButton->setEnabled( value );
mStandardButton->setEnabled( value );
}
#include "emaileditwidget.moc"
<|endoftext|> |
<commit_before>// BSD 2-Clause License, see github.com/ma16/rpio
#include "../rpio.h"
#include <Rpi/ArmTimer.h>
#include <Rpi/Pin.h>
#include <Rpi/Register.h>
#include <Ui/strto.h>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
static uint32_t getPins(Ui::ArgL *argL)
{
auto arg = argL->pop() ;
if (arg == "all")
return 0xffffffff ;
if (arg == "-m")
return Ui::strto<uint32_t>(argL->pop()) ;
if (arg == "-l") {
auto arg = argL->pop() ;
auto tail = arg.find(',') ;
decltype(tail) head = 0 ;
auto mask = 0u ;
while (tail != arg.npos) {
auto pin = Ui::strto(arg.substr(head,tail-head),Rpi::Pin()) ;
mask |= (1u << pin.value()) ;
head = tail + 1 ;
tail = arg.find(',',head) ;
}
auto pin = Ui::strto(arg.substr(head),Rpi::Pin()) ;
mask |= (1u << pin.value()) ;
return mask ;
}
auto pin = Ui::strto(arg,Rpi::Pin()) ;
return (1u << pin.value()) ;
}
// [todo] deduplicate
// --------------------------------------------------------------------
static std::string mkhdr(uint32_t mask)
{
std::ostringstream os ;
for (auto i=0 ; i<32 ; ++i)
if (mask & (1u<<i))
os << i/10 << ' ' ;
os << '\n' ;
for (auto i=0 ; i<32 ; ++i)
if (mask & (1u<<i))
os << i%10 << ' ' ;
return os.str() ;
}
static std::string mksep(uint32_t mask)
{
std::ostringstream os ;
for (auto i=0 ; i<32 ; ++i)
if (mask & (1u<<i))
os << "--" ;
return os.str() ;
}
static std::string mkstr(uint32_t mask,uint32_t bits)
{
char s[32*2] ;
auto ofs = 0u ;
for (uint32_t m=1u ; m!=0 ; m<<=1) {
if (m & mask) {
s[ofs++] = (bits & m) ? '1' : '0' ;
s[ofs++] = ' ' ;
}
}
return std::string(s,ofs) ;
}
// [todo] deduplicate
// --------------------------------------------------------------------
static void countInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ;
// [future] does also work with a pin mask
auto nsamples = Ui::strto<unsigned>(argL->pop()) ;
auto dry = argL->pop_if("-d") ;
argL->finalize() ;
auto gpio = rpi->page<Rpi::Register::Gpio::PageNo>() ;
auto status = gpio.at<Rpi::Register::Gpio::Event::Status0>().value() ;
auto mask = 1u << pin.value() ;
decltype(nsamples) nevents = 0 ;
decltype(nsamples) nsubseq = 0 ;
auto t0 = std::chrono::steady_clock::now() ;
if (dry)
{
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
auto w = mask & (*status) ;
if (w != 0)
(*status) = w ;
}
}
else
{
auto active = false ;
(*status) = mask ;
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
auto w = mask & (*status) ;
if (w != 0)
{
(*status) = w ;
++nevents ;
if (active) ++nsubseq ;
else active = true ;
}
else active = false ;
}
}
auto tn = std::chrono::steady_clock::now() ;
auto dt = std::chrono::duration<double>(tn-t0).count() ;
std::cout.setf(std::ios::scientific) ;
std::cout.precision(2) ;
std::cout << "f=" << static_cast<double>(nsamples)/dt << "/s "
<< "signal=" << static_cast<double>( nevents)/dt << "/s "
<< "subseq=" << static_cast<double>( nsubseq)/dt << "/s\n" ;
}
// --------------------------------------------------------------------
static void dutyInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ;
auto nsamples = Ui::strto<unsigned>(argL->pop()) ;
auto dry = argL->pop_if("-d") ;
argL->finalize() ;
auto input = rpi->at<Rpi::Register::Gpio::Input::Bank0>().value() ;
auto mask = 1u << pin.value() ;
decltype(nsamples) nchanges = 0 ;
decltype(nsamples) nhis = 0 ;
auto level = mask & (*input) ;
auto t0 = std::chrono::steady_clock::now() ;
if (dry) {
for (decltype(nsamples) i=0 ; i<nsamples ; ++i) {
level ^= mask & (*input) ;
}
auto volatile x = level ; (void)x ;
}
else {
for (decltype(nsamples) i=0 ; i<nsamples ; ++i) {
auto next = mask & (*input) ;
if (next != level) {
level = next ;
++nchanges ;
}
if (next)
++nhis ;
}
}
auto tn = std::chrono::steady_clock::now() ;
auto dt = std::chrono::duration<double>(tn-t0).count() ;
std::cout.setf(std::ios::scientific) ;
std::cout.precision(6) ;
std::cout << "f=" << static_cast<double>(nsamples)/dt << "/s "
<< "signal=" << static_cast<double>(nchanges)/dt << "/s "
<< "duty=" << static_cast<double>(nhis) / static_cast<double>(nsamples) << std::endl ;
}
// --------------------------------------------------------------------
static void pulseInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ;
argL->finalize() ;
auto gpio = rpi->page<Rpi::Register::Gpio::PageNo>() ;
Rpi::ArmTimer timer(rpi) ;
auto mask = 1u << pin.value() ;
namespace Register = Rpi::Register::Gpio::Event ;
auto wait4edge = [&](uint32_t *t0,uint32_t *t1)
{
auto status = gpio.at<Register::Status0>().value() ;
(*status) = mask ;
while (0 == (mask & (*status)))
(*t0) = timer.counter().read() ;
(*t1) = timer.counter().read() ;
} ;
auto t0=timer.counter().read() ; decltype(t0) t1 ;
auto rise = gpio.at<Register::Rise0>().value() ;
(*rise) |= mask ;
wait4edge(&t0,&t1) ;
(*rise) &= ~mask ;
auto t2 = t1 ; decltype(t2) t3 ;
auto fall = gpio.at<Register::Fall0>().value() ;
(*fall) |= mask ;
wait4edge(&t2,&t3) ;
(*fall) &= ~mask ;
auto t4 = t3 ; decltype(t4) t5 ;
(*rise) |= mask ;
wait4edge(&t4,&t5) ;
(*rise) &= ~mask ;
std::cout << 0 << '+' << (t1-t0) << ' '
<< (t2-t0) << '+' << (t3-t2) << ' '
<< (t4-t0) << '+' << (t5-t4) << '\n' ;
}
// --------------------------------------------------------------------
struct Record
{
uint32_t t0,t1,levels ;
Record(uint32_t t0,uint32_t t1,uint32_t levels) : t0(t0),t1(t1),levels(levels) {}
Record() : t0(0),t1(0),levels(0) {}
} ;
static void watchInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pins = getPins(argL) ;
auto nsamples = Ui::strto<unsigned>(argL->pop()) ;
argL->finalize() ;
auto input = rpi->at<Rpi::Register::Gpio::Input::Bank0>().value() ;
Rpi::ArmTimer timer(rpi) ;
std::vector<Record> v(0x10000) ; v.resize(0) ;
auto t0 = timer.counter().read() ;
auto levels = pins & (*input) ;
auto t1 = timer.counter().read() ;
v.push_back(Record(0,t1-t0,levels)) ;
for (decltype(nsamples) i=0 ; i<nsamples ; ++i) {
auto ti = timer.counter().read() ;
auto next = pins & (*input) ;
if (levels != next) {
auto tj = timer.counter().read() ;
levels = next ;
v.push_back(Record(ti-t0,tj-ti,levels)) ;
t0 = ti ;
}
}
std::cout << mkhdr(pins) << '\n'
<< mksep(pins) << '\n' ;
for (auto &r: v) {
std::cout << mkstr(pins,r.levels) << r.t0 << ' ' << r.t1 << '\n' ;
}
}
void Console::Sample::invoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
if (argL->empty() || argL->peek() == "help") {
std::cout << "arguments: MODE PIN NSAMPLES [-d]\n"
<< '\n'
<< "displays the sampling rate (f) and the signal rate"
<< '\n'
<< "MODE : count # count number of subsequent events\n"
<< " | duty # determine signal's duty cycle\n"
<< " | pulse # determine signal's pulse length\n"
<< '\n'
<< "-d : dry run to determine maximum sampling rate f\n"
<< std::flush ;
return ;
}
std::string arg = argL->pop() ;
if (arg == "count") { countInvoke(rpi,argL) ; }
else if (arg == "duty") { dutyInvoke(rpi,argL) ; }
else if (arg == "pulse") { pulseInvoke(rpi,argL) ; }
else if (arg == "watch") { watchInvoke(rpi,argL) ; }
else throw std::runtime_error("not supported option:<"+arg+'>') ;
}
<commit_msg>re-format source code<commit_after>// BSD 2-Clause License, see github.com/ma16/rpio
#include "../rpio.h"
#include <Rpi/ArmTimer.h>
#include <Rpi/Pin.h>
#include <Rpi/Register.h>
#include <Ui/strto.h>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
static uint32_t getPins(Ui::ArgL *argL)
{
auto arg = argL->pop() ;
if (arg == "all")
return 0xffffffff ;
if (arg == "-m")
return Ui::strto<uint32_t>(argL->pop()) ;
if (arg == "-l")
{
auto arg = argL->pop() ;
auto tail = arg.find(',') ;
decltype(tail) head = 0 ;
auto mask = 0u ;
while (tail != arg.npos)
{
auto pin = Ui::strto(arg.substr(head,tail-head),Rpi::Pin()) ;
mask |= (1u << pin.value()) ;
head = tail + 1 ;
tail = arg.find(',',head) ;
}
auto pin = Ui::strto(arg.substr(head),Rpi::Pin()) ;
mask |= (1u << pin.value()) ;
return mask ;
}
auto pin = Ui::strto(arg,Rpi::Pin()) ;
return (1u << pin.value()) ;
}
// [todo] deduplicate
// --------------------------------------------------------------------
static std::string mkhdr(uint32_t mask)
{
std::ostringstream os ;
for (auto i=0 ; i<32 ; ++i)
if (mask & (1u<<i))
os << i/10 << ' ' ;
os << '\n' ;
for (auto i=0 ; i<32 ; ++i)
if (mask & (1u<<i))
os << i%10 << ' ' ;
return os.str() ;
}
static std::string mksep(uint32_t mask)
{
std::ostringstream os ;
for (auto i=0 ; i<32 ; ++i)
if (mask & (1u<<i))
os << "--" ;
return os.str() ;
}
static std::string mkstr(uint32_t mask,uint32_t bits)
{
char s[32*2] ;
auto ofs = 0u ;
for (uint32_t m=1u ; m!=0 ; m<<=1)
{
if (m & mask)
{
s[ofs++] = (bits & m) ? '1' : '0' ;
s[ofs++] = ' ' ;
}
}
return std::string(s,ofs) ;
}
// [todo] deduplicate
// --------------------------------------------------------------------
static void countInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ;
// [future] does also work with a pin mask
auto nsamples = Ui::strto<unsigned>(argL->pop()) ;
auto dry = argL->pop_if("-d") ;
argL->finalize() ;
auto gpio = rpi->page<Rpi::Register::Gpio::PageNo>() ;
auto status = gpio.at<Rpi::Register::Gpio::Event::Status0>().value() ;
auto mask = 1u << pin.value() ;
decltype(nsamples) nevents = 0 ;
decltype(nsamples) nsubseq = 0 ;
auto t0 = std::chrono::steady_clock::now() ;
if (dry)
{
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
auto w = mask & (*status) ;
if (w != 0)
(*status) = w ;
}
}
else
{
auto active = false ;
(*status) = mask ;
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
auto w = mask & (*status) ;
if (w != 0)
{
(*status) = w ;
++nevents ;
if (active) ++nsubseq ;
else active = true ;
}
else active = false ;
}
}
auto tn = std::chrono::steady_clock::now() ;
auto dt = std::chrono::duration<double>(tn-t0).count() ;
std::cout.setf(std::ios::scientific) ;
std::cout.precision(2) ;
std::cout << "f=" << static_cast<double>(nsamples)/dt << "/s "
<< "signal=" << static_cast<double>( nevents)/dt << "/s "
<< "subseq=" << static_cast<double>( nsubseq)/dt << "/s\n" ;
}
// --------------------------------------------------------------------
static void dutyInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ;
auto nsamples = Ui::strto<unsigned>(argL->pop()) ;
auto dry = argL->pop_if("-d") ;
argL->finalize() ;
auto input = rpi->at<Rpi::Register::Gpio::Input::Bank0>().value() ;
auto mask = 1u << pin.value() ;
decltype(nsamples) nchanges = 0 ;
decltype(nsamples) nhis = 0 ;
auto level = mask & (*input) ;
auto t0 = std::chrono::steady_clock::now() ;
if (dry)
{
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
level ^= mask & (*input) ;
}
auto volatile x = level ; (void)x ;
}
else {
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
auto next = mask & (*input) ;
if (next != level)
{
level = next ;
++nchanges ;
}
if (next)
++nhis ;
}
}
auto tn = std::chrono::steady_clock::now() ;
auto dt = std::chrono::duration<double>(tn-t0).count() ;
std::cout.setf(std::ios::scientific) ;
std::cout.precision(6) ;
std::cout << "f=" << static_cast<double>(nsamples)/dt << "/s "
<< "signal=" << static_cast<double>(nchanges)/dt << "/s "
<< "duty=" << static_cast<double>(nhis) / static_cast<double>(nsamples) << std::endl ;
}
// --------------------------------------------------------------------
static void pulseInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ;
argL->finalize() ;
auto gpio = rpi->page<Rpi::Register::Gpio::PageNo>() ;
Rpi::ArmTimer timer(rpi) ;
auto mask = 1u << pin.value() ;
namespace Register = Rpi::Register::Gpio::Event ;
auto wait4edge = [&](uint32_t *t0,uint32_t *t1)
{
auto status = gpio.at<Register::Status0>().value() ;
(*status) = mask ;
while (0 == (mask & (*status)))
(*t0) = timer.counter().read() ;
(*t1) = timer.counter().read() ;
} ;
auto t0=timer.counter().read() ; decltype(t0) t1 ;
auto rise = gpio.at<Register::Rise0>().value() ;
(*rise) |= mask ;
wait4edge(&t0,&t1) ;
(*rise) &= ~mask ;
auto t2 = t1 ; decltype(t2) t3 ;
auto fall = gpio.at<Register::Fall0>().value() ;
(*fall) |= mask ;
wait4edge(&t2,&t3) ;
(*fall) &= ~mask ;
auto t4 = t3 ; decltype(t4) t5 ;
(*rise) |= mask ;
wait4edge(&t4,&t5) ;
(*rise) &= ~mask ;
std::cout << 0 << '+' << (t1-t0) << ' '
<< (t2-t0) << '+' << (t3-t2) << ' '
<< (t4-t0) << '+' << (t5-t4) << '\n' ;
}
// --------------------------------------------------------------------
struct Record
{
uint32_t t0,t1,levels ;
Record(uint32_t t0,uint32_t t1,uint32_t levels)
: t0(t0),t1(t1),levels(levels) {}
Record() : t0(0),t1(0),levels(0) {}
} ;
static void watchInvoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
auto pins = getPins(argL) ;
auto nsamples = Ui::strto<unsigned>(argL->pop()) ;
argL->finalize() ;
auto input = rpi->at<Rpi::Register::Gpio::Input::Bank0>().value() ;
Rpi::ArmTimer timer(rpi) ;
std::vector<Record> v(0x10000) ; v.resize(0) ;
auto t0 = timer.counter().read() ;
auto levels = pins & (*input) ;
auto t1 = timer.counter().read() ;
v.push_back(Record(0,t1-t0,levels)) ;
for (decltype(nsamples) i=0 ; i<nsamples ; ++i)
{
auto ti = timer.counter().read() ;
auto next = pins & (*input) ;
if (levels != next)
{
auto tj = timer.counter().read() ;
levels = next ;
v.push_back(Record(ti-t0,tj-ti,levels)) ;
t0 = ti ;
}
}
std::cout << mkhdr(pins) << '\n'
<< mksep(pins) << '\n' ;
for (auto &r: v)
{
std::cout << mkstr(pins,r.levels) << r.t0 << ' ' << r.t1 << '\n' ;
}
}
void Console::Sample::invoke(Rpi::Peripheral *rpi,Ui::ArgL *argL)
{
if (argL->empty() || argL->peek() == "help")
{
std::cout
<< "arguments: MODE PIN NSAMPLES [-d]\n"
<< '\n'
<< "displays the sampling rate (f) and the signal rate"
<< '\n'
<< "MODE : count # count number of subsequent events\n"
<< " | duty # determine signal's duty cycle\n"
<< " | pulse # determine signal's pulse length\n"
<< '\n'
<< "-d : dry run to determine maximum sampling rate f\n"
;
return ;
}
std::string arg = argL->pop() ;
if (arg == "count") { countInvoke(rpi,argL) ; }
else if (arg == "duty") { dutyInvoke(rpi,argL) ; }
else if (arg == "pulse") { pulseInvoke(rpi,argL) ; }
else if (arg == "watch") { watchInvoke(rpi,argL) ; }
else throw std::runtime_error("not supported option:<"+arg+'>') ;
}
<|endoftext|> |
<commit_before><commit_msg>Sort the stack.<commit_after><|endoftext|> |
<commit_before>/*
* load-file.cc
*
* Utility helper function -- load scheme code from a file
* Copyright (c) 2008 Linas Vepstas <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_GUILE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <boost/filesystem/operations.hpp>
#include <opencog/guile/SchemeEval.h>
#include <opencog/util/Config.h>
#include <opencog/util/files.h>
#include <opencog/util/Logger.h>
#include <opencog/util/misc.h>
namespace opencog {
/**
* Load scheme code from a file.
* The code will be loaded into a running instance of the evaluator.
* Parsing errors will be printed to stderr.
*
* Return errno if file cannot be opened.
*/
int load_scm_file (AtomSpace& as, const std::string& filename)
{
SchemeEval evaluator(&as);
evaluator.begin_eval();
std::string load_exp("(load \"");
load_exp += filename + "\")";
evaluator.eval_expr(load_exp.c_str());
std::string rv = evaluator.poll_result();
if (evaluator.eval_error()) {
printf("Error: %s\n", rv.c_str());
return 1;
}
return 0;
}
/**
* Load scheme file, with the filename specified as a relative path,
* and the search paths prepended to the relative path. If the search
* paths are null, a list of defaults search paths are used.
*/
int load_scm_file_relative (AtomSpace& as, const std::string& filename,
std::vector<std::string> search_paths)
{
if (search_paths.empty()) {
// Sometimes paths are given without the "opencog" part.
// Also check the build directory for autogen'ed files.
// XXX This is fairly tacky/broken, and needs a better fix.
for (auto p : DEFAULT_MODULE_PATHS) {
search_paths.push_back(p);
search_paths.push_back(p + "/examples/rule-engine");
search_paths.push_back(p + "/opencog");
search_paths.push_back(p + "/build");
search_paths.push_back(p + "/build/opencog");
}
}
int rc = 2;
for (const std::string& search_path : search_paths) {
boost::filesystem::path modulePath(search_path);
modulePath /= filename;
logger().fine("Searching path %s", modulePath.string().c_str());
if (boost::filesystem::exists(modulePath)) {
rc = load_scm_file(as, modulePath.string());
if (0 == rc) {
logger().info("Loaded %s", modulePath.string().c_str());
break;
}
}
}
if (rc)
{
logger().warn("Failed to load file %s: %d %s",
filename.c_str(), rc, strerror(rc));
}
return rc;
}
/**
* Pull the names of scm files out of the config file, the SCM_PRELOAD
* key, and try to load those, relative to the search paths.
*/
void load_scm_files_from_config(AtomSpace& atomSpace,
std::vector<std::string> search_paths)
{
// Load scheme modules specified in the config file
std::vector<std::string> scm_modules;
tokenize(config()["SCM_PRELOAD"], std::back_inserter(scm_modules), ", ");
for (const std::string& scm_module : scm_modules)
load_scm_file_relative(atomSpace, scm_module, search_paths);
}
}
#endif /* HAVE_GUILE */
<commit_msg>Remove insanely cheesy rule-engine hack!<commit_after>/*
* load-file.cc
*
* Utility helper function -- load scheme code from a file
* Copyright (c) 2008 Linas Vepstas <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_GUILE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <boost/filesystem/operations.hpp>
#include <opencog/guile/SchemeEval.h>
#include <opencog/util/Config.h>
#include <opencog/util/files.h>
#include <opencog/util/Logger.h>
#include <opencog/util/misc.h>
namespace opencog {
/**
* Load scheme code from a file.
* The code will be loaded into a running instance of the evaluator.
* Parsing errors will be printed to stderr.
*
* Return errno if file cannot be opened.
*/
int load_scm_file (AtomSpace& as, const std::string& filename)
{
SchemeEval evaluator(&as);
evaluator.begin_eval();
std::string load_exp("(load \"");
load_exp += filename + "\")";
evaluator.eval_expr(load_exp.c_str());
std::string rv = evaluator.poll_result();
if (evaluator.eval_error()) {
printf("Error: %s\n", rv.c_str());
return 1;
}
return 0;
}
/**
* Load scheme file, with the filename specified as a relative path,
* and the search paths prepended to the relative path. If the search
* paths are null, a list of defaults search paths are used.
*
* XXX FIXME DEPRECATED! -- DO NOT USE IN NEW CODE!
*/
int load_scm_file_relative (AtomSpace& as, const std::string& filename,
std::vector<std::string> search_paths)
{
if (search_paths.empty()) {
// Sometimes paths are given without the "opencog" part.
// Also check the build directory for autogen'ed files.
// XXX This is fairly tacky/broken, and needs a better fix.
for (auto p : DEFAULT_MODULE_PATHS) {
search_paths.push_back(p);
search_paths.push_back(p + "/opencog");
search_paths.push_back(p + "/build");
search_paths.push_back(p + "/build/opencog");
}
}
int rc = 2;
for (const std::string& search_path : search_paths) {
boost::filesystem::path modulePath(search_path);
modulePath /= filename;
logger().fine("Searching path %s", modulePath.string().c_str());
if (boost::filesystem::exists(modulePath)) {
rc = load_scm_file(as, modulePath.string());
if (0 == rc) {
logger().info("Loaded %s", modulePath.string().c_str());
break;
}
}
}
if (rc)
{
logger().warn("Failed to load file %s: %d %s",
filename.c_str(), rc, strerror(rc));
}
return rc;
}
/**
* Pull the names of scm files out of the config file, the SCM_PRELOAD
* key, and try to load those, relative to the search paths.
*
* XXX FIXME DEPRECATED! -- DO NOT USE IN NEW CODE!
*/
void load_scm_files_from_config(AtomSpace& atomSpace,
std::vector<std::string> search_paths)
{
// Load scheme modules specified in the config file
std::vector<std::string> scm_modules;
tokenize(config()["SCM_PRELOAD"], std::back_inserter(scm_modules), ", ");
for (const std::string& scm_module : scm_modules)
load_scm_file_relative(atomSpace, scm_module, search_paths);
}
}
#endif /* HAVE_GUILE */
<|endoftext|> |
<commit_before>#include "agent.h"
#include <string.h>
#include "helper.h"
using namespace v8;
v8::Persistent<v8::Function> Agent::constructor;
// lifecycle stuff
void Agent::init(v8::Handle<v8::Object> exports) {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("NiceAgent"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// protoype
NODE_SET_PROTOTYPE_METHOD(tpl, "createStream", createStream);
NODE_SET_PROTOTYPE_METHOD(tpl, "setStunServer", setStunServer);
NODE_SET_PROTOTYPE_METHOD(tpl, "setSoftware", setSoftware);
NODE_SET_PROTOTYPE_METHOD(tpl, "setControlling", setControlling);
NODE_SET_PROTOTYPE_METHOD(tpl, "resetart", restart);
constructor = Persistent<Function>::New(tpl->GetFunction());
// export
exports->Set(String::NewSymbol("NiceAgent"), constructor);
}
Agent::Agent() {
DEBUG("agent created");
//nice_debug_enable(true);
// initialize async worker
uv_async_init(uv_default_loop(), &_async, doWork);
_async.data = this;
// create glib stuff and agent
auto context = g_main_context_new();
_loop = g_main_loop_new(context, FALSE);
_agent = nice_agent_new(context, NICE_COMPATIBILITY_RFC5245);
// register callbacks
g_signal_connect(G_OBJECT(_agent), "candidate-gathering-done", G_CALLBACK(gatheringDone), this);
g_signal_connect(G_OBJECT(_agent), "component-state-changed", G_CALLBACK(stateChanged), this);
// this creates a new thread, secure your v8 calls!
_thread = std::thread([=]() {
g_main_loop_run(_loop);
g_main_loop_unref(_loop);
g_main_context_unref(context);
_loop = NULL;
});
}
Agent::~Agent() {
DEBUG("agent is dying");
uv_close((uv_handle_t*) &_async, NULL);
g_object_unref(_agent);
_agent = NULL;
g_main_loop_quit(_loop);
_thread.join();
DEBUG("agent loop finished");
}
bool Agent::removeStream(int stream_id) {
nice_agent_remove_stream(_agent, stream_id);
return _streams.erase(stream_id) > 0;
}
// do js work in right thread
void Agent::addWork(const work_fun& fun) {
std::lock_guard<std::mutex> guard(_work_mutex);
_work_queue.push_back(fun);
uv_async_send(&_async);
}
void Agent::doWork(uv_async_t *async, int status) {
Agent *agent = (Agent*) async->data;
std::lock_guard<std::mutex> guard(agent->_work_mutex);
DEBUG("doing work");
while(agent->_work_queue.size()) {
agent->_work_queue.front()();
agent->_work_queue.pop_front();
}
}
// js functions
v8::Handle<v8::Value> Agent::New(const v8::Arguments& args) {
HandleScope scope;
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
Agent* obj = new Agent();
obj->Wrap(args.This());
if(!args[0]->IsUndefined()) {
setStunServer(args);
}
return args.This();
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[1] = { argv[0] };
return scope.Close(constructor->NewInstance(argc, argv));
}
}
v8::Handle<v8::Value> Agent::createStream(const v8::Arguments& args) {
HandleScope scope;
// get native handles ...
Agent *agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject());
NiceAgent *nice_agent = agent->agent();
// create nice stream
int components = args[0]->IsUndefined() ? 1 : args[0]->IntegerValue();
int stream_id = nice_agent_add_stream(nice_agent, components);
// create stream object
const int argc = 3;
Local<Value> argv[argc] = {
args.This(),
Integer::New(stream_id),
Integer::New(components)
};
Local<Object> stream = Stream::constructor->NewInstance(argc, argv);
// register receive callback
auto context = g_main_loop_get_context(agent->_loop);
for(int i = 1; i <= components; ++i) {
nice_agent_attach_recv(nice_agent, stream_id, i, context, receive, agent);
}
// save stream for callback handling
Stream *obj = node::ObjectWrap::Unwrap<Stream>(stream);
agent->_streams[stream_id] = obj;
return scope.Close(stream);
}
v8::Handle<v8::Value> Agent::setStunServer(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
// set server address
v8::String::Utf8Value address(args[0]->ToString());
GValue g_addr = G_VALUE_INIT;
g_value_init(&g_addr, G_TYPE_STRING);
g_value_set_string(&g_addr, *address);
g_object_set_property(G_OBJECT(nice_agent), "stun-server", &g_addr);
// set port if given
if(!args[1]->IsUndefined()) {
GValue g_port = G_VALUE_INIT;
g_value_init(&g_port, G_TYPE_UINT);
g_value_set_uint(&g_port, args[1]->IntegerValue());
g_object_set_property(G_OBJECT(nice_agent), "stun-server-port", &g_port);
}
return scope.Close(Undefined());
}
v8::Handle<v8::Value> Agent::restart(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
bool res = nice_agent_restart(nice_agent);
return scope.Close(Boolean::New(res));
}
v8::Handle<v8::Value> Agent::setSoftware(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
v8::String::Utf8Value software(args[0]->ToString());
nice_agent_set_software(nice_agent, *software);
return scope.Close(Undefined());
}
v8::Handle<v8::Value> Agent::setControlling(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
bool controlling = args[0]->BooleanValue();
GValue g_controlling = G_VALUE_INIT;
g_value_init(&g_controlling, G_TYPE_BOOLEAN);
g_value_set_boolean(&g_controlling, controlling);
g_object_set_property(G_OBJECT(nice_agent), "controlling-mode", &g_controlling);
return scope.Close(Undefined());
}
// callbacks
void Agent::gatheringDone(NiceAgent *nice_agent, guint stream_id, gpointer user_data) {
Agent *agent = reinterpret_cast<Agent*>(user_data);
DEBUG("gathering done on stream " << stream_id);
agent->addWork([=]() {
auto it = agent->_streams.find(stream_id);
if(it != agent->_streams.end()) {
it->second->gatheringDone();
} else {
DEBUG("gathering done on unknown stream");
}
});
}
void Agent::stateChanged(NiceAgent *nice_agent, guint stream_id, guint component_id, guint state, gpointer user_data) {
Agent *agent = reinterpret_cast<Agent*>(user_data);
DEBUG("state changed to " << state << " on component " << component_id << " of stream " << stream_id);
agent->addWork([=]() {
auto it = agent->_streams.find(stream_id);
if(it != agent->_streams.end()) {
it->second->stateChanged(component_id, state);
} else {
DEBUG("state changed on unknown stream");
}
});
}
void Agent::receive(NiceAgent* nice_agent, guint stream_id, guint component_id, guint len, gchar* buf, gpointer user_data) {
Agent *agent = reinterpret_cast<Agent*>(user_data);
DEBUG("receiving " << len << " bytes on component " << component_id << " of stream " << stream_id);
// TODO: this might not be the best solution ...
char *tmp_buf = (char*) malloc(len);
memcpy(tmp_buf, buf, len);
agent->addWork([=]() {
auto it = agent->_streams.find(stream_id);
if(it != agent->_streams.end()) {
it->second->receive(component_id, buf, len);
} else {
DEBUG("receiving on unknown stream");
}
free(tmp_buf);
});
}
<commit_msg>Actually use tmp_buf in Agent::receive()<commit_after>#include "agent.h"
#include <string.h>
#include "helper.h"
using namespace v8;
v8::Persistent<v8::Function> Agent::constructor;
// lifecycle stuff
void Agent::init(v8::Handle<v8::Object> exports) {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("NiceAgent"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// protoype
NODE_SET_PROTOTYPE_METHOD(tpl, "createStream", createStream);
NODE_SET_PROTOTYPE_METHOD(tpl, "setStunServer", setStunServer);
NODE_SET_PROTOTYPE_METHOD(tpl, "setSoftware", setSoftware);
NODE_SET_PROTOTYPE_METHOD(tpl, "setControlling", setControlling);
NODE_SET_PROTOTYPE_METHOD(tpl, "resetart", restart);
constructor = Persistent<Function>::New(tpl->GetFunction());
// export
exports->Set(String::NewSymbol("NiceAgent"), constructor);
}
Agent::Agent() {
DEBUG("agent created");
//nice_debug_enable(true);
// initialize async worker
uv_async_init(uv_default_loop(), &_async, doWork);
_async.data = this;
// create glib stuff and agent
auto context = g_main_context_new();
_loop = g_main_loop_new(context, FALSE);
_agent = nice_agent_new(context, NICE_COMPATIBILITY_RFC5245);
// register callbacks
g_signal_connect(G_OBJECT(_agent), "candidate-gathering-done", G_CALLBACK(gatheringDone), this);
g_signal_connect(G_OBJECT(_agent), "component-state-changed", G_CALLBACK(stateChanged), this);
// this creates a new thread, secure your v8 calls!
_thread = std::thread([=]() {
g_main_loop_run(_loop);
g_main_loop_unref(_loop);
g_main_context_unref(context);
_loop = NULL;
});
}
Agent::~Agent() {
DEBUG("agent is dying");
uv_close((uv_handle_t*) &_async, NULL);
g_object_unref(_agent);
_agent = NULL;
g_main_loop_quit(_loop);
_thread.join();
DEBUG("agent loop finished");
}
bool Agent::removeStream(int stream_id) {
nice_agent_remove_stream(_agent, stream_id);
return _streams.erase(stream_id) > 0;
}
// do js work in right thread
void Agent::addWork(const work_fun& fun) {
std::lock_guard<std::mutex> guard(_work_mutex);
_work_queue.push_back(fun);
uv_async_send(&_async);
}
void Agent::doWork(uv_async_t *async, int status) {
Agent *agent = (Agent*) async->data;
std::lock_guard<std::mutex> guard(agent->_work_mutex);
DEBUG("doing work");
while(agent->_work_queue.size()) {
agent->_work_queue.front()();
agent->_work_queue.pop_front();
}
}
// js functions
v8::Handle<v8::Value> Agent::New(const v8::Arguments& args) {
HandleScope scope;
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
Agent* obj = new Agent();
obj->Wrap(args.This());
if(!args[0]->IsUndefined()) {
setStunServer(args);
}
return args.This();
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[1] = { argv[0] };
return scope.Close(constructor->NewInstance(argc, argv));
}
}
v8::Handle<v8::Value> Agent::createStream(const v8::Arguments& args) {
HandleScope scope;
// get native handles ...
Agent *agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject());
NiceAgent *nice_agent = agent->agent();
// create nice stream
int components = args[0]->IsUndefined() ? 1 : args[0]->IntegerValue();
int stream_id = nice_agent_add_stream(nice_agent, components);
// create stream object
const int argc = 3;
Local<Value> argv[argc] = {
args.This(),
Integer::New(stream_id),
Integer::New(components)
};
Local<Object> stream = Stream::constructor->NewInstance(argc, argv);
// register receive callback
auto context = g_main_loop_get_context(agent->_loop);
for(int i = 1; i <= components; ++i) {
nice_agent_attach_recv(nice_agent, stream_id, i, context, receive, agent);
}
// save stream for callback handling
Stream *obj = node::ObjectWrap::Unwrap<Stream>(stream);
agent->_streams[stream_id] = obj;
return scope.Close(stream);
}
v8::Handle<v8::Value> Agent::setStunServer(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
// set server address
v8::String::Utf8Value address(args[0]->ToString());
GValue g_addr = G_VALUE_INIT;
g_value_init(&g_addr, G_TYPE_STRING);
g_value_set_string(&g_addr, *address);
g_object_set_property(G_OBJECT(nice_agent), "stun-server", &g_addr);
// set port if given
if(!args[1]->IsUndefined()) {
GValue g_port = G_VALUE_INIT;
g_value_init(&g_port, G_TYPE_UINT);
g_value_set_uint(&g_port, args[1]->IntegerValue());
g_object_set_property(G_OBJECT(nice_agent), "stun-server-port", &g_port);
}
return scope.Close(Undefined());
}
v8::Handle<v8::Value> Agent::restart(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
bool res = nice_agent_restart(nice_agent);
return scope.Close(Boolean::New(res));
}
v8::Handle<v8::Value> Agent::setSoftware(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
v8::String::Utf8Value software(args[0]->ToString());
nice_agent_set_software(nice_agent, *software);
return scope.Close(Undefined());
}
v8::Handle<v8::Value> Agent::setControlling(const v8::Arguments& args) {
HandleScope scope;
NiceAgent *nice_agent = node::ObjectWrap::Unwrap<Agent>(args.This()->ToObject())->agent();
bool controlling = args[0]->BooleanValue();
GValue g_controlling = G_VALUE_INIT;
g_value_init(&g_controlling, G_TYPE_BOOLEAN);
g_value_set_boolean(&g_controlling, controlling);
g_object_set_property(G_OBJECT(nice_agent), "controlling-mode", &g_controlling);
return scope.Close(Undefined());
}
// callbacks
void Agent::gatheringDone(NiceAgent *nice_agent, guint stream_id, gpointer user_data) {
Agent *agent = reinterpret_cast<Agent*>(user_data);
DEBUG("gathering done on stream " << stream_id);
agent->addWork([=]() {
auto it = agent->_streams.find(stream_id);
if(it != agent->_streams.end()) {
it->second->gatheringDone();
} else {
DEBUG("gathering done on unknown stream");
}
});
}
void Agent::stateChanged(NiceAgent *nice_agent, guint stream_id, guint component_id, guint state, gpointer user_data) {
Agent *agent = reinterpret_cast<Agent*>(user_data);
DEBUG("state changed to " << state << " on component " << component_id << " of stream " << stream_id);
agent->addWork([=]() {
auto it = agent->_streams.find(stream_id);
if(it != agent->_streams.end()) {
it->second->stateChanged(component_id, state);
} else {
DEBUG("state changed on unknown stream");
}
});
}
void Agent::receive(NiceAgent* nice_agent, guint stream_id, guint component_id, guint len, gchar* buf, gpointer user_data) {
Agent *agent = reinterpret_cast<Agent*>(user_data);
DEBUG("receiving " << len << " bytes on component " << component_id << " of stream " << stream_id);
// TODO: this might not be the best solution ...
char *tmp_buf = (char*) malloc(len);
memcpy(tmp_buf, buf, len);
agent->addWork([=]() {
auto it = agent->_streams.find(stream_id);
if(it != agent->_streams.end()) {
it->second->receive(component_id, tmp_buf, len);
} else {
DEBUG("receiving on unknown stream");
}
free(tmp_buf);
});
}
<|endoftext|> |
<commit_before>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2013 EOS di Manlio Morini.
*
* \license
* 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/
*/
#include <boost/lexical_cast.hpp>
#include "kernel/argument.h"
#include "kernel/gene.h"
#include "kernel/interpreter.h"
namespace vita
{
///
/// \param[in] n argument index.
///
/// An adf function may have up to \a k_args arguments. Arguments' category is
/// special (here it is initialized with \c 0 but we could say they haven't a
/// type) because arguments are communication channels among adf functions
/// and their calling environments. So the type that is travelling on channel
/// \c i (argument(i)) varies depending on the function being evaluated
/// (instead, adf functions have a precise, fixed signature).
///
argument::argument(unsigned n)
: terminal("ARG", category_t(0), false, false, 0), index_(n)
{
assert(debug());
}
///
/// \return the index of the argument.
///
unsigned argument::index() const
{
return index_;
}
///
/// \return the string representiation of the argument.
///
std::string argument::display() const
{
return "ARG_" + boost::lexical_cast<std::string>(index_);
}
///
/// \param[in] agent current interpreter
/// \return the value of the argument.
///
any argument::eval(interpreter<individual> *agent) const
{
return agent->fetch_adf_arg(index_);
}
///
/// \return \a true if the object passes the internal consistency check.
///
bool argument::debug() const
{
return index_ < gene::k_args && terminal::debug();
}
} // Namespace vita
<commit_msg>[REF] argument class now using std::to_string instead of lexical_cast<commit_after>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2013 EOS di Manlio Morini.
*
* \license
* 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/
*/
#include "kernel/argument.h"
#include "kernel/gene.h"
#include "kernel/interpreter.h"
namespace vita
{
///
/// \param[in] n argument index.
///
/// An adf function may have up to \a k_args arguments. Arguments' category is
/// special (here it is initialized with \c 0 but we could say they haven't a
/// type) because arguments are communication channels among adf functions
/// and their calling environments. So the type that is travelling on channel
/// \c i (argument(i)) varies depending on the function being evaluated
/// (instead, adf functions have a precise, fixed signature).
///
argument::argument(unsigned n)
: terminal("ARG", category_t(0), false, false, 0), index_(n)
{
assert(debug());
}
///
/// \return the index of the argument.
///
unsigned argument::index() const
{
return index_;
}
///
/// \return the string representiation of the argument.
///
std::string argument::display() const
{
return "ARG_" + std::to_string(index_);
}
///
/// \param[in] agent current interpreter
/// \return the value of the argument.
///
any argument::eval(interpreter<individual> *agent) const
{
return agent->fetch_adf_arg(index_);
}
///
/// \return \a true if the object passes the internal consistency check.
///
bool argument::debug() const
{
return index_ < gene::k_args && terminal::debug();
}
} // Namespace vita
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <string>
#include <time.h>
using namespace clang;
namespace cling {
/*ClangInternalState::ClangInternalState(ASTContext& C, llvm::Module& M,
const std::string& name)
: m_Preprocessor(0), m_ASTContext(C), m_Module(M), m_DiffCommand("diff -u "), m_Name(name) {
store();
}*/
ClangInternalState::ClangInternalState(ASTContext& C, Preprocessor& PP, llvm::Module& M,
const std::string& name)
: m_ASTContext(C), m_Preprocessor(PP), m_Module(M), m_DiffCommand("diff -u ")
, m_Name(name) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
remove(m_MacrosFile.c_str());
}
void ClangInternalState::store() {
m_LookupTablesOS.reset(createOutputFile("lookup", &m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included", &m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
m_MacrosOS.reset(createOutputFile("macros", &m_MacrosFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
printLLVMModule(*m_LLVMModuleOS.get(), m_Module);
printMacroDefinitions(*m_MacrosOS.get(), m_Preprocessor);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(ClangInternalState& other) {
std::string differences = "";
// Ignore the builtins
typedef llvm::SmallVector<const char*, 1024> Builtins;
Builtins builtinNames;
m_ASTContext.BuiltinInfo.GetBuiltinNames(builtinNames);
for (Builtins::iterator I = builtinNames.begin();
I != builtinNames.end();) {
if (llvm::StringRef(*I).startswith("__builtin"))
I = builtinNames.erase(I);
else
++I;
}
builtinNames.push_back(".*__builtin.*");
if (differentContent(m_LookupTablesFile, other.m_LookupTablesFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the lookup tables\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, other.m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, other.m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, other.m_LLVMModuleFile, differences)){
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences,
const llvm::SmallVectorImpl<const char*>* ignores/*=0*/) const {
std::string diffCall = m_DiffCommand;
if (ignores) {
for (size_t i = 0, e = ignores->size(); i < e; ++i) {
diffCall += " --ignore-matching-lines=\".*";
diffCall += (*ignores)[i];
diffCall += ".*\"";
}
}
FILE* pipe = popen((diffCall + " " + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
llvm::raw_ostream& m_OS;
public:
DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
bool VisitDecl(Decl* D) {
if (DeclContext* DC = dyn_cast<DeclContext>(D))
VisitDeclContext(DC);
return true;
}
bool VisitDeclContext(DeclContext* DC) {
DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
void ClangInternalState::printMacroDefinitions(llvm::raw_ostream& Out,
clang::Preprocessor& PP) {
for (clang::Preprocessor::macro_iterator I = PP.macro_begin(),
E = PP.macro_end(); I != E; ++I) {
Out<<(*I).first<<'\n';
}
}
} // end namespace cling
<commit_msg>Print the macro in .compareState.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <string>
#include <time.h>
using namespace clang;
namespace cling {
/*ClangInternalState::ClangInternalState(ASTContext& C, llvm::Module& M,
const std::string& name)
: m_Preprocessor(0), m_ASTContext(C), m_Module(M), m_DiffCommand("diff -u "), m_Name(name) {
store();
}*/
ClangInternalState::ClangInternalState(ASTContext& C, Preprocessor& PP, llvm::Module& M,
const std::string& name)
: m_ASTContext(C), m_Preprocessor(PP), m_Module(M), m_DiffCommand("diff -u ")
, m_Name(name) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
remove(m_MacrosFile.c_str());
}
void ClangInternalState::store() {
m_LookupTablesOS.reset(createOutputFile("lookup", &m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included", &m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
m_MacrosOS.reset(createOutputFile("macros", &m_MacrosFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
printLLVMModule(*m_LLVMModuleOS.get(), m_Module);
printMacroDefinitions(*m_MacrosOS.get(), m_Preprocessor);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(ClangInternalState& other) {
std::string differences = "";
// Ignore the builtins
typedef llvm::SmallVector<const char*, 1024> Builtins;
Builtins builtinNames;
m_ASTContext.BuiltinInfo.GetBuiltinNames(builtinNames);
for (Builtins::iterator I = builtinNames.begin();
I != builtinNames.end();) {
if (llvm::StringRef(*I).startswith("__builtin"))
I = builtinNames.erase(I);
else
++I;
}
builtinNames.push_back(".*__builtin.*");
if (differentContent(m_LookupTablesFile, other.m_LookupTablesFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the lookup tables\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, other.m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, other.m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, other.m_LLVMModuleFile, differences)){
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_MacrosFile, other.m_MacrosFile, differences)){
llvm::errs() << "Differences in the Macro Definitions \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences,
const llvm::SmallVectorImpl<const char*>* ignores/*=0*/) const {
std::string diffCall = m_DiffCommand;
if (ignores) {
for (size_t i = 0, e = ignores->size(); i < e; ++i) {
diffCall += " --ignore-matching-lines=\".*";
diffCall += (*ignores)[i];
diffCall += ".*\"";
}
}
FILE* pipe = popen((diffCall + " " + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
llvm::raw_ostream& m_OS;
public:
DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
bool VisitDecl(Decl* D) {
if (DeclContext* DC = dyn_cast<DeclContext>(D))
VisitDeclContext(DC);
return true;
}
bool VisitDeclContext(DeclContext* DC) {
DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
void ClangInternalState::printMacroDefinitions(llvm::raw_ostream& Out,
clang::Preprocessor& PP) {
for (clang::Preprocessor::macro_iterator I = PP.macro_begin(),
E = PP.macro_end(); I != E; ++I) {
Out<<(*I).first->getName()<<'\n';
}
}
} // end namespace cling
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <sstream>
#include <string>
#include <time.h>
#ifdef WIN32
#define popen _popen
#define pclose _pclose
#endif
using namespace clang;
namespace cling {
ClangInternalState::ClangInternalState(ASTContext& AC, Preprocessor& PP,
llvm::Module* M,
const std::string& name)
: m_ASTContext(AC), m_Preprocessor(PP), m_Module(M),
m_DiffCommand("diff -u --text "), m_Name(name), m_DiffPair(0) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
remove(m_MacrosFile.c_str());
}
void ClangInternalState::store() {
// Cannot use the stack (private copy ctor)
llvm::OwningPtr<llvm::raw_fd_ostream> m_LookupTablesOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_IncludedFilesOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_ASTOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_LLVMModuleOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_MacrosOS;
m_LookupTablesOS.reset(createOutputFile("lookup",
&m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included",
&m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
m_MacrosOS.reset(createOutputFile("macros", &m_MacrosFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
if (m_Module)
printLLVMModule(*m_LLVMModuleOS.get(), *m_Module);
printMacroDefinitions(*m_MacrosOS.get(), m_Preprocessor);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, "cling-" + OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(const std::string& name) {
assert(name == m_Name && "Different names!?");
m_DiffPair.reset(new ClangInternalState(m_ASTContext, m_Preprocessor,
m_Module, name));
std::string differences = "";
// Ignore the builtins
typedef llvm::SmallVector<const char*, 1024> Builtins;
Builtins builtinNames;
m_ASTContext.BuiltinInfo.GetBuiltinNames(builtinNames);
for (Builtins::iterator I = builtinNames.begin();
I != builtinNames.end();) {
if (llvm::StringRef(*I).startswith("__builtin"))
I = builtinNames.erase(I);
else
++I;
}
builtinNames.push_back(".*__builtin.*");
if (differentContent(m_LookupTablesFile, m_DiffPair->m_LookupTablesFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the lookup tables\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, m_DiffPair->m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, m_DiffPair->m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, m_DiffPair->m_LLVMModuleFile,
differences)) {
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_MacrosFile, m_DiffPair->m_MacrosFile, differences)){
llvm::errs() << "Differences in the Macro Definitions \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences,
const llvm::SmallVectorImpl<const char*>* ignores/*=0*/) const {
std::string diffCall = m_DiffCommand;
if (ignores) {
for (size_t i = 0, e = ignores->size(); i < e; ++i) {
diffCall += " --ignore-matching-lines=\".*";
diffCall += (*ignores)[i];
diffCall += ".*\"";
}
}
FILE* pipe = popen((diffCall + " " + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
if (!differences.empty())
llvm::errs() << diffCall << " " << file1 << " " << file2 << "\n";
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
llvm::raw_ostream& m_OS;
public:
DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
bool VisitDecl(Decl* D) {
if (DeclContext* DC = dyn_cast<DeclContext>(D))
VisitDeclContext(DC);
return true;
}
bool VisitDeclContext(DeclContext* DC) {
// If the lookup is pending for building, force its creation.
if (DC == DC->getPrimaryContext() && !DC->getLookupPtr())
DC->buildLookup();
DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
void ClangInternalState::printMacroDefinitions(llvm::raw_ostream& Out,
clang::Preprocessor& PP) {
std::string contents;
llvm::raw_string_ostream contentsOS(contents);
PP.printMacros(contentsOS);
contentsOS.flush();
Out << "Ordered Alphabetically:\n";
std::vector<std::string> elems;
{
// Split the string into lines.
char delim = '\n';
std::stringstream ss(contents);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
// Sort them alphabetically
std::sort(elems.begin(), elems.end());
}
for(std::vector<std::string>::iterator I = elems.begin(),
E = elems.end(); I != E; ++I)
Out << *I << '\n';
Out.flush();
}
} // end namespace cling
<commit_msg>When we have no module don't try to dump it.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <sstream>
#include <string>
#include <time.h>
#ifdef WIN32
#define popen _popen
#define pclose _pclose
#endif
using namespace clang;
namespace cling {
ClangInternalState::ClangInternalState(ASTContext& AC, Preprocessor& PP,
llvm::Module* M,
const std::string& name)
: m_ASTContext(AC), m_Preprocessor(PP), m_Module(M),
m_DiffCommand("diff -u --text "), m_Name(name), m_DiffPair(0) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
remove(m_MacrosFile.c_str());
}
void ClangInternalState::store() {
// Cannot use the stack (private copy ctor)
llvm::OwningPtr<llvm::raw_fd_ostream> m_LookupTablesOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_IncludedFilesOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_ASTOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_LLVMModuleOS;
llvm::OwningPtr<llvm::raw_fd_ostream> m_MacrosOS;
m_LookupTablesOS.reset(createOutputFile("lookup",
&m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included",
&m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
m_MacrosOS.reset(createOutputFile("macros", &m_MacrosFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
if (m_Module)
printLLVMModule(*m_LLVMModuleOS.get(), *m_Module);
printMacroDefinitions(*m_MacrosOS.get(), m_Preprocessor);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, "cling-" + OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(const std::string& name) {
assert(name == m_Name && "Different names!?");
m_DiffPair.reset(new ClangInternalState(m_ASTContext, m_Preprocessor,
m_Module, name));
std::string differences = "";
// Ignore the builtins
typedef llvm::SmallVector<const char*, 1024> Builtins;
Builtins builtinNames;
m_ASTContext.BuiltinInfo.GetBuiltinNames(builtinNames);
for (Builtins::iterator I = builtinNames.begin();
I != builtinNames.end();) {
if (llvm::StringRef(*I).startswith("__builtin"))
I = builtinNames.erase(I);
else
++I;
}
builtinNames.push_back(".*__builtin.*");
if (differentContent(m_LookupTablesFile, m_DiffPair->m_LookupTablesFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the lookup tables\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, m_DiffPair->m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, m_DiffPair->m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (m_Module) {
// We want to skip the intrinsics
builtinNames.clear();
for (llvm::Module::const_iterator I = m_Module->begin(),
E = m_Module->end(); I != E; ++I)
if (I->isIntrinsic())
builtinNames.push_back(I->getName().data());
if (differentContent(m_LLVMModuleFile, m_DiffPair->m_LLVMModuleFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
if (differentContent(m_MacrosFile, m_DiffPair->m_MacrosFile, differences)){
llvm::errs() << "Differences in the Macro Definitions \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences,
const llvm::SmallVectorImpl<const char*>* ignores/*=0*/) const {
std::string diffCall = m_DiffCommand;
if (ignores) {
for (size_t i = 0, e = ignores->size(); i < e; ++i) {
diffCall += " --ignore-matching-lines=\".*";
diffCall += (*ignores)[i];
diffCall += ".*\"";
}
}
FILE* pipe = popen((diffCall + " " + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
if (!differences.empty())
llvm::errs() << diffCall << " " << file1 << " " << file2 << "\n";
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
llvm::raw_ostream& m_OS;
public:
DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
bool VisitDecl(Decl* D) {
if (DeclContext* DC = dyn_cast<DeclContext>(D))
VisitDeclContext(DC);
return true;
}
bool VisitDeclContext(DeclContext* DC) {
// If the lookup is pending for building, force its creation.
if (DC == DC->getPrimaryContext() && !DC->getLookupPtr())
DC->buildLookup();
DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
void ClangInternalState::printMacroDefinitions(llvm::raw_ostream& Out,
clang::Preprocessor& PP) {
std::string contents;
llvm::raw_string_ostream contentsOS(contents);
PP.printMacros(contentsOS);
contentsOS.flush();
Out << "Ordered Alphabetically:\n";
std::vector<std::string> elems;
{
// Split the string into lines.
char delim = '\n';
std::stringstream ss(contents);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
// Sort them alphabetically
std::sort(elems.begin(), elems.end());
}
for(std::vector<std::string>::iterator I = elems.begin(),
E = elems.end(); I != E; ++I)
Out << *I << '\n';
Out.flush();
}
} // end namespace cling
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "test/base_test_fixture.h"
#include <cstdio>
#include <cstdlib>
namespace
{
struct mysql_fixture : public base_test_fixture
{
mysql_fixture()
// connection string from command line or NANODBC_TEST_CONNSTR environment variable
: base_test_fixture()
{
if (connection_string_.empty())
connection_string_ = get_env("NANODBC_TEST_CONNSTR_MYSQL");
}
virtual ~mysql_fixture() NANODBC_NOEXCEPT {}
};
}
// FIXME: No catlog_* tests for MySQL. Not supported?
TEST_CASE_METHOD(mysql_fixture, "driver_test", "[mysql][driver]")
{
driver_test();
}
TEST_CASE_METHOD(mysql_fixture, "affected_rows_test", "[mysql][affected_rows]")
{
nanodbc::connection conn = connect();
// CREATE DATABASE|TABLE
{
execute(conn, NANODBC_TEXT("DROP DATABASE IF EXISTS nanodbc_test_temp_db"));
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("CREATE DATABASE nanodbc_test_temp_db"));
REQUIRE(result.affected_rows() == 1);
execute(conn, NANODBC_TEXT("USE nanodbc_test_temp_db"));
result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)"));
REQUIRE(result.affected_rows() == 0);
}
// INSERT
{
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)"));
REQUIRE(result.affected_rows() == 1);
result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)"));
REQUIRE(result.affected_rows() == 1);
}
// SELECT
{
auto result = execute(conn, NANODBC_TEXT("SELECT i FROM nanodbc_test_temp_table"));
REQUIRE(result.affected_rows() == 2);
}
// DELETE
{
auto result = execute(conn, NANODBC_TEXT("DELETE FROM nanodbc_test_temp_table"));
REQUIRE(result.affected_rows() == 2);
}
// DROP DATABASE|TABLE
{
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table"));
REQUIRE(result.affected_rows() == 0);
result = execute(conn, NANODBC_TEXT("DROP DATABASE nanodbc_test_temp_db"));
REQUIRE(result.affected_rows() == 0);
}
}
TEST_CASE_METHOD(mysql_fixture, "blob_test", "[mysql][blob]")
{
blob_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_list_catalogs_test", "[mysql][catalog][catalogs]")
{
catalog_list_catalogs_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_list_schemas_test", "[mysql][catalog][schemas]")
{
catalog_list_schemas_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_columns_test", "[mysql][catalog][columns]")
{
catalog_columns_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_primary_keys_test", "[mysql][catalog][primary_keys]")
{
catalog_primary_keys_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_tables_test", "[mysql][catalog][tables]")
{
catalog_tables_test();
}
// TODO: Add catalog_table_privileges_test - SQLTablePrivileges returns empty result set
TEST_CASE_METHOD(mysql_fixture, "column_descriptor_test", "[mysql][columns]")
{
column_descriptor_test();
}
TEST_CASE_METHOD(mysql_fixture, "dbms_info_test", "[mysql][dmbs][metadata][info]")
{
dbms_info_test();
}
TEST_CASE_METHOD(mysql_fixture, "decimal_conversion_test", "[mysql][decimal][conversion]")
{
decimal_conversion_test();
}
TEST_CASE_METHOD(mysql_fixture, "exception_test", "[mysql][exception]")
{
exception_test();
}
TEST_CASE_METHOD(
mysql_fixture,
"execute_multiple_transaction_test",
"[mysql][execute][transaction]")
{
execute_multiple_transaction_test();
}
TEST_CASE_METHOD(mysql_fixture, "execute_multiple_test", "[mysql][execute]")
{
execute_multiple_test();
}
TEST_CASE_METHOD(mysql_fixture, "integral_test", "[mysql][integral]")
{
integral_test<mysql_fixture>();
}
TEST_CASE_METHOD(mysql_fixture, "move_test", "[mysql][move]")
{
move_test();
}
TEST_CASE_METHOD(mysql_fixture, "null_test", "[mysql][null]")
{
null_test();
}
TEST_CASE_METHOD(mysql_fixture, "nullptr_nulls_test", "[mysql][null]")
{
nullptr_nulls_test();
}
TEST_CASE_METHOD(mysql_fixture, "result_iterator_test", "[mysql][iterator]")
{
result_iterator_test();
}
TEST_CASE_METHOD(mysql_fixture, "simple_test", "[mysql]")
{
simple_test();
}
TEST_CASE_METHOD(mysql_fixture, "string_test", "[mysql][string]")
{
string_test();
}
TEST_CASE_METHOD(mysql_fixture, "transaction_test", "[mysql][transaction]")
{
transaction_test();
}
TEST_CASE_METHOD(mysql_fixture, "while_not_end_iteration_test", "[mysql][looping]")
{
while_not_end_iteration_test();
}
TEST_CASE_METHOD(mysql_fixture, "while_next_iteration_test", "[mysql][looping]")
{
while_next_iteration_test();
}
<commit_msg>Added test for MySQL long strings<commit_after>#include "catch.hpp"
#include "test/base_test_fixture.h"
#include <cstdio>
#include <cstdlib>
#include <string>
namespace
{
struct mysql_fixture : public base_test_fixture
{
mysql_fixture()
// connection string from command line or NANODBC_TEST_CONNSTR environment variable
: base_test_fixture()
{
if (connection_string_.empty())
connection_string_ = get_env("NANODBC_TEST_CONNSTR_MYSQL");
}
virtual ~mysql_fixture() NANODBC_NOEXCEPT {}
};
}
// FIXME: No catlog_* tests for MySQL. Not supported?
TEST_CASE_METHOD(mysql_fixture, "driver_test", "[mysql][driver]")
{
driver_test();
}
TEST_CASE_METHOD(mysql_fixture, "affected_rows_test", "[mysql][affected_rows]")
{
nanodbc::connection conn = connect();
// CREATE DATABASE|TABLE
{
execute(conn, NANODBC_TEXT("DROP DATABASE IF EXISTS nanodbc_test_temp_db"));
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("CREATE DATABASE nanodbc_test_temp_db"));
REQUIRE(result.affected_rows() == 1);
execute(conn, NANODBC_TEXT("USE nanodbc_test_temp_db"));
result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)"));
REQUIRE(result.affected_rows() == 0);
}
// INSERT
{
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)"));
REQUIRE(result.affected_rows() == 1);
result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)"));
REQUIRE(result.affected_rows() == 1);
}
// SELECT
{
auto result = execute(conn, NANODBC_TEXT("SELECT i FROM nanodbc_test_temp_table"));
REQUIRE(result.affected_rows() == 2);
}
// DELETE
{
auto result = execute(conn, NANODBC_TEXT("DELETE FROM nanodbc_test_temp_table"));
REQUIRE(result.affected_rows() == 2);
}
// Inseting/retrieving long strings
{
std::string long_string(1024, '\0');
for (unsigned i=0; i<1024; i++)
long_string[i]=(i%64)+32;
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_longstring (t TEXT NOT NULL)"));
REQUIRE(result.affected_rows() == 0);
nanodbc::statement stmt(conn, NANODBC_TEXT("INSERT INTO nanodbc_longstring VALUES (?)"));
stmt.bind(0, long_string.c_str());
result = stmt.execute();
REQUIRE(result.affected_rows() == 1);
result = execute(conn, NANODBC_TEXT("SELECT t FROM nanodbc_longstring LIMIT 1"));
REQUIRE(result.affected_rows() == 1);
if (result.next()) {
std::string str_from_db = result.get<std::string>(0);
REQUIRE(str_from_db == long_string);
}
}
// DROP DATABASE|TABLE
{
nanodbc::result result;
result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table"));
REQUIRE(result.affected_rows() == 0);
result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_longstring"));
REQUIRE(result.affected_rows() == 0);
result = execute(conn, NANODBC_TEXT("DROP DATABASE nanodbc_test_temp_db"));
REQUIRE(result.affected_rows() == 0);
}
}
TEST_CASE_METHOD(mysql_fixture, "blob_test", "[mysql][blob]")
{
blob_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_list_catalogs_test", "[mysql][catalog][catalogs]")
{
catalog_list_catalogs_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_list_schemas_test", "[mysql][catalog][schemas]")
{
catalog_list_schemas_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_columns_test", "[mysql][catalog][columns]")
{
catalog_columns_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_primary_keys_test", "[mysql][catalog][primary_keys]")
{
catalog_primary_keys_test();
}
TEST_CASE_METHOD(mysql_fixture, "catalog_tables_test", "[mysql][catalog][tables]")
{
catalog_tables_test();
}
// TODO: Add catalog_table_privileges_test - SQLTablePrivileges returns empty result set
TEST_CASE_METHOD(mysql_fixture, "column_descriptor_test", "[mysql][columns]")
{
column_descriptor_test();
}
TEST_CASE_METHOD(mysql_fixture, "dbms_info_test", "[mysql][dmbs][metadata][info]")
{
dbms_info_test();
}
TEST_CASE_METHOD(mysql_fixture, "decimal_conversion_test", "[mysql][decimal][conversion]")
{
decimal_conversion_test();
}
TEST_CASE_METHOD(mysql_fixture, "exception_test", "[mysql][exception]")
{
exception_test();
}
TEST_CASE_METHOD(
mysql_fixture,
"execute_multiple_transaction_test",
"[mysql][execute][transaction]")
{
execute_multiple_transaction_test();
}
TEST_CASE_METHOD(mysql_fixture, "execute_multiple_test", "[mysql][execute]")
{
execute_multiple_test();
}
TEST_CASE_METHOD(mysql_fixture, "integral_test", "[mysql][integral]")
{
integral_test<mysql_fixture>();
}
TEST_CASE_METHOD(mysql_fixture, "move_test", "[mysql][move]")
{
move_test();
}
TEST_CASE_METHOD(mysql_fixture, "null_test", "[mysql][null]")
{
null_test();
}
TEST_CASE_METHOD(mysql_fixture, "nullptr_nulls_test", "[mysql][null]")
{
nullptr_nulls_test();
}
TEST_CASE_METHOD(mysql_fixture, "result_iterator_test", "[mysql][iterator]")
{
result_iterator_test();
}
TEST_CASE_METHOD(mysql_fixture, "simple_test", "[mysql]")
{
simple_test();
}
TEST_CASE_METHOD(mysql_fixture, "string_test", "[mysql][string]")
{
string_test();
}
TEST_CASE_METHOD(mysql_fixture, "transaction_test", "[mysql][transaction]")
{
transaction_test();
}
TEST_CASE_METHOD(mysql_fixture, "while_not_end_iteration_test", "[mysql][looping]")
{
while_not_end_iteration_test();
}
TEST_CASE_METHOD(mysql_fixture, "while_next_iteration_test", "[mysql][looping]")
{
while_next_iteration_test();
}
<|endoftext|> |
<commit_before>/* -*- c++ -*-
callback.cpp
This file is used by KMail's plugin interface.
Copyright (c) 2004 Bo Thorsen <[email protected]>
KMail 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 2 of the License, or
(at your option) any later version.
KMail 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "callback.h"
#include "kmkernel.h"
#include "kmmessage.h"
#include "kmmsgpart.h"
#include <libemailfunctions/email.h>
#include <libkpimidentities/identity.h>
#include <libkpimidentities/identitymanager.h>
#include "kmmainwin.h"
#include "composer.h"
#include "kmreaderwin.h"
#include "secondarywindow.h"
#include <mimelib/enum.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kdebug.h>
using namespace KMail;
Callback::Callback( KMMessage* msg, KMReaderWin* readerWin )
: mMsg( msg ), mReaderWin( readerWin ), mReceiverSet( false )
{
}
bool Callback::mailICal( const QString& to, const QString &iCal,
const QString& subject, const QString &status,
bool delMessage ) const
{
kdDebug(5006) << "Mailing message:\n" << iCal << endl;
KMMessage *msg = new KMMessage;
msg->initHeader();
msg->setSubject( subject );
if ( GlobalSettings::self()->exchangeCompatibleInvitations() ) {
if ( status == QString("cancel") )
msg->setSubject( QString("Declined: %1").arg(subject).replace("Answer: ","") );
else if ( status == QString("tentative") )
msg->setSubject(QString("Tentative: %1").arg(subject).replace("Answer: ","") );
else if ( status == QString("accepted") )
msg->setSubject( QString("Accepted: %1").arg(subject).replace("Answer: ","") );
else if ( status == QString("delegated") )
msg->setSubject( QString("Delegated: %1").arg(subject).replace("Answer: ","") );
}
msg->setTo( to );
msg->setFrom( receiver() );
if ( !GlobalSettings::self()->exchangeCompatibleInvitations() ) {
msg->setHeaderField( "Content-Type",
"text/calendar; method=reply; charset=\"utf-8\"" );
msg->setBody( iCal.utf8() );
}
if ( delMessage && deleteInvitationAfterReply() )
/* We want the triggering mail to be moved to the trash once this one
* has been sent successfully. Set a link header which accomplishes that. */
msg->link( mMsg, KMMsgStatusDeleted );
// Outlook will only understand the reply if the From: header is the
// same as the To: header of the invitation message.
KConfigGroup options( KMKernel::config(), "Groupware" );
if( !options.readBoolEntry( "LegacyMangleFromToHeaders", true ) ) {
// Try and match the receiver with an identity
const KPIM::Identity& identity =
kmkernel->identityManager()->identityForAddress( receiver() );
if( identity != KPIM::Identity::null() ) {
// Identity found. Use this
msg->setFrom( identity.fullEmailAddr() );
msg->setHeaderField("X-KMail-Identity", QString::number( identity.uoid() ));
}
// Remove BCC from identity on ical invitations (https://intevation.de/roundup/kolab/issue474)
msg->setBcc( "" );
}
KMail::Composer * cWin = KMail::makeComposer();
cWin->setMsg( msg, false /* mayAutoSign */ );
// cWin->setCharset( "", true );
cWin->disableWordWrap();
cWin->setSigningAndEncryptionDisabled( true );
if( GlobalSettings::self()->exchangeCompatibleInvitations() ) {
// For Exchange, send ical as attachment, with proper
// parameters
msg->setSubject( status );
msg->setCharset( "utf-8" );
KMMessagePart *msgPart = new KMMessagePart;
msgPart->setName( "cal.ics" );
// msgPart->setCteStr( attachCte ); // "base64" ?
msgPart->setBodyEncoded( iCal.utf8() );
msgPart->setTypeStr( "text" );
msgPart->setSubtypeStr( "calendar" );
msgPart->setParameter( "method", "reply" );
cWin->addAttach( msgPart );
}
if ( options.readBoolEntry( "AutomaticSending", true ) ) {
cWin->setAutoDeleteWindow( true );
cWin->slotSendNow();
} else {
cWin->show();
}
return true;
}
QString Callback::receiver() const
{
if ( mReceiverSet )
// Already figured this out
return mReceiver;
mReceiverSet = true;
QStringList addrs = KPIM::splitEmailAddrList( mMsg->to() );
int found = 0;
for( QStringList::Iterator it = addrs.begin(); it != addrs.end(); ++it ) {
if( kmkernel->identityManager()->identityForAddress( *it ) !=
KPIM::Identity::null() ) {
// Ok, this could be us
++found;
mReceiver = *it;
}
}
QStringList ccaddrs = KPIM::splitEmailAddrList( mMsg->cc() );
for( QStringList::Iterator it = ccaddrs.begin(); it != ccaddrs.end(); ++it ) {
if( kmkernel->identityManager()->identityForAddress( *it ) !=
KPIM::Identity::null() ) {
// Ok, this could be us
++found;
mReceiver = *it;
}
}
if( found != 1 ) {
bool ok;
QString selectMessage;
if (found == 0) {
selectMessage = i18n("<qt>None of your identities match the "
"receiver of this message,<br>please "
"choose which of the following addresses "
"is yours, if any, or select one of your identities to use in the reply:");
addrs += kmkernel->identityManager()->allEmails();
} else {
selectMessage = i18n("<qt>Several of your identities match the "
"receiver of this message,<br>please "
"choose which of the following addresses "
"is yours:");
}
mReceiver =
KInputDialog::getItem( i18n( "Select Address" ),
selectMessage,
addrs+ccaddrs, 0, FALSE, &ok, kmkernel->mainWin() );
if( !ok )
mReceiver = QString::null;
}
return mReceiver;
}
void Callback::closeIfSecondaryWindow() const
{
KMail::SecondaryWindow *window = dynamic_cast<KMail::SecondaryWindow*>( mReaderWin->mainWindow() );
if ( window )
window->close();
}
bool Callback::askForComment( KCal::Attendee::PartStat status ) const
{
if ( ( status != KCal::Attendee::Accepted
&& GlobalSettings::self()->askForCommentWhenReactingToInvitation()
== GlobalSettings:: EnumAskForCommentWhenReactingToInvitation::AskForAllButAcceptance )
|| GlobalSettings::self()->askForCommentWhenReactingToInvitation()
== GlobalSettings:: EnumAskForCommentWhenReactingToInvitation::AlwaysAsk )
return true;
return false;
}
bool Callback::deleteInvitationAfterReply() const
{
return GlobalSettings::self()->deleteInvitationEmailsAfterSendingReply();
}
QString Callback::sender() const
{
return mMsg->from();
}
<commit_msg>Pre-select the default identity.<commit_after>/* -*- c++ -*-
callback.cpp
This file is used by KMail's plugin interface.
Copyright (c) 2004 Bo Thorsen <[email protected]>
KMail 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 2 of the License, or
(at your option) any later version.
KMail 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "callback.h"
#include "kmkernel.h"
#include "kmmessage.h"
#include "kmmsgpart.h"
#include <libemailfunctions/email.h>
#include <libkpimidentities/identity.h>
#include <libkpimidentities/identitymanager.h>
#include "kmmainwin.h"
#include "composer.h"
#include "kmreaderwin.h"
#include "secondarywindow.h"
#include <mimelib/enum.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kdebug.h>
using namespace KMail;
Callback::Callback( KMMessage* msg, KMReaderWin* readerWin )
: mMsg( msg ), mReaderWin( readerWin ), mReceiverSet( false )
{
}
bool Callback::mailICal( const QString& to, const QString &iCal,
const QString& subject, const QString &status,
bool delMessage ) const
{
kdDebug(5006) << "Mailing message:\n" << iCal << endl;
KMMessage *msg = new KMMessage;
msg->initHeader();
msg->setSubject( subject );
if ( GlobalSettings::self()->exchangeCompatibleInvitations() ) {
if ( status == QString("cancel") )
msg->setSubject( QString("Declined: %1").arg(subject).replace("Answer: ","") );
else if ( status == QString("tentative") )
msg->setSubject(QString("Tentative: %1").arg(subject).replace("Answer: ","") );
else if ( status == QString("accepted") )
msg->setSubject( QString("Accepted: %1").arg(subject).replace("Answer: ","") );
else if ( status == QString("delegated") )
msg->setSubject( QString("Delegated: %1").arg(subject).replace("Answer: ","") );
}
msg->setTo( to );
msg->setFrom( receiver() );
if ( !GlobalSettings::self()->exchangeCompatibleInvitations() ) {
msg->setHeaderField( "Content-Type",
"text/calendar; method=reply; charset=\"utf-8\"" );
msg->setBody( iCal.utf8() );
}
if ( delMessage && deleteInvitationAfterReply() )
/* We want the triggering mail to be moved to the trash once this one
* has been sent successfully. Set a link header which accomplishes that. */
msg->link( mMsg, KMMsgStatusDeleted );
// Outlook will only understand the reply if the From: header is the
// same as the To: header of the invitation message.
KConfigGroup options( KMKernel::config(), "Groupware" );
if( !options.readBoolEntry( "LegacyMangleFromToHeaders", true ) ) {
// Try and match the receiver with an identity
const KPIM::Identity& identity =
kmkernel->identityManager()->identityForAddress( receiver() );
if( identity != KPIM::Identity::null() ) {
// Identity found. Use this
msg->setFrom( identity.fullEmailAddr() );
msg->setHeaderField("X-KMail-Identity", QString::number( identity.uoid() ));
}
// Remove BCC from identity on ical invitations (https://intevation.de/roundup/kolab/issue474)
msg->setBcc( "" );
}
KMail::Composer * cWin = KMail::makeComposer();
cWin->setMsg( msg, false /* mayAutoSign */ );
// cWin->setCharset( "", true );
cWin->disableWordWrap();
cWin->setSigningAndEncryptionDisabled( true );
if( GlobalSettings::self()->exchangeCompatibleInvitations() ) {
// For Exchange, send ical as attachment, with proper
// parameters
msg->setSubject( status );
msg->setCharset( "utf-8" );
KMMessagePart *msgPart = new KMMessagePart;
msgPart->setName( "cal.ics" );
// msgPart->setCteStr( attachCte ); // "base64" ?
msgPart->setBodyEncoded( iCal.utf8() );
msgPart->setTypeStr( "text" );
msgPart->setSubtypeStr( "calendar" );
msgPart->setParameter( "method", "reply" );
cWin->addAttach( msgPart );
}
if ( options.readBoolEntry( "AutomaticSending", true ) ) {
cWin->setAutoDeleteWindow( true );
cWin->slotSendNow();
} else {
cWin->show();
}
return true;
}
QString Callback::receiver() const
{
if ( mReceiverSet )
// Already figured this out
return mReceiver;
mReceiverSet = true;
QStringList addrs = KPIM::splitEmailAddrList( mMsg->to() );
int found = 0;
for( QStringList::Iterator it = addrs.begin(); it != addrs.end(); ++it ) {
if( kmkernel->identityManager()->identityForAddress( *it ) !=
KPIM::Identity::null() ) {
// Ok, this could be us
++found;
mReceiver = *it;
}
}
QStringList ccaddrs = KPIM::splitEmailAddrList( mMsg->cc() );
for( QStringList::Iterator it = ccaddrs.begin(); it != ccaddrs.end(); ++it ) {
if( kmkernel->identityManager()->identityForAddress( *it ) !=
KPIM::Identity::null() ) {
// Ok, this could be us
++found;
mReceiver = *it;
}
}
if( found != 1 ) {
bool ok;
QString selectMessage;
if (found == 0) {
selectMessage = i18n("<qt>None of your identities match the "
"receiver of this message,<br>please "
"choose which of the following addresses "
"is yours, if any, or select one of your identities to use in the reply:");
addrs += kmkernel->identityManager()->allEmails();
} else {
selectMessage = i18n("<qt>Several of your identities match the "
"receiver of this message,<br>please "
"choose which of the following addresses "
"is yours:");
}
// select default identity by default
const QString defaultAddr = kmkernel->identityManager()->defaultIdentity().emailAddr();
const int defaultIndex = QMAX( 0, addrs.findIndex( defaultAddr ) );
mReceiver =
KInputDialog::getItem( i18n( "Select Address" ),
selectMessage,
addrs+ccaddrs, defaultIndex, FALSE, &ok, kmkernel->mainWin() );
if( !ok )
mReceiver = QString::null;
}
return mReceiver;
}
void Callback::closeIfSecondaryWindow() const
{
KMail::SecondaryWindow *window = dynamic_cast<KMail::SecondaryWindow*>( mReaderWin->mainWindow() );
if ( window )
window->close();
}
bool Callback::askForComment( KCal::Attendee::PartStat status ) const
{
if ( ( status != KCal::Attendee::Accepted
&& GlobalSettings::self()->askForCommentWhenReactingToInvitation()
== GlobalSettings:: EnumAskForCommentWhenReactingToInvitation::AskForAllButAcceptance )
|| GlobalSettings::self()->askForCommentWhenReactingToInvitation()
== GlobalSettings:: EnumAskForCommentWhenReactingToInvitation::AlwaysAsk )
return true;
return false;
}
bool Callback::deleteInvitationAfterReply() const
{
return GlobalSettings::self()->deleteInvitationEmailsAfterSendingReply();
}
QString Callback::sender() const
{
return mMsg->from();
}
<|endoftext|> |
<commit_before><commit_msg>Fix OOM with uninitialized variable case.<commit_after><|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.