text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "mbedcrypto/random.hpp"
#include "mbedcrypto/types.hpp"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
///////////////////////////////////////////////////////////////////////////////
namespace mbedcrypto {
namespace {
///////////////////////////////////////////////////////////////////////////////
static_assert(std::is_copy_constructible<random>::value == false, "");
static_assert(std::is_move_constructible<random>::value == true , "");
int
make_chunked(
mbedtls_ctr_drbg_context& ctx,
unsigned char* buffer, size_t length) {
constexpr size_t MaxChunkSize = MBEDTLS_CTR_DRBG_MAX_REQUEST;
// length is smaller than
if ( length <= MaxChunkSize ) {
return mbedtls_ctr_drbg_random(
&ctx, buffer, length
);
}
// needs to make in chunks
for ( size_t i = 0; (i+MaxChunkSize) <= length; i += MaxChunkSize ) {
int ret = mbedtls_ctr_drbg_random(&ctx, buffer + i, MaxChunkSize);
if ( ret != 0 )
return ret;
}
// last chunk
size_t residue = length % MaxChunkSize;
if ( residue ) {
int ret = mbedtls_ctr_drbg_random(
&ctx, buffer + length - residue, residue
);
if ( ret != 0 )
return ret;
}
return 0; // success
}
///////////////////////////////////////////////////////////////////////////////
} // namespace anon
///////////////////////////////////////////////////////////////////////////////
struct random::impl
{
mbedtls_entropy_context entropy_;
mbedtls_ctr_drbg_context ctx_;
explicit impl() noexcept {
}
~impl() {
mbedtls_entropy_free(&entropy_);
mbedtls_ctr_drbg_free(&ctx_);
}
void setup(const unsigned char* custom, size_t length) {
mbedtls_entropy_init(&entropy_);
mbedtls_ctr_drbg_init(&ctx_);
mbedtls_ctr_drbg_seed(
&ctx_,
mbedtls_entropy_func,
&entropy_,
custom, length
);
mbedtls_ctr_drbg_set_prediction_resistance(
&ctx_,
MBEDTLS_CTR_DRBG_PR_OFF
);
}
}; // class random::imp
///////////////////////////////////////////////////////////////////////////////
random::random(const buffer_t& b) : pimpl(std::make_unique<impl>()) {
pimpl->setup(to_const_ptr(b), b.size());
}
random::random() : pimpl(std::make_unique<impl>()) {
pimpl->setup(nullptr, 0);
}
random::~random() {
}
void
random::entropy_length(size_t len) noexcept {
mbedtls_ctr_drbg_set_entropy_len(&pimpl->ctx_, len);
}
void
random::reseed_interval(size_t interval) noexcept {
mbedtls_ctr_drbg_set_reseed_interval(&pimpl->ctx_, interval);
}
void
random::prediction_resistance(bool p) noexcept {
mbedtls_ctr_drbg_set_prediction_resistance(
&pimpl->ctx_,
p ? MBEDTLS_CTR_DRBG_PR_ON : MBEDTLS_CTR_DRBG_PR_OFF
);
}
int
random::make(unsigned char* buffer, size_t length) noexcept {
return make_chunked(pimpl->ctx_, buffer, length);
}
buffer_t
random::make(size_t length) {
buffer_t buf(length, '\0');
mbedcrypto_c_call(make_chunked,
pimpl->ctx_,
to_ptr(buf),
length
);
return buf;
}
void
random::reseed() {
mbedcrypto_c_call(mbedtls_ctr_drbg_reseed,
&pimpl->ctx_, nullptr, 0
);
}
void
random::reseed(const buffer_t& custom) {
mbedcrypto_c_call(mbedtls_ctr_drbg_reseed,
&pimpl->ctx_,
to_const_ptr(custom),
custom.size()
);
}
int
random::reseed(const unsigned char* custom, size_t length) noexcept {
return mbedtls_ctr_drbg_reseed(&pimpl->ctx_, custom, length);
}
void
random::update(const buffer_t& additional) {
mbedtls_ctr_drbg_update(
&pimpl->ctx_,
to_const_ptr(additional),
additional.size()
);
}
void
random::update(const unsigned char* additional, size_t length) noexcept {
mbedtls_ctr_drbg_update(
&pimpl->ctx_, additional, length
);
}
///////////////////////////////////////////////////////////////////////////////
} // namespace mbedcrypto
///////////////////////////////////////////////////////////////////////////////
<commit_msg>random: minor update to chunker generator args<commit_after>#include "mbedcrypto/random.hpp"
#include "mbedcrypto/types.hpp"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
///////////////////////////////////////////////////////////////////////////////
namespace mbedcrypto {
namespace {
///////////////////////////////////////////////////////////////////////////////
static_assert(std::is_copy_constructible<random>::value == false, "");
static_assert(std::is_move_constructible<random>::value == true , "");
int
make_chunked(mbedtls_ctr_drbg_context* ctx,
unsigned char* buffer, size_t length) {
constexpr size_t MaxChunkSize = MBEDTLS_CTR_DRBG_MAX_REQUEST;
// length is smaller than
if ( length <= MaxChunkSize ) {
return mbedtls_ctr_drbg_random(ctx, buffer, length);
}
// needs to make in chunks
for ( size_t i = 0; (i+MaxChunkSize) <= length; i += MaxChunkSize ) {
int ret = mbedtls_ctr_drbg_random(ctx, buffer + i, MaxChunkSize);
if ( ret != 0 )
return ret;
}
// last chunk
size_t residue = length % MaxChunkSize;
if ( residue ) {
int ret = mbedtls_ctr_drbg_random(ctx,
buffer + length - residue,
residue
);
if ( ret != 0 )
return ret;
}
return 0; // success
}
///////////////////////////////////////////////////////////////////////////////
} // namespace anon
///////////////////////////////////////////////////////////////////////////////
struct random::impl
{
mbedtls_entropy_context entropy_;
mbedtls_ctr_drbg_context ctx_;
explicit impl() noexcept {
}
~impl() {
mbedtls_entropy_free(&entropy_);
mbedtls_ctr_drbg_free(&ctx_);
}
void setup(const unsigned char* custom, size_t length) {
mbedtls_entropy_init(&entropy_);
mbedtls_ctr_drbg_init(&ctx_);
mbedtls_ctr_drbg_seed(
&ctx_,
mbedtls_entropy_func,
&entropy_,
custom, length
);
mbedtls_ctr_drbg_set_prediction_resistance(
&ctx_,
MBEDTLS_CTR_DRBG_PR_OFF
);
}
}; // class random::imp
///////////////////////////////////////////////////////////////////////////////
random::random(const buffer_t& b) : pimpl(std::make_unique<impl>()) {
pimpl->setup(to_const_ptr(b), b.size());
}
random::random() : pimpl(std::make_unique<impl>()) {
pimpl->setup(nullptr, 0);
}
random::~random() {
}
void
random::entropy_length(size_t len) noexcept {
mbedtls_ctr_drbg_set_entropy_len(&pimpl->ctx_, len);
}
void
random::reseed_interval(size_t interval) noexcept {
mbedtls_ctr_drbg_set_reseed_interval(&pimpl->ctx_, interval);
}
void
random::prediction_resistance(bool p) noexcept {
mbedtls_ctr_drbg_set_prediction_resistance(
&pimpl->ctx_,
p ? MBEDTLS_CTR_DRBG_PR_ON : MBEDTLS_CTR_DRBG_PR_OFF
);
}
int
random::make(unsigned char* buffer, size_t olen) noexcept {
return make_chunked(&pimpl->ctx_, buffer, olen);
}
buffer_t
random::make(size_t length) {
buffer_t buf(length, '\0');
mbedcrypto_c_call(make_chunked,
&pimpl->ctx_,
to_ptr(buf),
length
);
return buf;
}
void
random::reseed() {
mbedcrypto_c_call(mbedtls_ctr_drbg_reseed,
&pimpl->ctx_, nullptr, 0
);
}
void
random::reseed(const buffer_t& custom) {
mbedcrypto_c_call(mbedtls_ctr_drbg_reseed,
&pimpl->ctx_,
to_const_ptr(custom),
custom.size()
);
}
int
random::reseed(const unsigned char* custom, size_t length) noexcept {
return mbedtls_ctr_drbg_reseed(&pimpl->ctx_, custom, length);
}
void
random::update(const buffer_t& additional) {
mbedtls_ctr_drbg_update(
&pimpl->ctx_,
to_const_ptr(additional),
additional.size()
);
}
void
random::update(const unsigned char* additional, size_t length) noexcept {
mbedtls_ctr_drbg_update(
&pimpl->ctx_, additional, length
);
}
///////////////////////////////////////////////////////////////////////////////
} // namespace mbedcrypto
///////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>/*
* BarabasiAlbertGenerator.cpp
*
* Created on: May 28, 2013
* Author: forigem
*/
#include "../auxiliary/Random.h"
#include "BarabasiAlbertGenerator.h"
#include <set>
namespace NetworKit {
BarabasiAlbertGenerator::BarabasiAlbertGenerator() {
}
BarabasiAlbertGenerator::BarabasiAlbertGenerator(count k, count nMax, count n0, bool batagelj) : initGraph(0), k(k), nMax(nMax), batagelj(batagelj) {
if (k > nMax)
throw std::runtime_error("k (number of attachments per node) may not be larger than the number of nodes in the target graph (nMax)");
if (n0 > nMax)
throw std::runtime_error("n0 (number of initially connected nodes) may not be larger than the number of nodes in the target graph (nMax)");
if (batagelj) {
this->n0 = n0;
} else {
if (n0 < k) {
if (n0 > 0) {
WARN("given n0 is smaller than k, setting n0 = k");
}
this->n0 = k;
} else {
this->n0 = n0;
}
}
}
BarabasiAlbertGenerator::BarabasiAlbertGenerator(count k, count nMax, const Graph& initGraph, bool batagelj) : initGraph(initGraph), k(k), nMax(nMax), n0(0), batagelj(batagelj) {
if (initGraph.numberOfNodes() != initGraph.upperNodeIdBound())
throw std::runtime_error("initGraph is expected to have consecutive node ids");
if (k > nMax)
throw std::runtime_error("k (number of attachments per node) may not be larger than the number of nodes in the target graph (nMax)");
if (initGraph.numberOfNodes() > nMax)
throw std::runtime_error("initialization graph cannot have more nodes than the target graph (nMax)");
if (!batagelj && initGraph.numberOfNodes() < k) {
throw std::runtime_error("initialization graph for the original method needs at least k nodes");
}
}
Graph BarabasiAlbertGenerator::generate() {
if (batagelj) {
return generateBatagelj();
} else {
return generateOriginal();
}
}
Graph BarabasiAlbertGenerator::generateOriginal() {
Graph G(nMax);
if (n0 != 0) {
// initialize the graph with n0 connected nodes
for (count i = 1; i < n0; i++) {
G.addEdge(i-1, i);
}
} else {
// initialize the graph with the edges from initGraph
// and set n0 accordingly
initGraph.forEdges([&G](node u, node v) {
G.addEdge(u, v);
});
n0 = initGraph.upperNodeIdBound();
}
assert (G.numberOfNodes() >= k);
for (count i = n0; i < nMax; i++) {
count degreeSum = G.numberOfEdges() * 2;
node u = i;
std::set<node> targets;
targets.insert(u);
int j = 0;
while (targets.size() - 1 < k) {
uint64_t random = (uint64_t) Aux::Random::integer(degreeSum);
j++;
///if (j > k) throw std::runtime_error("Possible infinite loop detected.");
bool found = false; // break from node iteration when done
auto notFound = [&](){ return ! found; };
G.forNodesWhile(notFound, [&](node v) {
if (random <= G.degree(v)) {
found = true; // found a node to connect to
targets.insert(v);
}
random -= G.degree(v);
//if (j >= G.numberOfNodes() && found==false) throw std::runtime_error("Last node, but still nothing happened.");
});
}
targets.erase(u);
for (node x : targets) {
G.addEdge(u, x);
}
}
G.shrinkToFit();
return G;
}
Graph BarabasiAlbertGenerator::generateBatagelj() {
count n = nMax;
Graph G(nMax);
std::vector<node> M(2 * k * n);
std::set<std::pair<node, node>> uniqueEdges;
if (initGraph.numberOfNodes() == 0) {
// initialize n0 connected nodes
for (index v = 0; v < n0; ++v) {
M[2 * v ] = v;
M[2 * v + 1] = v + 1;
}
} else {
index i = 0;
initGraph.forEdges( [&M,&i] (node u, node v) {
M[2 * i] = u;
M[2 * i +1] = v;
++i;
});
n0 = i;
}
// "draw" the edges
for (index v = n0; v < n; ++v) {
for (index i = 0; i < k; ++i) {
M[2 * (v * k + i)] = v;
index r = Aux::Random::integer(2 * (v * k + i));
M[2 * (v * k + i) + 1] = M[r];
}
}
// remove duplicates and avoid selfloops
// for some reason, it seems to be faster with a separate loop when compared to integrating it in the loop above
for (index i = 0; i < (k*n); ++i) {
if (M[2 * i] != M[2 * i + 1])
uniqueEdges.insert( {M[2 * i], M[2 * i + 1]} );
}
// add the edges to the graph
for (const auto& edge : uniqueEdges) {
G.addEdge(edge.first, edge.second);
}
G.shrinkToFit();
return G;
}
} /* namespace NetworKit */
<commit_msg>fix for Batagelj's method in BarabasiAlbertGenerator<commit_after>/*
* BarabasiAlbertGenerator.cpp
*
* Created on: May 28, 2013
* Author: forigem
*/
#include "../auxiliary/Random.h"
#include "BarabasiAlbertGenerator.h"
#include <set>
namespace NetworKit {
BarabasiAlbertGenerator::BarabasiAlbertGenerator() {
}
BarabasiAlbertGenerator::BarabasiAlbertGenerator(count k, count nMax, count n0, bool batagelj) : initGraph(0), k(k), nMax(nMax), batagelj(batagelj) {
if (k > nMax)
throw std::runtime_error("k (number of attachments per node) may not be larger than the number of nodes in the target graph (nMax)");
if (n0 > nMax)
throw std::runtime_error("n0 (number of initially connected nodes) may not be larger than the number of nodes in the target graph (nMax)");
if (batagelj) {
this->n0 = n0;
} else {
if (n0 < k) {
if (n0 > 0) {
WARN("given n0 is smaller than k, setting n0 = k");
}
this->n0 = k;
} else {
this->n0 = n0;
}
}
}
BarabasiAlbertGenerator::BarabasiAlbertGenerator(count k, count nMax, const Graph& initGraph, bool batagelj) : initGraph(initGraph), k(k), nMax(nMax), n0(0), batagelj(batagelj) {
if (initGraph.numberOfNodes() != initGraph.upperNodeIdBound())
throw std::runtime_error("initGraph is expected to have consecutive node ids");
if (k > nMax)
throw std::runtime_error("k (number of attachments per node) may not be larger than the number of nodes in the target graph (nMax)");
if (initGraph.numberOfNodes() > nMax)
throw std::runtime_error("initialization graph cannot have more nodes than the target graph (nMax)");
if (!batagelj && initGraph.numberOfNodes() < k) {
throw std::runtime_error("initialization graph for the original method needs at least k nodes");
}
}
Graph BarabasiAlbertGenerator::generate() {
if (batagelj) {
return generateBatagelj();
} else {
return generateOriginal();
}
}
Graph BarabasiAlbertGenerator::generateOriginal() {
Graph G(nMax);
if (n0 != 0) {
// initialize the graph with n0 connected nodes
for (count i = 1; i < n0; i++) {
G.addEdge(i-1, i);
}
} else {
// initialize the graph with the edges from initGraph
// and set n0 accordingly
initGraph.forEdges([&G](node u, node v) {
G.addEdge(u, v);
});
n0 = initGraph.upperNodeIdBound();
}
assert (G.numberOfNodes() >= k);
for (count i = n0; i < nMax; i++) {
count degreeSum = G.numberOfEdges() * 2;
node u = i;
std::set<node> targets;
targets.insert(u);
int j = 0;
while (targets.size() - 1 < k) {
uint64_t random = (uint64_t) Aux::Random::integer(degreeSum);
j++;
///if (j > k) throw std::runtime_error("Possible infinite loop detected.");
bool found = false; // break from node iteration when done
auto notFound = [&](){ return ! found; };
G.forNodesWhile(notFound, [&](node v) {
if (random <= G.degree(v)) {
found = true; // found a node to connect to
targets.insert(v);
}
random -= G.degree(v);
//if (j >= G.numberOfNodes() && found==false) throw std::runtime_error("Last node, but still nothing happened.");
});
}
targets.erase(u);
for (node x : targets) {
G.addEdge(u, x);
}
}
G.shrinkToFit();
return G;
}
Graph BarabasiAlbertGenerator::generateBatagelj() {
count n = nMax;
Graph G(nMax);
std::vector<node> M(2 * k * n);
std::set<std::pair<node, node>> uniqueEdges;
if (initGraph.numberOfNodes() == 0) {
// initialize n0 connected nodes
for (index v = 0; v < n0; ++v) {
M[2 * v ] = v;
M[2 * v + 1] = v + 1;
}
} else {
index i = 0;
initGraph.forEdges( [&M,&i] (node u, node v) {
M[2 * i] = u;
M[2 * i +1] = v;
++i;
});
n0 = i;
}
// "draw" the edges
for (index v = n0; v < n; ++v) {
for (index i = 0; i < k; ++i) {
M[2 * (v * k + i)] = v;
index r = Aux::Random::integer(2 * (v * k + i));
M[2 * (v * k + i) + 1] = M[r];
}
}
// remove duplicates and avoid selfloops
// for some reason, it seems to be faster with a separate loop when compared to integrating it in the loop above
for (index i = 0; i < (k*n); ++i) {
if (M[2 * i] != M[2 * i + 1])
uniqueEdges.insert( std::minmax({M[2 * i], M[2 * i + 1]}) );
}
// add the edges to the graph
for (const auto& edge : uniqueEdges) {
G.addEdge(edge.first, edge.second);
}
G.shrinkToFit();
return G;
}
} /* namespace NetworKit */
<|endoftext|>
|
<commit_before><commit_msg>MArray::permute() and MArray::window() can now operate on the same object they're called from<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2005, 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 "MIMEHeader.h"
#include "Dbg.h"
#include "AnythingUtils.h"
#include "AnyIterators.h"
#include "RE.h"
//#include "RECompiler.h"
#include <iostream>
#include <cstdio> // for EOF
#include <cstring> // for strlen
MIMEHeader::MIMEHeader(Coast::URLUtils::NormalizeTag normalizeKey) :
fNormalizeKey(normalizeKey) {
StartTrace(MIMEHeader.Ctor);
}
namespace Coast {
namespace StreamUtils {
void getLineFromStream(std::istream &in, String &line, long const maxlinelen) {
StartTrace(MIMEHeader.getLineFromStream);
if ( !in.good() ) throw MIMEHeader::StreamNotGoodException();
// reset line
line.Trim(0L);
// read line up to but not including next LF
line.Append(in, maxlinelen, LF);
Trace("Line length: " << line.Length() << " maxlinelen: " << maxlinelen << "\n" << line.DumpAsHex());
char c = '\0';
if ( in.peek() != EOF && in.get(c)) {
line.Append(c);
}
if (line.Length() > maxlinelen) throw MIMEHeader::LineSizeExceededException("Line size exceeded", line, maxlinelen, line.Length());
}
}
}
namespace {
char const *boundarySlotname = "BOUNDARY";
char const *contentLengthSlotname = "CONTENT-LENGTH";
char const *contentDispositionSlotname = "CONTENT-DISPOSITION";
char const *contentTypeSlotname = "CONTENT-TYPE";
String const boundaryToken("boundary=", -1, Coast::Storage::Global());
char const headerNamedDelimiter = ':';
char const contentDispositionDelimiter = ';';
char const headerArgumentsDelimiter = ',';
char const valueArgumentDelimiter = '=';
char const *strPreparedPrefix = "preparedHeaders.";
String const strSplitfields("^(accept|allow|cache-control|connection|content-(encoding|language)|expect|If-None-Match|pragma|Proxy-Authenticate|TE$|trailer|Transfer-Encoding|upgrade|vary|via|warning|WWW-Authenticate)", -1, Coast::Storage::Global());
// Anything const headersREProgram = RECompiler().compile(strSplitfields);
void StoreKeyValue(Anything &headers, String const& strKey, String const &strValue)
{
StartTrace(MIMEHeader.StoreKeyValue);
//!@FIXME: use precompiled RE-Program as soon as RE's ctor takes an ROAnything as program
RE multivalueRE(strSplitfields, RE::MATCH_ICASE);
if ( multivalueRE.ContainedIn(strKey) ) {
Anything &anyValues = headers[strKey];
Coast::URLUtils::Split(strValue, headerArgumentsDelimiter, anyValues, headerArgumentsDelimiter, Coast::URLUtils::eUpshift);
} else if ( strKey.IsEqual(contentDispositionSlotname)) {
Anything &anyValues = headers[strKey];
Coast::URLUtils::Split(strValue, contentDispositionDelimiter, anyValues, valueArgumentDelimiter, Coast::URLUtils::eUpshift);
} else {
Coast::URLUtils::AppendValueTo(headers, strKey, strValue);
}
}
String shiftedHeaderKey(String const &key, Coast::URLUtils::NormalizeTag const shiftFlag) {
return Coast::URLUtils::Normalize(key, shiftFlag);
}
void CheckMultipartBoundary(String const &contenttype, Anything &header, Coast::URLUtils::NormalizeTag const shiftFlag) {
StartTrace1(MIMEHeader.CheckMultipartBoundary, "Content-type: <" << contenttype << ">");
if ((contenttype.Length() >= 9) && (contenttype.Contains("multipart") != -1)) {
long index = contenttype.Contains(boundaryToken.cstr());
if (index > 0) {
String strBoundary = contenttype.SubString(index + boundaryToken.Length());
header[shiftedHeaderKey(boundarySlotname, shiftFlag)] = strBoundary;
Trace("Multipart boundary found: <" << strBoundary << ">");
}
}
}
long GetNormalizedFieldName(String const &line, String &fieldname, Coast::URLUtils::NormalizeTag const normTag) {
StartTrace1(MIMEHeader.GetNormalizedFieldName, "Line: <<<" << line << ">>>");
// following headerfield specification of HTTP/1.1 RFC 2068
long pos = line.StrChr(headerNamedDelimiter);
if (pos > 0) {
fieldname = shiftedHeaderKey(line.SubString(0, pos), normTag);
} Trace("Fieldname: " << fieldname << " Position of " << headerNamedDelimiter << " is: " << pos);
return pos;
}
void SplitAndAddHeaderLine(Anything &headers, String const &line, Coast::URLUtils::NormalizeTag const normTag) {
StartTrace1(MIMEHeader.SplitAndAddHeaderLine, "Line: <<<" << line << ">>>");
// following headerfield specification of HTTP/1.1 RFC 2616 (obsoletes 2068)
String fieldname;
long pos = GetNormalizedFieldName(line, fieldname, normTag);
if (pos <= 0) {
throw MIMEHeader::InvalidLineException("Missing header field name", line);
}
String fieldvalue = line.SubString(pos + 1);
if (fieldvalue.Length()) {
Coast::URLUtils::TrimBlanks(fieldvalue);
StoreKeyValue(headers, fieldname, fieldvalue);
}
if (fieldname.IsEqual(shiftedHeaderKey(contentTypeSlotname, normTag))) {
CheckMultipartBoundary(fieldvalue, headers, normTag);
}
TraceAny(headers, "headers on exit");
}
}
bool MIMEHeader::ParseHeaders(std::istream &in, long const maxlinelen, long const maxheaderlen) {
StartTrace(MIMEHeader.ParseHeaders);
String line(maxlinelen);
long headerlength = 0;
while ( true ) {
Coast::StreamUtils::getLineFromStream(in, line, maxlinelen);
headerlength += line.Length();
Trace("headerlength: " << headerlength << ", maxheaderlen: " << maxheaderlen);
if (not Coast::URLUtils::TrimENDL(line).Length()) {
return true; //!< successful header termination with empty line
}
if (headerlength > maxheaderlen) throw MIMEHeader::HeaderSizeExceededException("Header size exceeded", line, maxheaderlen, headerlength);
SplitAndAddHeaderLine(fHeader, line, fNormalizeKey);
}
return false;
}
//================= multipart specific section
bool MIMEHeader::IsMultiPart() const {
StartTrace(MIMEHeader.IsMultiPart);
return (Lookup(boundarySlotname).AsString().Length() > 0);
}
String MIMEHeader::GetBoundary() const {
String boundary = Lookup(boundarySlotname).AsString();
StatTrace(MIMEHeader.GetBoundary, boundaryToken << boundary, Coast::Storage::Current());
return boundary;
}
long MIMEHeader::GetContentLength() const {
long contentLength = Lookup(contentLengthSlotname).AsLong(-1L);
StatTrace(MIMEHeader.GetContentLength, "length: " << contentLength, Coast::Storage::Current());
return contentLength;
}
bool MIMEHeader::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const {
StartTrace1(MIMEHeader.DoLookup, "key: <" << NotNull(key) << ">" );
return ROAnything(fHeader).LookupPath(result, shiftedHeaderKey(key, fNormalizeKey), delim, indexdelim);
}
<commit_msg>removed unused constant<commit_after>/*
* Copyright (c) 2005, 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 "MIMEHeader.h"
#include "Dbg.h"
#include "AnythingUtils.h"
#include "AnyIterators.h"
#include "RE.h"
//#include "RECompiler.h"
#include <iostream>
#include <cstdio> // for EOF
#include <cstring> // for strlen
MIMEHeader::MIMEHeader(Coast::URLUtils::NormalizeTag normalizeKey) :
fNormalizeKey(normalizeKey) {
StartTrace(MIMEHeader.Ctor);
}
namespace Coast {
namespace StreamUtils {
void getLineFromStream(std::istream &in, String &line, long const maxlinelen) {
StartTrace(MIMEHeader.getLineFromStream);
if ( !in.good() ) throw MIMEHeader::StreamNotGoodException();
// reset line
line.Trim(0L);
// read line up to but not including next LF
line.Append(in, maxlinelen, LF);
Trace("Line length: " << line.Length() << " maxlinelen: " << maxlinelen << "\n" << line.DumpAsHex());
char c = '\0';
if ( in.peek() != EOF && in.get(c)) {
line.Append(c);
}
if (line.Length() > maxlinelen) throw MIMEHeader::LineSizeExceededException("Line size exceeded", line, maxlinelen, line.Length());
}
}
}
namespace {
char const *boundarySlotname = "BOUNDARY";
char const *contentLengthSlotname = "CONTENT-LENGTH";
char const *contentDispositionSlotname = "CONTENT-DISPOSITION";
char const *contentTypeSlotname = "CONTENT-TYPE";
String const boundaryToken("boundary=", -1, Coast::Storage::Global());
char const headerNamedDelimiter = ':';
char const contentDispositionDelimiter = ';';
char const headerArgumentsDelimiter = ',';
char const valueArgumentDelimiter = '=';
String const strSplitfields("^(accept|allow|cache-control|connection|content-(encoding|language)|expect|If-None-Match|pragma|Proxy-Authenticate|TE$|trailer|Transfer-Encoding|upgrade|vary|via|warning|WWW-Authenticate)", -1, Coast::Storage::Global());
// Anything const headersREProgram = RECompiler().compile(strSplitfields);
void StoreKeyValue(Anything &headers, String const& strKey, String const &strValue)
{
StartTrace(MIMEHeader.StoreKeyValue);
//!@FIXME: use precompiled RE-Program as soon as RE's ctor takes an ROAnything as program
RE multivalueRE(strSplitfields, RE::MATCH_ICASE);
if ( multivalueRE.ContainedIn(strKey) ) {
Anything &anyValues = headers[strKey];
Coast::URLUtils::Split(strValue, headerArgumentsDelimiter, anyValues, headerArgumentsDelimiter, Coast::URLUtils::eUpshift);
} else if ( strKey.IsEqual(contentDispositionSlotname)) {
Anything &anyValues = headers[strKey];
Coast::URLUtils::Split(strValue, contentDispositionDelimiter, anyValues, valueArgumentDelimiter, Coast::URLUtils::eUpshift);
} else {
Coast::URLUtils::AppendValueTo(headers, strKey, strValue);
}
}
String shiftedHeaderKey(String const &key, Coast::URLUtils::NormalizeTag const shiftFlag) {
return Coast::URLUtils::Normalize(key, shiftFlag);
}
void CheckMultipartBoundary(String const &contenttype, Anything &header, Coast::URLUtils::NormalizeTag const shiftFlag) {
StartTrace1(MIMEHeader.CheckMultipartBoundary, "Content-type: <" << contenttype << ">");
if ((contenttype.Length() >= 9) && (contenttype.Contains("multipart") != -1)) {
long index = contenttype.Contains(boundaryToken.cstr());
if (index > 0) {
String strBoundary = contenttype.SubString(index + boundaryToken.Length());
header[shiftedHeaderKey(boundarySlotname, shiftFlag)] = strBoundary;
Trace("Multipart boundary found: <" << strBoundary << ">");
}
}
}
long GetNormalizedFieldName(String const &line, String &fieldname, Coast::URLUtils::NormalizeTag const normTag) {
StartTrace1(MIMEHeader.GetNormalizedFieldName, "Line: <<<" << line << ">>>");
// following headerfield specification of HTTP/1.1 RFC 2068
long pos = line.StrChr(headerNamedDelimiter);
if (pos > 0) {
fieldname = shiftedHeaderKey(line.SubString(0, pos), normTag);
} Trace("Fieldname: " << fieldname << " Position of " << headerNamedDelimiter << " is: " << pos);
return pos;
}
void SplitAndAddHeaderLine(Anything &headers, String const &line, Coast::URLUtils::NormalizeTag const normTag) {
StartTrace1(MIMEHeader.SplitAndAddHeaderLine, "Line: <<<" << line << ">>>");
// following headerfield specification of HTTP/1.1 RFC 2616 (obsoletes 2068)
String fieldname;
long pos = GetNormalizedFieldName(line, fieldname, normTag);
if (pos <= 0) {
throw MIMEHeader::InvalidLineException("Missing header field name", line);
}
String fieldvalue = line.SubString(pos + 1);
if (fieldvalue.Length()) {
Coast::URLUtils::TrimBlanks(fieldvalue);
StoreKeyValue(headers, fieldname, fieldvalue);
}
if (fieldname.IsEqual(shiftedHeaderKey(contentTypeSlotname, normTag))) {
CheckMultipartBoundary(fieldvalue, headers, normTag);
}
TraceAny(headers, "headers on exit");
}
}
bool MIMEHeader::ParseHeaders(std::istream &in, long const maxlinelen, long const maxheaderlen) {
StartTrace(MIMEHeader.ParseHeaders);
String line(maxlinelen);
long headerlength = 0;
while ( true ) {
Coast::StreamUtils::getLineFromStream(in, line, maxlinelen);
headerlength += line.Length();
Trace("headerlength: " << headerlength << ", maxheaderlen: " << maxheaderlen);
if (not Coast::URLUtils::TrimENDL(line).Length()) {
return true; //!< successful header termination with empty line
}
if (headerlength > maxheaderlen) throw MIMEHeader::HeaderSizeExceededException("Header size exceeded", line, maxheaderlen, headerlength);
SplitAndAddHeaderLine(fHeader, line, fNormalizeKey);
}
return false;
}
//================= multipart specific section
bool MIMEHeader::IsMultiPart() const {
StartTrace(MIMEHeader.IsMultiPart);
return (Lookup(boundarySlotname).AsString().Length() > 0);
}
String MIMEHeader::GetBoundary() const {
String boundary = Lookup(boundarySlotname).AsString();
StatTrace(MIMEHeader.GetBoundary, boundaryToken << boundary, Coast::Storage::Current());
return boundary;
}
long MIMEHeader::GetContentLength() const {
long contentLength = Lookup(contentLengthSlotname).AsLong(-1L);
StatTrace(MIMEHeader.GetContentLength, "length: " << contentLength, Coast::Storage::Current());
return contentLength;
}
bool MIMEHeader::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const {
StartTrace1(MIMEHeader.DoLookup, "key: <" << NotNull(key) << ">" );
return ROAnything(fHeader).LookupPath(result, shiftedHeaderKey(key, fNormalizeKey), delim, indexdelim);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TextProcessor.hxx"
#include "strmap.hxx"
#include "istream/UnusedPtr.hxx"
#include "istream/SubstIstream.hxx"
#include "widget/Widget.hxx"
#include "widget/Class.hxx"
#include "penv.hxx"
#include "pool/pool.hxx"
#include <assert.h>
gcc_pure
static bool
text_processor_allowed_content_type(const char *content_type)
{
assert(content_type != NULL);
return strncmp(content_type, "text/", 5) == 0 ||
strncmp(content_type, "application/json", 16) == 0 ||
strncmp(content_type, "application/javascript", 22) == 0;
}
bool
text_processor_allowed(const StringMap &headers)
{
const char *content_type = headers.Get("content-type");
return content_type != NULL &&
text_processor_allowed_content_type(content_type);
}
gcc_pure
static const char *
base_uri(struct pool *pool, const char *absolute_uri)
{
const char *p;
if (absolute_uri == NULL)
return NULL;
p = strchr(absolute_uri, ';');
if (p == NULL) {
p = strchr(absolute_uri, '?');
if (p == NULL)
return absolute_uri;
}
return p_strndup(pool, absolute_uri, p - absolute_uri);
}
static SubstTree
processor_subst_beng_widget(struct pool &pool,
const Widget &widget,
const struct processor_env &env)
{
SubstTree subst;
subst.Add(pool, "&c:type;", widget.class_name);
subst.Add(pool, "&c:class;", widget.GetQuotedClassName());
subst.Add(pool, "&c:local;", widget.cls->local_uri);
subst.Add(pool, "&c:id;", widget.id);
subst.Add(pool, "&c:path;", widget.GetIdPath());
subst.Add(pool, "&c:prefix;", widget.GetPrefix());
subst.Add(pool, "&c:uri;", env.absolute_uri);
subst.Add(pool, "&c:base;", base_uri(&pool, env.uri));
subst.Add(pool, "&c:frame;", strmap_get_checked(env.args, "frame"));
subst.Add(pool, "&c:view;", widget.GetEffectiveView()->name);
subst.Add(pool, "&c:session;", nullptr); /* obsolete as of version 15.29 */
return subst;
}
UnusedIstreamPtr
text_processor(struct pool &pool, UnusedIstreamPtr input,
const Widget &widget, const struct processor_env &env)
{
return istream_subst_new(&pool, std::move(input),
processor_subst_beng_widget(pool, widget, env));
}
<commit_msg>bp/TextProcessor: indent with tabs<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TextProcessor.hxx"
#include "strmap.hxx"
#include "istream/UnusedPtr.hxx"
#include "istream/SubstIstream.hxx"
#include "widget/Widget.hxx"
#include "widget/Class.hxx"
#include "penv.hxx"
#include "pool/pool.hxx"
#include <assert.h>
gcc_pure
static bool
text_processor_allowed_content_type(const char *content_type)
{
assert(content_type != NULL);
return strncmp(content_type, "text/", 5) == 0 ||
strncmp(content_type, "application/json", 16) == 0 ||
strncmp(content_type, "application/javascript", 22) == 0;
}
bool
text_processor_allowed(const StringMap &headers)
{
const char *content_type = headers.Get("content-type");
return content_type != NULL &&
text_processor_allowed_content_type(content_type);
}
gcc_pure
static const char *
base_uri(struct pool *pool, const char *absolute_uri)
{
const char *p;
if (absolute_uri == NULL)
return NULL;
p = strchr(absolute_uri, ';');
if (p == NULL) {
p = strchr(absolute_uri, '?');
if (p == NULL)
return absolute_uri;
}
return p_strndup(pool, absolute_uri, p - absolute_uri);
}
static SubstTree
processor_subst_beng_widget(struct pool &pool,
const Widget &widget,
const struct processor_env &env)
{
SubstTree subst;
subst.Add(pool, "&c:type;", widget.class_name);
subst.Add(pool, "&c:class;", widget.GetQuotedClassName());
subst.Add(pool, "&c:local;", widget.cls->local_uri);
subst.Add(pool, "&c:id;", widget.id);
subst.Add(pool, "&c:path;", widget.GetIdPath());
subst.Add(pool, "&c:prefix;", widget.GetPrefix());
subst.Add(pool, "&c:uri;", env.absolute_uri);
subst.Add(pool, "&c:base;", base_uri(&pool, env.uri));
subst.Add(pool, "&c:frame;", strmap_get_checked(env.args, "frame"));
subst.Add(pool, "&c:view;", widget.GetEffectiveView()->name);
subst.Add(pool, "&c:session;", nullptr); /* obsolete as of version 15.29 */
return subst;
}
UnusedIstreamPtr
text_processor(struct pool &pool, UnusedIstreamPtr input,
const Widget &widget, const struct processor_env &env)
{
return istream_subst_new(&pool, std::move(input),
processor_subst_beng_widget(pool, widget, env));
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestRandomPContingencyStatisticsMPI.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* Copyright 2009 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay for implementing this test.
#include <mpi.h>
#include <time.h>
#include "vtkContingencyStatistics.h"
#include "vtkPContingencyStatistics.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
// For debugging purposes, output results of serial engines ran on each slice of the distributed data set
#define PRINT_ALL_SERIAL_STATS 0
struct RandomSampleStatisticsArgs
{
int nVals;
int* retVal;
int ioRank;
int argc;
char** argv;
};
// This will be called by all processes
void RandomSampleStatistics( vtkMultiProcessController* controller, void* arg )
{
// Get test parameters
RandomSampleStatisticsArgs* args = reinterpret_cast<RandomSampleStatisticsArgs*>( arg );
*(args->retVal) = 0;
// Get MPI communicator
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// Get local rank
int myRank = com->GetLocalProcessId();
// Seed random number generator
vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) );
// Generate an input table that contains samples of mutually independent discrete random variables
int nVariables = 2;
vtkIntArray* intArray[2];
vtkStdString columnNames[] = { "Uniform 0",
"Uniform 1" };
vtkTable* inputData = vtkTable::New();
// Discrete uniform samples
for ( int c = 0; c < nVariables; ++ c )
{
intArray[c] = vtkIntArray::New();
intArray[c]->SetNumberOfComponents( 1 );
intArray[c]->SetName( columnNames[c] );
int x;
for ( int r = 0; r < args->nVals; ++ r )
{
x = floor( vtkMath::Random() * 10. ) + 5;
intArray[c]->InsertNextValue( x );
}
inputData->AddColumn( intArray[c] );
intArray[c]->Delete();
}
// ************************** Contingency Statistics **************************
// Synchronize and start clock
com->Barrier();
time_t t0;
time ( &t0 );
// Instantiate a parallel contingency statistics engine and set its ports
vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New();
pcs->SetInput( 0, inputData );
vtkTable* outputData = pcs->GetOutput( 0 );
vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( 1 ) );
// Select column pairs (uniform vs. uniform, normal vs. normal)
pcs->AddColumnPair( columnNames[0], columnNames[1] );
// Test (in parallel) with Learn, Derive, and Assess options turned on
pcs->SetLearn( true );
pcs->SetDerive( true );
pcs->SetAssess( true );
pcs->Update();
// Synchronize and stop clock
com->Barrier();
time_t t1;
time ( &t1 );
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Completed parallel calculation of contingency statistics (with assessment):\n"
<< " \n"
<< " Wall time: "
<< difftime( t1, t0 )
<< " sec.\n";
// for ( unsigned int b = 0; b < outputMetaDS->GetNumberOfBlocks(); ++ b )
for ( unsigned int b = 0; b < 2; ++ b )
{
vtkTable* outputMeta = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) );
outputMeta->Dump();
}
}
com->Barrier();
outputData->Dump();
// Clean up
pcs->Delete();
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
// **************************** MPI Initialization ***************************
vtkMPIController* controller = vtkMPIController::New();
controller->Initialize( &argc, &argv );
// If an MPI controller was not created, terminate in error.
if ( ! controller->IsA( "vtkMPIController" ) )
{
vtkGenericWarningMacro("Failed to initialize a MPI controller.");
controller->Delete();
return 1;
}
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// ************************** Find an I/O node ********************************
int* ioPtr;
int ioRank;
int flag;
MPI_Attr_get( MPI_COMM_WORLD,
MPI_IO,
&ioPtr,
&flag );
if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )
{
// Getting MPI attributes did not return any I/O node found.
ioRank = MPI_PROC_NULL;
vtkGenericWarningMacro("No MPI I/O nodes found.");
// As no I/O node was found, we need an unambiguous way to report the problem.
// This is the only case when a testValue of -1 will be returned
controller->Finalize();
controller->Delete();
return -1;
}
else
{
if ( *ioPtr == MPI_ANY_SOURCE )
{
// Anyone can do the I/O trick--just pick node 0.
ioRank = 0;
}
else
{
// Only some nodes can do I/O. Make sure everyone agrees on the choice (min).
com->AllReduce( ioPtr,
&ioRank,
1,
vtkCommunicator::MIN_OP );
}
}
// ************************** Initialize test *********************************
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Houston, this is process "
<< ioRank
<< " speaking. I'll be the I/O node.\n";
}
// Check how many processes have been made available
int numProcs = controller->GetNumberOfProcesses();
if ( controller->GetLocalProcessId() == ioRank )
{
cout << "\n# Running test with "
<< numProcs
<< " processes...\n";
}
// Parameters for regression test.
int testValue = 0;
RandomSampleStatisticsArgs args;
args.nVals = 20;
args.retVal = &testValue;
args.ioRank = ioRank;
args.argc = argc;
args.argv = argv;
// Execute the function named "process" on both processes
controller->SetSingleMethod( RandomSampleStatistics, &args );
controller->SingleMethodExecute();
// Clean up and exit
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Test completed.\n\n";
}
controller->Finalize();
controller->Delete();
return testValue;
}
<commit_msg>COMP: killed a warning<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestRandomPContingencyStatisticsMPI.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* Copyright 2009 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay for implementing this test.
#include <mpi.h>
#include <time.h>
#include "vtkContingencyStatistics.h"
#include "vtkPContingencyStatistics.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
// For debugging purposes, output results of serial engines ran on each slice of the distributed data set
#define PRINT_ALL_SERIAL_STATS 0
struct RandomSampleStatisticsArgs
{
int nVals;
int* retVal;
int ioRank;
int argc;
char** argv;
};
// This will be called by all processes
void RandomSampleStatistics( vtkMultiProcessController* controller, void* arg )
{
// Get test parameters
RandomSampleStatisticsArgs* args = reinterpret_cast<RandomSampleStatisticsArgs*>( arg );
*(args->retVal) = 0;
// Get MPI communicator
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// Get local rank
int myRank = com->GetLocalProcessId();
// Seed random number generator
vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) );
// Generate an input table that contains samples of mutually independent discrete random variables
int nVariables = 2;
vtkIntArray* intArray[2];
vtkStdString columnNames[] = { "Uniform 0",
"Uniform 1" };
vtkTable* inputData = vtkTable::New();
// Discrete uniform samples
for ( int c = 0; c < nVariables; ++ c )
{
intArray[c] = vtkIntArray::New();
intArray[c]->SetNumberOfComponents( 1 );
intArray[c]->SetName( columnNames[c] );
int x;
for ( int r = 0; r < args->nVals; ++ r )
{
x = static_cast<int>( floor( vtkMath::Random() * 10. ) ) + 5;
intArray[c]->InsertNextValue( x );
}
inputData->AddColumn( intArray[c] );
intArray[c]->Delete();
}
// ************************** Contingency Statistics **************************
// Synchronize and start clock
com->Barrier();
time_t t0;
time ( &t0 );
// Instantiate a parallel contingency statistics engine and set its ports
vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New();
pcs->SetInput( 0, inputData );
vtkTable* outputData = pcs->GetOutput( 0 );
vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( 1 ) );
// Select column pairs (uniform vs. uniform, normal vs. normal)
pcs->AddColumnPair( columnNames[0], columnNames[1] );
// Test (in parallel) with Learn, Derive, and Assess options turned on
pcs->SetLearn( true );
pcs->SetDerive( true );
pcs->SetAssess( true );
pcs->Update();
// Synchronize and stop clock
com->Barrier();
time_t t1;
time ( &t1 );
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Completed parallel calculation of contingency statistics (with assessment):\n"
<< " \n"
<< " Wall time: "
<< difftime( t1, t0 )
<< " sec.\n";
// for ( unsigned int b = 0; b < outputMetaDS->GetNumberOfBlocks(); ++ b )
for ( unsigned int b = 0; b < 2; ++ b )
{
vtkTable* outputMeta = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) );
outputMeta->Dump();
}
}
com->Barrier();
outputData->Dump();
// Clean up
pcs->Delete();
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
// **************************** MPI Initialization ***************************
vtkMPIController* controller = vtkMPIController::New();
controller->Initialize( &argc, &argv );
// If an MPI controller was not created, terminate in error.
if ( ! controller->IsA( "vtkMPIController" ) )
{
vtkGenericWarningMacro("Failed to initialize a MPI controller.");
controller->Delete();
return 1;
}
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// ************************** Find an I/O node ********************************
int* ioPtr;
int ioRank;
int flag;
MPI_Attr_get( MPI_COMM_WORLD,
MPI_IO,
&ioPtr,
&flag );
if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )
{
// Getting MPI attributes did not return any I/O node found.
ioRank = MPI_PROC_NULL;
vtkGenericWarningMacro("No MPI I/O nodes found.");
// As no I/O node was found, we need an unambiguous way to report the problem.
// This is the only case when a testValue of -1 will be returned
controller->Finalize();
controller->Delete();
return -1;
}
else
{
if ( *ioPtr == MPI_ANY_SOURCE )
{
// Anyone can do the I/O trick--just pick node 0.
ioRank = 0;
}
else
{
// Only some nodes can do I/O. Make sure everyone agrees on the choice (min).
com->AllReduce( ioPtr,
&ioRank,
1,
vtkCommunicator::MIN_OP );
}
}
// ************************** Initialize test *********************************
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Houston, this is process "
<< ioRank
<< " speaking. I'll be the I/O node.\n";
}
// Check how many processes have been made available
int numProcs = controller->GetNumberOfProcesses();
if ( controller->GetLocalProcessId() == ioRank )
{
cout << "\n# Running test with "
<< numProcs
<< " processes...\n";
}
// Parameters for regression test.
int testValue = 0;
RandomSampleStatisticsArgs args;
args.nVals = 20;
args.retVal = &testValue;
args.ioRank = ioRank;
args.argc = argc;
args.argv = argv;
// Execute the function named "process" on both processes
controller->SetSingleMethod( RandomSampleStatistics, &args );
controller->SingleMethodExecute();
// Clean up and exit
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Test completed.\n\n";
}
controller->Finalize();
controller->Delete();
return testValue;
}
<|endoftext|>
|
<commit_before><commit_msg>dumpStatistics when an error in writeFrame occures<commit_after><|endoftext|>
|
<commit_before>/*
* This code is based off Adam Nielsen's cfgpath C header found at
* https://github.com/Malvineous/cfgpath
*
* Following his code being public domain I have licensed this using the
* unlicense http://unlicense.org/. Full license text is available in
* the LICENSE file
*/
#include "cfgpath.hpp"
#include <stdexcept>
\
#ifdef _WIN32
#include <shlobj.h>
#endif
string cfgpath::get_user_config_folder(const string& appname) {
//Windows first, then Apple, then other *nixes
string cfgPath;
#ifdef WIN32
TCHAR _confPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, _confPath))) {
throw std::runtime_error("Unable to get path from system");
}
cfgPath=_confPath;
cfgPath+= '\\';
#elif defined(__APPLE__)
#elif defined(__UNIX__)
#else
#endif
return cfgPath;
}
<commit_msg>Fixed unix identifier<commit_after>/*
* This code is based off Adam Nielsen's cfgpath C header found at
* https://github.com/Malvineous/cfgpath
*
* Following his code being public domain I have licensed this using the
* unlicense http://unlicense.org/. Full license text is available in
* the LICENSE file
*/
#include "cfgpath.hpp"
#include <stdexcept>
\
#ifdef _WIN32
#include <shlobj.h>
#endif
string cfgpath::get_user_config_folder(const string& appname) {
//Windows first, then Apple, then other *nixes
string cfgPath;
#ifdef WIN32
TCHAR _confPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, _confPath))) {
throw std::runtime_error("Unable to get path from system");
}
cfgPath=_confPath;
cfgPath+= '\\';
#elif defined(__APPLE__)
#elif defined(__unix__)
cfgPath = "test";
#else
#endif
return cfgPath;
}
<|endoftext|>
|
<commit_before>/*
* This code is based off Adam Nielsen's cfgpath C header found at
* https://github.com/Malvineous/cfgpath
*
* Following his code being public domain I have licensed this using the
* unlicense http://unlicense.org/. Full license text is available in
* the LICENSE file
*/
#include "cfgpath.hpp"
#include <stdexcept>
#include <cstdlib>
\
#ifdef _WIN32
#include <shlobj.h>
#include <direct.h>
const char _pathSep = '\\';
#endif
#ifdef __unix__
#include <sys/stat.h>
const char _pathSep = '/';
#endif
string get_standard_config_path() {
string cfgPath;
//Windows first, then Apple, then other *nixes
#ifdef WIN32
//using ansi windows for now
//assume appdata directory exists
char _confPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, _confPath))) {
throw std::runtime_error("Unable to get standard config path from system");
}
cfgPath=_confPath;
cfgPath+= '\\';
#elif defined(__APPLE__)
#elif defined(__unix__)
//Follow XDG Specification
//Assume $XDG_CONFIG_HOME exists if it's set
//Assume $HOME exists if it's set
const char * _confHome = getenv("XDG_CONFIG_HOME");
if (!_confHome) {
//XDG_CONFIG_HOME isn't set. USE $HOME/.config
_confHome = getenv("HOME");
if (!_confHome) throw std::runtime_error("Unable to find home directory");
cfgPath = _confHome;
cfgPath += '/';
cfgPath += ".config";
if (mkdir(cfgPath.c_str(), 0700) != 0 && errno != EEXIST)
throw std::runtime_error("Unable to create .config in user home");
} else {
cfgPath=_confHome;
}
cfgPath += '/';
#else
throw std::logic_error("Incompatible OS");
#endif
return cfgPath;
}
bool createDirectoryIfNotExist(const string& path) {
#ifdef WIN32
return (_mkdir(path.c_str()) == 0 || errno == EEXIST);
#elif defined(__APPLE__)
#elif defined(__unix__)
return (mkdir(path.c_str(), 0700) == 0 || errno == EEXIST)
#else
throw std::logic_error("Incompatible OS");
#endif
}
bool createFileIfNotExist(const string& path) {
return true;
}
string cfgpath::get_user_config_folder(const string& appname) {
string cfgPath = get_standard_config_path();
cfgPath += appname;
if (!createDirectoryIfNotExist(cfgPath))
throw std::runtime_error("Unable to create application config directory");
cfgPath += _pathSep;
return cfgPath;
}
string cfgpath::get_user_config_file(const string& appname) {
string cfgPath = get_standard_config_path();
cfgPath += appname;
if (!createFileIfNotExist(cfgPath))
throw std::runtime_error("Unable to create application config file");
return cfgPath;
}
<commit_msg>Stringstreams and path seperators<commit_after>/*
* This code is based off Adam Nielsen's cfgpath C header found at
* https://github.com/Malvineous/cfgpath
*
* Following his code being public domain I have licensed this using the
* unlicense http://unlicense.org/. Full license text is available in
* the LICENSE file
*/
#include "cfgpath.hpp"
#include <sstream>
#include <stdexcept>
#include <cstdlib>
\
#ifdef _WIN32
#include <shlobj.h>
#include <direct.h>
const char _pathSep = '\\';
#endif
#ifdef __unix__
#include <sys/stat.h>
const char _pathSep = '/';
#endif
using std::stringstream;
string get_standard_config_path() {
stringstream cfgPath;
//Windows first, then Apple, then other *nixes
#ifdef WIN32
//using ansi windows for now
//assume appdata directory exists
char _confPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, _confPath))) {
throw std::runtime_error("Unable to get standard config path from system");
}
cfgPath<< _confPath;
cfgPath<< _pathSep;
#elif defined(__APPLE__)
#elif defined(__unix__)
//Follow XDG Specification
//Assume $XDG_CONFIG_HOME exists if it's set
//Assume $HOME exists if it's set
const char * _confHome = getenv("XDG_CONFIG_HOME");
if (!_confHome) {
//XDG_CONFIG_HOME isn't set. USE $HOME/.config
_confHome = getenv("HOME");
if (!_confHome) throw std::runtime_error("Unable to find home directory");
cfgPath << _confHome;
cfgPath << _pathSep;
cfgPath << ".config";
if (mkdir(cfgPath.c_str(), 0700) != 0 && errno != EEXIST)
throw std::runtime_error("Unable to create .config in user home");
} else {
cfgPath << _confHome;
}
cfgPath << _pathSep;
#else
throw std::logic_error("Incompatible OS");
#endif
return cfgPath.str();
}
bool createDirectoryIfNotExist(const string& path) {
#ifdef WIN32
return (_mkdir(path.c_str()) == 0 || errno == EEXIST);
#elif defined(__APPLE__)
#elif defined(__unix__)
return (mkdir(path.c_str(), 0700) == 0 || errno == EEXIST)
#else
throw std::logic_error("Incompatible OS");
#endif
}
bool createFileIfNotExist(const string& path) {
return true;
}
string cfgpath::get_user_config_folder(const string& appname) {
stringstream cfgPath;
cfgPath << get_standard_config_path();
cfgPath << appname;
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create application config directory");
cfgPath << _pathSep;
return cfgPath.str();
}
string cfgpath::get_user_config_file(const string& appname) {
stringstream cfgPath;
cfgPath << get_standard_config_path();
cfgPath << appname;
if (!createFileIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create application config file");
return cfgPath.str();
}
<|endoftext|>
|
<commit_before><commit_msg>`EntityFactory` factory functions set global name and local name.<commit_after><|endoftext|>
|
<commit_before>
// A few useful routines which are used in CGI programs.
//
// ReZa 9/30/94
// $Log: cgi_util.cc,v $
// Revision 1.4 1995/03/16 16:29:24 reza
// Fixed bugs in ErrMsgT and mime type.
//
// Revision 1.3 1995/02/22 21:03:59 reza
// Added version number capability using CGI status_line.
//
// Revision 1.2 1995/02/22 19:53:32 jimg
// Fixed usage of time functions in ErrMsgT; use ctime instead of localtime
// and asctime.
// Fixed TimStr bug in ErrMsgT.
// Fixed dynamic memory bugs in name_path and fmakeword.
// Replaced malloc calls with calls to new char[]; C++ code will expect to
// be able to use delete.
// Fixed memory overrun error in fmakeword.
// Fixed potential bug in name_path (when called with null argument).
// Added assetions.
//
// Revision 1.1 1995/01/10 16:23:01 jimg
// Created new `common code' library for the net I/O stuff.
//
// Revision 1.1 1994/10/28 14:34:01 reza
// First version
static char rcsid[]={"$Id: cgi_util.cc,v 1.4 1995/03/16 16:29:24 reza Exp $"};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <iostream.h>
#include <String.h>
#ifdef TRACE_NEW
#include "trace_new.h"
#endif
#ifndef FILE_DELIMITER // default to unix
#define FILE_DELIMITER '/'
#endif
#define TimLen 26 // length of string from asctime()
#define CLUMP_SIZE 1024 // size of clumps to new in fmakeword()
// An error handling routine to append the error messege from CGI programs,
// a time stamp, and the client host name (or address) to HTTPD error-log.
// Use this instead of the functions in liberrmsg.a in the programs run by
// the CGIs to report errors so those errors show up in HTTPD's log files.
//
// Returns: void
void
ErrMsgT(char *Msgt)
{
#ifdef NEVER
// main() should call setlocale(); don't override its call. jhrg
(void)setlocale(LC_ALL, "");
#endif
time_t TimBin;
char TimStr[TimLen];
if (time(&TimBin) == (time_t)-1)
strcpy(TimStr, "time() error ");
else {
strcpy(TimStr, ctime(&TimBin));
TimStr[TimLen - 2] = '\0'; // overwrite the \n
}
if(getenv("REMOTE_HOST"))
cerr << "[" << TimStr << "] CGI: " << getenv("SCRIPT_NAME")
<< " faild for "
<< getenv("REMOTE_HOST")
<< " reason: "<< Msgt << endl;
else
cerr << "[" << TimStr << "] CGI: " << getenv("SCRIPT_NAME")
<< " faild for "
<< getenv("REMOTE_ADDR")
<< " reason: "<< Msgt << endl;
}
// Given an open FILE *IN, a separator character (in STOP) and the number of
// characters in the thing referenced by IN, return characters upto the
// STOP. The STOP character itself is discarded. Memory for the new word is
// dynamically allocated using C++'s new facility. In addition, the count of
// characters in the input source (CL; content length) is decremented.
//
// Once CL is zero, do not continue calling this function!
//
// Returns: a newly allocated string.
char *
fmakeword(FILE *f, const char stop, int *cl)
{
assert(f && stop && *cl);
int wsize = CLUMP_SIZE;
int ll = 0;
char *word = new char[wsize + 1];
while(1) {
assert(ll <= wsize);
word[ll] = (char)fgetc(f);
// If the word size is exceeded, allocate more space. What a kluge.
if(ll == wsize) {
wsize += CLUMP_SIZE;
char *tmp_word_buf = new char[wsize + 1];
memcpy(tmp_word_buf, word, wsize - (CLUMP_SIZE - 1));
delete word;
word = tmp_word_buf;
}
--(*cl);
if((word[ll] == stop) || (feof(f)) || (!(*cl))) {
if(word[ll] != stop)
ll++;
assert(ll <= wsize);
word[ll] = '\0';
return word;
}
++ll;
}
}
// Given a pathname, return just the filename component with any extension
// removed. The new string resides in newly allocated memory; the caller must
// delete it when done using the filename.
// Originally from the netcdf distribution (ver 2.3.2).
//
// *** Change to String class argument and return type. jhrg
//
// Returns: A filename, with path and extension information removed. If
// memory for the new name cannot be allocated, does not return!
char *
name_path(char *path)
{
if (!path)
return NULL;
char *cp = strrchr(path, FILE_DELIMITER);
if (cp == 0) // no delimiter
cp = path;
else // skip delimeter
cp++;
char *newp = new char[strlen(cp)+1];
if (newp == 0) {
ErrMsgT("name_path: out of memory.");
exit(-1);
}
(void) strcpy(newp, cp); // copy last component of path
if ((cp = strrchr(newp, '.')) != NULL)
*cp = '\0'; /* strip off any extension */
return newp;
}
// Send string to set the transfer (mime) type and server version
//
void
set_mime_text()
{
cout << "Status: 200 " << DVR << endl; /* send server version */
cout << "Content-type: text/plain\n" << endl;
}
void
set_mime_binary()
{
cout << "Status: 200 " << DVR << endl;
cout << "Content-type: application/octet-stream\n" << endl;
}
#ifdef TEST_CGI_UTIL
int
main(int argc, char *argv[])
{
// test ErrMsgT
ErrMsgT("Error");
String smsg = "String Error";
ErrMsgT(smsg);
char *cmsg = "char * error";
ErrMsgT(cmsg);
ErrMsgT("");
ErrMsgT(NULL);
// test fmakeword
FILE *in = fopen("./fmakeword.input", "r");
char stop = ' ';
int content_len = 68;
while (content_len) {
char *word = fmakeword(in, stop, &content_len);
cout << "Word: " << word << endl;
delete word;
}
fclose(in);
// this tests buffer extension in fmakeword, two words are 1111 and 11111
// char respectively.
in = fopen("./fmakeword2.input", "r");
stop = ' ';
content_len = 12467;
while (content_len) {
char *word = fmakeword(in, stop, &content_len);
cout << "Word: " << word << endl;
delete word;
}
fclose(in);
// test name_path
char *name = "stuff";
cout << name << ": " << name_path(name) << endl;
name = "stuff.Z";
cout << name << ": " << name_path(name) << endl;
name = "/usr/local/src/stuff.Z";
cout << name << ": " << name_path(name) << endl;
name = "/usr/local/src/stuff.tar.Z";
cout << name << ": " << name_path(name) << endl;
name = "/usr/local/src/stuff";
cout << name << ": " << name_path(name) << endl;
name = "";
cout << name << ": " << name_path(name) << endl;
name = 0;
cout << name << ": " << name_path(name) << endl;
}
#endif
<commit_msg>Added #include "config_netio.h" Removed old code.<commit_after>
// A few useful routines which are used in CGI programs.
//
// ReZa 9/30/94
// $Log: cgi_util.cc,v $
// Revision 1.5 1995/05/22 20:36:10 jimg
// Added #include "config_netio.h"
// Removed old code.
//
// Revision 1.4 1995/03/16 16:29:24 reza
// Fixed bugs in ErrMsgT and mime type.
//
// Revision 1.3 1995/02/22 21:03:59 reza
// Added version number capability using CGI status_line.
//
// Revision 1.2 1995/02/22 19:53:32 jimg
// Fixed usage of time functions in ErrMsgT; use ctime instead of localtime
// and asctime.
// Fixed TimStr bug in ErrMsgT.
// Fixed dynamic memory bugs in name_path and fmakeword.
// Replaced malloc calls with calls to new char[]; C++ code will expect to
// be able to use delete.
// Fixed memory overrun error in fmakeword.
// Fixed potential bug in name_path (when called with null argument).
// Added assetions.
//
// Revision 1.1 1995/01/10 16:23:01 jimg
// Created new `common code' library for the net I/O stuff.
//
// Revision 1.1 1994/10/28 14:34:01 reza
// First version
static char rcsid[]={"$Id: cgi_util.cc,v 1.5 1995/05/22 20:36:10 jimg Exp $"};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <iostream.h>
#include <String.h>
#include "config_netio.h"
#ifdef TRACE_NEW
#include "trace_new.h"
#endif
#ifndef FILE_DELIMITER // default to unix
#define FILE_DELIMITER '/'
#endif
#define TimLen 26 // length of string from asctime()
#define CLUMP_SIZE 1024 // size of clumps to new in fmakeword()
// An error handling routine to append the error messege from CGI programs,
// a time stamp, and the client host name (or address) to HTTPD error-log.
// Use this instead of the functions in liberrmsg.a in the programs run by
// the CGIs to report errors so those errors show up in HTTPD's log files.
//
// Returns: void
void
ErrMsgT(char *Msgt)
{
time_t TimBin;
char TimStr[TimLen];
if (time(&TimBin) == (time_t)-1)
strcpy(TimStr, "time() error ");
else {
strcpy(TimStr, ctime(&TimBin));
TimStr[TimLen - 2] = '\0'; // overwrite the \n
}
if(getenv("REMOTE_HOST"))
cerr << "[" << TimStr << "] CGI: " << getenv("SCRIPT_NAME")
<< " faild for "
<< getenv("REMOTE_HOST")
<< " reason: "<< Msgt << endl;
else
cerr << "[" << TimStr << "] CGI: " << getenv("SCRIPT_NAME")
<< " faild for "
<< getenv("REMOTE_ADDR")
<< " reason: "<< Msgt << endl;
}
// Given an open FILE *IN, a separator character (in STOP) and the number of
// characters in the thing referenced by IN, return characters upto the
// STOP. The STOP character itself is discarded. Memory for the new word is
// dynamically allocated using C++'s new facility. In addition, the count of
// characters in the input source (CL; content length) is decremented.
//
// Once CL is zero, do not continue calling this function!
//
// Returns: a newly allocated string.
char *
fmakeword(FILE *f, const char stop, int *cl)
{
assert(f && stop && *cl);
int wsize = CLUMP_SIZE;
int ll = 0;
char *word = new char[wsize + 1];
while(1) {
assert(ll <= wsize);
word[ll] = (char)fgetc(f);
// If the word size is exceeded, allocate more space. What a kluge.
if(ll == wsize) {
wsize += CLUMP_SIZE;
char *tmp_word_buf = new char[wsize + 1];
memcpy(tmp_word_buf, word, wsize - (CLUMP_SIZE - 1));
delete word;
word = tmp_word_buf;
}
--(*cl);
if((word[ll] == stop) || (feof(f)) || (!(*cl))) {
if(word[ll] != stop)
ll++;
assert(ll <= wsize);
word[ll] = '\0';
return word;
}
++ll;
}
}
// Given a pathname, return just the filename component with any extension
// removed. The new string resides in newly allocated memory; the caller must
// delete it when done using the filename.
// Originally from the netcdf distribution (ver 2.3.2).
//
// *** Change to String class argument and return type. jhrg
//
// Returns: A filename, with path and extension information removed. If
// memory for the new name cannot be allocated, does not return!
char *
name_path(char *path)
{
if (!path)
return NULL;
char *cp = strrchr(path, FILE_DELIMITER);
if (cp == 0) // no delimiter
cp = path;
else // skip delimeter
cp++;
char *newp = new char[strlen(cp)+1];
if (newp == 0) {
ErrMsgT("name_path: out of memory.");
exit(-1);
}
(void) strcpy(newp, cp); // copy last component of path
if ((cp = strrchr(newp, '.')) != NULL)
*cp = '\0'; /* strip off any extension */
return newp;
}
// Send string to set the transfer (mime) type and server version
//
void
set_mime_text()
{
cout << "Status: 200 " << DVR << endl; /* send server version */
cout << "Content-type: text/plain\n" << endl;
}
void
set_mime_binary()
{
cout << "Status: 200 " << DVR << endl;
cout << "Content-type: application/octet-stream\n" << endl;
}
#ifdef TEST_CGI_UTIL
int
main(int argc, char *argv[])
{
// test ErrMsgT
ErrMsgT("Error");
String smsg = "String Error";
ErrMsgT(smsg);
char *cmsg = "char * error";
ErrMsgT(cmsg);
ErrMsgT("");
ErrMsgT(NULL);
// test fmakeword
FILE *in = fopen("./fmakeword.input", "r");
char stop = ' ';
int content_len = 68;
while (content_len) {
char *word = fmakeword(in, stop, &content_len);
cout << "Word: " << word << endl;
delete word;
}
fclose(in);
// this tests buffer extension in fmakeword, two words are 1111 and 11111
// char respectively.
in = fopen("./fmakeword2.input", "r");
stop = ' ';
content_len = 12467;
while (content_len) {
char *word = fmakeword(in, stop, &content_len);
cout << "Word: " << word << endl;
delete word;
}
fclose(in);
// test name_path
char *name = "stuff";
cout << name << ": " << name_path(name) << endl;
name = "stuff.Z";
cout << name << ": " << name_path(name) << endl;
name = "/usr/local/src/stuff.Z";
cout << name << ": " << name_path(name) << endl;
name = "/usr/local/src/stuff.tar.Z";
cout << name << ": " << name_path(name) << endl;
name = "/usr/local/src/stuff";
cout << name << ": " << name_path(name) << endl;
name = "";
cout << name << ": " << name_path(name) << endl;
name = 0;
cout << name << ": " << name_path(name) << endl;
}
#endif
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "AudioMenu.h"
/* system implementation headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "TextUtils.h"
#include "FontManager.h"
/* local implementation headers */
#include "StateDatabase.h"
#include "MainMenu.h"
#include "sound.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiList.h"
#include "HUDuiTypeIn.h"
AudioMenu::AudioMenu()
{
// add controls
std::vector<HUDuiControl*>& list = getControls();
std::string currentDriver = BZDB.get("audioDriver");
std::string currentDevice = BZDB.get("audioDevice");
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(MainMenu::getFontFace());
label->setString("Audio Settings");
list.push_back(label);
HUDuiList* option = new HUDuiList;
option = new HUDuiList;
std::vector<std::string>* options;
// Sound Volume
option = new HUDuiList;
option->setFontFace(MainMenu::getFontFace());
option->setLabel("Sound Volume:");
option->setCallback(callback, (void*)"s");
options = &option->getList();
if (isSoundOpen()) {
options->push_back(std::string("Off"));
option->createSlider(10);
} else {
options->push_back(std::string("Unavailable"));
}
option->update();
list.push_back(option);
/* Right now only SDL_Media has a setDriver function.
Disable driver selection for others as it gets saved in config
and can screw things up if you switch from non-SDL to SDL build.
If more platforms get setDriver functions, they can be added. */
// Driver
#ifdef HAVE_SDL
driver = new HUDuiTypeIn;
driver->setFontFace(MainMenu::getFontFace());
driver->setLabel("Driver:");
driver->setMaxLength(10);
driver->setString(currentDriver);
list.push_back(driver);
#else
driver = NULL;
#endif // HAVE_SDL
// Device
#ifdef HAVE_SDL
device = new HUDuiTypeIn;
device->setFontFace(MainMenu::getFontFace());
device->setLabel("Device:");
device->setMaxLength(10);
device->setString(currentDevice);
list.push_back(device);
#else
device = NULL;
#endif // HAVE_SDL
// Remotes Sounds
option = new HUDuiList;
option->setFontFace(MainMenu::getFontFace());
option->setLabel("Remote Sounds:");
option->setCallback(callback, (void*)"r");
options = &option->getList();
options->push_back(std::string("Off"));
options->push_back(std::string("On"));
option->update();
list.push_back(option);
initNavigation(list, 1,list.size()-1);
}
AudioMenu::~AudioMenu()
{
}
void AudioMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == driver) {
BZDB.set("audioDriver", driver->getString().c_str());
} else if (focus == device) {
BZDB.set("audioDevice", device->getString().c_str());
}
}
void AudioMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
int i;
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 45.0f;
FontManager &fm = FontManager::instance();
int fontFace = MainMenu::getFontFace();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " ");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width);
y -= 0.6f * titleHeight;
const float h = fm.getStrHeight(fontFace, fontSize, " ");
const int count = list.size();
for (i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
}
i = 1;
// sound
((HUDuiList*)list[i++])->setIndex(getSoundVolume());
i++; // driver
i++; // device
((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("remoteSounds") ? 1 : 0);
}
void AudioMenu::callback(HUDuiControl* w, void* data) {
HUDuiList* list = (HUDuiList*)w;
std::vector<std::string> *options = &list->getList();
std::string selectedOption = (*options)[list->getIndex()];
switch (((const char*)data)[0]) {
case 's':
BZDB.set("volume", TextUtils::format("%d", list->getIndex()));
setSoundVolume(list->getIndex());
break;
case 'r':
BZDB.setBool("remoteSounds", (list->getIndex() == 0) ? false : true);
break;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>fix the audio menu when not using SDL<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "AudioMenu.h"
/* system implementation headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "TextUtils.h"
#include "FontManager.h"
/* local implementation headers */
#include "StateDatabase.h"
#include "MainMenu.h"
#include "sound.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiList.h"
#include "HUDuiTypeIn.h"
AudioMenu::AudioMenu()
{
// add controls
std::vector<HUDuiControl*>& list = getControls();
std::string currentDriver = BZDB.get("audioDriver");
std::string currentDevice = BZDB.get("audioDevice");
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(MainMenu::getFontFace());
label->setString("Audio Settings");
list.push_back(label);
HUDuiList* option = new HUDuiList;
option = new HUDuiList;
std::vector<std::string>* options;
// Sound Volume
option = new HUDuiList;
option->setFontFace(MainMenu::getFontFace());
option->setLabel("Sound Volume:");
option->setCallback(callback, (void*)"s");
options = &option->getList();
if (isSoundOpen()) {
options->push_back(std::string("Off"));
option->createSlider(10);
} else {
options->push_back(std::string("Unavailable"));
}
option->update();
list.push_back(option);
/* Right now only SDL_Media has a setDriver function.
Disable driver selection for others as it gets saved in config
and can screw things up if you switch from non-SDL to SDL build.
If more platforms get setDriver functions, they can be added. */
// Driver
#ifdef HAVE_SDL
driver = new HUDuiTypeIn;
driver->setFontFace(MainMenu::getFontFace());
driver->setLabel("Driver:");
driver->setMaxLength(10);
driver->setString(currentDriver);
list.push_back(driver);
#else
driver = NULL;
#endif // HAVE_SDL
// Device
#ifdef HAVE_SDL
device = new HUDuiTypeIn;
device->setFontFace(MainMenu::getFontFace());
device->setLabel("Device:");
device->setMaxLength(10);
device->setString(currentDevice);
list.push_back(device);
#else
device = NULL;
#endif // HAVE_SDL
// Remotes Sounds
option = new HUDuiList;
option->setFontFace(MainMenu::getFontFace());
option->setLabel("Remote Sounds:");
option->setCallback(callback, (void*)"r");
options = &option->getList();
options->push_back(std::string("Off"));
options->push_back(std::string("On"));
option->update();
list.push_back(option);
initNavigation(list, 1, list.size() - 1);
}
AudioMenu::~AudioMenu()
{
}
void AudioMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == driver) {
BZDB.set("audioDriver", driver->getString().c_str());
} else if (focus == device) {
BZDB.set("audioDevice", device->getString().c_str());
}
}
void AudioMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
int i;
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 45.0f;
FontManager &fm = FontManager::instance();
int fontFace = MainMenu::getFontFace();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " ");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width);
y -= 0.6f * titleHeight;
const float h = fm.getStrHeight(fontFace, fontSize, " ");
const int count = list.size();
for (i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
}
i = 1;
// sound
((HUDuiList*)list[i++])->setIndex(getSoundVolume());
#ifdef HAVE_SDL
i++; // driver
i++; // device
#endif // HAVE_SDL
((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("remoteSounds") ? 1 : 0);
}
void AudioMenu::callback(HUDuiControl* w, void* data) {
HUDuiList* list = (HUDuiList*)w;
std::vector<std::string> *options = &list->getList();
std::string selectedOption = (*options)[list->getIndex()];
switch (((const char*)data)[0]) {
case 's':
BZDB.set("volume", TextUtils::format("%d", list->getIndex()));
setSoundVolume(list->getIndex());
break;
case 'r':
BZDB.setBool("remoteSounds", (list->getIndex() == 0) ? false : true);
break;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <string>
#include <vector>
#include "common.h"
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "commands.h"
#include "bzfsAPI.h"
#include "DirectoryNames.h"
#ifdef _WIN32
std::string extension = ".dll";
std::string globalPluginDir = ".\\plugins\\";
#else
std::string extension = ".so";
std::string globalPluginDir = "$(prefix)/lib/bzflag/";
#endif
typedef struct
{
std::string plugin;
#ifdef _WIN32
HINSTANCE handle;
#else
void* handle;
#endif
}trPluginRecord;
std::string findPlugin ( std::string pluginName )
{
// see if we can just open the bloody thing
FILE *fp = fopen(pluginName.c_str(),"rb");
if (fp)
{
fclose(fp);
return pluginName;
}
// now try it with the standard extension
std::string name = pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the local users plugins dir
name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the global plugins dir
name = globalPluginDir + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
return std::string("");
}
std::vector<trPluginRecord> vPluginList;
void unload1Plugin ( int iPluginID );
#ifdef _WIN32
#include <windows.h>
int getPluginVersion ( HINSTANCE hLib )
{
int (*lpProc)(void);
lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion");
if (lpProc)
return lpProc();
return 0;
}
void loadPlugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
HINSTANCE hLib = LoadLibrary(realPluginName.c_str());
if (hLib)
{
if (getPluginVersion(hLib) < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
FreeLibrary(hLib);
}
else
{
lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
if (lpProc)
{
lpProc(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
else
{
DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
FreeLibrary(hLib);
}
}
}
else
DEBUG1("Plugin:%s not found\n",plugin.c_str());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload");
if (lpProc)
lpProc();
else
DEBUG1("Plugin does not contain bz_UnLoad method\n");
FreeLibrary(plugin.handle);
plugin.handle = NULL;
}
#else
#include <dlfcn.h>
std::vector<void*> vLibHandles;
int getPluginVersion ( void* hLib )
{
int (*lpProc)(void);
*(void**) &lpProc = dlsym(hLib,"bz_GetVersion");
if (lpProc)
return (*lpProc)();
return 0;
}
void loadPlugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
void* hLib = dlopen(realPluginName.c_str(),RTLD_LAZY);
if (hLib)
{
if (getPluginVersion(hLib) < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
dlclose(hLib);
}
else
{
*(void**) &lpProc = dlsym(hLib,"bz_Load");
if (lpProc)
{
(*lpProc)(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
else
{
DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
dlclose(hLib);
}
}
}
else
DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
*(void**) &lpProc = dlsym(plugin.handle, "bz_Unload");
if (lpProc)
(*lpProc)();
else
DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());
dlclose(plugin.handle);
plugin.handle = NULL;
}
#endif
void unloadPlugin ( std::string plugin )
{
// unload the first one of the name we find
for (unsigned int i = 0; i < vPluginList.size();i++)
{
if ( vPluginList[i].plugin == plugin )
{
unload1Plugin(i);
vPluginList.erase(vPluginList.begin()+i);
return;
}
}
}
void unloadPlugins ( void )
{
for (unsigned int i = 0; i < vPluginList.size();i++)
unload1Plugin(i);
vPluginList.clear();
removeCustomSlashCommand("loadplugin");
removeCustomSlashCommand("unloadplugin");
removeCustomSlashCommand("listplugins");
}
std::vector<std::string> getPluginList ( void )
{
std::vector<std::string> plugins;
for (unsigned int i = 0; i < vPluginList.size();i++)
plugins.push_back(vPluginList[i].plugin);
return plugins;
}
void parseServerCommand(const char *message, int dstPlayerId);
class DynamicPluginCommands : public CustomSlashCommandHandler
{
public:
virtual ~DynamicPluginCommands(){};
virtual bool handle ( int playerID, std::string command, std::string message )
{
bz_PlayerRecord record;
bz_getPlayerByIndex(playerID,&record);
if ( !record.admin )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Permision denied: ADMIN");
return true;
}
if ( !message.size() )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Error: Command must have a plugin name");
return true;
}
if ( TextUtils::tolower(command) == "loadplugin" )
{
std::vector<std::string> params = TextUtils::tokenize(message,std::string(","));
std::string config;
if ( params.size() >1)
config = params[1];
loadPlugin(params[0],config);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded");
return true;
}
if ( TextUtils::tolower(command) == "unloadplugin" )
{
unloadPlugin(message);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded");
return true;
}
if ( TextUtils::tolower(command) == "listplugins" )
{
std::vector<std::string> plugins = getPluginList();
if (!plugins.size())
bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded;");
else
{
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-isn loaded;");
for ( unsigned int i = 0; i < plugins.size(); i++)
bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str());
}
return true;
}
return true;
}
};
DynamicPluginCommands command;
void initPlugins ( void )
{
registerCustomSlashCommand("loadplugin",&command);
registerCustomSlashCommand("unloadplugin",&command);
registerCustomSlashCommand("listplugins",&command);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>plugins need to be loaded with RTLD_GLOBAL in order for symbol resolution on further libraries to work, like, say, a python builtin<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <string>
#include <vector>
#include "common.h"
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "commands.h"
#include "bzfsAPI.h"
#include "DirectoryNames.h"
#ifdef _WIN32
std::string extension = ".dll";
std::string globalPluginDir = ".\\plugins\\";
#else
std::string extension = ".so";
std::string globalPluginDir = "$(prefix)/lib/bzflag/";
#endif
typedef struct
{
std::string plugin;
#ifdef _WIN32
HINSTANCE handle;
#else
void* handle;
#endif
}trPluginRecord;
std::string findPlugin ( std::string pluginName )
{
// see if we can just open the bloody thing
FILE *fp = fopen(pluginName.c_str(),"rb");
if (fp)
{
fclose(fp);
return pluginName;
}
// now try it with the standard extension
std::string name = pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the local users plugins dir
name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the global plugins dir
name = globalPluginDir + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
return std::string("");
}
std::vector<trPluginRecord> vPluginList;
void unload1Plugin ( int iPluginID );
#ifdef _WIN32
#include <windows.h>
int getPluginVersion ( HINSTANCE hLib )
{
int (*lpProc)(void);
lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion");
if (lpProc)
return lpProc();
return 0;
}
void loadPlugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
HINSTANCE hLib = LoadLibrary(realPluginName.c_str());
if (hLib)
{
if (getPluginVersion(hLib) < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
FreeLibrary(hLib);
}
else
{
lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
if (lpProc)
{
lpProc(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
else
{
DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
FreeLibrary(hLib);
}
}
}
else
DEBUG1("Plugin:%s not found\n",plugin.c_str());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload");
if (lpProc)
lpProc();
else
DEBUG1("Plugin does not contain bz_UnLoad method\n");
FreeLibrary(plugin.handle);
plugin.handle = NULL;
}
#else
#include <dlfcn.h>
std::vector<void*> vLibHandles;
int getPluginVersion ( void* hLib )
{
int (*lpProc)(void);
*(void**) &lpProc = dlsym(hLib,"bz_GetVersion");
if (lpProc)
return (*lpProc)();
return 0;
}
void loadPlugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (hLib)
{
if (getPluginVersion(hLib) < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
dlclose(hLib);
}
else
{
*(void**) &lpProc = dlsym(hLib,"bz_Load");
if (lpProc)
{
(*lpProc)(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
else
{
DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
dlclose(hLib);
}
}
}
else
DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
*(void**) &lpProc = dlsym(plugin.handle, "bz_Unload");
if (lpProc)
(*lpProc)();
else
DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());
dlclose(plugin.handle);
plugin.handle = NULL;
}
#endif
void unloadPlugin ( std::string plugin )
{
// unload the first one of the name we find
for (unsigned int i = 0; i < vPluginList.size();i++)
{
if ( vPluginList[i].plugin == plugin )
{
unload1Plugin(i);
vPluginList.erase(vPluginList.begin()+i);
return;
}
}
}
void unloadPlugins ( void )
{
for (unsigned int i = 0; i < vPluginList.size();i++)
unload1Plugin(i);
vPluginList.clear();
removeCustomSlashCommand("loadplugin");
removeCustomSlashCommand("unloadplugin");
removeCustomSlashCommand("listplugins");
}
std::vector<std::string> getPluginList ( void )
{
std::vector<std::string> plugins;
for (unsigned int i = 0; i < vPluginList.size();i++)
plugins.push_back(vPluginList[i].plugin);
return plugins;
}
void parseServerCommand(const char *message, int dstPlayerId);
class DynamicPluginCommands : public CustomSlashCommandHandler
{
public:
virtual ~DynamicPluginCommands(){};
virtual bool handle ( int playerID, std::string command, std::string message )
{
bz_PlayerRecord record;
bz_getPlayerByIndex(playerID,&record);
if ( !record.admin )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Permision denied: ADMIN");
return true;
}
if ( !message.size() )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Error: Command must have a plugin name");
return true;
}
if ( TextUtils::tolower(command) == "loadplugin" )
{
std::vector<std::string> params = TextUtils::tokenize(message,std::string(","));
std::string config;
if ( params.size() >1)
config = params[1];
loadPlugin(params[0],config);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded");
return true;
}
if ( TextUtils::tolower(command) == "unloadplugin" )
{
unloadPlugin(message);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded");
return true;
}
if ( TextUtils::tolower(command) == "listplugins" )
{
std::vector<std::string> plugins = getPluginList();
if (!plugins.size())
bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded;");
else
{
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-isn loaded;");
for ( unsigned int i = 0; i < plugins.size(); i++)
bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str());
}
return true;
}
return true;
}
};
DynamicPluginCommands command;
void initPlugins ( void )
{
registerCustomSlashCommand("loadplugin",&command);
registerCustomSlashCommand("unloadplugin",&command);
registerCustomSlashCommand("listplugins",&command);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*
* ForwardChainer.cc
*
* Copyright (C) 2014,2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* 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.
*/
#include <opencog/util/Logger.h>
#include <opencog/atoms/bind/SatisfactionLink.h>
#include <opencog/atomutils/AtomUtils.h>
#include <opencog/query/DefaultImplicator.h>
#include <opencog/rule-engine/Rule.h>
#include <opencog/atoms/bind/BindLink.h>
#include "ForwardChainer.h"
#include "ForwardChainerCallBack.h"
using namespace opencog;
ForwardChainer::ForwardChainer(AtomSpace * as, string conf_path /*=""*/) :
_as(as), _rec(_as), _fcmem(_as)
{
if (conf_path != "")
_conf_path = conf_path;
init();
}
ForwardChainer::~ForwardChainer()
{
delete _cpolicy_loader;
}
void ForwardChainer::init()
{
_cpolicy_loader = new JsonicControlPolicyParamLoader(_as, _conf_path);
_cpolicy_loader->load_config();
_fcmem.set_search_in_af(_cpolicy_loader->get_attention_alloc());
_fcmem.set_rules(_cpolicy_loader->get_rules());
_fcmem.set_cur_rule(nullptr);
// Provide a logger
_log = NULL;
setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true));
}
void ForwardChainer::setLogger(Logger* log)
{
if (_log)
delete _log;
_log = log;
}
Logger* ForwardChainer::getLogger()
{
return _log;
}
/**
* Does one step forward chaining
* @return false if there is not target to explore
*/
bool ForwardChainer::step(ForwardChainerCallBack& fcb)
{
if (_fcmem.get_cur_source() == Handle::UNDEFINED) {
_log->info(
"[ForwardChainer] No current source, forward chaining aborted");
return false;
}
_log->info("[ForwardChainer] Next source %s",
_fcmem.get_cur_source()->toString().c_str());
// Add more premise to hcurrent_source by pattern matching.
_log->info("[ForwardChainer] Choose additional premises:");
HandleSeq input = fcb.choose_premises(_fcmem);
for (Handle h : input) {
if (not _fcmem.isin_premise_list(h))
_log->info("%s \n", h->toString().c_str());
}
_fcmem.update_premise_list(input);
// Choose the best rule to apply.
vector<Rule*> rules = fcb.choose_rules(_fcmem);
map<Rule*, float> rule_weight;
for (Rule* r : rules) {
_log->info("[ForwardChainer] Matching rule %s", r->get_name().c_str());
rule_weight[r] = r->get_cost();
}
auto r = _rec.tournament_select(rule_weight);
//! If no rules matches the pattern of the source, choose
//! another source if there is, else end forward chaining.
if (not r) {
auto new_source = fcb.choose_next_source(_fcmem);
if (new_source == Handle::UNDEFINED) {
_log->info(
"[ForwardChainer] No chosen rule and no more target to choose.Aborting forward chaining.");
return false;
} else {
_log->info(
"[ForwardChainer] No matching rule,attempting with another target %s.",
new_source->toString().c_str());
//set source and try another step
_fcmem.set_source(new_source);
return step(fcb);
}
}
_fcmem.set_cur_rule(r);
//! Apply rule.
_log->info("[ForwardChainer] Applying chosen rule %s",
r->get_name().c_str());
HandleSeq product = fcb.apply_rule(_fcmem);
_log->info("[ForwardChainer] Results of rule application");
for (auto p : product)
_log->info("%s", p->toString().c_str());
_log->info("[ForwardChainer] adding inference to history");
_fcmem.add_rules_product(_iteration, product);
_log->info(
"[ForwardChainer] updating premise list with the inference made");
_fcmem.update_premise_list(product);
return true;
}
void ForwardChainer::do_chain(ForwardChainerCallBack& fcb,
Handle hsource/*=Handle::UNDEFINED*/)
{
if (hsource == Handle::UNDEFINED) {
do_pm();
return;
}
// Variable fulfillment query.
UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource,
{ VARIABLE_NODE });
if (not var_nodes.empty())
return do_pm(hsource, var_nodes, fcb);
auto max_iter = _cpolicy_loader->get_max_iter();
_fcmem.set_source(hsource); //set initial source
while (_iteration < max_iter /*OR other termination criteria*/) {
_log->info("Iteration %d", _iteration);
if (not step(fcb))
break;
//! Choose next source.
_log->info("[ForwardChainer] setting next source");
_fcmem.set_source(fcb.choose_next_source(_fcmem));
}
_log->info("[ForwardChainer] finished do_chain.");
}
/**
* Does pattern matching for a variable containing query.
* @param source a variable containing handle passed as an input to the pattern matcher
* @param var_nodes the VariableNodes in @param hsource
* @param fcb a forward chainer callback implementation used here only for choosing rules
* that contain @param hsource in their implicant
*/
void ForwardChainer::do_pm(const Handle& hsource,
const UnorderedHandleSet& var_nodes,
ForwardChainerCallBack& fcb)
{
DefaultImplicator impl(_as);
impl.implicand = hsource;
HandleSeq vars;
for (auto h : var_nodes)
vars.push_back(h);
_fcmem.set_source(hsource);
Handle hvar_list = _as->addLink(VARIABLE_LIST, vars);
Handle hclause = _as->addLink(AND_LINK, hsource);
// Run the pattern matcher, find all patterns that satisfy the
// the clause, with the given variables in it.
SatisfactionLinkPtr sl(createSatisfactionLink(hvar_list, hclause));
sl->satisfy(impl);
// Update result
_fcmem.add_rules_product(0, impl.result_list);
// Delete the AND_LINK and LIST_LINK
_as->removeAtom(hvar_list);
_as->removeAtom(hclause);
//!Additionally, find applicable rules and apply.
vector<Rule*> rules = fcb.choose_rules(_fcmem);
for (Rule* rule : rules) {
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_fcmem.add_rules_product(0, impl.result_list);
}
}
/**
* Invokes pattern matcher using each rule declared in the configuration file.
*/
void ForwardChainer::do_pm()
{
//! Do pattern matching using the rules declared in the declaration file
_log->info(
"Forward chaining on the entire atomspace with rules declared in %s",
_conf_path.c_str());
vector<Rule*> rules = _fcmem.get_rules();
for (Rule* rule : rules) {
_log->info("Applying rule %s on ", rule->get_name().c_str());
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_log->info("OUTPUTS");
for (auto h : impl.result_list)
_log->info("%s", h->toString().c_str());
_fcmem.add_rules_product(0, impl.result_list);
}
}
HandleSeq ForwardChainer::get_chaining_result()
{
return _fcmem.get_result();
}
<commit_msg>Increment interation<commit_after>/*
* ForwardChainer.cc
*
* Copyright (C) 2014,2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com>
*
* 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.
*/
#include <opencog/util/Logger.h>
#include <opencog/atoms/bind/SatisfactionLink.h>
#include <opencog/atomutils/AtomUtils.h>
#include <opencog/query/DefaultImplicator.h>
#include <opencog/rule-engine/Rule.h>
#include <opencog/atoms/bind/BindLink.h>
#include "ForwardChainer.h"
#include "ForwardChainerCallBack.h"
using namespace opencog;
ForwardChainer::ForwardChainer(AtomSpace * as, string conf_path /*=""*/) :
_as(as), _rec(_as), _fcmem(_as)
{
if (conf_path != "")
_conf_path = conf_path;
init();
}
ForwardChainer::~ForwardChainer()
{
delete _cpolicy_loader;
}
void ForwardChainer::init()
{
_cpolicy_loader = new JsonicControlPolicyParamLoader(_as, _conf_path);
_cpolicy_loader->load_config();
_fcmem.set_search_in_af(_cpolicy_loader->get_attention_alloc());
_fcmem.set_rules(_cpolicy_loader->get_rules());
_fcmem.set_cur_rule(nullptr);
// Provide a logger
_log = NULL;
setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true));
}
void ForwardChainer::setLogger(Logger* log)
{
if (_log)
delete _log;
_log = log;
}
Logger* ForwardChainer::getLogger()
{
return _log;
}
/**
* Does one step forward chaining
* @return false if there is not target to explore
*/
bool ForwardChainer::step(ForwardChainerCallBack& fcb)
{
if (_fcmem.get_cur_source() == Handle::UNDEFINED) {
_log->info(
"[ForwardChainer] No current source, forward chaining aborted");
return false;
}
_log->info("[ForwardChainer] Next source %s",
_fcmem.get_cur_source()->toString().c_str());
// Add more premise to hcurrent_source by pattern matching.
_log->info("[ForwardChainer] Choose additional premises:");
HandleSeq input = fcb.choose_premises(_fcmem);
for (Handle h : input) {
if (not _fcmem.isin_premise_list(h))
_log->info("%s \n", h->toString().c_str());
}
_fcmem.update_premise_list(input);
// Choose the best rule to apply.
vector<Rule*> rules = fcb.choose_rules(_fcmem);
map<Rule*, float> rule_weight;
for (Rule* r : rules) {
_log->info("[ForwardChainer] Matching rule %s", r->get_name().c_str());
rule_weight[r] = r->get_cost();
}
auto r = _rec.tournament_select(rule_weight);
//! If no rules matches the pattern of the source, choose
//! another source if there is, else end forward chaining.
if (not r) {
auto new_source = fcb.choose_next_source(_fcmem);
if (new_source == Handle::UNDEFINED) {
_log->info(
"[ForwardChainer] No chosen rule and no more target to choose.Aborting forward chaining.");
return false;
} else {
_log->info(
"[ForwardChainer] No matching rule,attempting with another target %s.",
new_source->toString().c_str());
//set source and try another step
_fcmem.set_source(new_source);
return step(fcb);
}
}
_fcmem.set_cur_rule(r);
//! Apply rule.
_log->info("[ForwardChainer] Applying chosen rule %s",
r->get_name().c_str());
HandleSeq product = fcb.apply_rule(_fcmem);
_log->info("[ForwardChainer] Results of rule application");
for (auto p : product)
_log->info("%s", p->toString().c_str());
_log->info("[ForwardChainer] adding inference to history");
_fcmem.add_rules_product(_iteration, product);
_log->info(
"[ForwardChainer] updating premise list with the inference made");
_fcmem.update_premise_list(product);
return true;
}
void ForwardChainer::do_chain(ForwardChainerCallBack& fcb,
Handle hsource/*=Handle::UNDEFINED*/)
{
if (hsource == Handle::UNDEFINED) {
do_pm();
return;
}
// Variable fulfillment query.
UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource,
{ VARIABLE_NODE });
if (not var_nodes.empty())
return do_pm(hsource, var_nodes, fcb);
auto max_iter = _cpolicy_loader->get_max_iter();
_fcmem.set_source(hsource); //set initial source
while (_iteration < max_iter /*OR other termination criteria*/) {
_log->info("Iteration %d", _iteration);
if (not step(fcb))
break;
//! Choose next source.
_log->info("[ForwardChainer] setting next source");
_fcmem.set_source(fcb.choose_next_source(_fcmem));
_iteration++;
}
_log->info("[ForwardChainer] finished do_chain.");
}
/**
* Does pattern matching for a variable containing query.
* @param source a variable containing handle passed as an input to the pattern matcher
* @param var_nodes the VariableNodes in @param hsource
* @param fcb a forward chainer callback implementation used here only for choosing rules
* that contain @param hsource in their implicant
*/
void ForwardChainer::do_pm(const Handle& hsource,
const UnorderedHandleSet& var_nodes,
ForwardChainerCallBack& fcb)
{
DefaultImplicator impl(_as);
impl.implicand = hsource;
HandleSeq vars;
for (auto h : var_nodes)
vars.push_back(h);
_fcmem.set_source(hsource);
Handle hvar_list = _as->addLink(VARIABLE_LIST, vars);
Handle hclause = _as->addLink(AND_LINK, hsource);
// Run the pattern matcher, find all patterns that satisfy the
// the clause, with the given variables in it.
SatisfactionLinkPtr sl(createSatisfactionLink(hvar_list, hclause));
sl->satisfy(impl);
// Update result
_fcmem.add_rules_product(0, impl.result_list);
// Delete the AND_LINK and LIST_LINK
_as->removeAtom(hvar_list);
_as->removeAtom(hclause);
//!Additionally, find applicable rules and apply.
vector<Rule*> rules = fcb.choose_rules(_fcmem);
for (Rule* rule : rules) {
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_fcmem.add_rules_product(0, impl.result_list);
}
}
/**
* Invokes pattern matcher using each rule declared in the configuration file.
*/
void ForwardChainer::do_pm()
{
//! Do pattern matching using the rules declared in the declaration file
_log->info(
"Forward chaining on the entire atomspace with rules declared in %s",
_conf_path.c_str());
vector<Rule*> rules = _fcmem.get_rules();
for (Rule* rule : rules) {
_log->info("Applying rule %s on ", rule->get_name().c_str());
BindLinkPtr bl(BindLinkCast(rule->get_handle()));
DefaultImplicator impl(_as);
impl.implicand = bl->get_implicand();
bl->imply(impl);
_fcmem.set_cur_rule(rule);
_log->info("OUTPUTS");
for (auto h : impl.result_list)
_log->info("%s", h->toString().c_str());
_fcmem.add_rules_product(0, impl.result_list);
}
}
HandleSeq ForwardChainer::get_chaining_result()
{
return _fcmem.get_result();
}
<|endoftext|>
|
<commit_before>#include "calculator_thread.hh"
#include "sdl/event.hh"
#include "sdl/img.hh"
#include <chrono>
#include <cstdio>
#include <thread>
#include "entity.hh"
#include "key_state.hh"
#include "key_handler.hh"
#include "constants.hh"
namespace czipperz {
std::atomic<const czipperz::frame*> frame_to_render(nullptr);
static void
send_to_render(czipperz::frame*& frame,
czipperz::frame*& previous_frame) {
/* Update frame_to_render */
const czipperz::frame* expected_frame = nullptr;
// If done rendering, give renderer another frame
czipperz::frame_to_render.compare_exchange_strong(expected_frame,
frame);
// If renderer requested another frame, swap which one we write
// to.
if (!expected_frame) {
std::swap(frame, previous_frame);
*frame = *previous_frame;
}
}
static void handle_key_events(czipperz::key_state& key_state) {
// Key events
for (sdl::event event; sdl::get_event(&event);) {
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
// Handle the keys
czipperz::key_handler(key_state,
event.type == SDL_KEYDOWN,
event.key.keysym);
break;
case SDL_QUIT:
czipperz::quit = true;
break;
}
}
}
static void
calculate(czipperz::frame& frame, czipperz::key_state& key_state,
czipperz::key_state& previous_key_state) {
// Draw menu
if (key_state.escape && !previous_key_state.escape) {
frame.draw_menu = !frame.draw_menu;
frame.menu.index = 0;
}
// Update side
if (key_state.j && !previous_key_state.j) {
const auto old_side = frame.side;
czipperz::turn_left(frame.side);
frame.player.turn(old_side, frame.side);
std::printf("Side%d\t", frame.side);
}
if (key_state.l && !previous_key_state.l) {
const auto old_side = frame.side;
czipperz::turn_right(frame.side);
frame.player.turn(old_side, frame.side);
std::printf("Side%d\t", frame.side);
}
// Update objects
if (frame.draw_menu) {
frame.menu.update(key_state, previous_key_state);
} else {
frame.player.update(frame, key_state, previous_key_state);
}
}
static void sleep(std::chrono::microseconds& start_time) {
const std::chrono::microseconds current_time =
czipperz::current_time();
if (czipperz::calc_length + start_time > current_time) {
std::this_thread::sleep_for(czipperz::calc_length +
start_time - current_time);
} else {
#ifndef NDEBUG
std::puts("Skipped calc frame");
#endif
}
start_time += czipperz::calc_length;
}
void calculator_thread(sdl::renderer* rend) {
sdl::renderer& renderer = *rend;
czipperz::level
level(sdl::img::load_texture(renderer,
"res/level_1_background.png"),
sdl::img::load_texture(renderer,
"res/level_1_background.png"),
sdl::img::load_texture(renderer,
"res/level_1_background.png"),
sdl::img::load_texture(renderer,
"res/level_1_background.png"));
level.platforms.push_back(
czipperz::platform({0, 0}, {0, 0}, 100, 100, 50));
level.platforms.push_back(
czipperz::platform({200, 0}, {400, 0}, 250, 100, 50));
level.platforms.push_back(
czipperz::platform({400, 0}, {0, 0}, 400, 100, 50));
level.platforms.push_back(
czipperz::platform({500, 0}, {400, 0}, 550, 100, 50));
czipperz::frame frames[2];
frames[0].level = &level;
frames[1].level = &level;
czipperz::frame* frame = frames + 0;
czipperz::frame* previous_frame = frames + 1;
czipperz::key_state previous_key_state;
std::chrono::microseconds start_time = czipperz::current_time();
while (!czipperz::quit) {
send_to_render(frame, previous_frame);
czipperz::key_state key_state = previous_key_state;
handle_key_events(key_state);
calculate(*frame, key_state, previous_key_state);
previous_key_state = key_state;
sleep(start_time);
}
}
}
<commit_msg>Move third platform to the left for easier testing<commit_after>#include "calculator_thread.hh"
#include "sdl/event.hh"
#include "sdl/img.hh"
#include <chrono>
#include <cstdio>
#include <thread>
#include "entity.hh"
#include "key_state.hh"
#include "key_handler.hh"
#include "constants.hh"
namespace czipperz {
std::atomic<const czipperz::frame*> frame_to_render(nullptr);
static void
send_to_render(czipperz::frame*& frame,
czipperz::frame*& previous_frame) {
/* Update frame_to_render */
const czipperz::frame* expected_frame = nullptr;
// If done rendering, give renderer another frame
czipperz::frame_to_render.compare_exchange_strong(expected_frame,
frame);
// If renderer requested another frame, swap which one we write
// to.
if (!expected_frame) {
std::swap(frame, previous_frame);
*frame = *previous_frame;
}
}
static void handle_key_events(czipperz::key_state& key_state) {
// Key events
for (sdl::event event; sdl::get_event(&event);) {
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
// Handle the keys
czipperz::key_handler(key_state,
event.type == SDL_KEYDOWN,
event.key.keysym);
break;
case SDL_QUIT:
czipperz::quit = true;
break;
}
}
}
static void
calculate(czipperz::frame& frame, czipperz::key_state& key_state,
czipperz::key_state& previous_key_state) {
// Draw menu
if (key_state.escape && !previous_key_state.escape) {
frame.draw_menu = !frame.draw_menu;
frame.menu.index = 0;
}
// Update side
if (key_state.j && !previous_key_state.j) {
const auto old_side = frame.side;
czipperz::turn_left(frame.side);
frame.player.turn(old_side, frame.side);
std::printf("Side%d\t", frame.side);
}
if (key_state.l && !previous_key_state.l) {
const auto old_side = frame.side;
czipperz::turn_right(frame.side);
frame.player.turn(old_side, frame.side);
std::printf("Side%d\t", frame.side);
}
// Update objects
if (frame.draw_menu) {
frame.menu.update(key_state, previous_key_state);
} else {
frame.player.update(frame, key_state, previous_key_state);
}
}
static void sleep(std::chrono::microseconds& start_time) {
const std::chrono::microseconds current_time =
czipperz::current_time();
if (czipperz::calc_length + start_time > current_time) {
std::this_thread::sleep_for(czipperz::calc_length +
start_time - current_time);
} else {
#ifndef NDEBUG
std::puts("Skipped calc frame");
#endif
}
start_time += czipperz::calc_length;
}
void calculator_thread(sdl::renderer* rend) {
sdl::renderer& renderer = *rend;
czipperz::level
level(sdl::img::load_texture(renderer,
"res/level_1_background.png"),
sdl::img::load_texture(renderer,
"res/level_1_background.png"),
sdl::img::load_texture(renderer,
"res/level_1_background.png"),
sdl::img::load_texture(renderer,
"res/level_1_background.png"));
level.platforms.push_back(
czipperz::platform({0, 0}, {0, 0}, 100, 100, 50));
level.platforms.push_back(
czipperz::platform({200, 0}, {400, 0}, 250, 100, 50));
level.platforms.push_back(
czipperz::platform({350, 0}, {0, 0}, 400, 100, 50));
level.platforms.push_back(
czipperz::platform({500, 0}, {400, 0}, 550, 100, 50));
czipperz::frame frames[2];
frames[0].level = &level;
frames[1].level = &level;
czipperz::frame* frame = frames + 0;
czipperz::frame* previous_frame = frames + 1;
czipperz::key_state previous_key_state;
std::chrono::microseconds start_time = czipperz::current_time();
while (!czipperz::quit) {
send_to_render(frame, previous_frame);
czipperz::key_state key_state = previous_key_state;
handle_key_events(key_state);
calculate(*frame, key_state, previous_key_state);
previous_key_state = key_state;
sleep(start_time);
}
}
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "<WebSig>" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XSECCanon := Base (virtual) class for canonicalisation objects
*
* Author(s): Berin Lautenbach
*
* $ID$
*
* $LOG$
*
*/
#include <xsec/canon/XSECCanon.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <memory.h>
XERCES_CPP_NAMESPACE_USE
// --------------------------------------------------------------------------------
// XSECCanon Virtual Class implementation
// --------------------------------------------------------------------------------
// Constructors
XSECCanon::XSECCanon() {};
XSECCanon::XSECCanon(DOMDocument *newDoc) : m_buffer() {
mp_doc = newDoc;
mp_startNode = mp_nextNode = newDoc; // By default, start from startNode
m_bufferLength = m_bufferPoint = 0; // Start with an empty buffer
m_allNodesDone = false;
};
XSECCanon::XSECCanon(DOMDocument *newDoc, DOMNode *newStartNode) {
mp_doc = newDoc;
mp_startNode = mp_nextNode = newStartNode;
m_bufferLength = m_bufferPoint = 0; // Start with an empty buffer
m_allNodesDone = false;
};
// Destructors
XSECCanon::~XSECCanon() {};
// Public Methods
int XSECCanon::outputBuffer(unsigned char *outBuffer, int numBytes) {
// numBytes of data are required to be placed in outBuffer.
// Calculate amount left in buffer
int remaining = m_bufferLength - m_bufferPoint;
int bytesToGo = numBytes;
int i = 0; // current point in outBuffer
// While we don't have enough, and have not completed -
while (!m_allNodesDone && (remaining < bytesToGo)) {
// Copy what we have and get some more in the buffer
memcpy(&outBuffer[i], &m_buffer[m_bufferPoint], remaining);
i += remaining;
m_bufferPoint += remaining;
bytesToGo -= remaining;
// Get more
processNextNode();
remaining = m_bufferLength - m_bufferPoint; // This will be reset by processNextElement
// "-bufferPoint" is just in case.
}
if (m_allNodesDone) {
// Was not enough data to fill everything up
memcpy (&outBuffer[i], &m_buffer[m_bufferPoint], remaining);
m_bufferPoint += remaining;
return i + remaining;
}
// Copy the tail of the buffer
memcpy(&outBuffer[i], &m_buffer[m_bufferPoint], bytesToGo);
m_bufferPoint += bytesToGo;
return (bytesToGo + i);
}
// setStartNode sets the starting point for the output if it is a sub-document
// that needs canonicalisation and we want to re-start
bool XSECCanon::setStartNode(DOMNode *newStartNode) {
mp_startNode = newStartNode;
m_bufferPoint = 0;
m_bufferLength = 0;
mp_nextNode = mp_startNode;
m_allNodesDone = false; // Restart
return true; // Should check to ensure that the StartNode is part of the doc.
}
<commit_msg>Fix for 2nd Canonicalisation bug reported by Milan Tomic (Strings over 16K get truncated)<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "<WebSig>" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XSECCanon := Base (virtual) class for canonicalisation objects
*
* Author(s): Berin Lautenbach
*
* $ID$
*
* $LOG$
*
*/
#include <xsec/canon/XSECCanon.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <memory.h>
XERCES_CPP_NAMESPACE_USE
// --------------------------------------------------------------------------------
// XSECCanon Virtual Class implementation
// --------------------------------------------------------------------------------
// Constructors
XSECCanon::XSECCanon() {};
XSECCanon::XSECCanon(DOMDocument *newDoc) : m_buffer() {
mp_doc = newDoc;
mp_startNode = mp_nextNode = newDoc; // By default, start from startNode
m_bufferLength = m_bufferPoint = 0; // Start with an empty buffer
m_allNodesDone = false;
};
XSECCanon::XSECCanon(DOMDocument *newDoc, DOMNode *newStartNode) {
mp_doc = newDoc;
mp_startNode = mp_nextNode = newStartNode;
m_bufferLength = m_bufferPoint = 0; // Start with an empty buffer
m_allNodesDone = false;
};
// Destructors
XSECCanon::~XSECCanon() {};
// Public Methods
int XSECCanon::outputBuffer(unsigned char *outBuffer, int numBytes) {
// numBytes of data are required to be placed in outBuffer.
// Calculate amount left in buffer
int remaining = m_bufferLength - m_bufferPoint;
int bytesToGo = numBytes;
int i = 0; // current point in outBuffer
// While we don't have enough, and have not completed -
while (!m_allNodesDone && (remaining < bytesToGo)) {
// Copy what we have and get some more in the buffer
memcpy(&outBuffer[i], &m_buffer[m_bufferPoint], remaining);
i += remaining;
m_bufferPoint += remaining;
bytesToGo -= remaining;
// Get more
processNextNode();
remaining = m_bufferLength - m_bufferPoint; // This will be reset by processNextElement
// "-bufferPoint" is just in case.
}
if (m_allNodesDone && (remaining < bytesToGo)) {
// Was not enough data to fill everything up
memcpy (&outBuffer[i], &m_buffer[m_bufferPoint], remaining);
m_bufferPoint += remaining;
return i + remaining;
}
// Copy the tail of the buffer
memcpy(&outBuffer[i], &m_buffer[m_bufferPoint], bytesToGo);
m_bufferPoint += bytesToGo;
return (bytesToGo + i);
}
// setStartNode sets the starting point for the output if it is a sub-document
// that needs canonicalisation and we want to re-start
bool XSECCanon::setStartNode(DOMNode *newStartNode) {
mp_startNode = newStartNode;
m_bufferPoint = 0;
m_bufferLength = 0;
mp_nextNode = mp_startNode;
m_allNodesDone = false; // Restart
return true; // Should check to ensure that the StartNode is part of the doc.
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "BZip2.h"
#include <cbang/Exception.h>
#include <cbang/String.h>
#include <bzlib.h>
#include <string.h>
using namespace cb;
using namespace std;
#define BUFFER_SIZE (64 * 1024)
struct BZip2::Private : public bz_stream {
Private() {clear();}
void clear() {memset(this, 0, sizeof(bz_stream));}
};
BZip2::BZip2(ostream &out) :
out(out), bz(new Private), init(false), comp(true) {}
void BZip2::compressInit(int blockSize100k, int verbosity, int workFactor) {
if (init) THROW("BZip2: Already initialized");
init = true;
comp = true;
BZ2_bzCompressInit(bz.get(), blockSize100k, 0, 0);
}
void BZip2::decompressInit(int verbosity, int small) {
if (init) THROW("BZip2: Already initialized");
init = true;
comp = false;
BZ2_bzDecompressInit(bz.get(), 0, 0);
}
void BZip2::update(const char *data, unsigned length) {
if (!init) THROW("BZip2: Not initialized");
char buf[BUFFER_SIZE];
bz->next_in = const_cast<char *>(data);
bz->avail_in = length;
while (true) {
bz->next_out = buf;
bz->avail_out = BUFFER_SIZE;
if (comp) {
int ret = BZ2_bzCompress(bz.get(), BZ_RUN);
if (ret != BZ_RUN_OK)
THROW("BZip2: Compression failed " << errorStr(ret));
} else {
int ret = BZ2_bzDecompress(bz.get());
if (ret == BZ_STREAM_END) bz->avail_in = 0;
else if (ret != BZ_OK)
THROW("BZip2: Decompression failed " << errorStr(ret));
}
out.write(buf, BUFFER_SIZE - bz->avail_out);
if (out.fail()) THROW("BZip2: Output stream failed");
if (!bz->avail_in) break;
}
}
void BZip2::update(const std::string &s) {
update(CPP_TO_C_STR(s), s.length());
}
void BZip2::read(std::istream &in) {
char buf[BUFFER_SIZE];
while (!in.fail() && !out.fail()) {
in.read(buf, BUFFER_SIZE);
update(buf, in.gcount());
}
}
void BZip2::finish() {
if (!init) THROW("BZip2: Not initialized");
int ret;
if (comp) {
char buf[BUFFER_SIZE];
bz->next_in = 0;
bz->avail_in = 0;
do {
bz->next_out = buf;
bz->avail_out = BUFFER_SIZE;
ret = BZ2_bzCompress(bz.get(), BZ_FINISH);
out.write(buf, BUFFER_SIZE - bz->avail_out);
} while (ret == BZ_FINISH_OK);
if (ret != BZ_STREAM_END)
THROW("BZip2: compress finish " << errorStr(ret));
}
if (comp) ret = BZ2_bzCompressEnd(bz.get());
else ret = BZ2_bzDecompressEnd(bz.get());
if (ret != BZ_OK) THROW("BZip2: end failed " << errorStr(ret));
bz->clear();
init = false;
}
void BZip2::compress(istream &in, ostream &out, int blockSize100k,
int verbosity, int workFactor) {
BZip2 bzip2(out);
bzip2.compressInit(blockSize100k, verbosity, workFactor);
bzip2.read(in);
bzip2.finish();
}
void BZip2::decompress(istream &in, ostream &out, int verbosity, int small) {
BZip2 bzip2(out);
bzip2.decompressInit(verbosity, small);
bzip2.read(in);
bzip2.finish();
}
string BZip2::compress(const string &s, int blockSize100k, int verbosity,
int workFactor) {
ostringstream str;
BZip2 bzip2(str);
bzip2.compressInit(blockSize100k, verbosity, workFactor);
bzip2.update(s);
bzip2.finish();
return str.str();
}
string BZip2::decompress(const string &s, int verbosity, int small) {
ostringstream str;
BZip2 bzip2(str);
bzip2.decompressInit(verbosity, small);
bzip2.update(s);
bzip2.finish();
return str.str();
}
const char *BZip2::errorStr(int err) {
switch (err) {
case BZ_OK: return "OK";
case BZ_RUN_OK: return "RUN OK";
case BZ_FLUSH_OK: return "FLUSH OK";
case BZ_FINISH_OK: return "FINISH OK";
case BZ_STREAM_END: return "STREAM END";
case BZ_SEQUENCE_ERROR: return "SEQUENCE ERROR";
case BZ_PARAM_ERROR: return "PARAM ERROR";
case BZ_MEM_ERROR: return "MEM ERROR";
case BZ_DATA_ERROR: return "DATA ERROR";
case BZ_DATA_ERROR_MAGIC: return "DATA ERROR MAGIC";
case BZ_IO_ERROR: return "IO ERROR";
case BZ_UNEXPECTED_EOF: return "UNEXPECTED EOF";
case BZ_OUTBUFF_FULL: return "OUTBUFF FULL";
case BZ_CONFIG_ERROR: return "CONFIG ERROR";
default: return "UNKNOWN ERROR";
}
}
<commit_msg>Pass missing params<commit_after>/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "BZip2.h"
#include <cbang/Exception.h>
#include <cbang/String.h>
#include <bzlib.h>
#include <string.h>
using namespace cb;
using namespace std;
#define BUFFER_SIZE (64 * 1024)
struct BZip2::Private : public bz_stream {
Private() {clear();}
void clear() {memset(this, 0, sizeof(bz_stream));}
};
BZip2::BZip2(ostream &out) :
out(out), bz(new Private), init(false), comp(true) {}
void BZip2::compressInit(int blockSize100k, int verbosity, int workFactor) {
if (init) THROW("BZip2: Already initialized");
init = true;
comp = true;
BZ2_bzCompressInit(bz.get(), blockSize100k, verbosity, workFactor);
}
void BZip2::decompressInit(int verbosity, int small) {
if (init) THROW("BZip2: Already initialized");
init = true;
comp = false;
BZ2_bzDecompressInit(bz.get(), verbosity, small);
}
void BZip2::update(const char *data, unsigned length) {
if (!init) THROW("BZip2: Not initialized");
char buf[BUFFER_SIZE];
bz->next_in = const_cast<char *>(data);
bz->avail_in = length;
while (true) {
bz->next_out = buf;
bz->avail_out = BUFFER_SIZE;
if (comp) {
int ret = BZ2_bzCompress(bz.get(), BZ_RUN);
if (ret != BZ_RUN_OK)
THROW("BZip2: Compression failed " << errorStr(ret));
} else {
int ret = BZ2_bzDecompress(bz.get());
if (ret == BZ_STREAM_END) bz->avail_in = 0;
else if (ret != BZ_OK)
THROW("BZip2: Decompression failed " << errorStr(ret));
}
out.write(buf, BUFFER_SIZE - bz->avail_out);
if (out.fail()) THROW("BZip2: Output stream failed");
if (!bz->avail_in) break;
}
}
void BZip2::update(const std::string &s) {
update(CPP_TO_C_STR(s), s.length());
}
void BZip2::read(std::istream &in) {
char buf[BUFFER_SIZE];
while (!in.fail() && !out.fail()) {
in.read(buf, BUFFER_SIZE);
update(buf, in.gcount());
}
}
void BZip2::finish() {
if (!init) THROW("BZip2: Not initialized");
int ret;
if (comp) {
char buf[BUFFER_SIZE];
bz->next_in = 0;
bz->avail_in = 0;
do {
bz->next_out = buf;
bz->avail_out = BUFFER_SIZE;
ret = BZ2_bzCompress(bz.get(), BZ_FINISH);
out.write(buf, BUFFER_SIZE - bz->avail_out);
} while (ret == BZ_FINISH_OK);
if (ret != BZ_STREAM_END)
THROW("BZip2: compress finish " << errorStr(ret));
}
if (comp) ret = BZ2_bzCompressEnd(bz.get());
else ret = BZ2_bzDecompressEnd(bz.get());
if (ret != BZ_OK) THROW("BZip2: end failed " << errorStr(ret));
bz->clear();
init = false;
}
void BZip2::compress(istream &in, ostream &out, int blockSize100k,
int verbosity, int workFactor) {
BZip2 bzip2(out);
bzip2.compressInit(blockSize100k, verbosity, workFactor);
bzip2.read(in);
bzip2.finish();
}
void BZip2::decompress(istream &in, ostream &out, int verbosity, int small) {
BZip2 bzip2(out);
bzip2.decompressInit(verbosity, small);
bzip2.read(in);
bzip2.finish();
}
string BZip2::compress(const string &s, int blockSize100k, int verbosity,
int workFactor) {
ostringstream str;
BZip2 bzip2(str);
bzip2.compressInit(blockSize100k, verbosity, workFactor);
bzip2.update(s);
bzip2.finish();
return str.str();
}
string BZip2::decompress(const string &s, int verbosity, int small) {
ostringstream str;
BZip2 bzip2(str);
bzip2.decompressInit(verbosity, small);
bzip2.update(s);
bzip2.finish();
return str.str();
}
const char *BZip2::errorStr(int err) {
switch (err) {
case BZ_OK: return "OK";
case BZ_RUN_OK: return "RUN OK";
case BZ_FLUSH_OK: return "FLUSH OK";
case BZ_FINISH_OK: return "FINISH OK";
case BZ_STREAM_END: return "STREAM END";
case BZ_SEQUENCE_ERROR: return "SEQUENCE ERROR";
case BZ_PARAM_ERROR: return "PARAM ERROR";
case BZ_MEM_ERROR: return "MEM ERROR";
case BZ_DATA_ERROR: return "DATA ERROR";
case BZ_DATA_ERROR_MAGIC: return "DATA ERROR MAGIC";
case BZ_IO_ERROR: return "IO ERROR";
case BZ_UNEXPECTED_EOF: return "UNEXPECTED EOF";
case BZ_OUTBUFF_FULL: return "OUTBUFF FULL";
case BZ_CONFIG_ERROR: return "CONFIG ERROR";
default: return "UNKNOWN ERROR";
}
}
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Fernando José Iglesias García
* Copyright (C) 2012 Fernando José Iglesias García
*/
#include <shogun/structure/StructuredModel.h>
using namespace shogun;
CStructuredModel::CStructuredModel() : CSGObject()
{
init();
}
CStructuredModel::CStructuredModel(
CFeatures* features,
CStructuredLabels* labels)
: CSGObject()
{
init();
m_features = features;
m_labels = labels;
SG_REF(features);
SG_REF(labels);
}
CStructuredModel::~CStructuredModel()
{
SG_UNREF(m_labels);
SG_UNREF(m_features);
}
void CStructuredModel::init_opt(
SGMatrix< float64_t > & A,
SGVector< float64_t > a,
SGMatrix< float64_t > B,
SGVector< float64_t > & b,
SGVector< float64_t > lb,
SGVector< float64_t > ub,
SGMatrix< float64_t > & C)
{
SG_ERROR("init_opt is not implemented for %s!\n", get_name());
}
void CStructuredModel::set_labels(CStructuredLabels* labels)
{
SG_UNREF(m_labels);
SG_REF(labels);
m_labels = labels;
}
CStructuredLabels* CStructuredModel::get_labels()
{
SG_REF(m_labels);
return m_labels;
}
void CStructuredModel::set_features(CFeatures* features)
{
SG_UNREF(m_features);
SG_REF(features);
m_features = features;
}
CFeatures* CStructuredModel::get_features()
{
SG_REF(m_features);
return m_features;
}
SGVector< float64_t > CStructuredModel::get_joint_feature_vector(
int32_t feat_idx,
int32_t lab_idx)
{
CStructuredData* label = m_labels->get_label(lab_idx);
SGVector< float64_t > ret = get_joint_feature_vector(feat_idx, label);
SG_UNREF(label);
return ret;
}
SGVector< float64_t > CStructuredModel::get_joint_feature_vector(
int32_t feat_idx,
CStructuredData* y)
{
SG_ERROR("compute_joint_feature(int32_t, CStructuredData*) is not "
"implemented for %s!\n", get_name());
return SGVector< float64_t >();
}
float64_t CStructuredModel::delta_loss(int32_t ytrue_idx, CStructuredData* ypred)
{
REQUIRE(ytrue_idx >= 0 || ytrue_idx < m_labels->get_num_labels(),
"The label index must be inside [0, num_labels-1]\n");
CStructuredData* ytrue = m_labels->get_label(ytrue_idx);
float64_t ret = delta_loss(ytrue, ypred);
SG_UNREF(ytrue);
return ret;
}
float64_t CStructuredModel::delta_loss(CStructuredData* y1, CStructuredData* y2)
{
SG_ERROR("delta_loss(CStructuredData*, CStructuredData*) is not "
"implemented for %s!\n", get_name());
return 0.0;
}
void CStructuredModel::init()
{
SG_ADD((CSGObject**) &m_labels, "m_labels", "Structured labels",
MS_NOT_AVAILABLE);
SG_ADD((CSGObject**) &m_features, "m_features", "Feature vectors",
MS_NOT_AVAILABLE);
m_features = NULL;
m_labels = NULL;
}
bool CStructuredModel::check_training_setup() const
{
// Nothing to do here
return true;
}
int32_t CStructuredModel::get_num_aux() const
{
return 0;
}
int32_t CStructuredModel::get_num_aux_con() const
{
return 0;
}
float64_t CStructuredModel::risk(float64_t* subgrad, float64_t* W, TMultipleCPinfo* info)
{
int32_t from=0, to=0;
if (info)
{
from = info->_from;
to = (info->N == 0) ? m_features->get_num_vectors() : from+info->N;
}
else
{
from = 0;
to = m_features->get_num_vectors();
}
int32_t dim = this->get_dim();
float64_t R = 0.0;
for (int32_t i=from; i<to; i++)
{
CResultSet* result = this->argmax(SGVector<float64_t>(W,dim,false), i, true);
SGVector<float64_t> psi_pred = result->psi_pred;
SGVector<float64_t> psi_truth = result->psi_truth;
SGVector<float64_t>::vec1_plus_scalar_times_vec2(subgrad, 1.0, psi_pred.vector, dim);
SGVector<float64_t>::vec1_plus_scalar_times_vec2(subgrad, -1.0, psi_truth.vector, dim);
R += result->score;
SG_UNREF(result);
}
return R;
}
<commit_msg>* fix errors in StructuredModel::risk<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Fernando José Iglesias García
* Copyright (C) 2012 Fernando José Iglesias García
*/
#include <shogun/structure/StructuredModel.h>
using namespace shogun;
CStructuredModel::CStructuredModel() : CSGObject()
{
init();
}
CStructuredModel::CStructuredModel(
CFeatures* features,
CStructuredLabels* labels)
: CSGObject()
{
init();
m_features = features;
m_labels = labels;
SG_REF(features);
SG_REF(labels);
}
CStructuredModel::~CStructuredModel()
{
SG_UNREF(m_labels);
SG_UNREF(m_features);
}
void CStructuredModel::init_opt(
SGMatrix< float64_t > & A,
SGVector< float64_t > a,
SGMatrix< float64_t > B,
SGVector< float64_t > & b,
SGVector< float64_t > lb,
SGVector< float64_t > ub,
SGMatrix< float64_t > & C)
{
SG_ERROR("init_opt is not implemented for %s!\n", get_name());
}
void CStructuredModel::set_labels(CStructuredLabels* labels)
{
SG_UNREF(m_labels);
SG_REF(labels);
m_labels = labels;
}
CStructuredLabels* CStructuredModel::get_labels()
{
SG_REF(m_labels);
return m_labels;
}
void CStructuredModel::set_features(CFeatures* features)
{
SG_UNREF(m_features);
SG_REF(features);
m_features = features;
}
CFeatures* CStructuredModel::get_features()
{
SG_REF(m_features);
return m_features;
}
SGVector< float64_t > CStructuredModel::get_joint_feature_vector(
int32_t feat_idx,
int32_t lab_idx)
{
CStructuredData* label = m_labels->get_label(lab_idx);
SGVector< float64_t > ret = get_joint_feature_vector(feat_idx, label);
SG_UNREF(label);
return ret;
}
SGVector< float64_t > CStructuredModel::get_joint_feature_vector(
int32_t feat_idx,
CStructuredData* y)
{
SG_ERROR("compute_joint_feature(int32_t, CStructuredData*) is not "
"implemented for %s!\n", get_name());
return SGVector< float64_t >();
}
float64_t CStructuredModel::delta_loss(int32_t ytrue_idx, CStructuredData* ypred)
{
REQUIRE(ytrue_idx >= 0 || ytrue_idx < m_labels->get_num_labels(),
"The label index must be inside [0, num_labels-1]\n");
CStructuredData* ytrue = m_labels->get_label(ytrue_idx);
float64_t ret = delta_loss(ytrue, ypred);
SG_UNREF(ytrue);
return ret;
}
float64_t CStructuredModel::delta_loss(CStructuredData* y1, CStructuredData* y2)
{
SG_ERROR("delta_loss(CStructuredData*, CStructuredData*) is not "
"implemented for %s!\n", get_name());
return 0.0;
}
void CStructuredModel::init()
{
SG_ADD((CSGObject**) &m_labels, "m_labels", "Structured labels",
MS_NOT_AVAILABLE);
SG_ADD((CSGObject**) &m_features, "m_features", "Feature vectors",
MS_NOT_AVAILABLE);
m_features = NULL;
m_labels = NULL;
}
bool CStructuredModel::check_training_setup() const
{
// Nothing to do here
return true;
}
int32_t CStructuredModel::get_num_aux() const
{
return 0;
}
int32_t CStructuredModel::get_num_aux_con() const
{
return 0;
}
float64_t CStructuredModel::risk(float64_t* subgrad, float64_t* W, TMultipleCPinfo* info)
{
int32_t from=0, to=0;
if (info)
{
from = info->_from;
to = (info->N == 0) ? m_features->get_num_vectors() : from+info->N;
}
else
{
from = 0;
to = m_features->get_num_vectors();
}
int32_t dim = this->get_dim();
float64_t R = 0.0;
for (uint32_t i=0; i<dim; i++)
subgrad[i] = 0;
for (int32_t i=from; i<to; i++)
{
CResultSet* result = this->argmax(SGVector<float64_t>(W,dim,false), i, true);
SGVector<float64_t> psi_pred = result->psi_pred;
SGVector<float64_t> psi_truth = result->psi_truth;
SGVector<float64_t>::vec1_plus_scalar_times_vec2(subgrad, 1.0, psi_pred.vector, dim);
SGVector<float64_t>::vec1_plus_scalar_times_vec2(subgrad, -1.0, psi_truth.vector, dim);
R += result->score + result->delta - SGVector<float64_t>::dot(W, psi_truth.vector, dim);
SG_UNREF(result);
}
return R;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C -*-
$Id$
Copyright (C) 2001 by Klarlvdalens Datakonsult AB
GPGMEPLUG is free software; you can redistribute it and/or modify
it under the terms of GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
GPGMEPLUG is distributed in the hope that it will be useful,
it under the terms of GNU General Public License as published by
the Free Software Foundation; version 2 of the License
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
*/
#include <qlistview.h>
#include <qtextedit.h>
#include <qheader.h>
#include <qpushbutton.h>
#include <qcursor.h>
#include <qapplication.h>
#include <klocale.h>
#include <kdialogbase.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include "certificateinfowidgetimpl.h"
#include "certmanager.h"
CertificateInfoWidgetImpl::CertificateInfoWidgetImpl( CertManager* manager, bool external,
QWidget* parent, const char* name )
: CertificateInfoWidget( parent, name ), _manager(manager), _external( external )
{
if( !external ) importButton->setEnabled(false);
listView->setColumnWidthMode( 1, QListView::Manual );
listView->setResizeMode( QListView::LastColumn );
QFontMetrics fm = fontMetrics();
listView->setColumnWidth( 1, fm.width( i18n("Information") ) * 5 );
listView->header()->setClickEnabled( false );
listView->setSorting( -1 );
connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ),
this, SLOT( slotShowInfo( QListViewItem* ) ) );
pathView->setColumnWidthMode( 0, QListView::Manual );
pathView->setResizeMode( QListView::LastColumn );
pathView->header()->hide();
connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ),
this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ),
this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
connect( importButton, SIGNAL( clicked() ),
this, SLOT( slotImportCertificate() ) );
}
void CertificateInfoWidgetImpl::setCert( const CryptPlugWrapper::CertificateInfo& info )
{
listView->clear();
pathView->clear();
_info = info;
/* Check if we already have the cert in question */
if( _manager ) {
importButton->setEnabled( !_manager->haveCertificate( info.fingerprint ) );
} else {
importButton->setEnabled( false );
}
// These will show in the opposite order
new QListViewItem( listView, i18n("Fingerprint"), info.fingerprint );
new QListViewItem( listView, i18n("Can be used for certification"),
info.certify?i18n("Yes"):i18n("No") );
new QListViewItem( listView, i18n("Can be used for encryption"),
info.encrypt?i18n("Yes"):i18n("No") );
new QListViewItem( listView, i18n("Can be used for signing"),
info.sign?i18n("Yes"):i18n("No") );
new QListViewItem( listView, i18n("Valid"), QString("From %1 to %2")
.arg( info.created.toString() ).arg(info.expire.toString()) );
//new QListViewItem( listView, i18n("Email"), info.dn["1.2.840.113549.1.9.1"] );
new QListViewItem( listView, i18n("Country"), info.dn["C"] );
new QListViewItem( listView, i18n("Organizational Unit"), info.dn["OU"] );
new QListViewItem( listView, i18n("Organization"), info.dn["O"] );
new QListViewItem( listView, i18n("Location"), info.dn["L"] );
new QListViewItem( listView, i18n("Name"), info.dn["CN"] );
new QListViewItem( listView, i18n("Issuer"), info.issuer.stripWhiteSpace() );
QStringList::ConstIterator it = info.userid.begin();
QListViewItem* item = new QListViewItem( listView, i18n("Subject"),
(*it).stripWhiteSpace() );
++it;
while( it != info.userid.end() ) {
if( (*it)[0] == '<' ) {
item = new QListViewItem( listView, item, i18n("Email"), (*it).mid(1,(*it).length()-2));
} else {
item = new QListViewItem( listView, item, i18n("Aka"), (*it).stripWhiteSpace() );
}
++it;
}
// Set up cert. path
if( !_manager ) return;
const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
QString issuer = info.issuer;
QStringList items;
items << info.userid[0];
bool root_found = false;
while( true ) {
bool found = false;
CryptPlugWrapper::CertificateInfo info;
for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
it != lst.end(); ++it ) {
if( (*it).userid[0] == issuer && !items.contains( info.userid[0] ) ) {
info = (*it);
found = true;
break;
}
}
if( found ) {
items.prepend( info.userid[0] );
issuer = info.issuer;
// FIXME(steffen): Use real DN comparison
if( info.userid[0] == info.issuer ) {
// Root item
root_found = true;
break;
}
} else break;
}
item = 0;
if( !root_found ) {
if( items.count() > 0 ) items.prepend( QString::fromUtf8("Root certificate not found (%1)").arg( issuer ) );
else items.prepend( "Root certificate not found" );
}
for( QStringList::Iterator it = items.begin(); it != items.end(); ++it ) {
if( item ) item = new QListViewItem( item, (*it) );
else item = new QListViewItem( pathView, (*it) );
item->setOpen( true );
}
}
void CertificateInfoWidgetImpl::slotShowInfo( QListViewItem* item )
{
textView->setText( item->text(1) );
}
void CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem* item )
{
if( !_manager ) return;
const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
it != lst.end(); ++it ) {
if( (*it).userid[0] == item->text(0) ) {
KDialogBase* dialog = new KDialogBase( this, "dialog", true, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close );
CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog );
dialog->setMainWidget( top );
top->setCert( *it );
dialog->exec();
delete dialog;
}
}
}
static QString parseXMLInfo( const QString& info )
{
QString result;
QDomDocument doc;
if( !doc.setContent( info ) ) {
kdDebug() << "xml parser error in CertificateInfoWidgetImpl::slotImportCertificate()" << endl;
}
QDomNode importinfo = doc.documentElement().namedItem("importResult");
result = "<p align=\"center\"><table border=\"1\"><tr><th>Name</th><th>Value</th></tr>";
for( QDomNode n = importinfo.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if( n.isElement() ) {
QDomElement elem = n.toElement();
result += "<tr><td>"+ elem.tagName() + "</td><td>" + elem.text().stripWhiteSpace() + "</td></tr>";
}
}
result += "</table></p>";
return result;
}
void CertificateInfoWidgetImpl::slotImportCertificate()
{
if( !_manager ) return;
QApplication::setOverrideCursor( QCursor::WaitCursor );
QString info;
int retval = _manager->importCertificateWithFingerprint( _info.fingerprint, &info );
info = parseXMLInfo( info );
QApplication::restoreOverrideCursor();
if( retval == -42 ) {
KMessageBox::error( this, i18n("<qml>Cryptplug returned success, but no certiftcate was imported.<br>You may need to import the issuer certificate <b>%1</b> first.<br>Additional info:<br>%2</qml>").arg( _info.issuer ).arg(info),
i18n("Import error") );
} else if( retval ) {
KMessageBox::error( this, i18n("<qml>Error importing certificate.<br>CryptPlug returned %1. Additional info:<br>%2</qml>").arg(retval).arg( info ), i18n("Import error") );
} else {
KMessageBox::information( this, i18n("<qml>Certificate %1 with fingerprint <b>%2</b> is imported to the local database.<br>Additional info:<br>%3</qml>").arg(_info.userid[0]).arg(_info.fingerprint).arg( info ), i18n("Certificate Imported") );
importButton->setEnabled( false );
}
}
#include "certificateinfowidgetimpl.moc"
<commit_msg>forgot an i18n()<commit_after>/* -*- Mode: C -*-
$Id$
Copyright (C) 2001 by Klarlvdalens Datakonsult AB
GPGMEPLUG is free software; you can redistribute it and/or modify
it under the terms of GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
GPGMEPLUG is distributed in the hope that it will be useful,
it under the terms of GNU General Public License as published by
the Free Software Foundation; version 2 of the License
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
*/
#include <qlistview.h>
#include <qtextedit.h>
#include <qheader.h>
#include <qpushbutton.h>
#include <qcursor.h>
#include <qapplication.h>
#include <klocale.h>
#include <kdialogbase.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include "certificateinfowidgetimpl.h"
#include "certmanager.h"
CertificateInfoWidgetImpl::CertificateInfoWidgetImpl( CertManager* manager, bool external,
QWidget* parent, const char* name )
: CertificateInfoWidget( parent, name ), _manager(manager), _external( external )
{
if( !external ) importButton->setEnabled(false);
listView->setColumnWidthMode( 1, QListView::Manual );
listView->setResizeMode( QListView::LastColumn );
QFontMetrics fm = fontMetrics();
listView->setColumnWidth( 1, fm.width( i18n("Information") ) * 5 );
listView->header()->setClickEnabled( false );
listView->setSorting( -1 );
connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ),
this, SLOT( slotShowInfo( QListViewItem* ) ) );
pathView->setColumnWidthMode( 0, QListView::Manual );
pathView->setResizeMode( QListView::LastColumn );
pathView->header()->hide();
connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ),
this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ),
this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
connect( importButton, SIGNAL( clicked() ),
this, SLOT( slotImportCertificate() ) );
}
void CertificateInfoWidgetImpl::setCert( const CryptPlugWrapper::CertificateInfo& info )
{
listView->clear();
pathView->clear();
_info = info;
/* Check if we already have the cert in question */
if( _manager ) {
importButton->setEnabled( !_manager->haveCertificate( info.fingerprint ) );
} else {
importButton->setEnabled( false );
}
// These will show in the opposite order
new QListViewItem( listView, i18n("Fingerprint"), info.fingerprint );
new QListViewItem( listView, i18n("Can be used for certification"),
info.certify?i18n("Yes"):i18n("No") );
new QListViewItem( listView, i18n("Can be used for encryption"),
info.encrypt?i18n("Yes"):i18n("No") );
new QListViewItem( listView, i18n("Can be used for signing"),
info.sign?i18n("Yes"):i18n("No") );
new QListViewItem( listView, i18n("Valid"), QString("From %1 to %2")
.arg( info.created.toString() ).arg(info.expire.toString()) );
//new QListViewItem( listView, i18n("Email"), info.dn["1.2.840.113549.1.9.1"] );
new QListViewItem( listView, i18n("Country"), info.dn["C"] );
new QListViewItem( listView, i18n("Organizational Unit"), info.dn["OU"] );
new QListViewItem( listView, i18n("Organization"), info.dn["O"] );
new QListViewItem( listView, i18n("Location"), info.dn["L"] );
new QListViewItem( listView, i18n("Name"), info.dn["CN"] );
new QListViewItem( listView, i18n("Issuer"), info.issuer.stripWhiteSpace() );
QStringList::ConstIterator it = info.userid.begin();
QListViewItem* item = new QListViewItem( listView, i18n("Subject"),
(*it).stripWhiteSpace() );
++it;
while( it != info.userid.end() ) {
if( (*it)[0] == '<' ) {
item = new QListViewItem( listView, item, i18n("Email"), (*it).mid(1,(*it).length()-2));
} else {
item = new QListViewItem( listView, item, i18n("Aka"), (*it).stripWhiteSpace() );
}
++it;
}
// Set up cert. path
if( !_manager ) return;
const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
QString issuer = info.issuer;
QStringList items;
items << info.userid[0];
bool root_found = false;
while( true ) {
bool found = false;
CryptPlugWrapper::CertificateInfo info;
for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
it != lst.end(); ++it ) {
if( (*it).userid[0] == issuer && !items.contains( info.userid[0] ) ) {
info = (*it);
found = true;
break;
}
}
if( found ) {
items.prepend( info.userid[0] );
issuer = info.issuer;
// FIXME(steffen): Use real DN comparison
if( info.userid[0] == info.issuer ) {
// Root item
root_found = true;
break;
}
} else break;
}
item = 0;
if( !root_found ) {
if( items.count() > 0 ) items.prepend( QString::fromUtf8("Root certificate not found (%1)").arg( issuer ) );
else items.prepend( "Root certificate not found" );
}
for( QStringList::Iterator it = items.begin(); it != items.end(); ++it ) {
if( item ) item = new QListViewItem( item, (*it) );
else item = new QListViewItem( pathView, (*it) );
item->setOpen( true );
}
}
void CertificateInfoWidgetImpl::slotShowInfo( QListViewItem* item )
{
textView->setText( item->text(1) );
}
void CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem* item )
{
if( !_manager ) return;
const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
it != lst.end(); ++it ) {
if( (*it).userid[0] == item->text(0) ) {
KDialogBase* dialog = new KDialogBase( this, "dialog", true, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close );
CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog );
dialog->setMainWidget( top );
top->setCert( *it );
dialog->exec();
delete dialog;
}
}
}
static QString parseXMLInfo( const QString& info )
{
QString result;
QDomDocument doc;
if( !doc.setContent( info ) ) {
kdDebug() << "xml parser error in CertificateInfoWidgetImpl::slotImportCertificate()" << endl;
}
QDomNode importinfo = doc.documentElement().namedItem("importResult");
result = i18n("<p align=\"center\"><table border=\"1\"><tr><th>Name</th><th>Value</th></tr>");
for( QDomNode n = importinfo.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if( n.isElement() ) {
QDomElement elem = n.toElement();
result += "<tr><td>"+ elem.tagName() + "</td><td>" + elem.text().stripWhiteSpace() + "</td></tr>";
}
}
result += "</table></p>";
return result;
}
void CertificateInfoWidgetImpl::slotImportCertificate()
{
if( !_manager ) return;
QApplication::setOverrideCursor( QCursor::WaitCursor );
QString info;
int retval = _manager->importCertificateWithFingerprint( _info.fingerprint, &info );
info = parseXMLInfo( info );
QApplication::restoreOverrideCursor();
if( retval == -42 ) {
KMessageBox::error( this, i18n("<qml>Cryptplug returned success, but no certiftcate was imported.<br>You may need to import the issuer certificate <b>%1</b> first.<br>Additional info:<br>%2</qml>").arg( _info.issuer ).arg(info),
i18n("Import error") );
} else if( retval ) {
KMessageBox::error( this, i18n("<qml>Error importing certificate.<br>CryptPlug returned %1. Additional info:<br>%2</qml>").arg(retval).arg( info ), i18n("Import error") );
} else {
KMessageBox::information( this, i18n("<qml>Certificate %1 with fingerprint <b>%2</b> is imported to the local database.<br>Additional info:<br>%3</qml>").arg(_info.userid[0]).arg(_info.fingerprint).arg( info ), i18n("Certificate Imported") );
importButton->setEnabled( false );
}
}
#include "certificateinfowidgetimpl.moc"
<|endoftext|>
|
<commit_before>#define _USE_MATH_DEFINES
#include <cmath>
#include "consts.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include <sstream>
#include <cstdlib>
#include <set>
#include <math.h>
//TODO: not to use cout inside Element class
#include <iostream>
//
Element::Element()
{
}
Element::Element(string netlistLine,
int &numNodes,
vector<string> &variablesList):
polynomial(false)
{
stringstream sstream(netlistLine);
char na[MAX_NAME], nb[MAX_NAME], nc[MAX_NAME], nd[MAX_NAME];
vector<double> _params(MAX_PARAMS);
for (int i=0; i<MAX_PARAMS; i++){
_params[i] = 0;
}
sstream >> name;
cout << name << " ";
type = getType();
sstream.str( string(netlistLine, name.size(), string::npos) );
if (type=='R') {
sstream >> na >> nb;
cout << na << " " << nb << " ";
for (int i = 0; i < MAX_PARAMS; i++){
sstream >> _params[i];
if (i>=1 && _params[i]!=0)
polynomial = true;
}
if (!polynomial){
value = _params[0];
cout << value << endl;
}
else {
params = _params;
for (int i = 0; i < MAX_PARAMS; i++){
cout << params[i] << " ";
}
cout << endl;
}
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
}
else if (type == 'I' || type == 'V') {
polynomial = true; // XXX Ugly (time is running out!)
sstream >> na >> nb >> signalType;
cout << na << " " << nb << " " << signalType << " ";
for (int i = 0; i < MAX_PARAMS; i++){
sstream >> _params[i];
cout << _params[i] << " ";
}
params = _params;
cout << endl;
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
}
else if (type=='G' || type=='E' || type=='F' || type=='H') {
sstream >> na >> nb >> nc >> nd;
cout << na << " " << nb << " " << nc << " " << nd << " ";
for (int i = 0; i < MAX_PARAMS; i++){
sstream >> _params[i];
if (i >= 1 && _params[i] != 0)
polynomial = true;
}
if (!polynomial){
value = _params[0];
cout << value << endl;
}
else {
params = _params;
for (int i = 0; i < MAX_PARAMS; i++){
cout << params[i] << " ";
}
cout << endl;
}
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
c = getNodeNumber(nc, numNodes, variablesList);
d = getNodeNumber(nd, numNodes, variablesList);
}
else if (type=='O') {
sstream >> na >> nb >> nc >> nd;
cout << na << " " << nb << " " << nc << " " << nd << " " << endl;
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
c = getNodeNumber(nc, numNodes, variablesList);
d = getNodeNumber(nd, numNodes, variablesList);
}
else if (type == 'C' || type == 'L') {
sstream >> na >> nb >> value;
cout << na << " " << nb << " " << value << " ";
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
}
}
void Element::addCurrentVariables(int &numVariables, vector<string> &variablesList){
if (type=='V' || type=='E' || type=='F' || type=='O') {
numVariables++;
if (numVariables>MAX_NODES) {
cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NODES << ")" << endl;
exit(EXIT_FAILURE);
}
x=numVariables;
variablesList[numVariables] = "j" + name;
}
else if (type=='H') {
numVariables=numVariables+2;
x=numVariables-1;
y=numVariables;
variablesList[numVariables-1] = "jx" + name;
variablesList[numVariables] = "jy" + name;
}
else if (type=='L'){
numVariables++;
if (numVariables>MAX_NODES) {
cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NODES << ")" << endl;
exit(EXIT_FAILURE);
}
x = numVariables;
variablesList[numVariables] = "j" + name;
}
}
Element::Element(string name,
double value,
int a,
int b,
int c,
int d,
int x,
int y):
name(name),
value(value),
a(a),
b(b),
c(c),
d(d),
x(x),
y(y),
signalType("DC"),
polynomial(false)
{
type = getType();
}
Element::Element(string name,
vector<double> ¶ms,
int a,
int b,
int c,
int d):
name(name),
params(params),
a(a),
b(b),
c(c),
d(d),
polynomial(true)
{
type = getType();
}
void Element::calcNewtonRaphsonParameters(const double &Xn){
dFx = params[1];
FxMinusdFxTimesXn = params[0];
for (int i = 2; i < MAX_PARAMS; i++){
dFx += params[i]*(i)*pow(Xn, i-1);
FxMinusdFxTimesXn -= params[i]*(i-1)*pow(Xn, i);
}
}
double Element::calcSourceValue(double t){
if (signalType == "DC"){
if (polynomial)
value = params[0];
return value;
} else if (signalType == "SIN"){
double offset = params[0];
double amplitude = params[1];
double frequency = params[2];
double delay = params[3];
double attenuation = params[4];
double angle = params[5];
double cycles = params[6];
double innerTime = t - delay;
if (innerTime < delay || innerTime - delay > cycles / frequency)
return offset + amplitude * sin(M_PI * angle / 180);
return offset + amplitude*exp(innerTime*attenuation)*sin(2 * M_PI*frequency*innerTime - M_PI*angle / 180);
}
else if (signalType == "PULSE"){
//Parameters
double amp1 = params[0];
double amp2 = params[1];
double delay = params[2];
double riseTime = params[3];
double fallTime = params[4];
double onTime = params[5];
double period = params[6];
double cycles = params[7];
// Local variables for Operations
double CountPeriod = floor(t/period); // Which period is currently analyzing
double PeriodTime = (t - (period*CountPeriod)); // Time from the beggining of each period
double time2 = (delay + riseTime);
double time3 = (delay + riseTime + onTime);
double time4 = (delay + riseTime + onTime + fallTime);
// Limiting Cycle Numbers by the End of Period
while (CountPeriod < cycles) {
// Phase 1 of Pulse Source
if (PeriodTime <= delay)
return amp1;
// Phase 2 of Pulse Source
else if ((delay < PeriodTime) && (PeriodTime <= time2))
return amp1 + ((PeriodTime - delay) / riseTime) * (amp2 - amp1);
// Phase 3 of Pulse Source
else if ((time2 < PeriodTime) && (PeriodTime <= time3))
return amp2;
// Phase 4 of Pulse Source
else if ((time3 < PeriodTime) && (PeriodTime <= time4))
return amp2 - ((PeriodTime - time3) / fallTime)*(amp2 - amp1);
//Phase 5 of Pulse Source
else if ((time4 < PeriodTime) && (PeriodTime <= period))
return amp1;
}
// Finishing the last cycle => The amplitude is always == amp1
return amp1;
}
}
void Element::applyStamp(double Yn[MAX_NODES+1][MAX_NODES+2],
const int &numVariables,
double (&previousSolution)[MAX_NODES+1],
double t,
double step,
double (&lastStepSolution)[MAX_NODES+1])
{
if (type=='R') {
double G;
if (!polynomial){
G=1/value;
} else {
double Vab = previousSolution[a]-previousSolution[b];
calcNewtonRaphsonParameters(Vab);
G = dFx;
double I0;
I0 = FxMinusdFxTimesXn;
Yn[a][numVariables+1]-=I0;
Yn[b][numVariables+1]+=I0;
}
Yn[a][a]+=G;
Yn[b][b]+=G;
Yn[a][b]-=G;
Yn[b][a]-=G;
}
else if (type=='G') {
double G;
if (!polynomial){
G=value;
} else {
double Vcd = previousSolution[c]-previousSolution[d];
calcNewtonRaphsonParameters(Vcd);
G = dFx;
double I0 = FxMinusdFxTimesXn;
Yn[a][numVariables+1]-=I0;
Yn[b][numVariables+1]+=I0;
}
Yn[a][c]+=G;
Yn[b][d]+=G;
Yn[a][d]-=G;
Yn[b][c]-=G;
}
else if (type=='I') {
double I=calcSourceValue(t);
Yn[a][numVariables+1]-=I;
Yn[b][numVariables+1]+=I;
}
else if (type=='V') {
double V=calcSourceValue(t);
Yn[a][x]+=1;
Yn[b][x]-=1;
Yn[x][a]-=1;
Yn[x][b]+=1;
Yn[x][numVariables+1]-=V;
}
else if (type=='E') {
// Voltage Amplifier
double A;
double k;
if (!polynomial){
A=value;
k=1;
} else {
double Vcd = previousSolution[c]-previousSolution[d];
calcNewtonRaphsonParameters(Vcd);
A = dFx;
double V0 = FxMinusdFxTimesXn;
Yn[x][numVariables+1]-=V0;
k=2;
}
Yn[a][x]+=k*1;
Yn[b][x]-=k*1;
Yn[x][a]-=k*1;
Yn[x][b]+=k*1;
Yn[x][c]+=A;
Yn[x][d]-=A;
}
else if (type=='F') {
// Current Amplifier
double B;
if (!polynomial){
B=value;
} else {
double Jcd = previousSolution[x];
calcNewtonRaphsonParameters(Jcd);
B=dFx;
double I0 = FxMinusdFxTimesXn;
Yn[a][numVariables+1]-=I0;
Yn[b][numVariables+1]+=I0;
}
Yn[a][x]+=B;
Yn[b][x]-=B;
Yn[c][x]+=1;
Yn[d][x]-=1;
Yn[x][c]-=1;
Yn[x][d]+=1;
}
else if (type=='H') {
// CCVS: Transresistance
double Rm;
if (!polynomial){
Rm=value;
} else {
double Jcd = previousSolution[y];
calcNewtonRaphsonParameters(Jcd);
Yn[a][x]+=1;
Yn[b][x]-=1;
Yn[x][a]-=1;
Yn[x][b]+=1;
Rm=dFx;
double V0 = FxMinusdFxTimesXn;
Yn[x][numVariables+1]-=V0;
}
Yn[a][y]+=1;
Yn[b][y]-=1;
Yn[c][x]+=1;
Yn[d][x]-=1;
Yn[y][a]-=1;
Yn[y][b]+=1;
Yn[x][c]-=1;
Yn[x][d]+=1;
Yn[y][x]+=Rm;
}
else if (type=='O') {
Yn[a][x]+=1;
Yn[b][x]-=1;
Yn[x][c]+=1;
Yn[x][d]-=1;
}
else if (type == 'C') {
double Vc = lastStepSolution[a] - lastStepSolution[b];
double G;
double I0 = (value / step) * Vc;
if (!t){
G = TOLG;
}
else {
G = value / step;
Yn[a][numVariables + 1] += I0;
Yn[b][numVariables + 1] -= I0;
}
Yn[a][a] += G;
Yn[b][b] += G;
Yn[a][b] -= G;
Yn[b][a] -= G;
}
else if (type == 'L') {
// XXX
double Jl = previousSolution[x];
double G;
double I0 = (value / (t - step))*Jl;
if (!t){
G = TOLG;
Yn[a][a] += G;
Yn[b][b] += G;
Yn[a][b] -= G;
Yn[b][a] -= G;
} else {
G = value / (t - step);
Yn[a][x] += 1;
Yn[b][x] -= 1;
Yn[x][a] -= 1;
Yn[x][b] += 1;
Yn[x][x] += G;
}
}
}
int Element::getNodeNumber(const char *name,
int &numNodes,
vector<string> &variablesList)
{
int i=0, achou=0;
while (!achou && i<=numNodes)
if (!(achou=!variablesList[i].compare(name))) i++;
if (!achou) {
if (numNodes==MAX_NODES) {
cout << "Maximum number of nodes reached: " << MAX_NODES << endl;
#if defined (WIN32) || defined(_WIN32)
cin.get();
#endif
exit(EXIT_FAILURE);
}
numNodes++;
variablesList[numNodes] = name;
return numNodes; /* new node */
}
else {
return i; /* known node */
}
}
bool Element::isValidElement(const char &netlistLinePrefix){
// Initializing set with tmpElementPrefixes
char tmpElementPrefixes[] = {
'R', 'I', 'V', 'G', 'E', 'F', 'H', 'O', 'L', 'C'
};
set<char> elementPrefixes(
tmpElementPrefixes,
tmpElementPrefixes +
sizeof(tmpElementPrefixes) /
sizeof(tmpElementPrefixes[0])
);
// Returns whether or not line prefix corresponds to valid Element
// verifying if netlistLinePrefix is in elementPrefixes
return elementPrefixes.find(netlistLinePrefix) != elementPrefixes.end();
}
string Element::getName() const
{
return name;
}
char Element::getType() const
{
return name[0];
}
<commit_msg>Cleans code for Capacitor stamp<commit_after>#define _USE_MATH_DEFINES
#include <cmath>
#include "consts.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include <sstream>
#include <cstdlib>
#include <set>
#include <math.h>
//TODO: not to use cout inside Element class
#include <iostream>
//
Element::Element()
{
}
Element::Element(string netlistLine,
int &numNodes,
vector<string> &variablesList):
polynomial(false)
{
stringstream sstream(netlistLine);
char na[MAX_NAME], nb[MAX_NAME], nc[MAX_NAME], nd[MAX_NAME];
vector<double> _params(MAX_PARAMS);
for (int i=0; i<MAX_PARAMS; i++){
_params[i] = 0;
}
sstream >> name;
cout << name << " ";
type = getType();
sstream.str( string(netlistLine, name.size(), string::npos) );
if (type=='R') {
sstream >> na >> nb;
cout << na << " " << nb << " ";
for (int i = 0; i < MAX_PARAMS; i++){
sstream >> _params[i];
if (i>=1 && _params[i]!=0)
polynomial = true;
}
if (!polynomial){
value = _params[0];
cout << value << endl;
}
else {
params = _params;
for (int i = 0; i < MAX_PARAMS; i++){
cout << params[i] << " ";
}
cout << endl;
}
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
}
else if (type == 'I' || type == 'V') {
polynomial = true; // XXX Ugly (time is running out!)
sstream >> na >> nb >> signalType;
cout << na << " " << nb << " " << signalType << " ";
for (int i = 0; i < MAX_PARAMS; i++){
sstream >> _params[i];
cout << _params[i] << " ";
}
params = _params;
cout << endl;
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
}
else if (type=='G' || type=='E' || type=='F' || type=='H') {
sstream >> na >> nb >> nc >> nd;
cout << na << " " << nb << " " << nc << " " << nd << " ";
for (int i = 0; i < MAX_PARAMS; i++){
sstream >> _params[i];
if (i >= 1 && _params[i] != 0)
polynomial = true;
}
if (!polynomial){
value = _params[0];
cout << value << endl;
}
else {
params = _params;
for (int i = 0; i < MAX_PARAMS; i++){
cout << params[i] << " ";
}
cout << endl;
}
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
c = getNodeNumber(nc, numNodes, variablesList);
d = getNodeNumber(nd, numNodes, variablesList);
}
else if (type=='O') {
sstream >> na >> nb >> nc >> nd;
cout << na << " " << nb << " " << nc << " " << nd << " " << endl;
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
c = getNodeNumber(nc, numNodes, variablesList);
d = getNodeNumber(nd, numNodes, variablesList);
}
else if (type == 'C' || type == 'L') {
sstream >> na >> nb >> value;
cout << na << " " << nb << " " << value << " ";
a = getNodeNumber(na, numNodes, variablesList);
b = getNodeNumber(nb, numNodes, variablesList);
}
}
void Element::addCurrentVariables(int &numVariables, vector<string> &variablesList){
if (type=='V' || type=='E' || type=='F' || type=='O') {
numVariables++;
if (numVariables>MAX_NODES) {
cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NODES << ")" << endl;
exit(EXIT_FAILURE);
}
x=numVariables;
variablesList[numVariables] = "j" + name;
}
else if (type=='H') {
numVariables=numVariables+2;
x=numVariables-1;
y=numVariables;
variablesList[numVariables-1] = "jx" + name;
variablesList[numVariables] = "jy" + name;
}
else if (type=='L'){
numVariables++;
if (numVariables>MAX_NODES) {
cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NODES << ")" << endl;
exit(EXIT_FAILURE);
}
x = numVariables;
variablesList[numVariables] = "j" + name;
}
}
Element::Element(string name,
double value,
int a,
int b,
int c,
int d,
int x,
int y):
name(name),
value(value),
a(a),
b(b),
c(c),
d(d),
x(x),
y(y),
signalType("DC"),
polynomial(false)
{
type = getType();
}
Element::Element(string name,
vector<double> ¶ms,
int a,
int b,
int c,
int d):
name(name),
params(params),
a(a),
b(b),
c(c),
d(d),
polynomial(true)
{
type = getType();
}
void Element::calcNewtonRaphsonParameters(const double &Xn){
dFx = params[1];
FxMinusdFxTimesXn = params[0];
for (int i = 2; i < MAX_PARAMS; i++){
dFx += params[i]*(i)*pow(Xn, i-1);
FxMinusdFxTimesXn -= params[i]*(i-1)*pow(Xn, i);
}
}
double Element::calcSourceValue(double t){
if (signalType == "DC"){
if (polynomial)
value = params[0];
return value;
} else if (signalType == "SIN"){
double offset = params[0];
double amplitude = params[1];
double frequency = params[2];
double delay = params[3];
double attenuation = params[4];
double angle = params[5];
double cycles = params[6];
double innerTime = t - delay;
if (innerTime < delay || innerTime - delay > cycles / frequency)
return offset + amplitude * sin(M_PI * angle / 180);
return offset + amplitude*exp(innerTime*attenuation)*sin(2 * M_PI*frequency*innerTime - M_PI*angle / 180);
}
else if (signalType == "PULSE"){
//Parameters
double amp1 = params[0];
double amp2 = params[1];
double delay = params[2];
double riseTime = params[3];
double fallTime = params[4];
double onTime = params[5];
double period = params[6];
double cycles = params[7];
// Local variables for Operations
double CountPeriod = floor(t/period); // Which period is currently analyzing
double PeriodTime = (t - (period*CountPeriod)); // Time from the beggining of each period
double time2 = (delay + riseTime);
double time3 = (delay + riseTime + onTime);
double time4 = (delay + riseTime + onTime + fallTime);
// Limiting Cycle Numbers by the End of Period
while (CountPeriod < cycles) {
// Phase 1 of Pulse Source
if (PeriodTime <= delay)
return amp1;
// Phase 2 of Pulse Source
else if ((delay < PeriodTime) && (PeriodTime <= time2))
return amp1 + ((PeriodTime - delay) / riseTime) * (amp2 - amp1);
// Phase 3 of Pulse Source
else if ((time2 < PeriodTime) && (PeriodTime <= time3))
return amp2;
// Phase 4 of Pulse Source
else if ((time3 < PeriodTime) && (PeriodTime <= time4))
return amp2 - ((PeriodTime - time3) / fallTime)*(amp2 - amp1);
//Phase 5 of Pulse Source
else if ((time4 < PeriodTime) && (PeriodTime <= period))
return amp1;
}
// Finishing the last cycle => The amplitude is always == amp1
return amp1;
}
}
void Element::applyStamp(double Yn[MAX_NODES+1][MAX_NODES+2],
const int &numVariables,
double (&previousSolution)[MAX_NODES+1],
double t,
double step,
double (&lastStepSolution)[MAX_NODES+1])
{
if (type=='R') {
double G;
if (!polynomial){
G=1/value;
} else {
double Vab = previousSolution[a]-previousSolution[b];
calcNewtonRaphsonParameters(Vab);
G = dFx;
double I0;
I0 = FxMinusdFxTimesXn;
Yn[a][numVariables+1]-=I0;
Yn[b][numVariables+1]+=I0;
}
Yn[a][a]+=G;
Yn[b][b]+=G;
Yn[a][b]-=G;
Yn[b][a]-=G;
}
else if (type=='G') {
double G;
if (!polynomial){
G=value;
} else {
double Vcd = previousSolution[c]-previousSolution[d];
calcNewtonRaphsonParameters(Vcd);
G = dFx;
double I0 = FxMinusdFxTimesXn;
Yn[a][numVariables+1]-=I0;
Yn[b][numVariables+1]+=I0;
}
Yn[a][c]+=G;
Yn[b][d]+=G;
Yn[a][d]-=G;
Yn[b][c]-=G;
}
else if (type=='I') {
double I=calcSourceValue(t);
Yn[a][numVariables+1]-=I;
Yn[b][numVariables+1]+=I;
}
else if (type=='V') {
double V=calcSourceValue(t);
Yn[a][x]+=1;
Yn[b][x]-=1;
Yn[x][a]-=1;
Yn[x][b]+=1;
Yn[x][numVariables+1]-=V;
}
else if (type=='E') {
// Voltage Amplifier
double A;
double k;
if (!polynomial){
A=value;
k=1;
} else {
double Vcd = previousSolution[c]-previousSolution[d];
calcNewtonRaphsonParameters(Vcd);
A = dFx;
double V0 = FxMinusdFxTimesXn;
Yn[x][numVariables+1]-=V0;
k=2;
}
Yn[a][x]+=k*1;
Yn[b][x]-=k*1;
Yn[x][a]-=k*1;
Yn[x][b]+=k*1;
Yn[x][c]+=A;
Yn[x][d]-=A;
}
else if (type=='F') {
// Current Amplifier
double B;
if (!polynomial){
B=value;
} else {
double Jcd = previousSolution[x];
calcNewtonRaphsonParameters(Jcd);
B=dFx;
double I0 = FxMinusdFxTimesXn;
Yn[a][numVariables+1]-=I0;
Yn[b][numVariables+1]+=I0;
}
Yn[a][x]+=B;
Yn[b][x]-=B;
Yn[c][x]+=1;
Yn[d][x]-=1;
Yn[x][c]-=1;
Yn[x][d]+=1;
}
else if (type=='H') {
// CCVS: Transresistance
double Rm;
if (!polynomial){
Rm=value;
} else {
double Jcd = previousSolution[y];
calcNewtonRaphsonParameters(Jcd);
Yn[a][x]+=1;
Yn[b][x]-=1;
Yn[x][a]-=1;
Yn[x][b]+=1;
Rm=dFx;
double V0 = FxMinusdFxTimesXn;
Yn[x][numVariables+1]-=V0;
}
Yn[a][y]+=1;
Yn[b][y]-=1;
Yn[c][x]+=1;
Yn[d][x]-=1;
Yn[y][a]-=1;
Yn[y][b]+=1;
Yn[x][c]-=1;
Yn[x][d]+=1;
Yn[y][x]+=Rm;
}
else if (type=='O') {
Yn[a][x]+=1;
Yn[b][x]-=1;
Yn[x][c]+=1;
Yn[x][d]-=1;
}
else if (type == 'C') {
double G;
if (!t){
G = TOLG;
}
else {
G = value / step;
double Vc = lastStepSolution[a] - lastStepSolution[b];
double I0 = (value / step) * Vc;
Yn[a][numVariables + 1] += I0;
Yn[b][numVariables + 1] -= I0;
}
Yn[a][a] += G;
Yn[b][b] += G;
Yn[a][b] -= G;
Yn[b][a] -= G;
}
else if (type == 'L') {
// XXX
double Jl = previousSolution[x];
double G;
double I0 = (value / (t - step))*Jl;
if (!t){
G = TOLG;
Yn[a][a] += G;
Yn[b][b] += G;
Yn[a][b] -= G;
Yn[b][a] -= G;
} else {
G = value / (t - step);
Yn[a][x] += 1;
Yn[b][x] -= 1;
Yn[x][a] -= 1;
Yn[x][b] += 1;
Yn[x][x] += G;
}
}
}
int Element::getNodeNumber(const char *name,
int &numNodes,
vector<string> &variablesList)
{
int i=0, achou=0;
while (!achou && i<=numNodes)
if (!(achou=!variablesList[i].compare(name))) i++;
if (!achou) {
if (numNodes==MAX_NODES) {
cout << "Maximum number of nodes reached: " << MAX_NODES << endl;
#if defined (WIN32) || defined(_WIN32)
cin.get();
#endif
exit(EXIT_FAILURE);
}
numNodes++;
variablesList[numNodes] = name;
return numNodes; /* new node */
}
else {
return i; /* known node */
}
}
bool Element::isValidElement(const char &netlistLinePrefix){
// Initializing set with tmpElementPrefixes
char tmpElementPrefixes[] = {
'R', 'I', 'V', 'G', 'E', 'F', 'H', 'O', 'L', 'C'
};
set<char> elementPrefixes(
tmpElementPrefixes,
tmpElementPrefixes +
sizeof(tmpElementPrefixes) /
sizeof(tmpElementPrefixes[0])
);
// Returns whether or not line prefix corresponds to valid Element
// verifying if netlistLinePrefix is in elementPrefixes
return elementPrefixes.find(netlistLinePrefix) != elementPrefixes.end();
}
string Element::getName() const
{
return name;
}
char Element::getType() const
{
return name[0];
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "watchman/CommandRegistry.h"
#include "watchman/Logging.h"
#include "watchman/Shutdown.h"
#include "watchman/TriggerCommand.h"
#include "watchman/query/Query.h"
#include "watchman/sockname.h"
#include "watchman/state.h"
#include "watchman/watchman_cmd.h"
#include "watchman/watchman_root.h"
#include "watchman/watchman_stream.h"
#include <memory>
using namespace watchman;
/* trigger-del /root triggername
* Delete a trigger from a root
*/
static void cmd_trigger_delete(
struct watchman_client* client,
const json_ref& args) {
w_string tname;
bool res;
auto root = resolveRoot(client, args);
if (json_array_size(args) != 3) {
send_error_response(client, "wrong number of arguments");
return;
}
auto jname = args.at(2);
if (!jname.isString()) {
send_error_response(client, "expected 2nd parameter to be trigger name");
return;
}
tname = json_to_w_string(jname);
std::unique_ptr<TriggerCommand> cmd;
{
auto map = root->triggers.wlock();
auto it = map->find(tname);
if (it == map->end()) {
res = false;
} else {
std::swap(cmd, it->second);
map->erase(it);
res = true;
}
}
if (cmd) {
// Stop the thread
cmd->stop();
}
if (res) {
w_state_save();
}
auto resp = make_response();
resp.set({{"deleted", json_boolean(res)}, {"trigger", json_ref(jname)}});
send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("trigger-del", cmd_trigger_delete, CMD_DAEMON, w_cmd_realpath_root)
/* trigger-list /root
* Displays a list of registered triggers for a given root
*/
static void cmd_trigger_list(
struct watchman_client* client,
const json_ref& args) {
auto root = resolveRoot(client, args);
auto resp = make_response();
auto arr = root->triggerListToJson();
resp.set("triggers", std::move(arr));
send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("trigger-list", cmd_trigger_list, CMD_DAEMON, w_cmd_realpath_root)
static json_ref build_legacy_trigger(
const std::shared_ptr<watchman_root>& root,
struct watchman_client* client,
const json_ref& args) {
uint32_t next_arg = 0;
uint32_t i;
size_t n;
auto trig = json_object(
{{"name", args.at(2)},
{"append_files", json_true()},
{"stdin",
json_array(
{typed_string_to_json("name"),
typed_string_to_json("exists"),
typed_string_to_json("new"),
typed_string_to_json("size"),
typed_string_to_json("mode")})}});
json_ref expr;
auto query = w_query_parse_legacy(root, args, 3, &next_arg, nullptr, &expr);
query->request_id = w_string::build("trigger ", json_to_w_string(args.at(2)));
json_object_set(trig, "expression", expr.get_default("expression"));
if (next_arg >= args.array().size()) {
send_error_response(client, "no command was specified");
return nullptr;
}
n = json_array_size(args) - next_arg;
auto command = json_array_of_size(n);
for (i = 0; i < n; i++) {
auto ele = args.at(i + next_arg);
if (!ele.isString()) {
send_error_response(client, "expected argument %d to be a string", i);
return nullptr;
}
json_array_append(command, ele);
}
json_object_set_new(trig, "command", std::move(command));
return trig;
}
/* trigger /root triggername [watch patterns] -- cmd to run
* Sets up a trigger so that we can execute a command when a change
* is detected */
static void cmd_trigger(struct watchman_client* client, const json_ref& args) {
bool need_save = true;
std::unique_ptr<TriggerCommand> cmd;
json_ref trig;
json_ref resp;
auto root = resolveRoot(client, args);
if (json_array_size(args) < 3) {
send_error_response(client, "not enough arguments");
return;
}
trig = args.at(2);
if (trig.isString()) {
trig = build_legacy_trigger(root, client, args);
if (!trig) {
return;
}
}
cmd = std::make_unique<TriggerCommand>(root, trig);
resp = make_response();
resp.set("triggerid", w_string_to_json(cmd->triggername));
{
auto wlock = root->triggers.wlock();
auto& map = *wlock;
auto& old = map[cmd->triggername];
if (old && json_equal(cmd->definition, old->definition)) {
// Same definition: we don't and shouldn't touch things, so that we
// preserve the associated trigger clock and don't cause the trigger
// to re-run immediately
resp.set(
"disposition",
typed_string_to_json("already_defined", W_STRING_UNICODE));
need_save = false;
} else {
resp.set(
"disposition",
typed_string_to_json(old ? "replaced" : "created", W_STRING_UNICODE));
if (old) {
// If we're replacing an old definition, be sure to stop the old
// one before we destroy it, and before we start the new one.
old->stop();
}
// Start the new trigger thread
cmd->start(root);
old = std::move(cmd);
need_save = true;
}
}
if (need_save) {
w_state_save();
}
send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("trigger", cmd_trigger, CMD_DAEMON, w_cmd_realpath_root)
/* vim:ts=2:sw=2:et:
*/
<commit_msg>Remove dead includes in watchman/cmds<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "watchman/CommandRegistry.h"
#include "watchman/Logging.h"
#include "watchman/TriggerCommand.h"
#include "watchman/query/Query.h"
#include "watchman/state.h"
#include "watchman/watchman_cmd.h"
#include "watchman/watchman_root.h"
#include "watchman/watchman_stream.h"
#include <memory>
using namespace watchman;
/* trigger-del /root triggername
* Delete a trigger from a root
*/
static void cmd_trigger_delete(
struct watchman_client* client,
const json_ref& args) {
w_string tname;
bool res;
auto root = resolveRoot(client, args);
if (json_array_size(args) != 3) {
send_error_response(client, "wrong number of arguments");
return;
}
auto jname = args.at(2);
if (!jname.isString()) {
send_error_response(client, "expected 2nd parameter to be trigger name");
return;
}
tname = json_to_w_string(jname);
std::unique_ptr<TriggerCommand> cmd;
{
auto map = root->triggers.wlock();
auto it = map->find(tname);
if (it == map->end()) {
res = false;
} else {
std::swap(cmd, it->second);
map->erase(it);
res = true;
}
}
if (cmd) {
// Stop the thread
cmd->stop();
}
if (res) {
w_state_save();
}
auto resp = make_response();
resp.set({{"deleted", json_boolean(res)}, {"trigger", json_ref(jname)}});
send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("trigger-del", cmd_trigger_delete, CMD_DAEMON, w_cmd_realpath_root)
/* trigger-list /root
* Displays a list of registered triggers for a given root
*/
static void cmd_trigger_list(
struct watchman_client* client,
const json_ref& args) {
auto root = resolveRoot(client, args);
auto resp = make_response();
auto arr = root->triggerListToJson();
resp.set("triggers", std::move(arr));
send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("trigger-list", cmd_trigger_list, CMD_DAEMON, w_cmd_realpath_root)
static json_ref build_legacy_trigger(
const std::shared_ptr<watchman_root>& root,
struct watchman_client* client,
const json_ref& args) {
uint32_t next_arg = 0;
uint32_t i;
size_t n;
auto trig = json_object(
{{"name", args.at(2)},
{"append_files", json_true()},
{"stdin",
json_array(
{typed_string_to_json("name"),
typed_string_to_json("exists"),
typed_string_to_json("new"),
typed_string_to_json("size"),
typed_string_to_json("mode")})}});
json_ref expr;
auto query = w_query_parse_legacy(root, args, 3, &next_arg, nullptr, &expr);
query->request_id = w_string::build("trigger ", json_to_w_string(args.at(2)));
json_object_set(trig, "expression", expr.get_default("expression"));
if (next_arg >= args.array().size()) {
send_error_response(client, "no command was specified");
return nullptr;
}
n = json_array_size(args) - next_arg;
auto command = json_array_of_size(n);
for (i = 0; i < n; i++) {
auto ele = args.at(i + next_arg);
if (!ele.isString()) {
send_error_response(client, "expected argument %d to be a string", i);
return nullptr;
}
json_array_append(command, ele);
}
json_object_set_new(trig, "command", std::move(command));
return trig;
}
/* trigger /root triggername [watch patterns] -- cmd to run
* Sets up a trigger so that we can execute a command when a change
* is detected */
static void cmd_trigger(struct watchman_client* client, const json_ref& args) {
bool need_save = true;
std::unique_ptr<TriggerCommand> cmd;
json_ref trig;
json_ref resp;
auto root = resolveRoot(client, args);
if (json_array_size(args) < 3) {
send_error_response(client, "not enough arguments");
return;
}
trig = args.at(2);
if (trig.isString()) {
trig = build_legacy_trigger(root, client, args);
if (!trig) {
return;
}
}
cmd = std::make_unique<TriggerCommand>(root, trig);
resp = make_response();
resp.set("triggerid", w_string_to_json(cmd->triggername));
{
auto wlock = root->triggers.wlock();
auto& map = *wlock;
auto& old = map[cmd->triggername];
if (old && json_equal(cmd->definition, old->definition)) {
// Same definition: we don't and shouldn't touch things, so that we
// preserve the associated trigger clock and don't cause the trigger
// to re-run immediately
resp.set(
"disposition",
typed_string_to_json("already_defined", W_STRING_UNICODE));
need_save = false;
} else {
resp.set(
"disposition",
typed_string_to_json(old ? "replaced" : "created", W_STRING_UNICODE));
if (old) {
// If we're replacing an old definition, be sure to stop the old
// one before we destroy it, and before we start the new one.
old->stop();
}
// Start the new trigger thread
cmd->start(root);
old = std::move(cmd);
need_save = true;
}
}
if (need_save) {
w_state_save();
}
send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("trigger", cmd_trigger, CMD_DAEMON, w_cmd_realpath_root)
/* vim:ts=2:sw=2:et:
*/
<|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.
*/
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <map>
#include <stout/foreach.hpp>
#include <stout/os.hpp>
#include <stout/protobuf.hpp>
#include <stout/unreachable.hpp>
#include <stout/os/execenv.hpp>
#include "mesos/mesos.hpp"
#include "slave/containerizer/mesos/launch.hpp"
using std::cerr;
using std::endl;
using std::map;
using std::string;
namespace mesos {
namespace internal {
namespace slave {
const string MesosContainerizerLaunch::NAME = "launch";
MesosContainerizerLaunch::Flags::Flags()
{
add(&command,
"command",
"The command to execute.");
add(&directory,
"directory",
"The directory to chdir to.");
add(&user,
"user",
"The user to change to.");
add(&pipe_read,
"pipe_read",
"The read end of the control pipe.");
add(&pipe_write,
"pipe_write",
"The write end of the control pipe.");
add(&commands,
"commands",
"The additional preparation commands to execute before\n"
"executing the command.");
}
int MesosContainerizerLaunch::execute()
{
// Check command line flags.
if (flags.command.isNone()) {
cerr << "Flag --command is not specified" << endl;
return 1;
}
if (flags.directory.isNone()) {
cerr << "Flag --directory is not specified" << endl;
return 1;
}
if (flags.pipe_read.isNone()) {
cerr << "Flag --pipe_read is not specified" << endl;
return 1;
}
if (flags.pipe_write.isNone()) {
cerr << "Flag --pipe_write is not specified" << endl;
return 1;
}
// Parse the command.
Try<CommandInfo> command =
::protobuf::parse<CommandInfo>(flags.command.get());
if (command.isError()) {
cerr << "Failed to parse the command: " << command.error() << endl;
return 1;
}
// Validate the command.
if (command.get().shell()) {
if (!command.get().has_value()) {
cerr << "Shell command is not specified" << endl;
return 1;
}
} else {
if (!command.get().has_value()) {
cerr << "Executable path is not specified" << endl;
return 1;
}
}
Try<Nothing> close = os::close(flags.pipe_write.get());
if (close.isError()) {
cerr << "Failed to close pipe[1]: " << close.error() << endl;
return 1;
}
// Do a blocking read on the pipe until the parent signals us to continue.
char dummy;
ssize_t length;
while ((length = ::read(
flags.pipe_read.get(),
&dummy,
sizeof(dummy))) == -1 &&
errno == EINTR);
if (length != sizeof(dummy)) {
// There's a reasonable probability this will occur during slave
// restarts across a large/busy cluster.
cerr << "Failed to synchronize with slave (it's probably exited)" << endl;
return 1;
}
close = os::close(flags.pipe_read.get());
if (close.isError()) {
cerr << "Failed to close pipe[0]: " << close.error() << endl;
return 1;
}
// Run additional preparation commands. These are run as the same
// user and with the environment as the slave.
if (flags.commands.isSome()) {
// TODO(jieyu): Use JSON::Array if we have generic parse support.
JSON::Object object = flags.commands.get();
if (object.values.count("commands") == 0) {
cerr << "Invalid JSON format for flag --commands" << endl;
return 1;
}
if (!object.values["commands"].is<JSON::Array>()) {
cerr << "Invalid JSON format for flag --commands" << endl;
return 1;
}
JSON::Array array = object.values["commands"].as<JSON::Array>();
foreach (const JSON::Value& value, array.values) {
if (!value.is<JSON::Object>()) {
cerr << "Invalid JSON format for flag --commands" << endl;
return 1;
}
Try<CommandInfo> parse = ::protobuf::parse<CommandInfo>(value);
if (parse.isError()) {
cerr << "Failed to parse a preparation command: "
<< parse.error() << endl;
return 1;
}
// TODO(jieyu): Currently, we only accept shell commands for the
// preparation commands.
if (!parse.get().shell()) {
cerr << "Preparation commands need to be shell commands" << endl;
return 1;
}
if (!parse.get().has_value()) {
cerr << "The 'value' of a preparation command is not specified" << endl;
return 1;
}
// Block until the command completes.
int status = os::system(parse.get().value());
if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
cerr << "Failed to execute a preparation shell command" << endl;
return 1;
}
}
}
// Enter working directory.
Try<Nothing> chdir = os::chdir(flags.directory.get());
if (chdir.isError()) {
cerr << "Failed to chdir into work directory '"
<< flags.directory.get() << "': " << chdir.error() << endl;
return 1;
}
// Change user if provided. Note that we do that after executing the
// preparation commands so that those commands will be run with the
// same privilege as the mesos-slave.
if (flags.user.isSome()) {
Try<Nothing> su = os::su(flags.user.get());
if (su.isError()) {
cerr << "Failed to change user to '" << flags.user.get() << "': "
<< su.error() << endl;
return 1;
}
}
// Relay the environment variables.
// TODO(jieyu): Consider using a clean environment.
map<string, string> env;
os::ExecEnv envp(env);
if (command.get().shell()) {
// Execute the command using shell.
execle(
"/bin/sh",
"sh",
"-c",
command.get().value().c_str(),
(char*) NULL,
envp());
} else {
// Use os::execvpe to launch the command.
char** argv = new char*[command.get().arguments().size() + 1];
for (int i = 0; i < command.get().arguments().size(); i++) {
argv[i] = strdup(command.get().arguments(i).c_str());
}
argv[command.get().arguments().size()] = NULL;
os::execvpe(command.get().value().c_str(), argv, envp());
}
// If we get here, the execle call failed.
cerr << "Failed to execute command" << endl;
UNREACHABLE();
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Removed unnecessary use of os::ExecEnv.<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.
*/
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <stout/foreach.hpp>
#include <stout/os.hpp>
#include <stout/protobuf.hpp>
#include <stout/unreachable.hpp>
#include "mesos/mesos.hpp"
#include "slave/containerizer/mesos/launch.hpp"
using std::cerr;
using std::endl;
using std::string;
namespace mesos {
namespace internal {
namespace slave {
const string MesosContainerizerLaunch::NAME = "launch";
MesosContainerizerLaunch::Flags::Flags()
{
add(&command,
"command",
"The command to execute.");
add(&directory,
"directory",
"The directory to chdir to.");
add(&user,
"user",
"The user to change to.");
add(&pipe_read,
"pipe_read",
"The read end of the control pipe.");
add(&pipe_write,
"pipe_write",
"The write end of the control pipe.");
add(&commands,
"commands",
"The additional preparation commands to execute before\n"
"executing the command.");
}
int MesosContainerizerLaunch::execute()
{
// Check command line flags.
if (flags.command.isNone()) {
cerr << "Flag --command is not specified" << endl;
return 1;
}
if (flags.directory.isNone()) {
cerr << "Flag --directory is not specified" << endl;
return 1;
}
if (flags.pipe_read.isNone()) {
cerr << "Flag --pipe_read is not specified" << endl;
return 1;
}
if (flags.pipe_write.isNone()) {
cerr << "Flag --pipe_write is not specified" << endl;
return 1;
}
// Parse the command.
Try<CommandInfo> command =
::protobuf::parse<CommandInfo>(flags.command.get());
if (command.isError()) {
cerr << "Failed to parse the command: " << command.error() << endl;
return 1;
}
// Validate the command.
if (command.get().shell()) {
if (!command.get().has_value()) {
cerr << "Shell command is not specified" << endl;
return 1;
}
} else {
if (!command.get().has_value()) {
cerr << "Executable path is not specified" << endl;
return 1;
}
}
Try<Nothing> close = os::close(flags.pipe_write.get());
if (close.isError()) {
cerr << "Failed to close pipe[1]: " << close.error() << endl;
return 1;
}
// Do a blocking read on the pipe until the parent signals us to continue.
char dummy;
ssize_t length;
while ((length = ::read(
flags.pipe_read.get(),
&dummy,
sizeof(dummy))) == -1 &&
errno == EINTR);
if (length != sizeof(dummy)) {
// There's a reasonable probability this will occur during slave
// restarts across a large/busy cluster.
cerr << "Failed to synchronize with slave (it's probably exited)" << endl;
return 1;
}
close = os::close(flags.pipe_read.get());
if (close.isError()) {
cerr << "Failed to close pipe[0]: " << close.error() << endl;
return 1;
}
// Run additional preparation commands. These are run as the same
// user and with the environment as the slave.
if (flags.commands.isSome()) {
// TODO(jieyu): Use JSON::Array if we have generic parse support.
JSON::Object object = flags.commands.get();
if (object.values.count("commands") == 0) {
cerr << "Invalid JSON format for flag --commands" << endl;
return 1;
}
if (!object.values["commands"].is<JSON::Array>()) {
cerr << "Invalid JSON format for flag --commands" << endl;
return 1;
}
JSON::Array array = object.values["commands"].as<JSON::Array>();
foreach (const JSON::Value& value, array.values) {
if (!value.is<JSON::Object>()) {
cerr << "Invalid JSON format for flag --commands" << endl;
return 1;
}
Try<CommandInfo> parse = ::protobuf::parse<CommandInfo>(value);
if (parse.isError()) {
cerr << "Failed to parse a preparation command: "
<< parse.error() << endl;
return 1;
}
// TODO(jieyu): Currently, we only accept shell commands for the
// preparation commands.
if (!parse.get().shell()) {
cerr << "Preparation commands need to be shell commands" << endl;
return 1;
}
if (!parse.get().has_value()) {
cerr << "The 'value' of a preparation command is not specified" << endl;
return 1;
}
// Block until the command completes.
int status = os::system(parse.get().value());
if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
cerr << "Failed to execute a preparation shell command" << endl;
return 1;
}
}
}
// Enter working directory.
Try<Nothing> chdir = os::chdir(flags.directory.get());
if (chdir.isError()) {
cerr << "Failed to chdir into work directory '"
<< flags.directory.get() << "': " << chdir.error() << endl;
return 1;
}
// Change user if provided. Note that we do that after executing the
// preparation commands so that those commands will be run with the
// same privilege as the mesos-slave.
if (flags.user.isSome()) {
Try<Nothing> su = os::su(flags.user.get());
if (su.isError()) {
cerr << "Failed to change user to '" << flags.user.get() << "': "
<< su.error() << endl;
return 1;
}
}
// TODO(jieyu): Consider using a clean environment.
if (command.get().shell()) {
// Execute the command using shell.
execl("/bin/sh", "sh", "-c", command.get().value().c_str(), (char*) NULL);
} else {
// Use os::execvpe to launch the command.
char** argv = new char*[command.get().arguments().size() + 1];
for (int i = 0; i < command.get().arguments().size(); i++) {
argv[i] = strdup(command.get().arguments(i).c_str());
}
argv[command.get().arguments().size()] = NULL;
execvp(command.get().value().c_str(), argv);
}
// If we get here, the execle call failed.
cerr << "Failed to execute command" << endl;
UNREACHABLE();
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|>
|
<commit_before>
// Copyright (c) 2012, 2013 Pierre MOULON.
// 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 <cstdlib>
#include "openMVG/sfm/sfm.hpp"
#include "openMVG/system/timer.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::sfm;
bool computeIndexFromImageName(
const SfM_Data & sfm_data,
const std::string& initialName,
IndexT& initialIndex)
{
initialIndex = UndefinedIndexT;
bool isName = (initialName == stlplus::filename_part(initialName));
/// List views filenames and find the one that correspond to the user ones:
for(Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
std::string filename;
if(isName)
{
filename = stlplus::filename_part(v->s_Img_path);
}
else
{
if(stlplus::is_full_path(v->s_Img_path))
{
filename = v->s_Img_path;
}
else
{
filename = sfm_data.s_root_path + v->s_Img_path;
}
}
if (filename == initialName)
{
if(initialIndex == UndefinedIndexT)
{
initialIndex = v->id_view;
}
else
{
std::cout<<"Error: Two pictures named :" << initialName << " !" << std::endl;
}
}
}
return initialIndex != UndefinedIndexT;
}
int main(int argc, char **argv)
{
using namespace std;
std::cout << "Sequential/Incremental reconstruction" << std::endl
<< " Perform incremental SfM (Initial Pair Essential + Resection)." << std::endl
<< std::endl;
CmdLine cmd;
std::string sSfM_Data_Filename;
std::string sMatchesDir;
std::string sOutDir = "";
std::string sOutSfMDataFilepath = "";
std::string sOutInterFileExtension = ".ply";
std::pair<std::string,std::string> initialPairString("","");
bool bRefineIntrinsics = true;
int minInputTrackLength = 2;
int i_User_camera_model = PINHOLE_CAMERA_RADIAL3;
bool allowUserInteraction = true;
cmd.add( make_option('i', sSfM_Data_Filename, "input_file") );
cmd.add( make_option('m', sMatchesDir, "matchdir") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('s', sOutSfMDataFilepath, "out_sfmdata_file") );
cmd.add( make_option('e', sOutInterFileExtension, "inter_file_extension") );
cmd.add( make_option('a', initialPairString.first, "initialPairA") );
cmd.add( make_option('b', initialPairString.second, "initialPairB") );
cmd.add( make_option('c', i_User_camera_model, "camera_model") );
cmd.add( make_option('f', bRefineIntrinsics, "refineIntrinsics") );
cmd.add( make_option('t', minInputTrackLength, "minInputTrackLength") );
cmd.add( make_option('u', allowUserInteraction, "allowUserInteraction") );
try {
if (argc == 1) throw std::string("Invalid parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--input_file] path to a SfM_Data scene\n"
<< "[-m|--matchdir] path to the matches that corresponds to the provided SfM_Data scene\n"
<< "[-o|--outdir] path where the output data will be stored\n"
<< "[-s|--out_sfmdata_file] path of the output sfmdata file (default: $outdir/sfm_data.json)\n"
<< "[-e|--inter_file_extension] extension of the intermediate file export (default: .ply)\n"
<< "[-a|--initialPairA] filename of the first image (without path)\n"
<< "[-b|--initialPairB] filename of the second image (without path)\n"
<< "[-c|--camera_model] Camera model type for view with unknown intrinsic:\n"
<< "\t 1: Pinhole \n"
<< "\t 2: Pinhole radial 1\n"
<< "\t 3: Pinhole radial 3 (default)\n"
<< "[-f|--refineIntrinsics] \n"
<< "\t 0-> intrinsic parameters are kept as constant\n"
<< "\t 1-> refine intrinsic parameters (default). \n"
<< "[-t|--minInputTrackLength N] minimum track length in input of SfM (default: 2)\n"
<< "[-p|--matchFilePerImage] \n"
<< "\t To use one match file per image instead of a global file.\n"
<< "[-u|--allowUserInteraction] Enable/Disable user interactions. (default: true)\n"
<< "\t If the process is done on renderfarm, it doesn't make sense to wait for user inputs.\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if(sOutSfMDataFilepath.empty())
sOutSfMDataFilepath = stlplus::create_filespec(sOutDir, "sfm_data", "json");
// Load input SfM_Data scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) {
std::cerr << std::endl
<< "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Init the regions_type from the image describer file (used for image regions extraction)
using namespace openMVG::features;
const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json");
std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer);
if (!regions_type)
{
std::cerr << "Invalid: "
<< sImage_describer << " regions type file." << std::endl;
return EXIT_FAILURE;
}
// Features reading
std::shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>();
if (!feats_provider->load(sfm_data, sMatchesDir, regions_type)) {
std::cerr << std::endl
<< "Invalid features." << std::endl;
return EXIT_FAILURE;
}
// Matches reading
std::shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>();
if(!matches_provider->load(sfm_data, sMatchesDir, "f"))
{
std::cerr << std::endl << "Unable to load matches file from: " << sMatchesDir << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty())
{
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
stlplus::folder_create(sOutDir);
//---------------------------------------
// Sequential reconstruction process
//---------------------------------------
openMVG::system::Timer timer;
SequentialSfMReconstructionEngine sfmEngine(
sfm_data,
sOutDir,
stlplus::create_filespec(sOutDir, "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(!bRefineIntrinsics);
sfmEngine.SetUnknownCameraType(EINTRINSIC(i_User_camera_model));
sfmEngine.setMinInputTrackLength(minInputTrackLength);
sfmEngine.setSfmdataInterFileExtension(sOutInterFileExtension);
sfmEngine.setAllowUserInteraction(allowUserInteraction);
if (initialPairString.first == initialPairString.second)
{
std::cerr << "\nInvalid image names. You cannot use the same image to initialize a pair." << std::endl;
return false;
}
// Handle Initial pair parameter
if (!initialPairString.first.empty() && !initialPairString.second.empty())
{
Pair initialPairIndex;
if(!computeIndexFromImageName(sfm_data, initialPairString.first, initialPairIndex.first)
|| !computeIndexFromImageName(sfm_data, initialPairString.second, initialPairIndex.second))
{
std::cerr << "Could not find the initial pairs <" << initialPairString.first
<< ", " << initialPairString.second << ">!\n";
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if (!sfmEngine.Process())
{
return EXIT_FAILURE;
}
// get the color for the 3D points
sfmEngine.Colorize();
std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl;
std::cout << "...Generating SfM_Report.html" << std::endl;
Generate_SfM_Report(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "SfMReconstruction_Report.html"));
//-- Export to disk computed scene (data & visualizable results)
std::cout << "...Export SfM_Data to disk:" << std::endl;
std::cout << " " << sOutSfMDataFilepath << std::endl;
Save(sfmEngine.Get_SfM_Data(), sOutSfMDataFilepath, ESfM_Data(ALL));
Save(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "cloud_and_poses", sOutInterFileExtension), ESfM_Data(VIEWS | EXTRINSICS | INTRINSICS | STRUCTURE));
return EXIT_SUCCESS;
}
<commit_msg>[incremental sfm] fix for empty initial pair<commit_after>
// Copyright (c) 2012, 2013 Pierre MOULON.
// 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 <cstdlib>
#include "openMVG/sfm/sfm.hpp"
#include "openMVG/system/timer.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::sfm;
bool computeIndexFromImageName(
const SfM_Data & sfm_data,
const std::string& initialName,
IndexT& initialIndex)
{
initialIndex = UndefinedIndexT;
bool isName = (initialName == stlplus::filename_part(initialName));
/// List views filenames and find the one that correspond to the user ones:
for(Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
std::string filename;
if(isName)
{
filename = stlplus::filename_part(v->s_Img_path);
}
else
{
if(stlplus::is_full_path(v->s_Img_path))
{
filename = v->s_Img_path;
}
else
{
filename = sfm_data.s_root_path + v->s_Img_path;
}
}
if (filename == initialName)
{
if(initialIndex == UndefinedIndexT)
{
initialIndex = v->id_view;
}
else
{
std::cout<<"Error: Two pictures named :" << initialName << " !" << std::endl;
}
}
}
return initialIndex != UndefinedIndexT;
}
int main(int argc, char **argv)
{
using namespace std;
std::cout << "Sequential/Incremental reconstruction" << std::endl
<< " Perform incremental SfM (Initial Pair Essential + Resection)." << std::endl
<< std::endl;
CmdLine cmd;
std::string sSfM_Data_Filename;
std::string sMatchesDir;
std::string sOutDir = "";
std::string sOutSfMDataFilepath = "";
std::string sOutInterFileExtension = ".ply";
std::pair<std::string,std::string> initialPairString("","");
bool bRefineIntrinsics = true;
int minInputTrackLength = 2;
int i_User_camera_model = PINHOLE_CAMERA_RADIAL3;
bool allowUserInteraction = true;
cmd.add( make_option('i', sSfM_Data_Filename, "input_file") );
cmd.add( make_option('m', sMatchesDir, "matchdir") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('s', sOutSfMDataFilepath, "out_sfmdata_file") );
cmd.add( make_option('e', sOutInterFileExtension, "inter_file_extension") );
cmd.add( make_option('a', initialPairString.first, "initialPairA") );
cmd.add( make_option('b', initialPairString.second, "initialPairB") );
cmd.add( make_option('c', i_User_camera_model, "camera_model") );
cmd.add( make_option('f', bRefineIntrinsics, "refineIntrinsics") );
cmd.add( make_option('t', minInputTrackLength, "minInputTrackLength") );
cmd.add( make_option('u', allowUserInteraction, "allowUserInteraction") );
try {
if (argc == 1) throw std::string("Invalid parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--input_file] path to a SfM_Data scene\n"
<< "[-m|--matchdir] path to the matches that corresponds to the provided SfM_Data scene\n"
<< "[-o|--outdir] path where the output data will be stored\n"
<< "[-s|--out_sfmdata_file] path of the output sfmdata file (default: $outdir/sfm_data.json)\n"
<< "[-e|--inter_file_extension] extension of the intermediate file export (default: .ply)\n"
<< "[-a|--initialPairA] filename of the first image (without path)\n"
<< "[-b|--initialPairB] filename of the second image (without path)\n"
<< "[-c|--camera_model] Camera model type for view with unknown intrinsic:\n"
<< "\t 1: Pinhole \n"
<< "\t 2: Pinhole radial 1\n"
<< "\t 3: Pinhole radial 3 (default)\n"
<< "[-f|--refineIntrinsics] \n"
<< "\t 0-> intrinsic parameters are kept as constant\n"
<< "\t 1-> refine intrinsic parameters (default). \n"
<< "[-t|--minInputTrackLength N] minimum track length in input of SfM (default: 2)\n"
<< "[-p|--matchFilePerImage] \n"
<< "\t To use one match file per image instead of a global file.\n"
<< "[-u|--allowUserInteraction] Enable/Disable user interactions. (default: true)\n"
<< "\t If the process is done on renderfarm, it doesn't make sense to wait for user inputs.\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if(sOutSfMDataFilepath.empty())
sOutSfMDataFilepath = stlplus::create_filespec(sOutDir, "sfm_data", "json");
// Load input SfM_Data scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) {
std::cerr << std::endl
<< "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Init the regions_type from the image describer file (used for image regions extraction)
using namespace openMVG::features;
const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json");
std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer);
if (!regions_type)
{
std::cerr << "Invalid: "
<< sImage_describer << " regions type file." << std::endl;
return EXIT_FAILURE;
}
// Features reading
std::shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>();
if (!feats_provider->load(sfm_data, sMatchesDir, regions_type)) {
std::cerr << std::endl
<< "Invalid features." << std::endl;
return EXIT_FAILURE;
}
// Matches reading
std::shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>();
if(!matches_provider->load(sfm_data, sMatchesDir, "f"))
{
std::cerr << std::endl << "Unable to load matches file from: " << sMatchesDir << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty())
{
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
stlplus::folder_create(sOutDir);
//---------------------------------------
// Sequential reconstruction process
//---------------------------------------
openMVG::system::Timer timer;
SequentialSfMReconstructionEngine sfmEngine(
sfm_data,
sOutDir,
stlplus::create_filespec(sOutDir, "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(!bRefineIntrinsics);
sfmEngine.SetUnknownCameraType(EINTRINSIC(i_User_camera_model));
sfmEngine.setMinInputTrackLength(minInputTrackLength);
sfmEngine.setSfmdataInterFileExtension(sOutInterFileExtension);
sfmEngine.setAllowUserInteraction(allowUserInteraction);
// Handle Initial pair parameter
if (!initialPairString.first.empty() && !initialPairString.second.empty())
{
if (initialPairString.first == initialPairString.second)
{
std::cerr << "\nInvalid image names. You cannot use the same image to initialize a pair." << std::endl;
return EXIT_FAILURE;
}
Pair initialPairIndex;
if(!computeIndexFromImageName(sfm_data, initialPairString.first, initialPairIndex.first)
|| !computeIndexFromImageName(sfm_data, initialPairString.second, initialPairIndex.second))
{
std::cerr << "Could not find the initial pairs <" << initialPairString.first
<< ", " << initialPairString.second << ">!\n";
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if (!sfmEngine.Process())
{
return EXIT_FAILURE;
}
// get the color for the 3D points
sfmEngine.Colorize();
std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl;
std::cout << "...Generating SfM_Report.html" << std::endl;
Generate_SfM_Report(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "SfMReconstruction_Report.html"));
//-- Export to disk computed scene (data & visualizable results)
std::cout << "...Export SfM_Data to disk:" << std::endl;
std::cout << " " << sOutSfMDataFilepath << std::endl;
Save(sfmEngine.Get_SfM_Data(), sOutSfMDataFilepath, ESfM_Data(ALL));
Save(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "cloud_and_poses", sOutInterFileExtension), ESfM_Data(VIEWS | EXTRINSICS | INTRINSICS | STRUCTURE));
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <MainApplication/Viewer/TrackballCamera.hpp>
#include <iostream>
#include <QMessageBox>
#include <Core/Math/Math.hpp>
#include <Core/Event/MouseEvent.hpp>
#include <Core/Event/KeyEvent.hpp>
#include <Engine/Renderer/Camera/Camera.hpp>
namespace Ra
{
using Core::Math::Pi;
Gui::TrackballCamera::TrackballCamera( uint width, uint height )
: CameraInterface( width, height )
, m_trackballCenter( 0, 0, 0 )
, m_quickCameraModifier( 1.0 )
, m_cameraRotateMode( false )
, m_cameraPanMode( false )
, m_cameraZoomMode( false )
, m_wheelSpeedModifier(0.01)
{
resetCamera();
}
Gui::TrackballCamera::~TrackballCamera()
{
}
void Gui::TrackballCamera::resetCamera()
{
m_camera->setFrame( Core::Transform::Identity() );
m_trackballCenter = Core::Vector3::Zero();
m_camera->setPosition( Core::Vector3( 0, 0, 1 ) );
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
bool Gui::TrackballCamera::handleMousePressEvent( QMouseEvent* event )
{
// Whole manipulation is done with middle button and modifiers
if ( event->button() != Qt::MiddleButton )
{
return false;
}
bool handled = false;
m_lastMouseX = event->pos().x();
m_lastMouseY = event->pos().y();
if ( event->modifiers().testFlag( Qt::NoModifier ) )
{
m_cameraRotateMode = true;
handled = true;
}
if ( event->modifiers().testFlag( Qt::ShiftModifier ) )
{
m_cameraPanMode = true;
handled = true;
}
if ( event->modifiers().testFlag( Qt::ControlModifier ) )
{
m_cameraZoomMode = true;
handled = true;
}
return handled;
}
bool Gui::TrackballCamera::handleMouseMoveEvent( QMouseEvent* event )
{
Scalar dx = ( event->pos().x() - m_lastMouseX ) / m_camera->getWidth();
Scalar dy = ( event->pos().y() - m_lastMouseY ) / m_camera->getHeight();
if ( event->modifiers().testFlag( Qt::AltModifier ) )
{
m_quickCameraModifier = 10.0;
}
else
{
m_quickCameraModifier = 1.0;
}
if ( m_cameraRotateMode )
{
handleCameraRotate( dx, dy );
}
if ( m_cameraPanMode )
{
handleCameraPan( dx, dy );
}
if ( m_cameraZoomMode )
{
handleCameraZoom( dx, dy );
}
m_lastMouseX = event->pos().x();
m_lastMouseY = event->pos().y();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
return true;
}
bool Gui::TrackballCamera::handleMouseReleaseEvent( QMouseEvent* event )
{
m_cameraRotateMode = false;
m_cameraPanMode = false;
m_cameraZoomMode = false;
m_quickCameraModifier = 1.0;
return true;
}
bool Gui::TrackballCamera::handleWheelEvent(QWheelEvent* event)
{
handleCameraZoom((event->angleDelta().y() + event->angleDelta().x() * 0.1) * m_wheelSpeedModifier);
emit cameraPositionChanged( m_camera->getPosition() );
return true;
}
bool Gui::TrackballCamera::handleKeyPressEvent( QKeyEvent* )
{
// No keyboard manipulation
return false;
}
bool Gui::TrackballCamera::handleKeyReleaseEvent( QKeyEvent* )
{
return false;
}
void Gui::TrackballCamera::setCameraPosition( const Core::Vector3& position )
{
if ( position == m_trackballCenter )
{
QMessageBox::warning( nullptr,
"Error", "Position cannot be set to target point" );
return;
}
m_camera->setPosition( position );
m_camera->setDirection( m_trackballCenter - position );
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
void Gui::TrackballCamera::setCameraTarget( const Core::Vector3& target )
{
if ( m_camera->getPosition() == m_trackballCenter )
{
QMessageBox::warning( nullptr,
"Error", "Target cannot be set to current camera position" );
return;
}
m_trackballCenter = target;
m_camera->setDirection( target - m_camera->getPosition() );
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
void Gui::TrackballCamera::moveCameraToFitAabb( const Core::Aabb& aabb )
{
CameraInterface::moveCameraToFitAabb( aabb );
m_trackballCenter = aabb.center();
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
void Gui::TrackballCamera::handleCameraRotate( Scalar dx, Scalar dy )
{
Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier;
Scalar y = -dy * m_cameraSensitivity * m_quickCameraModifier;
Scalar phi = m_phi + x; // Keep phi between -pi and pi
Scalar theta = std::min( std::max( m_theta + y, Scalar( 0.0 ) ), Pi );
Scalar dphi = phi - m_phi;
Scalar dtheta = theta - m_theta;
const Core::Vector3 C = m_trackballCenter;
const Core::Vector3 P0 = m_camera->getPosition();
const Scalar r = ( C - P0 ).norm();
// Compute new camera position, on the sphere of radius r centered on C
Scalar px = C.x() + r * std::cos( phi ) * std::sin( theta );
Scalar py = C.y() + r * std::cos( theta );
Scalar pz = C.z() + r * std::sin( phi ) * std::sin( theta );
// Compute the translation from old pos to new pos
Core::Vector3 P( px, py, pz );
Core::Vector3 t( P - P0 );
// Translate the camera given this translation
Core::Transform T( Core::Transform::Identity() );
T.translation() = t;
// Rotate the camera so that it points to the center
Core::Transform R1( Core::Transform::Identity() );
Core::Transform R2( Core::Transform::Identity() );
Core::Vector3 U = Core::Vector3( 0, 1, 0 );
Core::Vector3 R = -m_camera->getRightVector().normalized();
R1 = Core::AngleAxis( -dphi, U );
R2 = Core::AngleAxis( -dtheta, R );
m_camera->applyTransform( T * R1 * R2 );
m_phi = phi;
m_theta = theta;
}
void Gui::TrackballCamera::handleCameraPan( Scalar dx, Scalar dy )
{
Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier;
Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier;
// Move camera and trackball center, keep the distance to the center
Core::Vector3 R = -m_camera->getRightVector();
Core::Vector3 U = m_camera->getUpVector();
Core::Transform T( Core::Transform::Identity() );
Core::Vector3 t = x * R + y * U;
T.translate( t );
m_camera->applyTransform( T );
m_trackballCenter += t;
}
void Gui::TrackballCamera::handleCameraZoom( Scalar dx, Scalar dy )
{
handleCameraZoom(dy);
}
void Gui::TrackballCamera::handleCameraZoom( Scalar z )
{
Scalar y = z * m_cameraSensitivity * m_quickCameraModifier;
Core::Vector3 F = m_camera->getDirection();
Core::Transform T( Core::Transform::Identity() );
Core::Vector3 t = y * F;
T.translate( t );
m_camera->applyTransform( T );
}
void Gui::TrackballCamera::updatePhiTheta()
{
const Core::Vector3 P = m_camera->getPosition();
const Core::Vector3 C = m_trackballCenter;
const Core::Vector3 R = P - C;
const Scalar r = R.norm();
m_theta = std::acos( R.y() / r );
m_phi = ( R.z() == 0.f && R.x() == 0.f ) ? 0.f : std::atan2( R.z() , R.x() );
CORE_ASSERT( std::isfinite( m_theta ) && std::isfinite( m_phi ), "Error in trackball camera" );
}
} // namespace Ra
<commit_msg>Fix an initialization order warning<commit_after>#include <MainApplication/Viewer/TrackballCamera.hpp>
#include <iostream>
#include <QMessageBox>
#include <Core/Math/Math.hpp>
#include <Core/Event/MouseEvent.hpp>
#include <Core/Event/KeyEvent.hpp>
#include <Engine/Renderer/Camera/Camera.hpp>
namespace Ra
{
using Core::Math::Pi;
Gui::TrackballCamera::TrackballCamera( uint width, uint height )
: CameraInterface( width, height )
, m_trackballCenter( 0, 0, 0 )
, m_quickCameraModifier( 1.0 )
, m_wheelSpeedModifier(0.01)
, m_cameraRotateMode( false )
, m_cameraPanMode( false )
, m_cameraZoomMode( false )
{
resetCamera();
}
Gui::TrackballCamera::~TrackballCamera()
{
}
void Gui::TrackballCamera::resetCamera()
{
m_camera->setFrame( Core::Transform::Identity() );
m_trackballCenter = Core::Vector3::Zero();
m_camera->setPosition( Core::Vector3( 0, 0, 1 ) );
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
bool Gui::TrackballCamera::handleMousePressEvent( QMouseEvent* event )
{
// Whole manipulation is done with middle button and modifiers
if ( event->button() != Qt::MiddleButton )
{
return false;
}
bool handled = false;
m_lastMouseX = event->pos().x();
m_lastMouseY = event->pos().y();
if ( event->modifiers().testFlag( Qt::NoModifier ) )
{
m_cameraRotateMode = true;
handled = true;
}
if ( event->modifiers().testFlag( Qt::ShiftModifier ) )
{
m_cameraPanMode = true;
handled = true;
}
if ( event->modifiers().testFlag( Qt::ControlModifier ) )
{
m_cameraZoomMode = true;
handled = true;
}
return handled;
}
bool Gui::TrackballCamera::handleMouseMoveEvent( QMouseEvent* event )
{
Scalar dx = ( event->pos().x() - m_lastMouseX ) / m_camera->getWidth();
Scalar dy = ( event->pos().y() - m_lastMouseY ) / m_camera->getHeight();
if ( event->modifiers().testFlag( Qt::AltModifier ) )
{
m_quickCameraModifier = 10.0;
}
else
{
m_quickCameraModifier = 1.0;
}
if ( m_cameraRotateMode )
{
handleCameraRotate( dx, dy );
}
if ( m_cameraPanMode )
{
handleCameraPan( dx, dy );
}
if ( m_cameraZoomMode )
{
handleCameraZoom( dx, dy );
}
m_lastMouseX = event->pos().x();
m_lastMouseY = event->pos().y();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
return true;
}
bool Gui::TrackballCamera::handleMouseReleaseEvent( QMouseEvent* event )
{
m_cameraRotateMode = false;
m_cameraPanMode = false;
m_cameraZoomMode = false;
m_quickCameraModifier = 1.0;
return true;
}
bool Gui::TrackballCamera::handleWheelEvent(QWheelEvent* event)
{
handleCameraZoom((event->angleDelta().y() + event->angleDelta().x() * 0.1) * m_wheelSpeedModifier);
emit cameraPositionChanged( m_camera->getPosition() );
return true;
}
bool Gui::TrackballCamera::handleKeyPressEvent( QKeyEvent* )
{
// No keyboard manipulation
return false;
}
bool Gui::TrackballCamera::handleKeyReleaseEvent( QKeyEvent* )
{
return false;
}
void Gui::TrackballCamera::setCameraPosition( const Core::Vector3& position )
{
if ( position == m_trackballCenter )
{
QMessageBox::warning( nullptr,
"Error", "Position cannot be set to target point" );
return;
}
m_camera->setPosition( position );
m_camera->setDirection( m_trackballCenter - position );
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
void Gui::TrackballCamera::setCameraTarget( const Core::Vector3& target )
{
if ( m_camera->getPosition() == m_trackballCenter )
{
QMessageBox::warning( nullptr,
"Error", "Target cannot be set to current camera position" );
return;
}
m_trackballCenter = target;
m_camera->setDirection( target - m_camera->getPosition() );
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
void Gui::TrackballCamera::moveCameraToFitAabb( const Core::Aabb& aabb )
{
CameraInterface::moveCameraToFitAabb( aabb );
m_trackballCenter = aabb.center();
updatePhiTheta();
emit cameraPositionChanged( m_camera->getPosition() );
emit cameraTargetChanged( m_trackballCenter );
}
void Gui::TrackballCamera::handleCameraRotate( Scalar dx, Scalar dy )
{
Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier;
Scalar y = -dy * m_cameraSensitivity * m_quickCameraModifier;
Scalar phi = m_phi + x; // Keep phi between -pi and pi
Scalar theta = std::min( std::max( m_theta + y, Scalar( 0.0 ) ), Pi );
Scalar dphi = phi - m_phi;
Scalar dtheta = theta - m_theta;
const Core::Vector3 C = m_trackballCenter;
const Core::Vector3 P0 = m_camera->getPosition();
const Scalar r = ( C - P0 ).norm();
// Compute new camera position, on the sphere of radius r centered on C
Scalar px = C.x() + r * std::cos( phi ) * std::sin( theta );
Scalar py = C.y() + r * std::cos( theta );
Scalar pz = C.z() + r * std::sin( phi ) * std::sin( theta );
// Compute the translation from old pos to new pos
Core::Vector3 P( px, py, pz );
Core::Vector3 t( P - P0 );
// Translate the camera given this translation
Core::Transform T( Core::Transform::Identity() );
T.translation() = t;
// Rotate the camera so that it points to the center
Core::Transform R1( Core::Transform::Identity() );
Core::Transform R2( Core::Transform::Identity() );
Core::Vector3 U = Core::Vector3( 0, 1, 0 );
Core::Vector3 R = -m_camera->getRightVector().normalized();
R1 = Core::AngleAxis( -dphi, U );
R2 = Core::AngleAxis( -dtheta, R );
m_camera->applyTransform( T * R1 * R2 );
m_phi = phi;
m_theta = theta;
}
void Gui::TrackballCamera::handleCameraPan( Scalar dx, Scalar dy )
{
Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier;
Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier;
// Move camera and trackball center, keep the distance to the center
Core::Vector3 R = -m_camera->getRightVector();
Core::Vector3 U = m_camera->getUpVector();
Core::Transform T( Core::Transform::Identity() );
Core::Vector3 t = x * R + y * U;
T.translate( t );
m_camera->applyTransform( T );
m_trackballCenter += t;
}
void Gui::TrackballCamera::handleCameraZoom( Scalar dx, Scalar dy )
{
handleCameraZoom(dy);
}
void Gui::TrackballCamera::handleCameraZoom( Scalar z )
{
Scalar y = z * m_cameraSensitivity * m_quickCameraModifier;
Core::Vector3 F = m_camera->getDirection();
Core::Transform T( Core::Transform::Identity() );
Core::Vector3 t = y * F;
T.translate( t );
m_camera->applyTransform( T );
}
void Gui::TrackballCamera::updatePhiTheta()
{
const Core::Vector3 P = m_camera->getPosition();
const Core::Vector3 C = m_trackballCenter;
const Core::Vector3 R = P - C;
const Scalar r = R.norm();
m_theta = std::acos( R.y() / r );
m_phi = ( R.z() == 0.f && R.x() == 0.f ) ? 0.f : std::atan2( R.z() , R.x() );
CORE_ASSERT( std::isfinite( m_theta ) && std::isfinite( m_phi ), "Error in trackball camera" );
}
} // namespace Ra
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// File : ReportNrrdInfo.cc
// Author : Martin Cole
// Date : Tue Feb 4 08:55:34 2003
#include <Modules/Legacy/Teem/Misc/ReportNrrdInfo.h>
#include <Core/Datatypes/Legacy/Nrrd/NrrdData.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Datatypes/Legacy/Base/PropertyManager.h>
using namespace SCIRun;
using namespace SCIRun::Modules::Teem;
using namespace SCIRun::Dataflow::Networks;
using namespace Core::Algorithms;
const ModuleLookupInfo ReportNrrdInfo::staticInfo_("ReportNrrdInfo", "Misc", "Teem");
ReportNrrdInfo::ReportNrrdInfo() : Module(staticInfo_)
{
INITIALIZE_PORT(Query_Nrrd);
}
void ReportNrrdInfo::setStateDefaults()
{
}
template <typename T>
void
ReportNrrdInfo::update_axis_var(std::ostringstream& info, const char *name, int axis, const T& val,
const char *pname)
{
info << name << " " << axis << ": value = " << val << "\n";
}
static const char *nrrd_kind_strings[] = { // nrrdKinds, Matches teem 1.9!
"nrrdKindUnknown",
"nrrdKindDomain", // 1: any image domain
"nrrdKindSpace", // 2: a spatial domain
"nrrdKindTime", // 3: a temporal domain
// -------------------------- end domain kinds
// -------------------------- begin range kinds
"nrrdKindList", // 4: any list of values, non-resample-able
"nrrdKindPoint", // 5: coords of a point
"nrrdKindVector", // 6: coeffs of (contravariant) vector
"nrrdKindCovariantVector", // 7: coeffs of covariant vector (eg gradient)
"nrrdKindNormal", // 8: coeffs of unit-length covariant vector
// -------------------------- end arbitrary size kinds
// -------------------------- begin size-specific kinds
"nrrdKindStub", // 9: axis with one sample (a placeholder)
"nrrdKindScalar", // 10: effectively, same as a stub
"nrrdKindComplex", // 11: real and imaginary components
"nrrdKind2Vector", // 12: 2 component vector
"nrrdKind3Color", // 13: ANY 3-component color value
"nrrdKindRGBColor", // 14: RGB, no colorimetry
"nrrdKindHSVColor", // 15: HSV, no colorimetry
"nrrdKindXYZColor", // 16: perceptual primary colors
"nrrdKind4Color", // 17: ANY 4-component color value
"nrrdKindRGBAColor", // 18: RGBA, no colorimetry
"nrrdKind3Vector", // 19: 3-component vector
"nrrdKind3Gradient", // 20: 3-component covariant vector
"nrrdKind3Normal", // 21: 3-component covector, assumed normalized
"nrrdKind4Vector", // 22: 4-component vector
"nrrdKindQuaternion", // 23: (w,x,y,z), not necessarily normalized
"nrrdKind2DSymMatrix", // 24: Mxx Mxy Myy
"nrrdKind2DMaskedSymMatrix", // 25: mask Mxx Mxy Myy
"nrrdKind2DMatrix", // 26: Mxx Mxy Myx Myy
"nrrdKind2DMaskedMatrix", // 27: mask Mxx Mxy Myx Myy
"nrrdKind3DSymMatrix", // 28: Mxx Mxy Mxz Myy Myz Mzz
"nrrdKind3DMaskedSymMatrix", // 29: mask Mxx Mxy Mxz Myy Myz Mzz
"nrrdKind3DMatrix", // 30: Mxx Mxy Mxz Myx Myy Myz Mzx Mzy Mzz
"nrrdKind3DMaskedMatrix", // 31: mask Mxx Mxy Mxz Myx Myy Myz Mzx Mzy Mzz
"nrrdKindLast"
};
void
ReportNrrdInfo::update_input_attributes(NrrdDataHandle nh)
{
std::ostringstream info;
std::string name;
if (!nh->properties().get_property( "Name", name))
name = "Unknown";
info << "Name: " << name << "\n";
std::string nrrdtype, stmp;
get_nrrd_compile_type(nh->getNrrd()->type, nrrdtype, stmp);
info << "Type: " << nrrdtype << "\n";
info << "Dimension: " << nh->getNrrd()->dim << "\n";
// space origin
std::ostringstream spaceor;
spaceor << "[ ";
unsigned int last_dim = nh->getNrrd()->spaceDim - 1;
for (unsigned int p = 0; p < nh->getNrrd()->spaceDim; ++p)
{
spaceor << nh->getNrrd()->spaceOrigin[p];
if (p < last_dim)
spaceor << ", ";
}
spaceor << " ]";
info << "Origin: " << spaceor.str() << "\n";
// TODO: Set Origin here.
bool haveSpaceInfo=false;
for (unsigned int i = 0; i < nh->getNrrd()->dim; i++)
if (airExists(nh->getNrrd()->axis[i].spaceDirection[0])) haveSpaceInfo=true;
// Go through all axes...
for (unsigned int i = 0; i < nh->getNrrd()->dim; i++)
{
std::string labelstr;
if (nh->getNrrd()->axis[i].label == 0 ||
std::string(nh->getNrrd()->axis[i].label).length() == 0)
{
labelstr = "---";
}
else
{
labelstr = nh->getNrrd()->axis[i].label;
}
update_axis_var(info, "label", i, labelstr, "Label");
int k = nh->getNrrd()->axis[i].kind;
if (k < 0 || k >= nrrdKindLast) k = 0;
const char *kindstr = nrrd_kind_strings[k];
update_axis_var(info, "kind", i, kindstr, "Kind");
update_axis_var(info, "size", i, nh->getNrrd()->axis[i].size, "Size");
update_axis_var(info, "min", i, nh->getNrrd()->axis[i].min, "Min");
update_axis_var(info, "max", i, nh->getNrrd()->axis[i].max, "Max");
std::string locstr;
switch (nh->getNrrd()->axis[i].center)
{
case nrrdCenterUnknown :
locstr = "Unknown";
break;
case nrrdCenterNode :
locstr = "Node";
break;
case nrrdCenterCell :
locstr = "Cell";
break;
}
update_axis_var(info, "center", i, locstr, "Center");
if (!haveSpaceInfo) { // no "spaceDirection" info, just "spacing"
update_axis_var(info, "spacing", i, (nh->getNrrd()->axis[i].spacing), "Spacing");
} else {
std::ostringstream spacedir;
spacedir << "[ ";
double l2 = 0;
for (unsigned int p = 0; p < nh->getNrrd()->spaceDim; ++p)
{
double tmp = nh->getNrrd()->axis[i].spaceDirection[p];
spacedir << tmp;
l2 += tmp*tmp;
if (p < last_dim)
spacedir << ", ";
}
spacedir << " ]";
update_axis_var(info, "spaceDir", i, spacedir.str(), "Spacing Direction");
update_axis_var(info, "spacing", i, (sqrt(l2)), "Spacing");
}
}
get_state()->setTransientValue(Variables::ObjectInfo, info.str());
}
void
ReportNrrdInfo::execute()
{
auto nh = getRequiredInput(Query_Nrrd);
update_input_attributes(nh);
}
<commit_msg>Closes #1200<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// File : ReportNrrdInfo.cc
// Author : Martin Cole
// Date : Tue Feb 4 08:55:34 2003
#include <Modules/Legacy/Teem/Misc/ReportNrrdInfo.h>
#include <Core/Datatypes/Legacy/Nrrd/NrrdData.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Datatypes/Legacy/Base/PropertyManager.h>
using namespace SCIRun;
using namespace SCIRun::Modules::Teem;
using namespace SCIRun::Dataflow::Networks;
using namespace Core::Algorithms;
const ModuleLookupInfo ReportNrrdInfo::staticInfo_("ReportNrrdInfo", "Misc", "Teem");
ReportNrrdInfo::ReportNrrdInfo() : Module(staticInfo_)
{
INITIALIZE_PORT(Query_Nrrd);
}
void ReportNrrdInfo::setStateDefaults()
{
}
template <typename T>
void
ReportNrrdInfo::update_axis_var(std::ostringstream& info, const char *name, int axis, const T& val,
const char *pname)
{
info << '\t' << pname << ": " << val << "\n";
}
static const char *nrrd_kind_strings[] = { // nrrdKinds, Matches teem 1.9!
"nrrdKindUnknown",
"nrrdKindDomain", // 1: any image domain
"nrrdKindSpace", // 2: a spatial domain
"nrrdKindTime", // 3: a temporal domain
// -------------------------- end domain kinds
// -------------------------- begin range kinds
"nrrdKindList", // 4: any list of values, non-resample-able
"nrrdKindPoint", // 5: coords of a point
"nrrdKindVector", // 6: coeffs of (contravariant) vector
"nrrdKindCovariantVector", // 7: coeffs of covariant vector (eg gradient)
"nrrdKindNormal", // 8: coeffs of unit-length covariant vector
// -------------------------- end arbitrary size kinds
// -------------------------- begin size-specific kinds
"nrrdKindStub", // 9: axis with one sample (a placeholder)
"nrrdKindScalar", // 10: effectively, same as a stub
"nrrdKindComplex", // 11: real and imaginary components
"nrrdKind2Vector", // 12: 2 component vector
"nrrdKind3Color", // 13: ANY 3-component color value
"nrrdKindRGBColor", // 14: RGB, no colorimetry
"nrrdKindHSVColor", // 15: HSV, no colorimetry
"nrrdKindXYZColor", // 16: perceptual primary colors
"nrrdKind4Color", // 17: ANY 4-component color value
"nrrdKindRGBAColor", // 18: RGBA, no colorimetry
"nrrdKind3Vector", // 19: 3-component vector
"nrrdKind3Gradient", // 20: 3-component covariant vector
"nrrdKind3Normal", // 21: 3-component covector, assumed normalized
"nrrdKind4Vector", // 22: 4-component vector
"nrrdKindQuaternion", // 23: (w,x,y,z), not necessarily normalized
"nrrdKind2DSymMatrix", // 24: Mxx Mxy Myy
"nrrdKind2DMaskedSymMatrix", // 25: mask Mxx Mxy Myy
"nrrdKind2DMatrix", // 26: Mxx Mxy Myx Myy
"nrrdKind2DMaskedMatrix", // 27: mask Mxx Mxy Myx Myy
"nrrdKind3DSymMatrix", // 28: Mxx Mxy Mxz Myy Myz Mzz
"nrrdKind3DMaskedSymMatrix", // 29: mask Mxx Mxy Mxz Myy Myz Mzz
"nrrdKind3DMatrix", // 30: Mxx Mxy Mxz Myx Myy Myz Mzx Mzy Mzz
"nrrdKind3DMaskedMatrix", // 31: mask Mxx Mxy Mxz Myx Myy Myz Mzx Mzy Mzz
"nrrdKindLast"
};
void
ReportNrrdInfo::update_input_attributes(NrrdDataHandle nh)
{
std::ostringstream info;
std::string name;
if (!nh->properties().get_property( "Name", name))
name = "Unknown";
info << "Name: " << name << "\n";
std::string nrrdtype, stmp;
get_nrrd_compile_type(nh->getNrrd()->type, nrrdtype, stmp);
info << "Type: " << nrrdtype << "\n";
info << "Dimension: " << nh->getNrrd()->dim << "\n";
// space origin
std::ostringstream spaceor;
spaceor << "[ ";
unsigned int last_dim = nh->getNrrd()->spaceDim - 1;
for (unsigned int p = 0; p < nh->getNrrd()->spaceDim; ++p)
{
spaceor << nh->getNrrd()->spaceOrigin[p];
if (p < last_dim)
spaceor << ", ";
}
spaceor << " ]";
info << "Origin: " << spaceor.str() << "\n";
// TODO: Set Origin here.
bool haveSpaceInfo=false;
for (unsigned int i = 0; i < nh->getNrrd()->dim; i++)
if (airExists(nh->getNrrd()->axis[i].spaceDirection[0])) haveSpaceInfo=true;
// Go through all axes...
for (unsigned int i = 0; i < nh->getNrrd()->dim; i++)
{
info << "Axis " << i << ":\n";
std::string labelstr;
if (nh->getNrrd()->axis[i].label == 0 ||
std::string(nh->getNrrd()->axis[i].label).length() == 0)
{
labelstr = "---";
}
else
{
labelstr = nh->getNrrd()->axis[i].label;
}
update_axis_var(info, "label", i, labelstr, "Label");
int k = nh->getNrrd()->axis[i].kind;
if (k < 0 || k >= nrrdKindLast) k = 0;
const char *kindstr = nrrd_kind_strings[k];
update_axis_var(info, "kind", i, kindstr, "Kind");
update_axis_var(info, "size", i, nh->getNrrd()->axis[i].size, "Size");
update_axis_var(info, "min", i, nh->getNrrd()->axis[i].min, "Min");
update_axis_var(info, "max", i, nh->getNrrd()->axis[i].max, "Max");
std::string locstr;
switch (nh->getNrrd()->axis[i].center)
{
case nrrdCenterUnknown :
locstr = "Unknown";
break;
case nrrdCenterNode :
locstr = "Node";
break;
case nrrdCenterCell :
locstr = "Cell";
break;
}
update_axis_var(info, "center", i, locstr, "Center");
if (!haveSpaceInfo) { // no "spaceDirection" info, just "spacing"
update_axis_var(info, "spacing", i, (nh->getNrrd()->axis[i].spacing), "Spacing");
} else {
std::ostringstream spacedir;
spacedir << "[ ";
double l2 = 0;
for (unsigned int p = 0; p < nh->getNrrd()->spaceDim; ++p)
{
double tmp = nh->getNrrd()->axis[i].spaceDirection[p];
spacedir << tmp;
l2 += tmp*tmp;
if (p < last_dim)
spacedir << ", ";
}
spacedir << " ]";
update_axis_var(info, "spaceDir", i, spacedir.str(), "Spacing Direction");
update_axis_var(info, "spacing", i, (sqrt(l2)), "Spacing");
}
}
get_state()->setTransientValue(Variables::ObjectInfo, info.str());
}
void
ReportNrrdInfo::execute()
{
auto nh = getRequiredInput(Query_Nrrd);
update_input_attributes(nh);
}
<|endoftext|>
|
<commit_before>//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$
#include <otb/HermiteInterpolator.h>
#include <string>
#include <cassert>
#include <iostream> //tmp
#include <iomanip> //tmp
namespace ossimplugins
{
HermiteInterpolator::HermiteInterpolator():
theNPointsAvailable(0),
theXValues(NULL),
theYValues(NULL),
thedYValues(NULL),
prodC(NULL),
sumC(NULL),
isComputed(false)
{
}
HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):
theNPointsAvailable(nbrPoints),
isComputed(false)
{
if(x != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = x[i];
}
}
else
{
theXValues = NULL;
}
if(y != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = y[i];
}
}
else
{
theYValues = NULL;
}
if(dy != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = dy[i];
}
}
else
{
thedYValues = NULL;
}
for (int i = 1 ; i < theNPointsAvailable ; i++)
{
/**
* @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes
*/
/*
* Les abscisses ne sont pas croissantes
*/
// if (theXValues[i] <= theXValues[i-1])
// std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl;
assert(theXValues[i] > theXValues[i-1]);
}
}
HermiteInterpolator::~HermiteInterpolator()
{
Clear();
}
HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):
theNPointsAvailable(rhs.theNPointsAvailable),
isComputed(false)
{
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
}
HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)
{
Clear();
theNPointsAvailable = rhs.theNPointsAvailable;
isComputed = false;
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
return *this;
}
// Interpolation method for the value and the derivative
int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
dy = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double ui = 0; //derivative computation
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
ui = ui + 1 / (x - theXValues[j]);//derivative computation
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
ui *= hi;//derivative computation
double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation
double d = hi * (hi + 2.0 * r * ui);//derivative computation
dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation
}
return 0;
}
// Interpolation method for the value only
// this is about 5 times faster and should be used when time
// is a constraint.
int HermiteInterpolator::Interpolate(double x, double& y) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
}
return 0;
}
int HermiteInterpolator::Precompute() const
{
prodC = new double[theNPointsAvailable];
sumC= new double[theNPointsAvailable];
for (int i = 0; i < theNPointsAvailable; i++)
{
prodC[i] = 1;
sumC[i] = 0;
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
double v = 1.0 / (theXValues[i] - theXValues[j]);
prodC[i] *= v;
sumC[i] += v;
}
}
}
isComputed = true;
}
void HermiteInterpolator::Clear()
{
if (theXValues != NULL)
{
delete[] theXValues;
theXValues = NULL;
}
if (theYValues != NULL)
{
delete[] theYValues;
theYValues = NULL;
}
if (thedYValues != NULL)
{
delete[] thedYValues;
thedYValues = NULL;
}
if (prodC != NULL)
{
delete[] prodC;
prodC = NULL;
}
if (sumC != NULL)
{
delete[] sumC;
prodC = NULL;
}
isComputed = false;
theNPointsAvailable = 0;
}
}
<commit_msg>BUG: remove useless include<commit_after>//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$
#include <otb/HermiteInterpolator.h>
#include <string>
#include <cassert>
namespace ossimplugins
{
HermiteInterpolator::HermiteInterpolator():
theNPointsAvailable(0),
theXValues(NULL),
theYValues(NULL),
thedYValues(NULL),
prodC(NULL),
sumC(NULL),
isComputed(false)
{
}
HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):
theNPointsAvailable(nbrPoints),
isComputed(false)
{
if(x != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = x[i];
}
}
else
{
theXValues = NULL;
}
if(y != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = y[i];
}
}
else
{
theYValues = NULL;
}
if(dy != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = dy[i];
}
}
else
{
thedYValues = NULL;
}
for (int i = 1 ; i < theNPointsAvailable ; i++)
{
/**
* @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes
*/
/*
* Les abscisses ne sont pas croissantes
*/
// if (theXValues[i] <= theXValues[i-1])
// std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl;
assert(theXValues[i] > theXValues[i-1]);
}
}
HermiteInterpolator::~HermiteInterpolator()
{
Clear();
}
HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):
theNPointsAvailable(rhs.theNPointsAvailable),
isComputed(false)
{
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
}
HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)
{
Clear();
theNPointsAvailable = rhs.theNPointsAvailable;
isComputed = false;
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
return *this;
}
// Interpolation method for the value and the derivative
int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
dy = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double ui = 0; //derivative computation
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
ui = ui + 1 / (x - theXValues[j]);//derivative computation
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
ui *= hi;//derivative computation
double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation
double d = hi * (hi + 2.0 * r * ui);//derivative computation
dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation
}
return 0;
}
// Interpolation method for the value only
// this is about 5 times faster and should be used when time
// is a constraint.
int HermiteInterpolator::Interpolate(double x, double& y) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
}
return 0;
}
int HermiteInterpolator::Precompute() const
{
prodC = new double[theNPointsAvailable];
sumC= new double[theNPointsAvailable];
for (int i = 0; i < theNPointsAvailable; i++)
{
prodC[i] = 1;
sumC[i] = 0;
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
double v = 1.0 / (theXValues[i] - theXValues[j]);
prodC[i] *= v;
sumC[i] += v;
}
}
}
isComputed = true;
}
void HermiteInterpolator::Clear()
{
if (theXValues != NULL)
{
delete[] theXValues;
theXValues = NULL;
}
if (theYValues != NULL)
{
delete[] theYValues;
theYValues = NULL;
}
if (thedYValues != NULL)
{
delete[] thedYValues;
thedYValues = NULL;
}
if (prodC != NULL)
{
delete[] prodC;
prodC = NULL;
}
if (sumC != NULL)
{
delete[] sumC;
prodC = NULL;
}
isComputed = false;
theNPointsAvailable = 0;
}
}
<|endoftext|>
|
<commit_before>/*
* HyPerCol.cpp
*
* Created on: Jul 30, 2008
* Author: rasmussn
*/
#undef TIMER_ON
#include "HyPerCol.hpp"
#include "InterColComm.hpp"
#include "../connections/PVConnection.h"
#include "../io/clock.h"
#include "../io/imageio.hpp"
#include "../io/io.h"
#include <assert.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
namespace PV {
HyPerCol::HyPerCol(const char * name, int argc, char * argv[])
: warmStart(false)
{
// TODO - fix these numbers to dynamically grow
maxLayers = MAX_LAYERS;
maxConnections = MAX_CONNECTIONS;
this->name = strdup(name);
char * param_file;
time = 0;
numLayers = 0;
numConnections = 0;
layers = (HyPerLayer **) malloc(maxLayers * sizeof(HyPerLayer *));
connections = (HyPerConn **) malloc(maxConnections * sizeof(HyPerConn *));
#ifdef MULTITHREADED
numThreads = 1;
#else
numThreads = 0;
#endif
numSteps = 2;
image_file = NULL;
param_file = NULL;
parse_options(argc, argv, &image_file, ¶m_file, &numSteps, &numThreads);
// estimate for now
// TODO -get rid of maxGroups
int maxGroups = 2*(maxLayers + maxConnections);
params = new PVParams(param_file, maxGroups);
icComm = new InterColComm(&argc, &argv);
if (param_file != NULL) free(param_file);
deltaTime = DELTA_T;
if (params->present(name, "dt")) deltaTime = params->value(name, "dt");
int status = -1;
if (image_file) {
status = getImageInfo(image_file, icComm, &imageLoc);
}
if (status) {
imageLoc.nx = params->value(name, "nx");
imageLoc.ny = params->value(name, "ny");
imageLoc.nxGlobal = imageLoc.nx * icComm->numCommColumns();
imageLoc.nyGlobal = imageLoc.ny * icComm->numCommRows();
imageLoc.kx0 = imageLoc.nx * icComm->commColumn();
imageLoc.ky0 = imageLoc.ny * icComm->commRow();
imageLoc.nPad = 0;
imageLoc.nBands = 1;
}
}
HyPerCol::~HyPerCol()
{
int n;
#ifdef MULTITHREADED
finalizeThreads();
#endif
if (image_file != NULL) free(image_file);
for (n = 0; n < numConnections; n++) {
delete connections[n];
}
free(threadCLayers);
for (n = 0; n < numLayers; n++) {
// TODO: check to see if finalize called
if (layers[n] != NULL) {
delete layers[n]; // will call *_finalize
}
else {
// TODO move finalize
// PVLayer_finalize(getCLayer(n));
}
}
delete icComm;
free(connections);
free(layers);
free(name);
}
int HyPerCol::initFinish(void)
{
int err = 0;
for (int i = 0; i < this->numLayers; i++) {
err = layers[i]->initFinish();
if (err != 0) {
fprintf(stderr, "[%d]: HyPerCol::initFinish: ERROR condition, exiting...\n", this->columnId());
exit(err);
}
}
log_parameters(numSteps, image_file);
#ifdef MULTITHREADED
initializeThreads();
#endif
return err;
}
int HyPerCol::columnId()
{
return icComm->commRank();
}
int HyPerCol::numberOfColumns()
{
return icComm->numCommRows() * icComm->numCommColumns();
}
int HyPerCol::commColumn(int colId)
{
return colId % icComm->numCommColumns();
}
int HyPerCol::commRow(int colId)
{
return colId / icComm->numCommColumns();
}
int HyPerCol::addLayer(HyPerLayer * l)
{
assert(numLayers < maxLayers);
l->columnWillAddLayer(icComm, numLayers);
layers[numLayers++] = l;
return (numLayers - 1);
}
int HyPerCol::addConnection(HyPerConn * conn)
{
int connId = numConnections;
assert(numConnections < maxConnections);
// numConnections is the ID of this connection
icComm->subscribe(conn);
connections[numConnections++] = conn;
return connId;
}
int HyPerCol::run(int nTimeSteps)
{
int step = 0;
int stop = nTimeSteps;
numSteps = nTimeSteps;
#ifdef DEBUG_OUTPUT
if (columnId() == 0) {
printf("[0]: HyPerCol: running...\n"); fflush(stdout);
}
#endif
// publish initial conditions
for (int l = 0; l < numLayers; l++) {
layers[l]->publish(icComm, time);
}
while (step++ < stop) {
#ifdef TIMER_ON
if (step == 10) start_clock();
#endif
// deliver published data for each layer
for (int l = 0; l < numLayers; l++) {
// this function blocks until all data for a layer has been delivered
#ifdef DEBUG_OUTPUT
printf("[%d]: HyPerCol::run will deliver layer %d\n", columnId(), l);
fflush(stdout);
#endif
icComm->deliver(this, l);
}
#ifdef DEBUG_OUTPUT
if (columnId() == 0) {
printf("[0]: HyPerCol::run: data delivery finished\n"); fflush(stdout);
}
#endif
for (int l = 0; l < numLayers; l++) {
layers[l]->updateState(time, deltaTime);
layers[l]->outputState(time+deltaTime);
icComm->increaseTimeLevel(layers[l]->getLayerId());
layers[l]->publish(icComm, time);
}
// layer activity has been calculated, inform connections
for (int c = 0; c < numConnections; c++) {
connections[c]->updateState(time, deltaTime);
connections[c]->outputState(time+deltaTime);
}
time += deltaTime;
} // end run loop
#ifdef DEBUG_OUTPUT
if (columnId() == 0) {
printf("[0]: HyPerCol::run done...\n"); fflush(stdout);
}
#endif
// output final state of layers and connections
//
bool last = true;
for (int l = 0; l < numLayers; l++) {
layers[l]->writeState(layers[l]->getName(), time, last);
}
for (int c = 0; c < numConnections; c++) {
connections[c]->outputState(time, last);
}
#ifdef TIMER_ON
stop_clock();
#endif
return 0;
}
int HyPerCol::initializeThreads()
{
int err = 0;
#ifdef IBM_CELL_BE
err = pv_cell_thread_init(columnId(), numThreads);
#endif
return err;
}
int HyPerCol::finalizeThreads()
{
int err = 0;
#ifdef IBM_CELL_BE
err = pv_cell_thread_finalize(columnId(), numThreads);
#endif
return err;
}
int HyPerCol::loadState()
{
return 0;
}
int HyPerCol::writeState()
{
for (int l = 0; l < numLayers; l++) {
layers[l]->writeState(OUTPUT_PATH, time);
}
return 0;
}
}; // PV namespace
extern "C" {
void * run1connection(void * arg)
{
#ifdef DELETE
int layers = ((run_struct *) arg)->layers;
int proc = ((run_struct *) arg)->proc;
PV::HyPerCol * hc = ((run_struct *) arg)->hc;
clock_t ticks;
ticks = clock();
srand(ticks + proc);
printf("c%d start: %ld\n", i, ticks);
hc->connections[layers].recvFunc(hc->connections[layers].pre,
hc->connections[proc].recvFunc(&hc->connections[proc],
&hc->shmemCLayers[layers], hc->connections[proc].pre->numNeurons,
hc->connections[proc].pre->fActivity[hc->connections[proc].readIdx]);
ticks = clock() - ticks;
printf("c%d diff : %ld\n", i, ticks);
#ifdef MULTITHREADED
pthread_exit(0);
#endif
#endif
return NULL;
}
void * update1layer(void * arg)
{
#ifdef DELETE
run_struct * info = (run_struct *) arg;
int itl = info->proc;
PV::HyPerCol * hc = info->hc;
clock_t ticks;
ticks = clock();
srand(ticks + itl);
hc->threadCLayers[itl].updateFunc(&hc->threadCLayers[itl]);
#ifdef MULTITHREADED
pthread_exit(0);
#endif
#endif
return NULL;
}
}
; // extern "C"
<commit_msg>Added runtime delegation to work with OpenGL displays. Deleted run1connection (pthreads from old PV version).<commit_after>/*
* HyPerCol.cpp
*
* Created on: Jul 30, 2008
* Author: rasmussn
*/
#undef TIMER_ON
#include "HyPerCol.hpp"
#include "InterColComm.hpp"
#include "../connections/PVConnection.h"
#include "../io/clock.h"
#include "../io/imageio.hpp"
#include "../io/io.h"
#include <assert.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
namespace PV {
HyPerCol::HyPerCol(const char * name, int argc, char * argv[])
: warmStart(false)
{
// TODO - fix these numbers to dynamically grow
maxLayers = MAX_LAYERS;
maxConnections = MAX_CONNECTIONS;
this->name = strdup(name);
char * param_file;
time = 0;
numLayers = 0;
numConnections = 0;
layers = (HyPerLayer **) malloc(maxLayers * sizeof(HyPerLayer *));
connections = (HyPerConn **) malloc(maxConnections * sizeof(HyPerConn *));
#ifdef MULTITHREADED
numThreads = 1;
#else
numThreads = 0;
#endif
numSteps = 2;
image_file = NULL;
param_file = NULL;
parse_options(argc, argv, &image_file, ¶m_file, &numSteps, &numThreads);
// estimate for now
// TODO -get rid of maxGroups
int maxGroups = 2*(maxLayers + maxConnections);
params = new PVParams(param_file, maxGroups);
icComm = new InterColComm(&argc, &argv);
if (param_file != NULL) free(param_file);
deltaTime = DELTA_T;
if (params->present(name, "dt")) deltaTime = params->value(name, "dt");
int status = -1;
if (image_file) {
status = getImageInfo(image_file, icComm, &imageLoc);
}
if (status) {
imageLoc.nx = params->value(name, "nx");
imageLoc.ny = params->value(name, "ny");
imageLoc.nxGlobal = imageLoc.nx * icComm->numCommColumns();
imageLoc.nyGlobal = imageLoc.ny * icComm->numCommRows();
imageLoc.kx0 = imageLoc.nx * icComm->commColumn();
imageLoc.ky0 = imageLoc.ny * icComm->commRow();
imageLoc.nPad = 0;
imageLoc.nBands = 1;
}
runDelegate = NULL;
}
HyPerCol::~HyPerCol()
{
int n;
#ifdef MULTITHREADED
finalizeThreads();
#endif
if (image_file != NULL) free(image_file);
for (n = 0; n < numConnections; n++) {
delete connections[n];
}
free(threadCLayers);
for (n = 0; n < numLayers; n++) {
// TODO: check to see if finalize called
if (layers[n] != NULL) {
delete layers[n]; // will call *_finalize
}
else {
// TODO move finalize
// PVLayer_finalize(getCLayer(n));
}
}
delete icComm;
free(connections);
free(layers);
free(name);
}
int HyPerCol::initFinish(void)
{
int err = 0;
for (int i = 0; i < this->numLayers; i++) {
err = layers[i]->initFinish();
if (err != 0) {
fprintf(stderr, "[%d]: HyPerCol::initFinish: ERROR condition, exiting...\n", this->columnId());
exit(err);
}
}
log_parameters(numSteps, image_file);
#ifdef MULTITHREADED
initializeThreads();
#endif
return err;
}
int HyPerCol::columnId()
{
return icComm->commRank();
}
int HyPerCol::numberOfColumns()
{
return icComm->numCommRows() * icComm->numCommColumns();
}
int HyPerCol::commColumn(int colId)
{
return colId % icComm->numCommColumns();
}
int HyPerCol::commRow(int colId)
{
return colId / icComm->numCommColumns();
}
int HyPerCol::addLayer(HyPerLayer * l)
{
assert(numLayers < maxLayers);
l->columnWillAddLayer(icComm, numLayers);
layers[numLayers++] = l;
return (numLayers - 1);
}
int HyPerCol::addConnection(HyPerConn * conn)
{
int connId = numConnections;
assert(numConnections < maxConnections);
// numConnections is the ID of this connection
icComm->subscribe(conn);
connections[numConnections++] = conn;
return connId;
}
int HyPerCol::run(int nTimeSteps)
{
int step = 0;
float stopTime = time + nTimeSteps * deltaTime;
const bool exitOnFinish = false;
numSteps = nTimeSteps;
#ifdef DEBUG_OUTPUT
if (columnId() == 0) {
printf("[0]: HyPerCol: running...\n"); fflush(stdout);
}
#endif
// publish initial conditions
//
for (int l = 0; l < numLayers; l++) {
layers[l]->publish(icComm, time);
}
if (runDelegate) {
// let delegate advance the time
//
runDelegate->run(time, stopTime);
}
// time loop
//
while (time < stopTime) {
time = advanceTime(time);
step += 1;
#ifdef TIMER_ON
if (step == 10) start_clock();
#endif
} // end time loop
#ifdef DEBUG_OUTPUT
if (columnId() == 0) {
printf("[0]: HyPerCol::run done...\n"); fflush(stdout);
}
#endif
exitRunLoop(exitOnFinish);
#ifdef TIMER_ON
stop_clock();
#endif
return 0;
}
float HyPerCol::advanceTime(float simTime)
{
// deliver published data for each layer
//
for (int l = 0; l < numLayers; l++) {
#ifdef DEBUG_OUTPUT
printf("[%d]: HyPerCol::run will deliver layer %d\n", columnId(), l);
fflush(stdout);
#endif
// this function blocks until all data for a layer has been delivered
//
icComm->deliver(this, l);
}
#ifdef DEBUG_OUTPUT
if (columnId() == 0) {
printf("[0]: HyPerCol::run: data delivery finished\n"); fflush(stdout);
}
#endif
for (int l = 0; l < numLayers; l++) {
layers[l]->updateState(simTime, deltaTime);
layers[l]->outputState(simTime+deltaTime);
icComm->increaseTimeLevel(layers[l]->getLayerId());
layers[l]->publish(icComm, simTime);
}
// layer activity has been calculated, inform connections
for (int c = 0; c < numConnections; c++) {
connections[c]->updateState(simTime, deltaTime);
connections[c]->outputState(simTime+deltaTime);
}
return simTime + deltaTime;
}
int HyPerCol::exitRunLoop(bool exitOnFinish)
{
int status = 0;
// output final state of layers and connections
//
bool last = true;
for (int l = 0; l < numLayers; l++) {
layers[l]->writeState(layers[l]->getName(), time, last);
}
for (int c = 0; c < numConnections; c++) {
connections[c]->outputState(time, last);
}
if (exitOnFinish) {
delete this;
exit(0);
}
return status;
}
int HyPerCol::initializeThreads()
{
int err = 0;
#ifdef IBM_CELL_BE
err = pv_cell_thread_init(columnId(), numThreads);
#endif
return err;
}
int HyPerCol::finalizeThreads()
{
int err = 0;
#ifdef IBM_CELL_BE
err = pv_cell_thread_finalize(columnId(), numThreads);
#endif
return err;
}
int HyPerCol::loadState()
{
return 0;
}
int HyPerCol::writeState()
{
for (int l = 0; l < numLayers; l++) {
layers[l]->writeState(OUTPUT_PATH, time);
}
return 0;
}
}; // PV namespace
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkTypes.h"
#if defined(SK_BUILD_FOR_WIN)
#include "include/core/SkTypes.h"
#include "include/private/SkTFitsIn.h"
#include "include/private/SkTemplates.h"
#include "src/utils/win/SkDWriteFontFileStream.h"
#include "src/utils/win/SkHRESULT.h"
#include "src/utils/win/SkTScopedComPtr.h"
#include <dwrite.h>
///////////////////////////////////////////////////////////////////////////////
// SkIDWriteFontFileStream
SkDWriteFontFileStream::SkDWriteFontFileStream(IDWriteFontFileStream* fontFileStream)
: fFontFileStream(SkRefComPtr(fontFileStream))
, fPos(0)
, fLockedMemory(nullptr)
, fFragmentLock(nullptr) {
}
SkDWriteFontFileStream::~SkDWriteFontFileStream() {
if (fFragmentLock) {
fFontFileStream->ReleaseFileFragment(fFragmentLock);
}
}
size_t SkDWriteFontFileStream::read(void* buffer, size_t size) {
HRESULT hr = S_OK;
if (nullptr == buffer) {
size_t fileSize = this->getLength();
if (fPos + size > fileSize) {
size_t skipped = fileSize - fPos;
fPos = fileSize;
return skipped;
} else {
fPos += size;
return size;
}
}
const void* start;
void* fragmentLock;
hr = fFontFileStream->ReadFileFragment(&start, fPos, size, &fragmentLock);
if (SUCCEEDED(hr)) {
memcpy(buffer, start, size);
fFontFileStream->ReleaseFileFragment(fragmentLock);
fPos += size;
return size;
}
//The read may have failed because we asked for too much data.
size_t fileSize = this->getLength();
if (fPos + size <= fileSize) {
//This means we were within bounds, but failed for some other reason.
return 0;
}
size_t read = fileSize - fPos;
hr = fFontFileStream->ReadFileFragment(&start, fPos, read, &fragmentLock);
if (SUCCEEDED(hr)) {
memcpy(buffer, start, read);
fFontFileStream->ReleaseFileFragment(fragmentLock);
fPos = fileSize;
return read;
}
return 0;
}
bool SkDWriteFontFileStream::isAtEnd() const {
return fPos == this->getLength();
}
bool SkDWriteFontFileStream::rewind() {
fPos = 0;
return true;
}
SkDWriteFontFileStream* SkDWriteFontFileStream::onDuplicate() const {
return new SkDWriteFontFileStream(fFontFileStream.get());
}
size_t SkDWriteFontFileStream::getPosition() const {
return fPos;
}
bool SkDWriteFontFileStream::seek(size_t position) {
size_t length = this->getLength();
fPos = (position > length) ? length : position;
return true;
}
bool SkDWriteFontFileStream::move(long offset) {
return seek(fPos + offset);
}
SkDWriteFontFileStream* SkDWriteFontFileStream::onFork() const {
std::unique_ptr<SkDWriteFontFileStream> that(this->duplicate());
that->seek(fPos);
return that.release();
}
size_t SkDWriteFontFileStream::getLength() const {
HRESULT hr = S_OK;
UINT64 realFileSize = 0;
hr = fFontFileStream->GetFileSize(&realFileSize);
if (!SkTFitsIn<size_t>(realFileSize)) {
return 0;
}
return static_cast<size_t>(realFileSize);
}
const void* SkDWriteFontFileStream::getMemoryBase() {
if (fLockedMemory) {
return fLockedMemory;
}
UINT64 fileSize;
HRNM(fFontFileStream->GetFileSize(&fileSize), "Could not get file size");
HRNM(fFontFileStream->ReadFileFragment(&fLockedMemory, 0, fileSize, &fFragmentLock),
"Could not lock file fragment.");
return fLockedMemory;
}
///////////////////////////////////////////////////////////////////////////////
// SkIDWriteFontFileStreamWrapper
HRESULT SkDWriteFontFileStreamWrapper::Create(SkStreamAsset* stream,
SkDWriteFontFileStreamWrapper** streamFontFileStream)
{
*streamFontFileStream = new SkDWriteFontFileStreamWrapper(stream);
if (nullptr == *streamFontFileStream) {
return E_OUTOFMEMORY;
}
return S_OK;
}
SkDWriteFontFileStreamWrapper::SkDWriteFontFileStreamWrapper(SkStreamAsset* stream)
: fRefCount(1), fStream(stream) {
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::QueryInterface(REFIID iid, void** ppvObject) {
if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileStream)) {
*ppvObject = this;
AddRef();
return S_OK;
} else {
*ppvObject = nullptr;
return E_NOINTERFACE;
}
}
SK_STDMETHODIMP_(ULONG) SkDWriteFontFileStreamWrapper::AddRef() {
return InterlockedIncrement(&fRefCount);
}
SK_STDMETHODIMP_(ULONG) SkDWriteFontFileStreamWrapper::Release() {
ULONG newCount = InterlockedDecrement(&fRefCount);
if (0 == newCount) {
delete this;
}
return newCount;
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::ReadFileFragment(
void const** fragmentStart,
UINT64 fileOffset,
UINT64 fragmentSize,
void** fragmentContext)
{
// The loader is responsible for doing a bounds check.
UINT64 fileSize;
this->GetFileSize(&fileSize);
if (fileOffset > fileSize || fragmentSize > fileSize - fileOffset) {
*fragmentStart = nullptr;
*fragmentContext = nullptr;
return E_FAIL;
}
if (!SkTFitsIn<size_t>(fileOffset + fragmentSize)) {
return E_FAIL;
}
const void* data = fStream->getMemoryBase();
if (data) {
*fragmentStart = static_cast<BYTE const*>(data) + static_cast<size_t>(fileOffset);
*fragmentContext = nullptr;
} else {
// May be called from multiple threads.
SkAutoMutexExclusive ama(fStreamMutex);
*fragmentStart = nullptr;
*fragmentContext = nullptr;
if (!fStream->seek(static_cast<size_t>(fileOffset))) {
return E_FAIL;
}
SkAutoTMalloc<uint8_t> streamData(static_cast<size_t>(fragmentSize));
if (fStream->read(streamData.get(), static_cast<size_t>(fragmentSize)) != fragmentSize) {
return E_FAIL;
}
*fragmentStart = streamData.get();
*fragmentContext = streamData.release();
}
return S_OK;
}
SK_STDMETHODIMP_(void) SkDWriteFontFileStreamWrapper::ReleaseFileFragment(void* fragmentContext) {
sk_free(fragmentContext);
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::GetFileSize(UINT64* fileSize) {
*fileSize = fStream->getLength();
return S_OK;
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::GetLastWriteTime(UINT64* lastWriteTime) {
// The concept of last write time does not apply to this loader.
*lastWriteTime = 0;
return E_NOTIMPL;
}
#endif//defined(SK_BUILD_FOR_WIN)
<commit_msg>Fix an instance of -Wunused-but-set-variable.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkTypes.h"
#if defined(SK_BUILD_FOR_WIN)
#include "include/core/SkTypes.h"
#include "include/private/SkTFitsIn.h"
#include "include/private/SkTemplates.h"
#include "src/utils/win/SkDWriteFontFileStream.h"
#include "src/utils/win/SkHRESULT.h"
#include "src/utils/win/SkTScopedComPtr.h"
#include <dwrite.h>
///////////////////////////////////////////////////////////////////////////////
// SkIDWriteFontFileStream
SkDWriteFontFileStream::SkDWriteFontFileStream(IDWriteFontFileStream* fontFileStream)
: fFontFileStream(SkRefComPtr(fontFileStream))
, fPos(0)
, fLockedMemory(nullptr)
, fFragmentLock(nullptr) {
}
SkDWriteFontFileStream::~SkDWriteFontFileStream() {
if (fFragmentLock) {
fFontFileStream->ReleaseFileFragment(fFragmentLock);
}
}
size_t SkDWriteFontFileStream::read(void* buffer, size_t size) {
HRESULT hr = S_OK;
if (nullptr == buffer) {
size_t fileSize = this->getLength();
if (fPos + size > fileSize) {
size_t skipped = fileSize - fPos;
fPos = fileSize;
return skipped;
} else {
fPos += size;
return size;
}
}
const void* start;
void* fragmentLock;
hr = fFontFileStream->ReadFileFragment(&start, fPos, size, &fragmentLock);
if (SUCCEEDED(hr)) {
memcpy(buffer, start, size);
fFontFileStream->ReleaseFileFragment(fragmentLock);
fPos += size;
return size;
}
//The read may have failed because we asked for too much data.
size_t fileSize = this->getLength();
if (fPos + size <= fileSize) {
//This means we were within bounds, but failed for some other reason.
return 0;
}
size_t read = fileSize - fPos;
hr = fFontFileStream->ReadFileFragment(&start, fPos, read, &fragmentLock);
if (SUCCEEDED(hr)) {
memcpy(buffer, start, read);
fFontFileStream->ReleaseFileFragment(fragmentLock);
fPos = fileSize;
return read;
}
return 0;
}
bool SkDWriteFontFileStream::isAtEnd() const {
return fPos == this->getLength();
}
bool SkDWriteFontFileStream::rewind() {
fPos = 0;
return true;
}
SkDWriteFontFileStream* SkDWriteFontFileStream::onDuplicate() const {
return new SkDWriteFontFileStream(fFontFileStream.get());
}
size_t SkDWriteFontFileStream::getPosition() const {
return fPos;
}
bool SkDWriteFontFileStream::seek(size_t position) {
size_t length = this->getLength();
fPos = (position > length) ? length : position;
return true;
}
bool SkDWriteFontFileStream::move(long offset) {
return seek(fPos + offset);
}
SkDWriteFontFileStream* SkDWriteFontFileStream::onFork() const {
std::unique_ptr<SkDWriteFontFileStream> that(this->duplicate());
that->seek(fPos);
return that.release();
}
size_t SkDWriteFontFileStream::getLength() const {
UINT64 realFileSize = 0;
fFontFileStream->GetFileSize(&realFileSize);
if (!SkTFitsIn<size_t>(realFileSize)) {
return 0;
}
return static_cast<size_t>(realFileSize);
}
const void* SkDWriteFontFileStream::getMemoryBase() {
if (fLockedMemory) {
return fLockedMemory;
}
UINT64 fileSize;
HRNM(fFontFileStream->GetFileSize(&fileSize), "Could not get file size");
HRNM(fFontFileStream->ReadFileFragment(&fLockedMemory, 0, fileSize, &fFragmentLock),
"Could not lock file fragment.");
return fLockedMemory;
}
///////////////////////////////////////////////////////////////////////////////
// SkIDWriteFontFileStreamWrapper
HRESULT SkDWriteFontFileStreamWrapper::Create(SkStreamAsset* stream,
SkDWriteFontFileStreamWrapper** streamFontFileStream)
{
*streamFontFileStream = new SkDWriteFontFileStreamWrapper(stream);
if (nullptr == *streamFontFileStream) {
return E_OUTOFMEMORY;
}
return S_OK;
}
SkDWriteFontFileStreamWrapper::SkDWriteFontFileStreamWrapper(SkStreamAsset* stream)
: fRefCount(1), fStream(stream) {
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::QueryInterface(REFIID iid, void** ppvObject) {
if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileStream)) {
*ppvObject = this;
AddRef();
return S_OK;
} else {
*ppvObject = nullptr;
return E_NOINTERFACE;
}
}
SK_STDMETHODIMP_(ULONG) SkDWriteFontFileStreamWrapper::AddRef() {
return InterlockedIncrement(&fRefCount);
}
SK_STDMETHODIMP_(ULONG) SkDWriteFontFileStreamWrapper::Release() {
ULONG newCount = InterlockedDecrement(&fRefCount);
if (0 == newCount) {
delete this;
}
return newCount;
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::ReadFileFragment(
void const** fragmentStart,
UINT64 fileOffset,
UINT64 fragmentSize,
void** fragmentContext)
{
// The loader is responsible for doing a bounds check.
UINT64 fileSize;
this->GetFileSize(&fileSize);
if (fileOffset > fileSize || fragmentSize > fileSize - fileOffset) {
*fragmentStart = nullptr;
*fragmentContext = nullptr;
return E_FAIL;
}
if (!SkTFitsIn<size_t>(fileOffset + fragmentSize)) {
return E_FAIL;
}
const void* data = fStream->getMemoryBase();
if (data) {
*fragmentStart = static_cast<BYTE const*>(data) + static_cast<size_t>(fileOffset);
*fragmentContext = nullptr;
} else {
// May be called from multiple threads.
SkAutoMutexExclusive ama(fStreamMutex);
*fragmentStart = nullptr;
*fragmentContext = nullptr;
if (!fStream->seek(static_cast<size_t>(fileOffset))) {
return E_FAIL;
}
SkAutoTMalloc<uint8_t> streamData(static_cast<size_t>(fragmentSize));
if (fStream->read(streamData.get(), static_cast<size_t>(fragmentSize)) != fragmentSize) {
return E_FAIL;
}
*fragmentStart = streamData.get();
*fragmentContext = streamData.release();
}
return S_OK;
}
SK_STDMETHODIMP_(void) SkDWriteFontFileStreamWrapper::ReleaseFileFragment(void* fragmentContext) {
sk_free(fragmentContext);
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::GetFileSize(UINT64* fileSize) {
*fileSize = fStream->getLength();
return S_OK;
}
SK_STDMETHODIMP SkDWriteFontFileStreamWrapper::GetLastWriteTime(UINT64* lastWriteTime) {
// The concept of last write time does not apply to this loader.
*lastWriteTime = 0;
return E_NOTIMPL;
}
#endif//defined(SK_BUILD_FOR_WIN)
<|endoftext|>
|
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2015 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "commandmanager.h"
#include "../Models/artworksrepository.h"
#include "../Models/artitemsmodel.h"
#include "../Models/combinedartworksmodel.h"
#include "../Models/iptcprovider.h"
#include "../Models/artworkuploader.h"
#include "../Models/uploadinforepository.h"
#include "../Models/warningsmanager.h"
#include "../Models/uploadinfo.h"
#include "../Models/artworkmetadata.h"
#include "../Encryption/secretsmanager.h"
#include "../UndoRedo/undoredomanager.h"
#include "../Models/ziparchiver.h"
#include "../Suggestion/keywordssuggestor.h"
#include "../Commands/addartworkscommand.h"
#include "../Models/filteredartitemsproxymodel.h"
#include "../Models/recentdirectoriesmodel.h"
#include "../Models/artiteminfo.h"
#include "../SpellCheck/spellcheckerservice.h"
#include "../Models/settingsmodel.h"
#include "../SpellCheck/spellchecksuggestionmodel.h"
#include "../SpellCheck/ispellcheckable.h"
#include "../Helpers/backupsaverservice.h"
#include "../Conectivity/telemetryservice.h"
#include "../Helpers/updateservice.h"
void Commands::CommandManager::InjectDependency(Models::ArtworksRepository *artworkRepository) {
Q_ASSERT(artworkRepository != NULL); m_ArtworksRepository = artworkRepository;
m_ArtworksRepository->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::ArtItemsModel *artItemsModel) {
Q_ASSERT(artItemsModel != NULL); m_ArtItemsModel = artItemsModel;
m_ArtItemsModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::FilteredArtItemsProxyModel *filteredItemsModel) {
Q_ASSERT(filteredItemsModel != NULL); m_FilteredItemsModel = filteredItemsModel;
m_FilteredItemsModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::CombinedArtworksModel *combinedArtworksModel) {
Q_ASSERT(combinedArtworksModel != NULL); m_CombinedArtworksModel = combinedArtworksModel;
m_CombinedArtworksModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::IptcProvider *iptcProvider) {
Q_ASSERT(iptcProvider != NULL); m_IptcProvider = iptcProvider;
m_IptcProvider->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::ArtworkUploader *artworkUploader) {
Q_ASSERT(artworkUploader != NULL); m_ArtworkUploader = artworkUploader;
m_ArtworkUploader->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::UploadInfoRepository *uploadInfoRepository) {
Q_ASSERT(uploadInfoRepository != NULL); m_UploadInfoRepository = uploadInfoRepository;
m_UploadInfoRepository->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::WarningsManager *warningsManager) {
Q_ASSERT(warningsManager != NULL); m_WarningsManager = warningsManager;
m_WarningsManager->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Encryption::SecretsManager *secretsManager) {
Q_ASSERT(secretsManager != NULL); m_SecretsManager = secretsManager;
m_SecretsManager->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(UndoRedo::UndoRedoManager *undoRedoManager) {
Q_ASSERT(undoRedoManager != NULL); m_UndoRedoManager = undoRedoManager;
m_UndoRedoManager->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::ZipArchiver *zipArchiver)
{
Q_ASSERT(zipArchiver != NULL); m_ZipArchiver = zipArchiver;
m_ZipArchiver->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Suggestion::KeywordsSuggestor *keywordsSuggestor)
{
Q_ASSERT(keywordsSuggestor != NULL); m_KeywordsSuggestor = keywordsSuggestor;
m_KeywordsSuggestor->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::SettingsModel *settingsModel) {
Q_ASSERT(settingsModel != NULL); m_SettingsModel = settingsModel;
}
void Commands::CommandManager::InjectDependency(Models::RecentDirectoriesModel *recentDirectories) {
Q_ASSERT(recentDirectories != NULL); m_RecentDirectories = recentDirectories;
}
void Commands::CommandManager::InjectDependency(SpellCheck::SpellCheckerService *spellCheckerService) {
Q_ASSERT(spellCheckerService != NULL); m_SpellCheckerService = spellCheckerService;
}
void Commands::CommandManager::InjectDependency(SpellCheck::SpellCheckSuggestionModel *spellCheckSuggestionModel) {
Q_ASSERT(spellCheckSuggestionModel != NULL); m_SpellCheckSuggestionModel = spellCheckSuggestionModel;
m_SpellCheckSuggestionModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Helpers::BackupSaverService *backupSaverService) {
Q_ASSERT(backupSaverService != NULL); m_MetadataSaverService = backupSaverService;
}
void Commands::CommandManager::InjectDependency(Conectivity::TelemetryService *telemetryService) {
Q_ASSERT(telemetryService != NULL); m_TelemetryService = telemetryService;
}
void Commands::CommandManager::InjectDependency(Helpers::UpdateService *updateService) {
Q_ASSERT(updateService != NULL); m_UpdateService = updateService;
}
Commands::CommandResult *Commands::CommandManager::processCommand(Commands::CommandBase *command) const
{
Commands::CommandResult *result = command->execute(this);
delete command;
return result;
}
void Commands::CommandManager::recordHistoryItem(UndoRedo::HistoryItem *historyItem) const
{
if (m_UndoRedoManager) {
m_UndoRedoManager->recordHistoryItem(historyItem);
}
}
void Commands::CommandManager::connectEntitiesSignalsSlots() const
{
QObject::connect(m_SecretsManager, SIGNAL(beforeMasterPasswordChange(QString,QString)),
m_UploadInfoRepository, SLOT(onBeforeMasterPasswordChanged(QString,QString)));
QObject::connect(m_SecretsManager, SIGNAL(afterMasterPasswordReset()),
m_UploadInfoRepository, SLOT(onAfterMasterPasswordReset()));
QObject::connect(m_ArtItemsModel, SIGNAL(needCheckItemsForWarnings(QVector<ArtItemInfo*>)),
m_WarningsManager, SLOT(onCheckWarnings(QVector<ArtItemInfo*>)));
QObject::connect(m_FilteredItemsModel, SIGNAL(needCheckItemsForWarnings(QVector<ArtItemInfo*>)),
m_WarningsManager, SLOT(onCheckWarnings(QVector<ArtItemInfo*>)));
QObject::connect(m_ArtItemsModel, SIGNAL(selectedArtworkRemoved()),
m_FilteredItemsModel, SLOT(onSelectedArtworksRemoved()));
}
void Commands::CommandManager::recodePasswords(const QString &oldMasterPassword,
const QString &newMasterPassword,
const QVector<Models::UploadInfo *> &uploadInfos) const {
foreach (Models::UploadInfo *info, uploadInfos) {
if (info->hasPassword()) {
QString newPassword = m_SecretsManager->recodePassword(
info->getPassword(), oldMasterPassword, newMasterPassword);
info->setPassword(newPassword);
}
}
}
void Commands::CommandManager::combineArtwork(Models::ArtItemInfo *itemInfo) const {
if (m_CombinedArtworksModel) {
m_CombinedArtworksModel->resetModelData();
m_CombinedArtworksModel->initArtworks(QVector<Models::ArtItemInfo*>() << itemInfo);
m_CombinedArtworksModel->recombineArtworks();
submitForSpellCheck(itemInfo->getOrigin());
}
}
void Commands::CommandManager::combineArtworks(const QVector<Models::ArtItemInfo *> &artworks) const {
if (m_CombinedArtworksModel) {
m_CombinedArtworksModel->resetModelData();
m_CombinedArtworksModel->initArtworks(artworks);
m_CombinedArtworksModel->recombineArtworks();
}
}
void Commands::CommandManager::setArtworksForIPTCProcessing(const QVector<Models::ArtworkMetadata*> &artworks) const
{
if (m_IptcProvider) {
m_IptcProvider->setArtworks(artworks);
}
}
void Commands::CommandManager::setArtworksForUpload(const QVector<Models::ArtworkMetadata *> &artworks) const
{
if (m_ArtworkUploader) {
m_ArtworkUploader->setArtworks(artworks);
}
}
void Commands::CommandManager::setArtworksForZipping(const QVector<Models::ArtworkMetadata *> &artworks) const {
if (m_ZipArchiver) {
m_ZipArchiver->setArtworks(artworks);
}
}
/*virtual*/
void Commands::CommandManager::connectArtworkSignals(Models::ArtworkMetadata *metadata) const
{
if (m_ArtItemsModel) {
QObject::connect(metadata, SIGNAL(modifiedChanged(bool)),
m_ArtItemsModel, SLOT(itemModifiedChanged(bool)));
}
if (m_FilteredItemsModel) {
QObject::connect(metadata, SIGNAL(selectedChanged(bool)),
m_FilteredItemsModel, SLOT(itemSelectedChanged(bool)));
}
if (m_ArtworksRepository) {
QObject::connect(metadata, SIGNAL(fileSelectedChanged(QString,bool)),
m_ArtworksRepository, SLOT(fileSelectedChanged(QString,bool)));
}
}
void Commands::CommandManager::updateArtworks(const QVector<int> &indices) const
{
if (m_ArtItemsModel) {
m_ArtItemsModel->updateItemsAtIndices(indices);
}
}
void Commands::CommandManager::addToRecentDirectories(const QString &path) const {
if (m_RecentDirectories) {
m_RecentDirectories->pushDirectory(path);
}
}
#ifdef QT_DEBUG
void Commands::CommandManager::addInitialArtworks(const QStringList &artworksFilepathes)
{
Commands::AddArtworksCommand *command = new Commands::AddArtworksCommand(artworksFilepathes);
CommandResult *result = this->processCommand(command);
delete result;
}
#endif
void Commands::CommandManager::submitForSpellCheck(SpellCheck::ISpellCheckable *item, int keywordIndex) const {
if (m_SettingsModel->getUseSpellCheck()) {
m_SpellCheckerService->submitKeyword(item, keywordIndex);
}
}
void Commands::CommandManager::submitForSpellCheck(const QVector<Models::ArtworkMetadata *> &items) const {
if (m_SettingsModel->getUseSpellCheck() && !items.isEmpty()) {
QVector<SpellCheck::ISpellCheckable*> itemsToSubmit;
int count = items.length();
itemsToSubmit.reserve(count);
for (int i = 0; i < count; ++i) {
itemsToSubmit << items.at(i);
}
this->submitForSpellCheck(itemsToSubmit);
}
}
void Commands::CommandManager::submitForSpellCheck(const QVector<SpellCheck::ISpellCheckable *> &items) const {
if (m_SettingsModel->getUseSpellCheck()) {
m_SpellCheckerService->submitItems(items);
reportUserAction(Conectivity::UserActionSpellCheck);
}
}
void Commands::CommandManager::submitForSpellCheck(SpellCheck::ISpellCheckable *item) const {
if (m_SettingsModel->getUseSpellCheck()) {
m_SpellCheckerService->submitItems(QVector<SpellCheck::ISpellCheckable*>() << item);
}
}
void Commands::CommandManager::setupSpellCheckSuggestions(SpellCheck::ISpellCheckable *item, int index, int flags) {
m_SpellCheckSuggestionModel->setupModel(item, index, flags);
}
void Commands::CommandManager::saveMetadata(Models::ArtworkMetadata *metadata) const {
if (m_SettingsModel->getSaveBackups()) {
m_MetadataSaverService->saveArtwork(metadata);
}
}
void Commands::CommandManager::reportUserAction(Conectivity::UserAction userAction) const {
if (m_TelemetryService) {
m_TelemetryService->reportAction(userAction);
}
}
void Commands::CommandManager::afterConstructionCallback() const {
m_SpellCheckerService->startChecking();
m_MetadataSaverService->startSaving();
m_UpdateService->checkForUpdates();
m_TelemetryService->reportAction(Conectivity::UserActionOpen);
}
void Commands::CommandManager::beforeDestructionCallback() const {
// we have a second for important stuff
m_TelemetryService->reportAction(Conectivity::UserActionClose);
m_SpellCheckerService->stopChecking();
m_MetadataSaverService->stopSaving();
}
<commit_msg>Added linux-related constrain for updates checking<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2015 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "commandmanager.h"
#include "../Models/artworksrepository.h"
#include "../Models/artitemsmodel.h"
#include "../Models/combinedartworksmodel.h"
#include "../Models/iptcprovider.h"
#include "../Models/artworkuploader.h"
#include "../Models/uploadinforepository.h"
#include "../Models/warningsmanager.h"
#include "../Models/uploadinfo.h"
#include "../Models/artworkmetadata.h"
#include "../Encryption/secretsmanager.h"
#include "../UndoRedo/undoredomanager.h"
#include "../Models/ziparchiver.h"
#include "../Suggestion/keywordssuggestor.h"
#include "../Commands/addartworkscommand.h"
#include "../Models/filteredartitemsproxymodel.h"
#include "../Models/recentdirectoriesmodel.h"
#include "../Models/artiteminfo.h"
#include "../SpellCheck/spellcheckerservice.h"
#include "../Models/settingsmodel.h"
#include "../SpellCheck/spellchecksuggestionmodel.h"
#include "../SpellCheck/ispellcheckable.h"
#include "../Helpers/backupsaverservice.h"
#include "../Conectivity/telemetryservice.h"
#include "../Helpers/updateservice.h"
void Commands::CommandManager::InjectDependency(Models::ArtworksRepository *artworkRepository) {
Q_ASSERT(artworkRepository != NULL); m_ArtworksRepository = artworkRepository;
m_ArtworksRepository->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::ArtItemsModel *artItemsModel) {
Q_ASSERT(artItemsModel != NULL); m_ArtItemsModel = artItemsModel;
m_ArtItemsModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::FilteredArtItemsProxyModel *filteredItemsModel) {
Q_ASSERT(filteredItemsModel != NULL); m_FilteredItemsModel = filteredItemsModel;
m_FilteredItemsModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::CombinedArtworksModel *combinedArtworksModel) {
Q_ASSERT(combinedArtworksModel != NULL); m_CombinedArtworksModel = combinedArtworksModel;
m_CombinedArtworksModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::IptcProvider *iptcProvider) {
Q_ASSERT(iptcProvider != NULL); m_IptcProvider = iptcProvider;
m_IptcProvider->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::ArtworkUploader *artworkUploader) {
Q_ASSERT(artworkUploader != NULL); m_ArtworkUploader = artworkUploader;
m_ArtworkUploader->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::UploadInfoRepository *uploadInfoRepository) {
Q_ASSERT(uploadInfoRepository != NULL); m_UploadInfoRepository = uploadInfoRepository;
m_UploadInfoRepository->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::WarningsManager *warningsManager) {
Q_ASSERT(warningsManager != NULL); m_WarningsManager = warningsManager;
m_WarningsManager->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Encryption::SecretsManager *secretsManager) {
Q_ASSERT(secretsManager != NULL); m_SecretsManager = secretsManager;
m_SecretsManager->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(UndoRedo::UndoRedoManager *undoRedoManager) {
Q_ASSERT(undoRedoManager != NULL); m_UndoRedoManager = undoRedoManager;
m_UndoRedoManager->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::ZipArchiver *zipArchiver)
{
Q_ASSERT(zipArchiver != NULL); m_ZipArchiver = zipArchiver;
m_ZipArchiver->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Suggestion::KeywordsSuggestor *keywordsSuggestor)
{
Q_ASSERT(keywordsSuggestor != NULL); m_KeywordsSuggestor = keywordsSuggestor;
m_KeywordsSuggestor->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Models::SettingsModel *settingsModel) {
Q_ASSERT(settingsModel != NULL); m_SettingsModel = settingsModel;
}
void Commands::CommandManager::InjectDependency(Models::RecentDirectoriesModel *recentDirectories) {
Q_ASSERT(recentDirectories != NULL); m_RecentDirectories = recentDirectories;
}
void Commands::CommandManager::InjectDependency(SpellCheck::SpellCheckerService *spellCheckerService) {
Q_ASSERT(spellCheckerService != NULL); m_SpellCheckerService = spellCheckerService;
}
void Commands::CommandManager::InjectDependency(SpellCheck::SpellCheckSuggestionModel *spellCheckSuggestionModel) {
Q_ASSERT(spellCheckSuggestionModel != NULL); m_SpellCheckSuggestionModel = spellCheckSuggestionModel;
m_SpellCheckSuggestionModel->setCommandManager(this);
}
void Commands::CommandManager::InjectDependency(Helpers::BackupSaverService *backupSaverService) {
Q_ASSERT(backupSaverService != NULL); m_MetadataSaverService = backupSaverService;
}
void Commands::CommandManager::InjectDependency(Conectivity::TelemetryService *telemetryService) {
Q_ASSERT(telemetryService != NULL); m_TelemetryService = telemetryService;
}
void Commands::CommandManager::InjectDependency(Helpers::UpdateService *updateService) {
Q_ASSERT(updateService != NULL); m_UpdateService = updateService;
}
Commands::CommandResult *Commands::CommandManager::processCommand(Commands::CommandBase *command) const
{
Commands::CommandResult *result = command->execute(this);
delete command;
return result;
}
void Commands::CommandManager::recordHistoryItem(UndoRedo::HistoryItem *historyItem) const
{
if (m_UndoRedoManager) {
m_UndoRedoManager->recordHistoryItem(historyItem);
}
}
void Commands::CommandManager::connectEntitiesSignalsSlots() const
{
QObject::connect(m_SecretsManager, SIGNAL(beforeMasterPasswordChange(QString,QString)),
m_UploadInfoRepository, SLOT(onBeforeMasterPasswordChanged(QString,QString)));
QObject::connect(m_SecretsManager, SIGNAL(afterMasterPasswordReset()),
m_UploadInfoRepository, SLOT(onAfterMasterPasswordReset()));
QObject::connect(m_ArtItemsModel, SIGNAL(needCheckItemsForWarnings(QVector<ArtItemInfo*>)),
m_WarningsManager, SLOT(onCheckWarnings(QVector<ArtItemInfo*>)));
QObject::connect(m_FilteredItemsModel, SIGNAL(needCheckItemsForWarnings(QVector<ArtItemInfo*>)),
m_WarningsManager, SLOT(onCheckWarnings(QVector<ArtItemInfo*>)));
QObject::connect(m_ArtItemsModel, SIGNAL(selectedArtworkRemoved()),
m_FilteredItemsModel, SLOT(onSelectedArtworksRemoved()));
}
void Commands::CommandManager::recodePasswords(const QString &oldMasterPassword,
const QString &newMasterPassword,
const QVector<Models::UploadInfo *> &uploadInfos) const {
foreach (Models::UploadInfo *info, uploadInfos) {
if (info->hasPassword()) {
QString newPassword = m_SecretsManager->recodePassword(
info->getPassword(), oldMasterPassword, newMasterPassword);
info->setPassword(newPassword);
}
}
}
void Commands::CommandManager::combineArtwork(Models::ArtItemInfo *itemInfo) const {
if (m_CombinedArtworksModel) {
m_CombinedArtworksModel->resetModelData();
m_CombinedArtworksModel->initArtworks(QVector<Models::ArtItemInfo*>() << itemInfo);
m_CombinedArtworksModel->recombineArtworks();
submitForSpellCheck(itemInfo->getOrigin());
}
}
void Commands::CommandManager::combineArtworks(const QVector<Models::ArtItemInfo *> &artworks) const {
if (m_CombinedArtworksModel) {
m_CombinedArtworksModel->resetModelData();
m_CombinedArtworksModel->initArtworks(artworks);
m_CombinedArtworksModel->recombineArtworks();
}
}
void Commands::CommandManager::setArtworksForIPTCProcessing(const QVector<Models::ArtworkMetadata*> &artworks) const
{
if (m_IptcProvider) {
m_IptcProvider->setArtworks(artworks);
}
}
void Commands::CommandManager::setArtworksForUpload(const QVector<Models::ArtworkMetadata *> &artworks) const
{
if (m_ArtworkUploader) {
m_ArtworkUploader->setArtworks(artworks);
}
}
void Commands::CommandManager::setArtworksForZipping(const QVector<Models::ArtworkMetadata *> &artworks) const {
if (m_ZipArchiver) {
m_ZipArchiver->setArtworks(artworks);
}
}
/*virtual*/
void Commands::CommandManager::connectArtworkSignals(Models::ArtworkMetadata *metadata) const
{
if (m_ArtItemsModel) {
QObject::connect(metadata, SIGNAL(modifiedChanged(bool)),
m_ArtItemsModel, SLOT(itemModifiedChanged(bool)));
}
if (m_FilteredItemsModel) {
QObject::connect(metadata, SIGNAL(selectedChanged(bool)),
m_FilteredItemsModel, SLOT(itemSelectedChanged(bool)));
}
if (m_ArtworksRepository) {
QObject::connect(metadata, SIGNAL(fileSelectedChanged(QString,bool)),
m_ArtworksRepository, SLOT(fileSelectedChanged(QString,bool)));
}
}
void Commands::CommandManager::updateArtworks(const QVector<int> &indices) const
{
if (m_ArtItemsModel) {
m_ArtItemsModel->updateItemsAtIndices(indices);
}
}
void Commands::CommandManager::addToRecentDirectories(const QString &path) const {
if (m_RecentDirectories) {
m_RecentDirectories->pushDirectory(path);
}
}
#ifdef QT_DEBUG
void Commands::CommandManager::addInitialArtworks(const QStringList &artworksFilepathes)
{
Commands::AddArtworksCommand *command = new Commands::AddArtworksCommand(artworksFilepathes);
CommandResult *result = this->processCommand(command);
delete result;
}
#endif
void Commands::CommandManager::submitForSpellCheck(SpellCheck::ISpellCheckable *item, int keywordIndex) const {
if (m_SettingsModel->getUseSpellCheck()) {
m_SpellCheckerService->submitKeyword(item, keywordIndex);
}
}
void Commands::CommandManager::submitForSpellCheck(const QVector<Models::ArtworkMetadata *> &items) const {
if (m_SettingsModel->getUseSpellCheck() && !items.isEmpty()) {
QVector<SpellCheck::ISpellCheckable*> itemsToSubmit;
int count = items.length();
itemsToSubmit.reserve(count);
for (int i = 0; i < count; ++i) {
itemsToSubmit << items.at(i);
}
this->submitForSpellCheck(itemsToSubmit);
}
}
void Commands::CommandManager::submitForSpellCheck(const QVector<SpellCheck::ISpellCheckable *> &items) const {
if (m_SettingsModel->getUseSpellCheck()) {
m_SpellCheckerService->submitItems(items);
reportUserAction(Conectivity::UserActionSpellCheck);
}
}
void Commands::CommandManager::submitForSpellCheck(SpellCheck::ISpellCheckable *item) const {
if (m_SettingsModel->getUseSpellCheck()) {
m_SpellCheckerService->submitItems(QVector<SpellCheck::ISpellCheckable*>() << item);
}
}
void Commands::CommandManager::setupSpellCheckSuggestions(SpellCheck::ISpellCheckable *item, int index, int flags) {
m_SpellCheckSuggestionModel->setupModel(item, index, flags);
}
void Commands::CommandManager::saveMetadata(Models::ArtworkMetadata *metadata) const {
if (m_SettingsModel->getSaveBackups()) {
m_MetadataSaverService->saveArtwork(metadata);
}
}
void Commands::CommandManager::reportUserAction(Conectivity::UserAction userAction) const {
if (m_TelemetryService) {
m_TelemetryService->reportAction(userAction);
}
}
void Commands::CommandManager::afterConstructionCallback() const {
m_SpellCheckerService->startChecking();
m_MetadataSaverService->startSaving();
#ifndef Q_OS_LINUX
m_UpdateService->checkForUpdates();
#endif
m_TelemetryService->reportAction(Conectivity::UserActionOpen);
}
void Commands::CommandManager::beforeDestructionCallback() const {
// we have a second for important stuff
m_TelemetryService->reportAction(Conectivity::UserActionClose);
m_SpellCheckerService->stopChecking();
m_MetadataSaverService->stopSaving();
}
<|endoftext|>
|
<commit_before>//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
/*! \file
\brief Inline definitions for prob::mean
*/
namespace prob
{
namespace mean
{
template <typename FwdIter, typename DataType>
inline
DataType
arithmetic
( FwdIter const & beg
, FwdIter const & end
)
{
DataType mean(dat::nullValue<DataType>());
if (beg != end)
{
DataType const sum
(std::accumulate(beg, end, static_cast<DataType>(0)));
size_t const numSamps(std::distance(beg, end));
mean = (1./(double)numSamps) * sum;
}
return mean;
}
template <typename FwdIter, typename DataType = double>
inline
DataType
geometric
( FwdIter const & beg
, FwdIter const & end
)
{
DataType mean(dat::nullValue<DataType>());
if (beg != end)
{
double sumLogs{ 0. };
double count{ 0. };
bool hitAnyZeros{ false };
for (FwdIter iter{beg} ; end != iter ; ++iter)
{
double const & value = *iter;
if (! (0. < value))
{
if (value < 0.)
{
count = 0u;
break;
}
else // == 0.
{
hitAnyZeros = true;
}
}
sumLogs += std::log(value);
count += 1.;
}
if (0. < count)
{
if (hitAnyZeros)
{
mean = 0.;
}
else // all samples were positive
{
double const aveLog{ (1./count) * sumLogs };
mean = std::exp(aveLog);
}
}
}
return mean;
}
template <typename FwdIter, typename DataType = double>
inline
DataType
harmonic
( FwdIter const & beg
, FwdIter const & end
)
{
DataType mean(dat::nullValue<DataType>());
if (beg != end)
{
double sumInvs{ 0. };
double count{ 0. };
for (FwdIter iter{beg} ; end != iter ; ++iter)
{
double const & value = *iter;
if (! (0. < value))
{
count = 0u;
break;
}
sumInvs += (1. / value);
count += 1.;
}
if (0. < count)
{
if (0. < sumInvs)
{
mean = count / sumInvs;
}
}
}
return mean;
}
} // mean
} // prob
<commit_msg>libprob/mean factored mean computation logic into template function<commit_after>//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
/*! \file
\brief Inline definitions for prob::mean
*/
namespace prob
{
namespace mean
{
template <typename FwdIter, typename DataType>
inline
DataType
arithmetic
( FwdIter const & beg
, FwdIter const & end
)
{
DataType mean(dat::nullValue<DataType>());
if (beg != end)
{
DataType const sum
(std::accumulate(beg, end, static_cast<DataType>(0)));
size_t const numSamps(std::distance(beg, end));
mean = (1./(double)numSamps) * sum;
}
return mean;
}
namespace priv
{
//! Generic sample accumulation and normalization
template
< typename FwdIter
, typename FuncFwd
, typename FuncInv
, typename DataType = double
>
inline
DataType
meanFor
( FwdIter const & beg
, FwdIter const & end
, FuncFwd const & fwdFunc
, FuncInv const & invFunc
)
{
DataType mean(dat::nullValue<DataType>());
if (beg != end)
{
double sumFwd{ 0u };
size_t count{ 0u };
bool hitAnyZeros{ false };
for (FwdIter iter{beg} ; end != iter ; ++iter)
{
double const & value = *iter;
if (! (0. < value))
{
if (value < 0.)
{
count = 0u;
break;
}
else // == 0.
{
hitAnyZeros = true;
}
}
sumFwd += fwdFunc(value);
++count;
}
if (0u < count)
{
if (hitAnyZeros)
{
mean = 0.;
}
else // all samples were positive
{
double const aveFwd{ (1./(double)count) * sumFwd };
mean = invFunc(aveFwd);
}
}
}
return mean;
}
//! Functions that define the geometric mean
namespace geo
{
//! Forward function is logarithm
inline
double
funcFwd
( double const & arg
)
{
return std::log(arg);
}
//! Inverse function is exponential
inline
double
funcInv
( double const & arg
)
{
return std::exp(arg);
}
}
//! Functions that define the harmonic mean
namespace har
{
//! Reciprocal is both forward and inverse function
inline
double
funcRecip
( double const & arg
)
{
return { 1. / arg };
}
}
}
template <typename FwdIter, typename DataType = double>
inline
DataType
geometric
( FwdIter const & beg
, FwdIter const & end
)
{
return priv::meanFor(beg, end, priv::geo::funcFwd, priv::geo::funcInv);
}
template <typename FwdIter, typename DataType = double>
inline
DataType
harmonic
( FwdIter const & beg
, FwdIter const & end
)
{
return priv::meanFor(beg, end, priv::har::funcRecip, priv::har::funcRecip);
}
} // mean
} // prob
<|endoftext|>
|
<commit_before>/*
* Copyright 2022 Google LLC
*
* 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 "libs/base/ipc.h"
#include "libs/base/check.h"
#include "libs/base/tasks.h"
#include "third_party/nxp/rt1176-sdk/middleware/multicore/mcmgr/src/mcmgr.h"
namespace coralmicro {
extern "C" uint32_t __RPMSG_SH_MEM_START[];
void Ipc::FreeRtosMessageEventHandler(uint16_t eventData) {
BaseType_t higher_priority_woken = pdFALSE;
xStreamBufferSendCompletedFromISR(
reinterpret_cast<StreamBufferHandle_t>(
reinterpret_cast<uint32_t>(__RPMSG_SH_MEM_START) | eventData),
&higher_priority_woken);
portYIELD_FROM_ISR(higher_priority_woken);
}
void Ipc::SendMessage(const IpcMessage& message) {
if (!tx_task_ || !tx_semaphore_) {
return;
}
// TODO(ljonas): Check usage of eSetValueWithOverwrite.
xTaskNotifyIndexed(tx_task_, kSendMessageNotification,
reinterpret_cast<uint32_t>(&message),
eSetValueWithOverwrite);
CHECK(xSemaphoreTake(tx_semaphore_, portMAX_DELAY) == pdTRUE);
}
void Ipc::TxTaskFn() {
while (true) {
IpcMessage* message;
xTaskNotifyWaitIndexed(kSendMessageNotification, 0, 0,
reinterpret_cast<uint32_t*>(&message),
portMAX_DELAY);
xMessageBufferSend(tx_queue_->message_buffer, message, sizeof(*message),
portMAX_DELAY);
CHECK(xSemaphoreGive(tx_semaphore_) == pdTRUE);
}
}
void Ipc::RxTaskFn() {
while (true) {
IpcMessage rx_message;
size_t rx_bytes =
xMessageBufferReceive(rx_queue_->message_buffer, &rx_message,
sizeof(rx_message), portMAX_DELAY);
if (rx_bytes == 0) continue;
switch (rx_message.type) {
case IpcMessageType::kSystem:
HandleSystemMessage(rx_message.message.system);
break;
case IpcMessageType::kApp:
HandleAppMessage(rx_message.message.data);
break;
default:
printf("Unhandled IPC message type %d\r\n",
static_cast<int>(rx_message.type));
break;
}
}
}
void Ipc::Init() {
tx_semaphore_ = xSemaphoreCreateBinary();
CHECK(tx_semaphore_);
MCMGR_RegisterEvent(kMCMGR_FreeRtosMessageBuffersEvent,
StaticFreeRtosMessageEventHandler, this);
CHECK(xTaskCreate(Ipc::StaticTxTaskFn, "ipc_tx_task",
configMINIMAL_STACK_SIZE * 10, this, kIpcTaskPriority,
&tx_task_) == pdPASS);
CHECK(xTaskCreate(Ipc::StaticRxTaskFn, "ipc_rx_task",
configMINIMAL_STACK_SIZE * 10, this, kIpcTaskPriority,
&rx_task_) == pdPASS);
vTaskSuspend(tx_task_);
vTaskSuspend(rx_task_);
}
} // namespace coralmicro
<commit_msg>Fix IPC concurrency issue<commit_after>/*
* Copyright 2022 Google LLC
*
* 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 "libs/base/ipc.h"
#include "libs/base/check.h"
#include "libs/base/tasks.h"
#include "third_party/nxp/rt1176-sdk/middleware/multicore/mcmgr/src/mcmgr.h"
namespace coralmicro {
extern "C" uint32_t __RPMSG_SH_MEM_START[];
void Ipc::FreeRtosMessageEventHandler(uint16_t eventData) {
BaseType_t higher_priority_woken = pdFALSE;
xStreamBufferSendCompletedFromISR(
reinterpret_cast<StreamBufferHandle_t>(
reinterpret_cast<uint32_t>(__RPMSG_SH_MEM_START) | eventData),
&higher_priority_woken);
portYIELD_FROM_ISR(higher_priority_woken);
}
void Ipc::SendMessage(const IpcMessage& message) {
if (!tx_task_ || !tx_semaphore_) {
return;
}
while (xTaskNotifyIndexed(tx_task_, kSendMessageNotification,
reinterpret_cast<uint32_t>(&message),
eSetValueWithoutOverwrite) == pdFALSE) {
taskYIELD();
}
CHECK(xSemaphoreTake(tx_semaphore_, portMAX_DELAY) == pdTRUE);
}
void Ipc::TxTaskFn() {
while (true) {
IpcMessage* message;
xTaskNotifyWaitIndexed(kSendMessageNotification, 0, 0,
reinterpret_cast<uint32_t*>(&message),
portMAX_DELAY);
xMessageBufferSend(tx_queue_->message_buffer, message, sizeof(*message),
portMAX_DELAY);
CHECK(xSemaphoreGive(tx_semaphore_) == pdTRUE);
}
}
void Ipc::RxTaskFn() {
while (true) {
IpcMessage rx_message;
size_t rx_bytes =
xMessageBufferReceive(rx_queue_->message_buffer, &rx_message,
sizeof(rx_message), portMAX_DELAY);
if (rx_bytes == 0) continue;
switch (rx_message.type) {
case IpcMessageType::kSystem:
HandleSystemMessage(rx_message.message.system);
break;
case IpcMessageType::kApp:
HandleAppMessage(rx_message.message.data);
break;
default:
printf("Unhandled IPC message type %d\r\n",
static_cast<int>(rx_message.type));
break;
}
}
}
void Ipc::Init() {
tx_semaphore_ = xSemaphoreCreateBinary();
CHECK(tx_semaphore_);
MCMGR_RegisterEvent(kMCMGR_FreeRtosMessageBuffersEvent,
StaticFreeRtosMessageEventHandler, this);
CHECK(xTaskCreate(Ipc::StaticTxTaskFn, "ipc_tx_task",
configMINIMAL_STACK_SIZE * 10, this, kIpcTaskPriority,
&tx_task_) == pdPASS);
CHECK(xTaskCreate(Ipc::StaticRxTaskFn, "ipc_rx_task",
configMINIMAL_STACK_SIZE * 10, this, kIpcTaskPriority,
&rx_task_) == pdPASS);
vTaskSuspend(tx_task_);
vTaskSuspend(rx_task_);
}
} // namespace coralmicro
<|endoftext|>
|
<commit_before>#ifndef ITER_ZIP_HPP_
#define ITER_ZIP_HPP_
#include "iterbase.hpp"
#include <iterator>
#include <tuple>
#include <utility>
namespace iter {
template <typename... RestContainers>
class Zipped;
template <typename... Containers>
Zipped<Containers...> zip(Containers&&...);
// specialization for at least 1 template argument
template <typename Container, typename... RestContainers>
class Zipped <Container, RestContainers...> {
using ZipIterDeref =
std::tuple<iterator_deref<Container>,
iterator_deref<RestContainers>...>;
friend Zipped zip<Container, RestContainers...>(
Container&&, RestContainers&&...);
template <typename... RC>
friend class Zipped;
private:
Container container;
Zipped<RestContainers...> rest_zipped;
Zipped(Container&& container, RestContainers&&... rest)
: container(std::forward<Container>(container)),
rest_zipped{std::forward<RestContainers>(rest)...}
{ }
public:
class Iterator :
public std::iterator<std::input_iterator_tag, ZipIterDeref>
{
private:
using RestIter =
typename Zipped<RestContainers...>::Iterator;
iterator_type<Container> iter;
RestIter rest_iter;
public:
constexpr static const bool is_base_iter = false;
Iterator(iterator_type<Container> it, const RestIter& rest)
: iter{it},
rest_iter{rest}
{ }
Iterator& operator++() {
++this->iter;
++this->rest_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->iter != other.iter &&
(RestIter::is_base_iter ||
this->rest_iter != other.rest_iter);
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
auto operator*() ->
decltype(std::tuple_cat(
std::tuple<iterator_deref<Container>>{
*this->iter},
*this->rest_iter))
{
return std::tuple_cat(
std::tuple<iterator_deref<Container>>{
*this->iter},
*this->rest_iter);
}
};
Iterator begin() {
return {std::begin(this->container),
std::begin(this->rest_zipped)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->rest_zipped)};
}
};
template <>
class Zipped<> {
public:
class Iterator
: public std::iterator<std::input_iterator_tag, std::tuple<>>
{
public:
constexpr static const bool is_base_iter = true;
Iterator() { }
Iterator(const Iterator&) { }
Iterator& operator=(const Iterator&) { return *this; }
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
return *this;
}
// if this were to return true, there would be no need
// for the is_base_iter static class attribute.
// However, returning false causes an empty zip() call
// to reach the "end" immediately. Returning true here
// instead results in an infinite loop in the zip() case
bool operator!=(const Iterator&) const {
return false;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
std::tuple<> operator*() {
return std::tuple<>{};
}
};
Iterator begin() {
return {};
}
Iterator end() {
return {};
}
};
template <typename... Containers>
Zipped<Containers...> zip(Containers&&... containers) {
return {std::forward<Containers>(containers)...};
}
}
#endif
<commit_msg>moves rather than copies iterators<commit_after>#ifndef ITER_ZIP_HPP_
#define ITER_ZIP_HPP_
#include "iterbase.hpp"
#include <iterator>
#include <tuple>
#include <utility>
namespace iter {
template <typename... RestContainers>
class Zipped;
template <typename... Containers>
Zipped<Containers...> zip(Containers&&...);
// specialization for at least 1 template argument
template <typename Container, typename... RestContainers>
class Zipped <Container, RestContainers...> {
using ZipIterDeref =
std::tuple<iterator_deref<Container>,
iterator_deref<RestContainers>...>;
friend Zipped zip<Container, RestContainers...>(
Container&&, RestContainers&&...);
template <typename... RC>
friend class Zipped;
private:
Container container;
Zipped<RestContainers...> rest_zipped;
Zipped(Container&& container, RestContainers&&... rest)
: container(std::forward<Container>(container)),
rest_zipped{std::forward<RestContainers>(rest)...}
{ }
public:
class Iterator :
public std::iterator<std::input_iterator_tag, ZipIterDeref>
{
private:
using RestIter =
typename Zipped<RestContainers...>::Iterator;
iterator_type<Container> iter;
RestIter rest_iter;
public:
constexpr static const bool is_base_iter = false;
Iterator(iterator_type<Container>&& it, RestIter&& rest)
: iter{std::move(it)},
rest_iter{std::move(rest)}
{ }
Iterator& operator++() {
++this->iter;
++this->rest_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->iter != other.iter &&
(RestIter::is_base_iter ||
this->rest_iter != other.rest_iter);
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
auto operator*() ->
decltype(std::tuple_cat(
std::tuple<iterator_deref<Container>>{
*this->iter},
*this->rest_iter))
{
return std::tuple_cat(
std::tuple<iterator_deref<Container>>{
*this->iter},
*this->rest_iter);
}
};
Iterator begin() {
return {std::begin(this->container),
std::begin(this->rest_zipped)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->rest_zipped)};
}
};
template <>
class Zipped<> {
public:
class Iterator
: public std::iterator<std::input_iterator_tag, std::tuple<>>
{
public:
constexpr static const bool is_base_iter = true;
Iterator() { }
Iterator(const Iterator&) { }
Iterator& operator=(const Iterator&) { return *this; }
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
return *this;
}
// if this were to return true, there would be no need
// for the is_base_iter static class attribute.
// However, returning false causes an empty zip() call
// to reach the "end" immediately. Returning true here
// instead results in an infinite loop in the zip() case
bool operator!=(const Iterator&) const {
return false;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
std::tuple<> operator*() {
return std::tuple<>{};
}
};
Iterator begin() {
return {};
}
Iterator end() {
return {};
}
};
template <typename... Containers>
Zipped<Containers...> zip(Containers&&... containers) {
return {std::forward<Containers>(containers)...};
}
}
#endif
<|endoftext|>
|
<commit_before>//Copyright (c) 2007-2008, Marton Anka
//
//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 "mhook-lib/mhook.h"
//=========================================================================
// Define _NtOpenProcess so we can dynamically bind to the function
//
typedef struct _CLIENT_ID {
DWORD_PTR UniqueProcess;
DWORD_PTR UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef ULONG (WINAPI* _NtOpenProcess)(OUT PHANDLE ProcessHandle,
IN ACCESS_MASK AccessMask, IN PVOID ObjectAttributes,
IN PCLIENT_ID ClientId );
//=========================================================================
// Define _SelectObject so we can dynamically bind to the function
typedef HGDIOBJ (WINAPI* _SelectObject)(HDC hdc, HGDIOBJ hgdiobj);
//=========================================================================
// Define _getaddrinfo so we can dynamically bind to the function
typedef int (WSAAPI* _getaddrinfo)(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res);
//=========================================================================
// Define _HeapAlloc so we can dynamically bind to the function
typedef LPVOID (WINAPI *_HeapAlloc)(HANDLE, DWORD, SIZE_T);
//=========================================================================
// Define _NtClose so we can dynamically bind to the function
typedef ULONG (WINAPI* _NtClose)(IN HANDLE Handle);
//=========================================================================
// Get the current (original) address to the functions to be hooked
//
_NtOpenProcess TrueNtOpenProcess = (_NtOpenProcess)
GetProcAddress(GetModuleHandle(L"ntdll"), "NtOpenProcess");
_SelectObject TrueSelectObject = (_SelectObject)
GetProcAddress(GetModuleHandle(L"gdi32"), "SelectObject");
_getaddrinfo Truegetaddrinfo = (_getaddrinfo)GetProcAddress(GetModuleHandle(L"ws2_32"), "getaddrinfo");
_HeapAlloc TrueHeapAlloc = (_HeapAlloc)GetProcAddress(GetModuleHandle(L"kernel32"), "HeapAlloc");
_NtClose TrueNtClose = (_NtClose)GetProcAddress(GetModuleHandle(L"ntdll"), "NtClose");
//=========================================================================
// This is the function that will replace NtOpenProcess once the hook
// is in place
//
ULONG WINAPI HookNtOpenProcess(OUT PHANDLE ProcessHandle,
IN ACCESS_MASK AccessMask,
IN PVOID ObjectAttributes,
IN PCLIENT_ID ClientId)
{
printf("***** Call to open process %ld\n", (DWORD)ClientId->UniqueProcess);
return TrueNtOpenProcess(ProcessHandle, AccessMask,
ObjectAttributes, ClientId);
}
//=========================================================================
// This is the function that will replace SelectObject once the hook
// is in place
//
HGDIOBJ WINAPI HookSelectobject(HDC hdc, HGDIOBJ hgdiobj)
{
printf("***** Call to SelectObject(0x%p, 0x%p)\n", hdc, hgdiobj);
return TrueSelectObject(hdc, hgdiobj);
}
//=========================================================================
// This is the function that will replace SelectObject once the hook
// is in place
//
int WSAAPI Hookgetaddrinfo(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res)
{
printf("***** Call to getaddrinfo(0x%p, 0x%p, 0x%p, 0x%p)\n", nodename, servname, hints, res);
return Truegetaddrinfo(nodename, servname, hints, res);
}
//=========================================================================
// This is the function that will replace HeapAlloc once the hook
// is in place
//
LPVOID WINAPI HookHeapAlloc(HANDLE a_Handle, DWORD a_Bla, SIZE_T a_Bla2) {
static int recurse = 0;
if (recurse == 0) {
++recurse;
printf("***** Call to HeapAlloc(0x%p, %lu, 0x%p)\n", a_Handle, a_Bla, (LPVOID)a_Bla2);
--recurse;
}
return TrueHeapAlloc(a_Handle, a_Bla, a_Bla2);
}
//=========================================================================
// This is the function that will replace NtClose once the hook
// is in place
//
ULONG WINAPI HookNtClose(HANDLE hHandle) {
printf("***** Call to NtClose(0x%p)\n", hHandle);
return TrueNtClose(hHandle);
}
//=========================================================================
// This is where the work gets done.
//
#ifndef _MSC_VER
int main(int argc, char* argv[])
#else
int wmain(int argc, WCHAR* argv[])
#endif
{
HANDLE hProc = NULL;
// Set the hook
if (Mhook_SetHook((PVOID*)&TrueNtOpenProcess, (PVOID)HookNtOpenProcess)) {
// Now call OpenProcess and observe NtOpenProcess being redirected
// under the hood.
hProc = OpenProcess(PROCESS_ALL_ACCESS,
FALSE, GetCurrentProcessId());
if (hProc) {
printf("Successfully opened self: %p\n", hProc);
CloseHandle(hProc);
} else {
printf("Could not open self: %ld\n", GetLastError());
}
// Remove the hook
Mhook_Unhook((PVOID*)&TrueNtOpenProcess);
}
// Call OpenProces again - this time there won't be a redirection as
// the hook has bee removed.
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
if (hProc) {
printf("Successfully opened self: %p\n", hProc);
CloseHandle(hProc);
} else {
printf("Could not open self: %ld\n", GetLastError());
}
// Test another hook, this time in SelectObject
// (SelectObject is interesting in that on XP x64, the second instruction
// in the trampoline uses IP-relative addressing and we need to do some
// extra work under the hood to make things work properly. This really
// is more of a test case rather than a demo.)
printf("Testing SelectObject.\n");
if (Mhook_SetHook((PVOID*)&TrueSelectObject, (PVOID)HookSelectobject)) {
// error checking omitted for brevity. doesn't matter much
// in this context anyway.
HDC hdc = GetDC(NULL);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbm = CreateCompatibleBitmap(hdc, 32, 32);
HBITMAP hbmOld = (HBITMAP)SelectObject(hdcMem, hbm);
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdc);
// Remove the hook
Mhook_Unhook((PVOID*)&TrueSelectObject);
}
printf("Testing getaddrinfo.\n");
if (Mhook_SetHook((PVOID*)&Truegetaddrinfo, (PVOID)Hookgetaddrinfo)) {
// error checking omitted for brevity. doesn't matter much
// in this context anyway.
WSADATA wd = {0};
WSAStartup(MAKEWORD(2, 2), &wd);
const char* ip = "localhost";
struct addrinfo aiHints;
struct addrinfo *res = NULL;
memset(&aiHints, 0, sizeof(aiHints));
aiHints.ai_family = PF_UNSPEC;
aiHints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(ip, NULL, &aiHints, &res)) {
printf("getaddrinfo failed\n");
} else {
int n = 0;
while(res) {
res = res->ai_next;
n++;
}
printf("got %d addresses\n", n);
}
WSACleanup();
// Remove the hook
Mhook_Unhook((PVOID*)&Truegetaddrinfo);
}
printf("Testing HeapAlloc.\n");
if (Mhook_SetHook((PVOID*)&TrueHeapAlloc, (PVOID)HookHeapAlloc))
{
free(malloc(10));
// Remove the hook
Mhook_Unhook((PVOID*)&TrueHeapAlloc);
}
printf("Testing NtClose.\n");
if (Mhook_SetHook((PVOID*)&TrueNtClose, (PVOID)HookNtClose))
{
CloseHandle(NULL);
// Remove the hook
Mhook_Unhook((PVOID*)&TrueNtClose);
}
return 0;
}
<commit_msg>mhook: Remove HeapAlloc anti-recursion hack.<commit_after>//Copyright (c) 2007-2008, Marton Anka
//
//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 "mhook-lib/mhook.h"
//=========================================================================
// Define _NtOpenProcess so we can dynamically bind to the function
//
typedef struct _CLIENT_ID {
DWORD_PTR UniqueProcess;
DWORD_PTR UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef ULONG (WINAPI* _NtOpenProcess)(OUT PHANDLE ProcessHandle,
IN ACCESS_MASK AccessMask, IN PVOID ObjectAttributes,
IN PCLIENT_ID ClientId );
//=========================================================================
// Define _SelectObject so we can dynamically bind to the function
typedef HGDIOBJ (WINAPI* _SelectObject)(HDC hdc, HGDIOBJ hgdiobj);
//=========================================================================
// Define _getaddrinfo so we can dynamically bind to the function
typedef int (WSAAPI* _getaddrinfo)(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res);
//=========================================================================
// Define _HeapAlloc so we can dynamically bind to the function
typedef LPVOID (WINAPI *_HeapAlloc)(HANDLE, DWORD, SIZE_T);
//=========================================================================
// Define _NtClose so we can dynamically bind to the function
typedef ULONG (WINAPI* _NtClose)(IN HANDLE Handle);
//=========================================================================
// Get the current (original) address to the functions to be hooked
//
_NtOpenProcess TrueNtOpenProcess = (_NtOpenProcess)
GetProcAddress(GetModuleHandle(L"ntdll"), "NtOpenProcess");
_SelectObject TrueSelectObject = (_SelectObject)
GetProcAddress(GetModuleHandle(L"gdi32"), "SelectObject");
_getaddrinfo Truegetaddrinfo = (_getaddrinfo)GetProcAddress(GetModuleHandle(L"ws2_32"), "getaddrinfo");
_HeapAlloc TrueHeapAlloc = (_HeapAlloc)GetProcAddress(GetModuleHandle(L"kernel32"), "HeapAlloc");
_NtClose TrueNtClose = (_NtClose)GetProcAddress(GetModuleHandle(L"ntdll"), "NtClose");
//=========================================================================
// This is the function that will replace NtOpenProcess once the hook
// is in place
//
ULONG WINAPI HookNtOpenProcess(OUT PHANDLE ProcessHandle,
IN ACCESS_MASK AccessMask,
IN PVOID ObjectAttributes,
IN PCLIENT_ID ClientId)
{
printf("***** Call to open process %ld\n", (DWORD)ClientId->UniqueProcess);
return TrueNtOpenProcess(ProcessHandle, AccessMask,
ObjectAttributes, ClientId);
}
//=========================================================================
// This is the function that will replace SelectObject once the hook
// is in place
//
HGDIOBJ WINAPI HookSelectobject(HDC hdc, HGDIOBJ hgdiobj)
{
printf("***** Call to SelectObject(0x%p, 0x%p)\n", hdc, hgdiobj);
return TrueSelectObject(hdc, hgdiobj);
}
//=========================================================================
// This is the function that will replace SelectObject once the hook
// is in place
//
int WSAAPI Hookgetaddrinfo(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res)
{
printf("***** Call to getaddrinfo(0x%p, 0x%p, 0x%p, 0x%p)\n", nodename, servname, hints, res);
return Truegetaddrinfo(nodename, servname, hints, res);
}
//=========================================================================
// This is the function that will replace HeapAlloc once the hook
// is in place
//
LPVOID WINAPI HookHeapAlloc(HANDLE a_Handle, DWORD a_Bla, SIZE_T a_Bla2) {
printf("***** Call to HeapAlloc(0x%p, %lu, 0x%p)\n", a_Handle, a_Bla, (LPVOID)a_Bla2);
return TrueHeapAlloc(a_Handle, a_Bla, a_Bla2);
}
//=========================================================================
// This is the function that will replace NtClose once the hook
// is in place
//
ULONG WINAPI HookNtClose(HANDLE hHandle) {
printf("***** Call to NtClose(0x%p)\n", hHandle);
return TrueNtClose(hHandle);
}
//=========================================================================
// This is where the work gets done.
//
#ifndef _MSC_VER
int main(int argc, char* argv[])
#else
int wmain(int argc, WCHAR* argv[])
#endif
{
HANDLE hProc = NULL;
// Set the hook
if (Mhook_SetHook((PVOID*)&TrueNtOpenProcess, (PVOID)HookNtOpenProcess)) {
// Now call OpenProcess and observe NtOpenProcess being redirected
// under the hood.
hProc = OpenProcess(PROCESS_ALL_ACCESS,
FALSE, GetCurrentProcessId());
if (hProc) {
printf("Successfully opened self: %p\n", hProc);
CloseHandle(hProc);
} else {
printf("Could not open self: %ld\n", GetLastError());
}
// Remove the hook
Mhook_Unhook((PVOID*)&TrueNtOpenProcess);
}
// Call OpenProces again - this time there won't be a redirection as
// the hook has bee removed.
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
if (hProc) {
printf("Successfully opened self: %p\n", hProc);
CloseHandle(hProc);
} else {
printf("Could not open self: %ld\n", GetLastError());
}
// Test another hook, this time in SelectObject
// (SelectObject is interesting in that on XP x64, the second instruction
// in the trampoline uses IP-relative addressing and we need to do some
// extra work under the hood to make things work properly. This really
// is more of a test case rather than a demo.)
printf("Testing SelectObject.\n");
if (Mhook_SetHook((PVOID*)&TrueSelectObject, (PVOID)HookSelectobject)) {
// error checking omitted for brevity. doesn't matter much
// in this context anyway.
HDC hdc = GetDC(NULL);
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbm = CreateCompatibleBitmap(hdc, 32, 32);
HBITMAP hbmOld = (HBITMAP)SelectObject(hdcMem, hbm);
SelectObject(hdcMem, hbmOld);
DeleteObject(hbm);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdc);
// Remove the hook
Mhook_Unhook((PVOID*)&TrueSelectObject);
}
printf("Testing getaddrinfo.\n");
if (Mhook_SetHook((PVOID*)&Truegetaddrinfo, (PVOID)Hookgetaddrinfo)) {
// error checking omitted for brevity. doesn't matter much
// in this context anyway.
WSADATA wd = {0};
WSAStartup(MAKEWORD(2, 2), &wd);
const char* ip = "localhost";
struct addrinfo aiHints;
struct addrinfo *res = NULL;
memset(&aiHints, 0, sizeof(aiHints));
aiHints.ai_family = PF_UNSPEC;
aiHints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(ip, NULL, &aiHints, &res)) {
printf("getaddrinfo failed\n");
} else {
int n = 0;
while(res) {
res = res->ai_next;
n++;
}
printf("got %d addresses\n", n);
}
WSACleanup();
// Remove the hook
Mhook_Unhook((PVOID*)&Truegetaddrinfo);
}
printf("Testing HeapAlloc.\n");
if (Mhook_SetHook((PVOID*)&TrueHeapAlloc, (PVOID)HookHeapAlloc))
{
free(malloc(10));
// Remove the hook
Mhook_Unhook((PVOID*)&TrueHeapAlloc);
}
printf("Testing NtClose.\n");
if (Mhook_SetHook((PVOID*)&TrueNtClose, (PVOID)HookNtClose))
{
CloseHandle(NULL);
// Remove the hook
Mhook_Unhook((PVOID*)&TrueNtClose);
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2015 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 "flutter/lib/ui/compositing/scene_builder.h"
#include "flutter/flow/layers/backdrop_filter_layer.h"
#if defined(OS_FUCHSIA)
#include "flutter/flow/layers/child_scene_layer.h"
#endif
#include "flutter/flow/layers/clip_path_layer.h"
#include "flutter/flow/layers/clip_rect_layer.h"
#include "flutter/flow/layers/clip_rrect_layer.h"
#include "flutter/flow/layers/color_filter_layer.h"
#include "flutter/flow/layers/container_layer.h"
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/flow/layers/opacity_layer.h"
#include "flutter/flow/layers/performance_overlay_layer.h"
#include "flutter/flow/layers/physical_shape_layer.h"
#include "flutter/flow/layers/picture_layer.h"
#include "flutter/flow/layers/shader_mask_layer.h"
#include "flutter/flow/layers/texture_layer.h"
#include "flutter/flow/layers/transform_layer.h"
#include "flutter/fml/build_config.h"
#include "flutter/lib/ui/painting/matrix.h"
#include "flutter/lib/ui/painting/shader.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/window.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
namespace blink {
static void SceneBuilder_constructor(Dart_NativeArguments args) {
DartCallConstructor(&SceneBuilder::create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder);
#define FOR_EACH_BINDING(V) \
V(SceneBuilder, pushTransform) \
V(SceneBuilder, pushClipRect) \
V(SceneBuilder, pushClipRRect) \
V(SceneBuilder, pushClipPath) \
V(SceneBuilder, pushOpacity) \
V(SceneBuilder, pushColorFilter) \
V(SceneBuilder, pushBackdropFilter) \
V(SceneBuilder, pushShaderMask) \
V(SceneBuilder, pushPhysicalShape) \
V(SceneBuilder, pop) \
V(SceneBuilder, addPicture) \
V(SceneBuilder, addTexture) \
V(SceneBuilder, addChildScene) \
V(SceneBuilder, addPerformanceOverlay) \
V(SceneBuilder, setRasterizerTracingThreshold) \
V(SceneBuilder, setCheckerboardOffscreenLayers) \
V(SceneBuilder, setCheckerboardRasterCacheImages) \
V(SceneBuilder, build)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void SceneBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"SceneBuilder_constructor", SceneBuilder_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
static const SkRect kGiantRect = SkRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F);
SceneBuilder::SceneBuilder() {
cull_rects_.push(kGiantRect);
}
SceneBuilder::~SceneBuilder() = default;
void SceneBuilder::pushTransform(const tonic::Float64List& matrix4) {
SkMatrix sk_matrix = ToSkMatrix(matrix4);
SkMatrix inverse_sk_matrix;
SkRect cullRect;
// Perspective projections don't produce rectangles that are useful for
// culling for some reason.
if (!sk_matrix.hasPerspective() && sk_matrix.invert(&inverse_sk_matrix)) {
inverse_sk_matrix.mapRect(&cullRect, cull_rects_.top());
} else {
cullRect = kGiantRect;
}
auto layer = std::make_unique<flow::TransformLayer>();
layer->set_transform(sk_matrix);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushOffset(double dx, double dy) {
SkMatrix sk_matrix = SkMatrix::MakeTrans(dx, dy);
auto layer = std::make_unique<flow::TransformLayer>();
layer->set_transform(sk_matrix);
PushLayer(std::move(layer), cull_rects_.top().makeOffset(-dx, -dy));
}
void SceneBuilder::pushClipRect(double left,
double right,
double top,
double bottom,
int clipBehavior) {
SkRect clipRect = SkRect::MakeLTRB(left, top, right, bottom);
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
SkRect cullRect;
if (!cullRect.intersect(clipRect, cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::ClipRectLayer>(clip_behavior);
layer->set_clip_rect(clipRect);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushClipRRect(const RRect& rrect, int clipBehavior) {
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
SkRect cullRect;
if (!cullRect.intersect(rrect.sk_rrect.rect(), cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::ClipRRectLayer>(clip_behavior);
layer->set_clip_rrect(rrect.sk_rrect);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushClipPath(const CanvasPath* path, int clipBehavior) {
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
FML_DCHECK(clip_behavior != flow::Clip::none);
SkRect cullRect;
if (!cullRect.intersect(path->path().getBounds(), cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::ClipPathLayer>(clip_behavior);
layer->set_clip_path(path->path());
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushOpacity(int alpha) {
auto layer = std::make_unique<flow::OpacityLayer>();
layer->set_alpha(alpha);
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushColorFilter(int color, int blendMode) {
auto layer = std::make_unique<flow::ColorFilterLayer>();
layer->set_color(static_cast<SkColor>(color));
layer->set_blend_mode(static_cast<SkBlendMode>(blendMode));
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushBackdropFilter(ImageFilter* filter) {
auto layer = std::make_unique<flow::BackdropFilterLayer>();
layer->set_filter(filter->filter());
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushShaderMask(Shader* shader,
double maskRectLeft,
double maskRectRight,
double maskRectTop,
double maskRectBottom,
int blendMode) {
SkRect rect = SkRect::MakeLTRB(maskRectLeft, maskRectTop, maskRectRight,
maskRectBottom);
auto layer = std::make_unique<flow::ShaderMaskLayer>();
layer->set_shader(shader->shader());
layer->set_mask_rect(rect);
layer->set_blend_mode(static_cast<SkBlendMode>(blendMode));
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushPhysicalShape(const CanvasPath* path,
double elevation,
int color,
int shadow_color,
int clipBehavior) {
const SkPath& sk_path = path->path();
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
SkRect cullRect;
if (!cullRect.intersect(sk_path.getBounds(), cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::PhysicalShapeLayer>(clip_behavior);
layer->set_path(sk_path);
layer->set_elevation(elevation);
layer->set_color(static_cast<SkColor>(color));
layer->set_shadow_color(static_cast<SkColor>(shadow_color));
layer->set_device_pixel_ratio(
UIDartState::Current()->window()->viewport_metrics().device_pixel_ratio);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pop() {
if (!current_layer_) {
return;
}
cull_rects_.pop();
current_layer_ = current_layer_->parent();
}
void SceneBuilder::addPicture(double dx,
double dy,
Picture* picture,
int hints) {
if (!current_layer_) {
return;
}
SkPoint offset = SkPoint::Make(dx, dy);
SkRect pictureRect = picture->picture()->cullRect();
pictureRect.offset(offset.x(), offset.y());
if (!SkRect::Intersects(pictureRect, cull_rects_.top())) {
return;
}
auto layer = std::make_unique<flow::PictureLayer>();
layer->set_offset(offset);
layer->set_picture(UIDartState::CreateGPUObject(picture->picture()));
layer->set_is_complex(!!(hints & 1));
layer->set_will_change(!!(hints & 2));
current_layer_->Add(std::move(layer));
}
void SceneBuilder::addTexture(double dx,
double dy,
double width,
double height,
int64_t textureId,
bool freeze) {
if (!current_layer_) {
return;
}
auto layer = std::make_unique<flow::TextureLayer>();
layer->set_offset(SkPoint::Make(dx, dy));
layer->set_size(SkSize::Make(width, height));
layer->set_texture_id(textureId);
layer->set_freeze(freeze);
current_layer_->Add(std::move(layer));
}
void SceneBuilder::addChildScene(double dx,
double dy,
double width,
double height,
SceneHost* sceneHost,
bool hitTestable) {
#if defined(OS_FUCHSIA)
if (!current_layer_) {
return;
}
SkRect sceneRect = SkRect::MakeXYWH(dx, dy, width, height);
if (!SkRect::Intersects(sceneRect, cull_rects_.top())) {
return;
}
auto layer = std::make_unique<flow::ChildSceneLayer>();
layer->set_offset(SkPoint::Make(dx, dy));
layer->set_size(SkSize::Make(width, height));
layer->set_export_node_holder(sceneHost->export_node_holder());
layer->set_hit_testable(hitTestable);
current_layer_->Add(std::move(layer));
#endif // defined(OS_FUCHSIA)
}
void SceneBuilder::addPerformanceOverlay(uint64_t enabledOptions,
double left,
double right,
double top,
double bottom) {
if (!current_layer_) {
return;
}
SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
auto layer = std::make_unique<flow::PerformanceOverlayLayer>(enabledOptions);
layer->set_paint_bounds(rect);
current_layer_->Add(std::move(layer));
}
void SceneBuilder::setRasterizerTracingThreshold(uint32_t frameInterval) {
rasterizer_tracing_threshold_ = frameInterval;
}
void SceneBuilder::setCheckerboardRasterCacheImages(bool checkerboard) {
checkerboard_raster_cache_images_ = checkerboard;
}
void SceneBuilder::setCheckerboardOffscreenLayers(bool checkerboard) {
checkerboard_offscreen_layers_ = checkerboard;
}
fml::RefPtr<Scene> SceneBuilder::build() {
fml::RefPtr<Scene> scene = Scene::create(
std::move(root_layer_), rasterizer_tracing_threshold_,
checkerboard_raster_cache_images_, checkerboard_offscreen_layers_);
ClearDartWrapper();
return scene;
}
void SceneBuilder::PushLayer(std::unique_ptr<flow::ContainerLayer> layer,
const SkRect& cullRect) {
FML_DCHECK(layer);
cull_rects_.push(cullRect);
if (!root_layer_) {
root_layer_ = std::move(layer);
current_layer_ = root_layer_.get();
return;
}
if (!current_layer_) {
return;
}
flow::ContainerLayer* newLayer = layer.get();
current_layer_->Add(std::move(layer));
current_layer_ = newLayer;
}
} // namespace blink
<commit_msg>Add missing binding for pushOffset (#6367)<commit_after>// Copyright 2015 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 "flutter/lib/ui/compositing/scene_builder.h"
#include "flutter/flow/layers/backdrop_filter_layer.h"
#if defined(OS_FUCHSIA)
#include "flutter/flow/layers/child_scene_layer.h"
#endif
#include "flutter/flow/layers/clip_path_layer.h"
#include "flutter/flow/layers/clip_rect_layer.h"
#include "flutter/flow/layers/clip_rrect_layer.h"
#include "flutter/flow/layers/color_filter_layer.h"
#include "flutter/flow/layers/container_layer.h"
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/flow/layers/opacity_layer.h"
#include "flutter/flow/layers/performance_overlay_layer.h"
#include "flutter/flow/layers/physical_shape_layer.h"
#include "flutter/flow/layers/picture_layer.h"
#include "flutter/flow/layers/shader_mask_layer.h"
#include "flutter/flow/layers/texture_layer.h"
#include "flutter/flow/layers/transform_layer.h"
#include "flutter/fml/build_config.h"
#include "flutter/lib/ui/painting/matrix.h"
#include "flutter/lib/ui/painting/shader.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/window.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
namespace blink {
static void SceneBuilder_constructor(Dart_NativeArguments args) {
DartCallConstructor(&SceneBuilder::create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder);
#define FOR_EACH_BINDING(V) \
V(SceneBuilder, pushOffset) \
V(SceneBuilder, pushTransform) \
V(SceneBuilder, pushClipRect) \
V(SceneBuilder, pushClipRRect) \
V(SceneBuilder, pushClipPath) \
V(SceneBuilder, pushOpacity) \
V(SceneBuilder, pushColorFilter) \
V(SceneBuilder, pushBackdropFilter) \
V(SceneBuilder, pushShaderMask) \
V(SceneBuilder, pushPhysicalShape) \
V(SceneBuilder, pop) \
V(SceneBuilder, addPicture) \
V(SceneBuilder, addTexture) \
V(SceneBuilder, addChildScene) \
V(SceneBuilder, addPerformanceOverlay) \
V(SceneBuilder, setRasterizerTracingThreshold) \
V(SceneBuilder, setCheckerboardOffscreenLayers) \
V(SceneBuilder, setCheckerboardRasterCacheImages) \
V(SceneBuilder, build)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void SceneBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"SceneBuilder_constructor", SceneBuilder_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
static const SkRect kGiantRect = SkRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F);
SceneBuilder::SceneBuilder() {
cull_rects_.push(kGiantRect);
}
SceneBuilder::~SceneBuilder() = default;
void SceneBuilder::pushTransform(const tonic::Float64List& matrix4) {
SkMatrix sk_matrix = ToSkMatrix(matrix4);
SkMatrix inverse_sk_matrix;
SkRect cullRect;
// Perspective projections don't produce rectangles that are useful for
// culling for some reason.
if (!sk_matrix.hasPerspective() && sk_matrix.invert(&inverse_sk_matrix)) {
inverse_sk_matrix.mapRect(&cullRect, cull_rects_.top());
} else {
cullRect = kGiantRect;
}
auto layer = std::make_unique<flow::TransformLayer>();
layer->set_transform(sk_matrix);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushOffset(double dx, double dy) {
SkMatrix sk_matrix = SkMatrix::MakeTrans(dx, dy);
auto layer = std::make_unique<flow::TransformLayer>();
layer->set_transform(sk_matrix);
PushLayer(std::move(layer), cull_rects_.top().makeOffset(-dx, -dy));
}
void SceneBuilder::pushClipRect(double left,
double right,
double top,
double bottom,
int clipBehavior) {
SkRect clipRect = SkRect::MakeLTRB(left, top, right, bottom);
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
SkRect cullRect;
if (!cullRect.intersect(clipRect, cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::ClipRectLayer>(clip_behavior);
layer->set_clip_rect(clipRect);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushClipRRect(const RRect& rrect, int clipBehavior) {
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
SkRect cullRect;
if (!cullRect.intersect(rrect.sk_rrect.rect(), cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::ClipRRectLayer>(clip_behavior);
layer->set_clip_rrect(rrect.sk_rrect);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushClipPath(const CanvasPath* path, int clipBehavior) {
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
FML_DCHECK(clip_behavior != flow::Clip::none);
SkRect cullRect;
if (!cullRect.intersect(path->path().getBounds(), cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::ClipPathLayer>(clip_behavior);
layer->set_clip_path(path->path());
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pushOpacity(int alpha) {
auto layer = std::make_unique<flow::OpacityLayer>();
layer->set_alpha(alpha);
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushColorFilter(int color, int blendMode) {
auto layer = std::make_unique<flow::ColorFilterLayer>();
layer->set_color(static_cast<SkColor>(color));
layer->set_blend_mode(static_cast<SkBlendMode>(blendMode));
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushBackdropFilter(ImageFilter* filter) {
auto layer = std::make_unique<flow::BackdropFilterLayer>();
layer->set_filter(filter->filter());
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushShaderMask(Shader* shader,
double maskRectLeft,
double maskRectRight,
double maskRectTop,
double maskRectBottom,
int blendMode) {
SkRect rect = SkRect::MakeLTRB(maskRectLeft, maskRectTop, maskRectRight,
maskRectBottom);
auto layer = std::make_unique<flow::ShaderMaskLayer>();
layer->set_shader(shader->shader());
layer->set_mask_rect(rect);
layer->set_blend_mode(static_cast<SkBlendMode>(blendMode));
PushLayer(std::move(layer), cull_rects_.top());
}
void SceneBuilder::pushPhysicalShape(const CanvasPath* path,
double elevation,
int color,
int shadow_color,
int clipBehavior) {
const SkPath& sk_path = path->path();
flow::Clip clip_behavior = static_cast<flow::Clip>(clipBehavior);
SkRect cullRect;
if (!cullRect.intersect(sk_path.getBounds(), cull_rects_.top())) {
cullRect = SkRect::MakeEmpty();
}
auto layer = std::make_unique<flow::PhysicalShapeLayer>(clip_behavior);
layer->set_path(sk_path);
layer->set_elevation(elevation);
layer->set_color(static_cast<SkColor>(color));
layer->set_shadow_color(static_cast<SkColor>(shadow_color));
layer->set_device_pixel_ratio(
UIDartState::Current()->window()->viewport_metrics().device_pixel_ratio);
PushLayer(std::move(layer), cullRect);
}
void SceneBuilder::pop() {
if (!current_layer_) {
return;
}
cull_rects_.pop();
current_layer_ = current_layer_->parent();
}
void SceneBuilder::addPicture(double dx,
double dy,
Picture* picture,
int hints) {
if (!current_layer_) {
return;
}
SkPoint offset = SkPoint::Make(dx, dy);
SkRect pictureRect = picture->picture()->cullRect();
pictureRect.offset(offset.x(), offset.y());
if (!SkRect::Intersects(pictureRect, cull_rects_.top())) {
return;
}
auto layer = std::make_unique<flow::PictureLayer>();
layer->set_offset(offset);
layer->set_picture(UIDartState::CreateGPUObject(picture->picture()));
layer->set_is_complex(!!(hints & 1));
layer->set_will_change(!!(hints & 2));
current_layer_->Add(std::move(layer));
}
void SceneBuilder::addTexture(double dx,
double dy,
double width,
double height,
int64_t textureId,
bool freeze) {
if (!current_layer_) {
return;
}
auto layer = std::make_unique<flow::TextureLayer>();
layer->set_offset(SkPoint::Make(dx, dy));
layer->set_size(SkSize::Make(width, height));
layer->set_texture_id(textureId);
layer->set_freeze(freeze);
current_layer_->Add(std::move(layer));
}
void SceneBuilder::addChildScene(double dx,
double dy,
double width,
double height,
SceneHost* sceneHost,
bool hitTestable) {
#if defined(OS_FUCHSIA)
if (!current_layer_) {
return;
}
SkRect sceneRect = SkRect::MakeXYWH(dx, dy, width, height);
if (!SkRect::Intersects(sceneRect, cull_rects_.top())) {
return;
}
auto layer = std::make_unique<flow::ChildSceneLayer>();
layer->set_offset(SkPoint::Make(dx, dy));
layer->set_size(SkSize::Make(width, height));
layer->set_export_node_holder(sceneHost->export_node_holder());
layer->set_hit_testable(hitTestable);
current_layer_->Add(std::move(layer));
#endif // defined(OS_FUCHSIA)
}
void SceneBuilder::addPerformanceOverlay(uint64_t enabledOptions,
double left,
double right,
double top,
double bottom) {
if (!current_layer_) {
return;
}
SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
auto layer = std::make_unique<flow::PerformanceOverlayLayer>(enabledOptions);
layer->set_paint_bounds(rect);
current_layer_->Add(std::move(layer));
}
void SceneBuilder::setRasterizerTracingThreshold(uint32_t frameInterval) {
rasterizer_tracing_threshold_ = frameInterval;
}
void SceneBuilder::setCheckerboardRasterCacheImages(bool checkerboard) {
checkerboard_raster_cache_images_ = checkerboard;
}
void SceneBuilder::setCheckerboardOffscreenLayers(bool checkerboard) {
checkerboard_offscreen_layers_ = checkerboard;
}
fml::RefPtr<Scene> SceneBuilder::build() {
fml::RefPtr<Scene> scene = Scene::create(
std::move(root_layer_), rasterizer_tracing_threshold_,
checkerboard_raster_cache_images_, checkerboard_offscreen_layers_);
ClearDartWrapper();
return scene;
}
void SceneBuilder::PushLayer(std::unique_ptr<flow::ContainerLayer> layer,
const SkRect& cullRect) {
FML_DCHECK(layer);
cull_rects_.push(cullRect);
if (!root_layer_) {
root_layer_ = std::move(layer);
current_layer_ = root_layer_.get();
return;
}
if (!current_layer_) {
return;
}
flow::ContainerLayer* newLayer = layer.get();
current_layer_->Add(std::move(layer));
current_layer_ = newLayer;
}
} // namespace blink
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <pcl/filters/fast_bilateral.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
float default_sigma_s = 15;
float default_sigma_r = 0.05;
bool default_early_division = false;
void
printHelp (int, char **argv)
{
print_info ("Note: only works with organized point clouds\n");
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -sigma_s X = size of the filter window (default: ");
print_value ("%f", default_sigma_s); print_info (")\n");
print_info (" -sigma_r X = standard deviation of the filter (default: ");
print_value ("%f", default_sigma_r); print_info (")\n");
print_info (" -early_division X = early division (default: ");
print_value ("%d", default_early_division); print_info (")\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
float sigma_s, float sigma_r, bool early_division)
{
PointCloud<PointXYZRGBA>::Ptr cloud (new PointCloud<PointXYZRGBA> ());
fromROSMsg (*input, *cloud);
FastBilateralFilter<PointXYZRGBA> filter;
filter.setSigmaS (sigma_s);
filter.setSigmaR (sigma_r);
filter.setEarlyDivision (early_division);
filter.setInputCloud (cloud);
PointCloud<PointXYZRGBA>::Ptr out_cloud (new PointCloud<PointXYZRGBA> ());
TicToc tt;
tt.tic ();
filter.filter (*out_cloud);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", out_cloud->width * out_cloud->height); print_info (" points]\n");
toROSMsg (*out_cloud, output);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output, Eigen::Vector4f::Zero (),
Eigen::Quaternionf::Identity (), true);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Moving Least Squares smoothing of a point cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Command line parsing
float sigma_s = default_sigma_s;
float sigma_r = default_sigma_r;
bool early_division = default_early_division;
parse_argument (argc, argv, "-sigma_s", sigma_s);
parse_argument (argc, argv, "-sigma_r", sigma_r);
parse_argument (argc, argv, "-early_division", early_division);
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the filter
sensor_msgs::PointCloud2 output;
compute (cloud, output, sigma_s, sigma_r, early_division);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<commit_msg>fixed compiler warnings<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <pcl/filters/fast_bilateral.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
float default_sigma_s = 15.0f;
float default_sigma_r = 0.05f;
bool default_early_division = false;
void
printHelp (int, char **argv)
{
print_info ("Note: only works with organized point clouds\n");
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -sigma_s X = size of the filter window (default: ");
print_value ("%f", default_sigma_s); print_info (")\n");
print_info (" -sigma_r X = standard deviation of the filter (default: ");
print_value ("%f", default_sigma_r); print_info (")\n");
print_info (" -early_division X = early division (default: ");
print_value ("%d", default_early_division); print_info (")\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
float sigma_s, float sigma_r, bool early_division)
{
PointCloud<PointXYZRGBA>::Ptr cloud (new PointCloud<PointXYZRGBA> ());
fromROSMsg (*input, *cloud);
FastBilateralFilter<PointXYZRGBA> filter;
filter.setSigmaS (sigma_s);
filter.setSigmaR (sigma_r);
filter.setEarlyDivision (early_division);
filter.setInputCloud (cloud);
PointCloud<PointXYZRGBA>::Ptr out_cloud (new PointCloud<PointXYZRGBA> ());
TicToc tt;
tt.tic ();
filter.filter (*out_cloud);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", out_cloud->width * out_cloud->height); print_info (" points]\n");
toROSMsg (*out_cloud, output);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output, Eigen::Vector4f::Zero (),
Eigen::Quaternionf::Identity (), true);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Moving Least Squares smoothing of a point cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Command line parsing
float sigma_s = default_sigma_s;
float sigma_r = default_sigma_r;
bool early_division = default_early_division;
parse_argument (argc, argv, "-sigma_s", sigma_s);
parse_argument (argc, argv, "-sigma_r", sigma_r);
parse_argument (argc, argv, "-early_division", early_division);
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the filter
sensor_msgs::PointCloud2 output;
compute (cloud, output, sigma_s, sigma_r, early_division);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<|endoftext|>
|
<commit_before><commit_msg>No need to go via floating-point calculations<commit_after><|endoftext|>
|
<commit_before>#include "page_manager.h"
#include "../utils/utils.h"
#include "page.h"
#include "../utils/fs.h"
#include "../utils/locker.h"
#include <cstring>
#include <queue>
#include <thread>
using namespace dariadb::storage;
dariadb::storage::PageManager* PageManager::_instance = nullptr;
class PageManager::Private
{
public:
Private(const PageManager::Params¶m) :
_cur_page(nullptr),
_param(param)
{
_write_thread_stop = false;
_write_thread_handle = std::move(std::thread{ &PageManager::Private::write_thread,this });
}
~Private() {
_write_thread_stop = true;
_data_cond.notify_one();
_write_thread_handle.join();
if (_cur_page != nullptr) {
delete _cur_page;
_cur_page = nullptr;
}
}
uint64_t calc_page_size()const {
auto sz_index = sizeof(Page_ChunkIndex)*_param.chunk_per_storage;
auto sz_buffers = _param.chunk_per_storage*_param.chunk_size;
return sizeof(PageHeader)
+ sz_index
+ sz_buffers;
}
Page* create_page() {
if (!dariadb::utils::fs::path_exists(_param.path)) {
dariadb::utils::fs::mkdir(_param.path);
}
std::string page_name = ((_param.mode == MODE::SINGLE) ? "single.page" : "_.page");
std::string file_name = dariadb::utils::fs::append_path(_param.path, page_name);
Page*res = nullptr;
if (!utils::fs::path_exists(file_name)) {
auto sz = calc_page_size();
res = Page::create(file_name, sz,_param.chunk_per_storage,_param.chunk_size,_param.mode);
}
else {
res = Page::open(file_name);
}
return res;
}
void flush() {
const std::chrono::milliseconds sleep_time = std::chrono::milliseconds(100);
while (!this->_in_queue.empty()) {
std::this_thread::sleep_for(sleep_time);
}
}
void write_thread() {
while (!_write_thread_stop) {
std::unique_lock<std::mutex> lk(_locker);
_data_cond.wait(lk, [&] {return !_in_queue.empty() || _write_thread_stop; });
while (!_in_queue.empty()) {
auto ch = _in_queue.front();
_in_queue.pop();
write_to_page(ch);
}
}
}
Page* get_cur_page() {
if (_cur_page == nullptr) {
_cur_page = create_page();
}
return _cur_page;
}
bool write_to_page(const Chunk_Ptr&ch) {
std::lock_guard<std::mutex> lg(_locker_write);
auto pg = get_cur_page();
return pg->append(ch);
}
bool append(const Chunk_Ptr&ch) {
std::lock_guard<std::mutex> lg(_locker);
_in_queue.push(ch);
_data_cond.notify_one();
return true;
}
bool append(const ChunksList&lst) {
for(auto &c:lst){
if(!append(c)){
return false;
}
}
return true;
}
Cursor_ptr chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to){
std::lock_guard<std::mutex> lg(_locker);
auto p = get_cur_page();
return p->chunksByIterval(ids, flag, from, to);
}
IdToChunkMap chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint){
std::lock_guard<std::mutex> lg(_locker);
auto cur_page = this->get_cur_page();
return cur_page->chunksBeforeTimePoint(ids, flag, timePoint);
}
dariadb::IdArray getIds() {
std::lock_guard<std::mutex> lg(_locker);
if(_cur_page==nullptr){
return dariadb::IdArray{};
}
auto cur_page = this->get_cur_page();
return cur_page->getIds();
}
dariadb::storage::ChunksList get_open_chunks() {
if(!dariadb::utils::fs::path_exists(_param.path)) {
return ChunksList{};
}
return this->get_cur_page()->get_open_chunks();
}
size_t chunks_in_cur_page() const {
if (_cur_page == nullptr) {
return 0;
}
return _cur_page->header->addeded_chunks;
}
size_t in_queue_size()const {
return _in_queue.size();
}
dariadb::Time minTime(){
std::lock_guard<std::mutex> lg(_locker);
if(_cur_page==nullptr){
return dariadb::Time(0);
}else{
return _cur_page->header->minTime;
}
}
dariadb::Time maxTime(){
std::lock_guard<std::mutex> lg(_locker);
if(_cur_page==nullptr){
return dariadb::Time(0);
}else{
return _cur_page->header->maxTime;
}
}
protected:
Page* _cur_page;
PageManager::Params _param;
std::mutex _locker,_locker_write;
std::queue<Chunk_Ptr> _in_queue;
bool _write_thread_stop;
std::thread _write_thread_handle;
std::condition_variable _data_cond;
};
PageManager::PageManager(const PageManager::Params¶m):
impl(new PageManager::Private{param})
{}
PageManager::~PageManager() {
}
void PageManager::start(const PageManager::Params¶m){
if(PageManager::_instance==nullptr){
PageManager::_instance=new PageManager(param);
}
}
void PageManager::stop(){
if(_instance!=nullptr){
delete PageManager::_instance;
_instance = nullptr;
}
}
void PageManager::flush() {
this->impl->flush();
}
PageManager* PageManager::instance(){
return _instance;
}
bool PageManager::append(const Chunk_Ptr&c){
return impl->append(c);
}
bool PageManager::append(const ChunksList&c){
return impl->append(c);
}
//Cursor_ptr PageManager::get_chunks(const dariadb::IdArray&ids, dariadb::Time from, dariadb::Time to, dariadb::Flag flag) {
// return impl->get_chunks(ids, from, to, flag);
//}
dariadb::storage::Cursor_ptr PageManager::chunksByIterval(const dariadb::IdArray &ids, dariadb::Flag flag, dariadb::Time from, dariadb::Time to){
return impl->chunksByIterval(ids,flag,from,to);
}
dariadb::storage::IdToChunkMap PageManager::chunksBeforeTimePoint(const dariadb::IdArray &ids, dariadb::Flag flag, dariadb::Time timePoint){
return impl->chunksBeforeTimePoint(ids,flag,timePoint);
}
dariadb::IdArray PageManager::getIds() {
return impl->getIds();
}
dariadb::storage::ChunksList PageManager::get_open_chunks() {
return impl->get_open_chunks();
}
size_t PageManager::chunks_in_cur_page() const{
return impl->chunks_in_cur_page();
}
size_t PageManager::in_queue_size()const{
return impl->in_queue_size();
}
dariadb::Time PageManager::minTime(){
return impl->minTime();
}
dariadb::Time PageManager::maxTime(){
return impl->maxTime();
}
<commit_msg>build.<commit_after>#include "page_manager.h"
#include "../utils/utils.h"
#include "page.h"
#include "../utils/fs.h"
#include "../utils/locker.h"
#include <cstring>
#include <queue>
#include <thread>
#include <condition_variable>
using namespace dariadb::storage;
dariadb::storage::PageManager* PageManager::_instance = nullptr;
class PageManager::Private
{
public:
Private(const PageManager::Params¶m) :
_cur_page(nullptr),
_param(param)
{
_write_thread_stop = false;
_write_thread_handle = std::move(std::thread{ &PageManager::Private::write_thread,this });
}
~Private() {
_write_thread_stop = true;
_data_cond.notify_one();
_write_thread_handle.join();
if (_cur_page != nullptr) {
delete _cur_page;
_cur_page = nullptr;
}
}
uint64_t calc_page_size()const {
auto sz_index = sizeof(Page_ChunkIndex)*_param.chunk_per_storage;
auto sz_buffers = _param.chunk_per_storage*_param.chunk_size;
return sizeof(PageHeader)
+ sz_index
+ sz_buffers;
}
Page* create_page() {
if (!dariadb::utils::fs::path_exists(_param.path)) {
dariadb::utils::fs::mkdir(_param.path);
}
std::string page_name = ((_param.mode == MODE::SINGLE) ? "single.page" : "_.page");
std::string file_name = dariadb::utils::fs::append_path(_param.path, page_name);
Page*res = nullptr;
if (!utils::fs::path_exists(file_name)) {
auto sz = calc_page_size();
res = Page::create(file_name, sz,_param.chunk_per_storage,_param.chunk_size,_param.mode);
}
else {
res = Page::open(file_name);
}
return res;
}
void flush() {
const std::chrono::milliseconds sleep_time = std::chrono::milliseconds(100);
while (!this->_in_queue.empty()) {
std::this_thread::sleep_for(sleep_time);
}
}
void write_thread() {
while (!_write_thread_stop) {
std::unique_lock<std::mutex> lk(_locker);
_data_cond.wait(lk, [&] {return !_in_queue.empty() || _write_thread_stop; });
while (!_in_queue.empty()) {
auto ch = _in_queue.front();
_in_queue.pop();
write_to_page(ch);
}
}
}
Page* get_cur_page() {
if (_cur_page == nullptr) {
_cur_page = create_page();
}
return _cur_page;
}
bool write_to_page(const Chunk_Ptr&ch) {
std::lock_guard<std::mutex> lg(_locker_write);
auto pg = get_cur_page();
return pg->append(ch);
}
bool append(const Chunk_Ptr&ch) {
std::lock_guard<std::mutex> lg(_locker);
_in_queue.push(ch);
_data_cond.notify_one();
return true;
}
bool append(const ChunksList&lst) {
for(auto &c:lst){
if(!append(c)){
return false;
}
}
return true;
}
Cursor_ptr chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to){
std::lock_guard<std::mutex> lg(_locker);
auto p = get_cur_page();
return p->chunksByIterval(ids, flag, from, to);
}
IdToChunkMap chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint){
std::lock_guard<std::mutex> lg(_locker);
auto cur_page = this->get_cur_page();
return cur_page->chunksBeforeTimePoint(ids, flag, timePoint);
}
dariadb::IdArray getIds() {
std::lock_guard<std::mutex> lg(_locker);
if(_cur_page==nullptr){
return dariadb::IdArray{};
}
auto cur_page = this->get_cur_page();
return cur_page->getIds();
}
dariadb::storage::ChunksList get_open_chunks() {
if(!dariadb::utils::fs::path_exists(_param.path)) {
return ChunksList{};
}
return this->get_cur_page()->get_open_chunks();
}
size_t chunks_in_cur_page() const {
if (_cur_page == nullptr) {
return 0;
}
return _cur_page->header->addeded_chunks;
}
size_t in_queue_size()const {
return _in_queue.size();
}
dariadb::Time minTime(){
std::lock_guard<std::mutex> lg(_locker);
if(_cur_page==nullptr){
return dariadb::Time(0);
}else{
return _cur_page->header->minTime;
}
}
dariadb::Time maxTime(){
std::lock_guard<std::mutex> lg(_locker);
if(_cur_page==nullptr){
return dariadb::Time(0);
}else{
return _cur_page->header->maxTime;
}
}
protected:
Page* _cur_page;
PageManager::Params _param;
std::mutex _locker,_locker_write;
std::queue<Chunk_Ptr> _in_queue;
bool _write_thread_stop;
std::thread _write_thread_handle;
std::condition_variable _data_cond;
};
PageManager::PageManager(const PageManager::Params¶m):
impl(new PageManager::Private{param})
{}
PageManager::~PageManager() {
}
void PageManager::start(const PageManager::Params¶m){
if(PageManager::_instance==nullptr){
PageManager::_instance=new PageManager(param);
}
}
void PageManager::stop(){
if(_instance!=nullptr){
delete PageManager::_instance;
_instance = nullptr;
}
}
void PageManager::flush() {
this->impl->flush();
}
PageManager* PageManager::instance(){
return _instance;
}
bool PageManager::append(const Chunk_Ptr&c){
return impl->append(c);
}
bool PageManager::append(const ChunksList&c){
return impl->append(c);
}
//Cursor_ptr PageManager::get_chunks(const dariadb::IdArray&ids, dariadb::Time from, dariadb::Time to, dariadb::Flag flag) {
// return impl->get_chunks(ids, from, to, flag);
//}
dariadb::storage::Cursor_ptr PageManager::chunksByIterval(const dariadb::IdArray &ids, dariadb::Flag flag, dariadb::Time from, dariadb::Time to){
return impl->chunksByIterval(ids,flag,from,to);
}
dariadb::storage::IdToChunkMap PageManager::chunksBeforeTimePoint(const dariadb::IdArray &ids, dariadb::Flag flag, dariadb::Time timePoint){
return impl->chunksBeforeTimePoint(ids,flag,timePoint);
}
dariadb::IdArray PageManager::getIds() {
return impl->getIds();
}
dariadb::storage::ChunksList PageManager::get_open_chunks() {
return impl->get_open_chunks();
}
size_t PageManager::chunks_in_cur_page() const{
return impl->chunks_in_cur_page();
}
size_t PageManager::in_queue_size()const{
return impl->in_queue_size();
}
dariadb::Time PageManager::minTime(){
return impl->minTime();
}
dariadb::Time PageManager::maxTime(){
return impl->maxTime();
}
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include "remoteobject_p.hpp"
#include "src/object_p.hpp"
#include "src/metasignal_p.hpp"
#include <qimessaging/message.hpp>
#include <qimessaging/transportsocket.hpp>
#include <qi/log.hpp>
#include <boost/thread/mutex.hpp>
namespace qi {
RemoteObject::RemoteObject(unsigned int service, qi::MetaObject metaObject, TransportSocketPtr socket)
: _socket(socket)
, _service(service)
, _linkMessageDispatcher(0)
{
setMetaObject(metaObject);
setTransportSocket(socket);
}
//### RemoteObject
void RemoteObject::setTransportSocket(qi::TransportSocketPtr socket) {
if (_socket)
_socket->messagePendingDisconnect(_service, _linkMessageDispatcher);
_socket = socket;
if (socket)
_linkMessageDispatcher = _socket->messagePendingConnect(_service, boost::bind<void>(&RemoteObject::onMessagePending, this, _1));
}
RemoteObject::~RemoteObject()
{
//close may already have been called. (by Session_Service.close)
close();
}
void RemoteObject::onMessagePending(const qi::Message &msg)
{
qi::Promise<GenericValue> promise;
bool found = false;
std::map<int, qi::Promise<GenericValue> >::iterator it;
qiLogDebug("RemoteObject") << this << " msg " << msg.type() << " " << msg.buffer().size();
{
boost::mutex::scoped_lock lock(_mutex);
it = _promises.find(msg.id());
if (it != _promises.end()) {
promise = _promises[msg.id()];
_promises.erase(it);
found = true;
}
}
switch (msg.type()) {
case qi::Message::Type_Reply:
{
if (!found) {
qiLogError("remoteobject") << "no promise found for req id:" << msg.id()
<< " obj: " << msg.service() << " func: " << msg.function();
return;
}
// Get call signature
MetaMethod* mm = metaObject().method(msg.function());
if (!mm)
{
qiLogError("remoteobject") << "Result for unknown function "
<< msg.function();
promise.setError("Result for unknown function");
return;
}
Type* type = Type::fromSignature(mm->sigreturn());
if (!type)
{
promise.setError("Unable to find a type for signature " + mm->sigreturn());
return;
}
IDataStream in(msg.buffer());
promise.setValue(type->deserialize(in));
return;
}
case qi::Message::Type_Error: {
qi::IDataStream ds(msg.buffer());
std::string err;
std::string sig;
ds >> sig;
if (sig != "s") {
qiLogError("qi.RemoteObject") << "Invalid error signature: " << sig;
//houston we have an error about the error..
promise.setError("unknown error");
return;
}
ds >> err;
qiLogVerbose("remoteobject") << "Received error message" << msg.address() << ":" << err;
promise.setError(err);
return;
}
case qi::Message::Type_Event: {
SignalBase* sb = signalBase(msg.event());
if (sb)
{
try {
std::string sig = sb->signature();
sig = signatureSplit(sig)[2];
sig = sig.substr(1, sig.length()-2);
GenericFunctionParameters args
= GenericFunctionParameters::fromBuffer(sig, msg.buffer());
sb->trigger(args);
args.destroy();
}
catch (const std::exception& e)
{
qiLogWarning("remoteobject") << "Deserialize error on event: " << e.what();
}
}
else
{
qiLogWarning("remoteobject") << "Event message on unknown signal " << msg.event();
qiLogDebug("remoteobject") << metaObject().signalMap().size();
}
return;
}
default:
qiLogError("remoteobject") << "Message " << msg.address() << " type not handled: " << msg.type();
return;
}
}
qi::Future<GenericValue> RemoteObject::metaCall(unsigned int method, const qi::GenericFunctionParameters &in, MetaCallType callType)
{
qi::Promise<GenericValue> out;
qi::Message msg;
msg.setBuffer(in.toBuffer());
#ifndef NDEBUG
std::string sig = metaObject().method(method)->signature();
sig = signatureSplit(sig)[2];
// Remove extra tuple layer
sig = sig.substr(1, sig.length()-2);
if (sig != msg.buffer().signature().str())
{
qiLogError("remoteobject") << "call signature mismatch "
<< sig << ' '
<< msg.buffer().signature().str();
}
#endif
msg.setType(qi::Message::Type_Call);
msg.setService(_service);
msg.setObject(qi::Message::GenericObject_Main);
msg.setFunction(method);
qiLogDebug("remoteobject") << this << " metacall " << msg.service() << " "
<< msg.function() <<" " << msg.id();
{
boost::mutex::scoped_lock lock(_mutex);
if (_promises.find(msg.id()) != _promises.end())
{
qiLogError("remoteobject") << "There is already a pending promise with id "
<< msg.id();
}
_promises[msg.id()] = out;
}
//error will come back as a error message
if (!_socket || !_socket->send(msg)) {
qiLogError("remoteobject") << "error while sending answer";
qi::MetaMethod* meth = metaObject().method(method);
std::stringstream ss;
if (meth) {
ss << "Network error while sending data to method: '";
ss << meth->signature();;
ss << "'";
} else {
ss << "Network error while sending data an unknown method (id=" << method << ")";
}
out.setError(ss.str());
{
boost::mutex::scoped_lock lock(_mutex);
_promises.erase(msg.id());
}
}
return out.future();
}
void RemoteObject::metaEmit(unsigned int event, const qi::GenericFunctionParameters &args)
{
// Bounce the emit request to server
// TODO: one optimisation that could be done is to trigger the local
// subscribers immediately.
// But it is a bit complex, because the server will bounce the
// event back to us.
qi::Message msg;
msg.setBuffer(args.toBuffer());
msg.setType(Message::Type_Event);
msg.setService(_service);
msg.setObject(qi::Message::GenericObject_Main);
msg.setFunction(event);
if (!_socket->send(msg)) {
qiLogError("remoteobject") << "error while emiting event";
}
}
unsigned int RemoteObject::connect(unsigned int event, const SignalSubscriber& sub)
{
// Bind the subscriber locally.
unsigned int uid = DynamicObject::connect(event, sub);
// Notify the Service that we are interested in its event.
// Provide our uid as payload
// We send one message per connect, even on the same event: the remot
// end is doing the refcounting
qi::Message msg;
qi::Buffer buf;
qi::ODataStream ds(buf);
ds << _service << event << uid;
msg.setBuffer(buf);
msg.setObject(qi::Message::GenericObject_Main);
msg.setType(Message::Type_Event);
msg.setService(Message::Service_Server);
msg.setFunction(Message::ServerFunction_RegisterEvent);
if (!_socket->send(msg)) {
qiLogError("remoteobject") << "error while registering event";
}
qiLogDebug("remoteobject") <<"connect() to " << event <<" gave " << uid;
return uid;
}
bool RemoteObject::disconnect(unsigned int linkId)
{
unsigned int event = linkId >> 16;
//disconnect locally
bool ok = DynamicObject::disconnect(linkId);
if (!ok)
{
qiLogWarning("qi.object") << "Disconnection failure for " << linkId;
return false;
}
else
{
// Tell the remote we are no longer interested.
qi::Message msg;
qi::Buffer buf;
qi::ODataStream ds(buf);
ds << _service << event << linkId;
msg.setBuffer(buf);
msg.setType(Message::Type_Event);
msg.setService(Message::Service_Server);
msg.setObject(Message::GenericObject_Main);
msg.setFunction(Message::ServerFunction_UnregisterEvent);
if (!_socket->send(msg)) {
qiLogError("remoteobject") << "error while disconnecting signal";
}
return true;
}
}
void RemoteObject::close() {
if (_socket)
_socket->messagePendingDisconnect(_service, _linkMessageDispatcher);
}
}
<commit_msg>squasha restore async<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include "remoteobject_p.hpp"
#include "src/object_p.hpp"
#include "src/metasignal_p.hpp"
#include <qimessaging/message.hpp>
#include <qimessaging/transportsocket.hpp>
#include <qi/log.hpp>
#include <boost/thread/mutex.hpp>
namespace qi {
RemoteObject::RemoteObject(unsigned int service, qi::MetaObject metaObject, TransportSocketPtr socket)
: _socket(socket)
, _service(service)
, _linkMessageDispatcher(0)
{
setMetaObject(metaObject);
setTransportSocket(socket);
}
//### RemoteObject
void RemoteObject::setTransportSocket(qi::TransportSocketPtr socket) {
if (_socket)
_socket->messagePendingDisconnect(_service, _linkMessageDispatcher);
_socket = socket;
if (socket)
_linkMessageDispatcher = _socket->messagePendingConnect(_service, boost::bind<void>(&RemoteObject::onMessagePending, this, _1));
}
RemoteObject::~RemoteObject()
{
//close may already have been called. (by Session_Service.close)
close();
}
void RemoteObject::onMessagePending(const qi::Message &msg)
{
qi::Promise<GenericValue> promise;
bool found = false;
std::map<int, qi::Promise<GenericValue> >::iterator it;
qiLogDebug("RemoteObject") << this << " msg " << msg.type() << " " << msg.buffer().size();
{
boost::mutex::scoped_lock lock(_mutex);
it = _promises.find(msg.id());
if (it != _promises.end()) {
promise = _promises[msg.id()];
_promises.erase(it);
found = true;
}
}
switch (msg.type()) {
case qi::Message::Type_Reply:
{
if (!found) {
qiLogError("remoteobject") << "no promise found for req id:" << msg.id()
<< " obj: " << msg.service() << " func: " << msg.function();
return;
}
// Get call signature
MetaMethod* mm = metaObject().method(msg.function());
if (!mm)
{
qiLogError("remoteobject") << "Result for unknown function "
<< msg.function();
promise.setError("Result for unknown function");
return;
}
Type* type = Type::fromSignature(mm->sigreturn());
if (!type)
{
promise.setError("Unable to find a type for signature " + mm->sigreturn());
return;
}
IDataStream in(msg.buffer());
promise.setValue(type->deserialize(in));
return;
}
case qi::Message::Type_Error: {
qi::IDataStream ds(msg.buffer());
std::string err;
std::string sig;
ds >> sig;
if (sig != "s") {
qiLogError("qi.RemoteObject") << "Invalid error signature: " << sig;
//houston we have an error about the error..
promise.setError("unknown error");
return;
}
ds >> err;
qiLogVerbose("remoteobject") << "Received error message" << msg.address() << ":" << err;
promise.setError(err);
return;
}
case qi::Message::Type_Event: {
SignalBase* sb = signalBase(msg.event());
if (sb)
{
try {
std::string sig = sb->signature();
sig = signatureSplit(sig)[2];
sig = sig.substr(1, sig.length()-2);
GenericFunctionParameters args
= GenericFunctionParameters::fromBuffer(sig, msg.buffer());
sb->trigger(args);
args.destroy();
}
catch (const std::exception& e)
{
qiLogWarning("remoteobject") << "Deserialize error on event: " << e.what();
}
}
else
{
qiLogWarning("remoteobject") << "Event message on unknown signal " << msg.event();
qiLogDebug("remoteobject") << metaObject().signalMap().size();
}
return;
}
default:
qiLogError("remoteobject") << "Message " << msg.address() << " type not handled: " << msg.type();
return;
}
}
qi::Future<GenericValue> RemoteObject::metaCall(unsigned int method, const qi::GenericFunctionParameters &in, MetaCallType callType)
{
qi::Promise<GenericValue> out;
qi::Message msg;
msg.setBuffer(in.toBuffer());
#ifndef NDEBUG
std::string sig = metaObject().method(method)->signature();
sig = signatureSplit(sig)[2];
// Remove extra tuple layer
sig = sig.substr(1, sig.length()-2);
if (sig != msg.buffer().signature().str())
{
qiLogError("remoteobject") << "call signature mismatch "
<< sig << ' '
<< msg.buffer().signature().str();
}
#endif
msg.setType(qi::Message::Type_Call);
msg.setService(_service);
msg.setObject(qi::Message::GenericObject_Main);
msg.setFunction(method);
qiLogDebug("remoteobject") << this << " metacall " << msg.service() << " "
<< msg.function() <<" " << msg.id();
{
boost::mutex::scoped_lock lock(_mutex);
if (_promises.find(msg.id()) != _promises.end())
{
qiLogError("remoteobject") << "There is already a pending promise with id "
<< msg.id();
}
_promises[msg.id()] = out;
}
//error will come back as a error message
if (!_socket || !_socket->isConnected() || !_socket->send(msg)) {
qiLogError("remoteobject") << "error while sending answer";
qi::MetaMethod* meth = metaObject().method(method);
std::stringstream ss;
if (meth) {
ss << "Network error while sending data to method: '";
ss << meth->signature();;
ss << "'";
} else {
ss << "Network error while sending data an unknown method (id=" << method << ")";
}
out.setError(ss.str());
{
boost::mutex::scoped_lock lock(_mutex);
_promises.erase(msg.id());
}
}
return out.future();
}
void RemoteObject::metaEmit(unsigned int event, const qi::GenericFunctionParameters &args)
{
// Bounce the emit request to server
// TODO: one optimisation that could be done is to trigger the local
// subscribers immediately.
// But it is a bit complex, because the server will bounce the
// event back to us.
qi::Message msg;
msg.setBuffer(args.toBuffer());
msg.setType(Message::Type_Event);
msg.setService(_service);
msg.setObject(qi::Message::GenericObject_Main);
msg.setFunction(event);
if (!_socket->send(msg)) {
qiLogError("remoteobject") << "error while emiting event";
}
}
unsigned int RemoteObject::connect(unsigned int event, const SignalSubscriber& sub)
{
// Bind the subscriber locally.
unsigned int uid = DynamicObject::connect(event, sub);
// Notify the Service that we are interested in its event.
// Provide our uid as payload
// We send one message per connect, even on the same event: the remot
// end is doing the refcounting
qi::Message msg;
qi::Buffer buf;
qi::ODataStream ds(buf);
ds << _service << event << uid;
msg.setBuffer(buf);
msg.setObject(qi::Message::GenericObject_Main);
msg.setType(Message::Type_Event);
msg.setService(Message::Service_Server);
msg.setFunction(Message::ServerFunction_RegisterEvent);
if (!_socket->send(msg)) {
qiLogError("remoteobject") << "error while registering event";
}
qiLogDebug("remoteobject") <<"connect() to " << event <<" gave " << uid;
return uid;
}
bool RemoteObject::disconnect(unsigned int linkId)
{
unsigned int event = linkId >> 16;
//disconnect locally
bool ok = DynamicObject::disconnect(linkId);
if (!ok)
{
qiLogWarning("qi.object") << "Disconnection failure for " << linkId;
return false;
}
else
{
// Tell the remote we are no longer interested.
qi::Message msg;
qi::Buffer buf;
qi::ODataStream ds(buf);
ds << _service << event << linkId;
msg.setBuffer(buf);
msg.setType(Message::Type_Event);
msg.setService(Message::Service_Server);
msg.setObject(Message::GenericObject_Main);
msg.setFunction(Message::ServerFunction_UnregisterEvent);
if (!_socket->send(msg)) {
qiLogError("remoteobject") << "error while disconnecting signal";
}
return true;
}
}
void RemoteObject::close() {
if (_socket)
_socket->messagePendingDisconnect(_service, _linkMessageDispatcher);
}
}
<|endoftext|>
|
<commit_before>#include <eosio/se-helpers/se-helpers.hpp>
#include <fc/fwd_impl.hpp>
#include <Security/Security.h>
namespace eosio::secure_enclave {
static std::string string_for_cferror(CFErrorRef error) {
CFStringRef errorString = CFCopyDescription(error);
char buff[CFStringGetLength(errorString) + 1];
std::string ret;
if(CFStringGetCString(errorString, buff, sizeof(buff), kCFStringEncodingUTF8))
ret = buff;
else
ret = "Unknown";
CFRelease(errorString);
return ret;
}
struct secure_enclave_key::impl {
SecKeyRef key_ref = NULL;
fc::crypto::public_key pub_key;
~impl() {
if(key_ref)
CFRelease(key_ref);
key_ref = NULL;
}
void populate_public_key() {
//without a good way to create fc::public_key direct, create a serialized version to create a public_key from
char serialized_public_key[1 + sizeof(fc::crypto::r1::public_key_data)] = {fc::crypto::public_key::storage_type::position<fc::crypto::r1::public_key_shim>()};
SecKeyRef pubkey = SecKeyCopyPublicKey(key_ref);
CFErrorRef error = NULL;
CFDataRef keyrep = NULL;
keyrep = SecKeyCopyExternalRepresentation(pubkey, &error);
if(!error) {
const UInt8 *cfdata = CFDataGetBytePtr(keyrep);
memcpy(serialized_public_key + 2, cfdata + 1, 32);
serialized_public_key[1] = 0x02u + (cfdata[64] & 1u);
}
CFRelease(keyrep);
CFRelease(pubkey);
if(error) {
std::string error_string = string_for_cferror(error);
CFRelease(error);
FC_ASSERT(false, "Failed to get public key from Secure Enclave: ${m}", ("m", error_string));
}
fc::datastream<const char*> ds(serialized_public_key, sizeof(serialized_public_key));
fc::raw::unpack(ds, pub_key);
}
};
secure_enclave_key::secure_enclave_key(void* seckeyref) {
static_assert(sizeof(impl) <= fwd_size);
my->key_ref = (SecKeyRef)seckeyref;
my->populate_public_key();
}
secure_enclave_key::secure_enclave_key(const secure_enclave_key& o) {
my->key_ref = (SecKeyRef)CFRetain(o.my->key_ref);
my->pub_key = o.public_key();
}
secure_enclave_key::secure_enclave_key(secure_enclave_key&& o) {
my->key_ref = o.my->key_ref;
o.my->key_ref = NULL;
my->pub_key = o.my->pub_key;
}
const fc::crypto::public_key &secure_enclave_key::public_key() const {
return my->pub_key;
}
fc::crypto::signature secure_enclave_key::sign(const fc::sha256& digest) const {
fc::ecdsa_sig sig = ECDSA_SIG_new();
CFErrorRef error = NULL;
CFDataRef digestData = CFDataCreateWithBytesNoCopy(NULL, (UInt8*)digest.data(), digest.data_size(), kCFAllocatorNull);
CFDataRef signature = SecKeyCreateSignature(my->key_ref, kSecKeyAlgorithmECDSASignatureDigestX962SHA256, digestData, &error);
if(error) {
std::string error_string = string_for_cferror(error);
CFRelease(error);
CFRelease(digestData);
FC_ASSERT(false, "Failed to sign digest in Secure Enclave: ${m}", ("m", error_string));
}
const UInt8* der_bytes = CFDataGetBytePtr(signature);
long derSize = CFDataGetLength(signature);
d2i_ECDSA_SIG(&sig.obj, &der_bytes, derSize);
char serialized_signature[sizeof(fc::crypto::r1::compact_signature) + 1] = {fc::crypto::signature::storage_type::position<fc::crypto::r1::signature_shim>()};
try {
fc::crypto::r1::compact_signature* compact_sig = (fc::crypto::r1::compact_signature *)(serialized_signature + 1);
fc::ec_key key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
*compact_sig = fc::crypto::r1::signature_from_ecdsa(key,my->pub_key._storage.get<fc::crypto::r1::public_key_shim>()._data, sig, digest);
} catch(...) {
CFRelease(signature);
CFRelease(digestData);
throw;
}
CFRelease(signature);
CFRelease(digestData);
fc::crypto::signature final_signature;
fc::datastream<const char*> ds(serialized_signature, sizeof(serialized_signature));
fc::raw::unpack(ds, final_signature);
return final_signature;
}
secure_enclave_key create_key() {
SecAccessControlRef accessControlRef = SecAccessControlCreateWithFlags(NULL, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage, NULL);
int keySizeValue = 256;
CFNumberRef keySizeNumber = CFNumberCreate(NULL, kCFNumberIntType, &keySizeValue);
const void* keyAttrKeys[] = {
kSecAttrIsPermanent,
kSecAttrAccessControl
};
const void* keyAttrValues[] = {
kCFBooleanTrue,
accessControlRef
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(NULL, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
const void* attrKeys[] = {
kSecAttrKeyType,
kSecAttrKeySizeInBits,
kSecAttrTokenID,
kSecPrivateKeyAttrs
};
const void* atrrValues[] = {
kSecAttrKeyTypeECSECPrimeRandom,
keySizeNumber,
kSecAttrTokenIDSecureEnclave,
keyAttrDic
};
CFDictionaryRef attributesDic = CFDictionaryCreate(NULL, attrKeys, atrrValues, sizeof(attrKeys)/sizeof(attrKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey(attributesDic, &error);
std::string error_string;
if(error) {
error_string = string_for_cferror(error);
CFRelease(error);
}
CFRelease(attributesDic);
CFRelease(keyAttrDic);
CFRelease(keySizeNumber);
CFRelease(accessControlRef);
if(error_string.size())
FC_ASSERT(false, "Failed to create key in Secure Enclave: ${m}", ("m", error_string));
return secure_enclave_key(privateKey);
}
std::set<secure_enclave_key> get_all_keys() {
const void* keyAttrKeys[] = {
kSecClass,
kSecAttrKeyClass,
kSecMatchLimit,
kSecReturnRef,
kSecAttrTokenID
};
const void* keyAttrValues[] = {
kSecClassKey,
kSecAttrKeyClassPrivate,
kSecMatchLimitAll,
kCFBooleanTrue,
kSecAttrTokenIDSecureEnclave,
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(NULL, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFArrayRef keyRefs = NULL;
if(SecItemCopyMatching(keyAttrDic, (CFTypeRef*)&keyRefs) || !keyRefs) {
CFRelease(keyAttrDic);
return std::set<secure_enclave_key>();
}
std::set<secure_enclave_key> ret;
CFIndex count = CFArrayGetCount(keyRefs);
for(long i = 0; i < count; ++i) {
try {
ret.emplace((void*)CFRetain(CFArrayGetValueAtIndex(keyRefs, i)));
}
catch(...) {} //swallow keys we couldn't read for whatever reason
}
CFRelease(keyRefs);
CFRelease(keyAttrDic);
return ret;
}
void delete_key(secure_enclave_key&& key) {
CFDictionaryRef deleteDic = CFDictionaryCreate(NULL, (const void**)&kSecValueRef, (const void**)&key.my->key_ref, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
OSStatus ret = SecItemDelete(deleteDic);
CFRelease(deleteDic);
FC_ASSERT(ret == 0, "Failed to remove key from Secure Enclave");
}
bool hardware_supports_secure_enclave() {
//How to figure out if SE is available?!
char model[256];
size_t model_size = sizeof(model);
if(sysctlbyname("hw.model", model, &model_size, nullptr, 0) == 0) {
if(strncmp(model, "iMacPro", strlen("iMacPro")) == 0)
return true;
unsigned int major, minor;
if(sscanf(model, "MacBookPro%u,%u", &major, &minor) == 2) {
if((major >= 15) || (major >= 13 && minor >= 2)) {
return true;
}
}
if(sscanf(model, "Macmini%u", &major) == 1 && major >= 8)
return true;
if(sscanf(model, "MacBookAir%u", &major) == 1 && major >= 8)
return true;
if(sscanf(model, "MacPro%u", &major) == 1 && major >= 7)
return true;
}
return false;
}
bool application_signed() {
OSStatus is_valid{-1};
pid_t pid = getpid();
SecCodeRef code = NULL;
CFNumberRef pidnumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pid);
CFDictionaryRef piddict = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&kSecGuestAttributePid, (const void**)&pidnumber, 1, NULL, NULL);
if(!SecCodeCopyGuestWithAttributes(NULL, piddict, kSecCSDefaultFlags, &code)) {
is_valid = SecCodeCheckValidity(code, kSecCSDefaultFlags, 0);
CFRelease(code);
}
CFRelease(piddict);
CFRelease(pidnumber);
return is_valid == errSecSuccess;
}
}<commit_msg>resolve leakage of CoreFoundation objects on exceptional exceptions<commit_after>#include <eosio/se-helpers/se-helpers.hpp>
#include <fc/fwd_impl.hpp>
#include <fc/scoped_exit.hpp>
#include <Security/Security.h>
namespace eosio::secure_enclave {
static std::string string_for_cferror(CFErrorRef error) {
CFStringRef errorString = CFCopyDescription(error);
auto release_errorString = fc::make_scoped_exit([&errorString](){CFRelease(errorString);});
std::string ret(CFStringGetLength(errorString), '\0');
if(!CFStringGetCString(errorString, ret.data(), ret.size(), kCFStringEncodingUTF8))
ret = "Unknown";
return ret;
}
struct secure_enclave_key::impl {
SecKeyRef key_ref = NULL;
fc::crypto::public_key pub_key;
~impl() {
if(key_ref)
CFRelease(key_ref);
key_ref = NULL;
}
void populate_public_key() {
//without a good way to create fc::public_key direct, create a serialized version to create a public_key from
char serialized_public_key[1 + sizeof(fc::crypto::r1::public_key_data)] = {fc::crypto::public_key::storage_type::position<fc::crypto::r1::public_key_shim>()};
SecKeyRef pubkey = SecKeyCopyPublicKey(key_ref);
CFErrorRef error = NULL;
CFDataRef keyrep = NULL;
keyrep = SecKeyCopyExternalRepresentation(pubkey, &error);
if(!error) {
const UInt8 *cfdata = CFDataGetBytePtr(keyrep);
memcpy(serialized_public_key + 2, cfdata + 1, 32);
serialized_public_key[1] = 0x02u + (cfdata[64] & 1u);
}
CFRelease(keyrep);
CFRelease(pubkey);
if(error) {
auto release_error = fc::make_scoped_exit([&error](){CFRelease(error);});
FC_ASSERT(false, "Failed to get public key from Secure Enclave: ${m}", ("m", string_for_cferror(error)));
}
fc::datastream<const char*> ds(serialized_public_key, sizeof(serialized_public_key));
fc::raw::unpack(ds, pub_key);
}
};
secure_enclave_key::secure_enclave_key(void* seckeyref) {
static_assert(sizeof(impl) <= fwd_size);
my->key_ref = (SecKeyRef)(seckeyref);
my->populate_public_key();
CFRetain(my->key_ref);
}
secure_enclave_key::secure_enclave_key(const secure_enclave_key& o) {
my->key_ref = (SecKeyRef)CFRetain(o.my->key_ref);
my->pub_key = o.public_key();
}
secure_enclave_key::secure_enclave_key(secure_enclave_key&& o) {
my->key_ref = o.my->key_ref;
o.my->key_ref = NULL;
my->pub_key = o.my->pub_key;
}
const fc::crypto::public_key &secure_enclave_key::public_key() const {
return my->pub_key;
}
fc::crypto::signature secure_enclave_key::sign(const fc::sha256& digest) const {
fc::ecdsa_sig sig = ECDSA_SIG_new();
CFErrorRef error = NULL;
CFDataRef digestData = CFDataCreateWithBytesNoCopy(NULL, (UInt8*)digest.data(), digest.data_size(), kCFAllocatorNull);
CFDataRef signature = SecKeyCreateSignature(my->key_ref, kSecKeyAlgorithmECDSASignatureDigestX962SHA256, digestData, &error);
auto cleanup = fc::make_scoped_exit([&digestData, &signature]() {
CFRelease(digestData);
if(signature)
CFRelease(signature);
});
if(error) {
auto release_error = fc::make_scoped_exit([&error](){CFRelease(error);});
std::string error_string = string_for_cferror(error);
FC_ASSERT(false, "Failed to sign digest in Secure Enclave: ${m}", ("m", error_string));
}
const UInt8* der_bytes = CFDataGetBytePtr(signature);
long derSize = CFDataGetLength(signature);
d2i_ECDSA_SIG(&sig.obj, &der_bytes, derSize);
char serialized_signature[sizeof(fc::crypto::r1::compact_signature) + 1] = {fc::crypto::signature::storage_type::position<fc::crypto::r1::signature_shim>()};
fc::crypto::r1::compact_signature* compact_sig = (fc::crypto::r1::compact_signature *)(serialized_signature + 1);
fc::ec_key key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
*compact_sig = fc::crypto::r1::signature_from_ecdsa(key,my->pub_key._storage.get<fc::crypto::r1::public_key_shim>()._data, sig, digest);
fc::crypto::signature final_signature;
fc::datastream<const char*> ds(serialized_signature, sizeof(serialized_signature));
fc::raw::unpack(ds, final_signature);
return final_signature;
}
secure_enclave_key create_key() {
SecAccessControlRef accessControlRef = SecAccessControlCreateWithFlags(NULL, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage, NULL);
int keySizeValue = 256;
CFNumberRef keySizeNumber = CFNumberCreate(NULL, kCFNumberIntType, &keySizeValue);
const void* keyAttrKeys[] = {
kSecAttrIsPermanent,
kSecAttrAccessControl
};
const void* keyAttrValues[] = {
kCFBooleanTrue,
accessControlRef
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(NULL, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
const void* attrKeys[] = {
kSecAttrKeyType,
kSecAttrKeySizeInBits,
kSecAttrTokenID,
kSecPrivateKeyAttrs
};
const void* atrrValues[] = {
kSecAttrKeyTypeECSECPrimeRandom,
keySizeNumber,
kSecAttrTokenIDSecureEnclave,
keyAttrDic
};
CFDictionaryRef attributesDic = CFDictionaryCreate(NULL, attrKeys, atrrValues, sizeof(attrKeys)/sizeof(attrKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
auto cleanup = fc::make_scoped_exit([&attributesDic, &keyAttrDic, &keySizeNumber, &accessControlRef]() {
CFRelease(attributesDic);
CFRelease(keyAttrDic);
CFRelease(keySizeNumber);
CFRelease(accessControlRef);
});
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey(attributesDic, &error);
if(error) {
auto release_error = fc::make_scoped_exit([&error](){CFRelease(error);});
FC_ASSERT(false, "Failed to create key in Secure Enclave: ${m}", ("m", string_for_cferror(error)));
}
return secure_enclave_key(privateKey);
}
std::set<secure_enclave_key> get_all_keys() {
const void* keyAttrKeys[] = {
kSecClass,
kSecAttrKeyClass,
kSecMatchLimit,
kSecReturnRef,
kSecAttrTokenID
};
const void* keyAttrValues[] = {
kSecClassKey,
kSecAttrKeyClassPrivate,
kSecMatchLimitAll,
kCFBooleanTrue,
kSecAttrTokenIDSecureEnclave,
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(NULL, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
auto cleanup_keyAttrDic = fc::make_scoped_exit([&keyAttrDic](){CFRelease(keyAttrDic);});
std::set<secure_enclave_key> ret;
CFArrayRef keyRefs = NULL;
if(SecItemCopyMatching(keyAttrDic, (CFTypeRef*)&keyRefs) || !keyRefs)
return ret;
auto cleanup_keyRefs = fc::make_scoped_exit([&keyRefs](){CFRelease(keyRefs);});
CFIndex count = CFArrayGetCount(keyRefs);
for(long i = 0; i < count; ++i)
ret.emplace((void*)CFArrayGetValueAtIndex(keyRefs, i));
return ret;
}
void delete_key(secure_enclave_key&& key) {
CFDictionaryRef deleteDic = CFDictionaryCreate(NULL, (const void**)&kSecValueRef, (const void**)&key.my->key_ref, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
OSStatus ret = SecItemDelete(deleteDic);
CFRelease(deleteDic);
FC_ASSERT(ret == 0, "Failed to remove key from Secure Enclave");
}
bool hardware_supports_secure_enclave() {
//How to figure out if SE is available?!
char model[256];
size_t model_size = sizeof(model);
if(sysctlbyname("hw.model", model, &model_size, nullptr, 0) == 0) {
if(strncmp(model, "iMacPro", strlen("iMacPro")) == 0)
return true;
unsigned int major, minor;
if(sscanf(model, "MacBookPro%u,%u", &major, &minor) == 2) {
if((major >= 15) || (major >= 13 && minor >= 2)) {
return true;
}
}
if(sscanf(model, "Macmini%u", &major) == 1 && major >= 8)
return true;
if(sscanf(model, "MacBookAir%u", &major) == 1 && major >= 8)
return true;
if(sscanf(model, "MacPro%u", &major) == 1 && major >= 7)
return true;
}
return false;
}
bool application_signed() {
OSStatus is_valid{-1};
pid_t pid = getpid();
SecCodeRef code = NULL;
CFNumberRef pidnumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pid);
CFDictionaryRef piddict = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&kSecGuestAttributePid, (const void**)&pidnumber, 1, NULL, NULL);
if(!SecCodeCopyGuestWithAttributes(NULL, piddict, kSecCSDefaultFlags, &code)) {
is_valid = SecCodeCheckValidity(code, kSecCSDefaultFlags, 0);
CFRelease(code);
}
CFRelease(piddict);
CFRelease(pidnumber);
return is_valid == errSecSuccess;
}
}<|endoftext|>
|
<commit_before>/* Copyright (C) LinBox
*
* Author: Zhendong Wan
*
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/*! @file tests/test-rational-solver.C
* @ingroup tests
* @brief no doc.
* @test no doc.
*/
#include "linbox/field/PID-integer.h"
#include "linbox/field/modular.h"
#include "linbox/blackbox/diagonal.h"
#include "linbox/algorithms/rational-solver.h"
#include "linbox/randiter/random-prime.h"
#include <iostream>
#include "test-common.h"
#include "linbox/vector/stream.h"
#include "linbox/util/commentator.h"
using namespace LinBox;
/// Testing Nonsingular Random Diagonal solve.
template <class Ring, class Field, class Vector>
bool testRandomSolve (const Ring& R,
const Field& f,
LinBox::VectorStream<Vector>& stream1,
LinBox::VectorStream<Vector>& stream2)
{
std::ostringstream str;
commentator().start ("Testing Nonsingular Random Diagonal solve ","testNonsingularRandomDiagonalSolve", stream1.size());// "testNonsingularRandomMatrixSolve", stream1.m ());
bool ret = true;
bool iter_passed = true;
VectorDomain<Ring> VD (R);
Vector d, b, x, y;
VectorWrapper::ensureDim (d, stream1.n ());
VectorWrapper::ensureDim (b, stream1.n ());
VectorWrapper::ensureDim (x, stream1.n ());
VectorWrapper::ensureDim (y, stream1.n ());
int n = (int)d. size();
while (stream1 && stream2) {
commentator().startIteration ((unsigned)stream1.j ());
//ActivityState state = commentator().saveActivityState ();
iter_passed = true;
bool zeroEntry;
do {
stream1.next (d);
zeroEntry = false;
for (size_t i=0; i<stream1.n(); i++)
zeroEntry |= R.isZero(d[(size_t)i]);
} while (zeroEntry);
stream2.next (b);
std::ostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);
report << "Diagonal entries: ";
VD.write (report, d);
report << endl;
report << "Right-hand side: ";
VD.write (report, b);
report << endl;
//Diagonal<Ring> D(R, d);
BlasMatrix<Ring> D(R, n, n);
for(int i = 0; i < n; ++i) R.init (D[(size_t)i][(size_t)i], d[(size_t)i]);
typedef RationalSolver<Ring, Field, LinBox::RandomPrimeIterator> RSolver;
RSolver rsolver;
//std::vector<std::pair<typename Ring::Element, typename Ring::Element> > answer(n);
std::vector<typename Ring::Element> num((size_t)n);
typename Ring::Element den;
SolverReturnStatus solveResult = rsolver.solve(num, den, D, b, 30); //often 5 primes are not enough
#if 0
typename Ring::Element lden;
R. init (lden, 1);
typename std::vector<std::pair<typename Ring::Element, typename Ring::Element> >::iterator p;
for (p = answer.begin(); p != answer.end(); ++ p)
R. lcm (lden, lden, p->second);
typename Vector::iterator p_x;
//typename Vector::iterator p_y;
#endif
if (solveResult == SS_OK) {
#if 0
for (p = answer.begin(), p_x = x. begin();
p != answer.end();
++ p, ++ p_x) {
R. mul (*p_x, p->first, lden);
R. divin (*p_x, p->second);
}
D. apply (y, x);
#endif
D. apply (y, num);
VD. mulin(b, den);
if (!VD.areEqual (y, b)) {
ret = iter_passed = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Computed solution is incorrect" << endl;
}
}
else {
ret = iter_passed = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Did not return OK solving status" << endl;
}
commentator().stop ("done");
commentator().progress ();
}
stream1.reset ();
stream2.reset ();
commentator().stop (MSG_STATUS (ret), (const char *) 0, "testNonsingularRandomDiagonalSolve");
return ret;
}
int main(int argc, char** argv)
{
bool pass = true;
static size_t n = 10;
static int iterations = 1;
static Argument args[] = {
{ 'n', "-n N", "Set order of test matrices to N.", TYPE_INT, &n},
{ 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations },
END_OF_ARGUMENTS
};
parseArguments (argc, argv, args);
typedef Modular<int32_t> Field;
// typedef Modular<double> Field;
typedef PID_integer Ring;
Ring R;
Field F(101);
RandomDenseStream<Ring> s1 (R, n, (unsigned int)iterations), s2 (R, n, (unsigned int)iterations);
if (!testRandomSolve(R, F, s1, s2)) pass = false;
return pass ? 0 : -1;
}
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s
// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:
<commit_msg>test-rational-solver passes<commit_after>/* Copyright (C) LinBox
*
* Author: Zhendong Wan
*
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/*! @file tests/test-rational-solver.C
* @ingroup tests
* @brief no doc.
* @test no doc.
*/
#include "linbox/field/PID-integer.h"
#include "linbox/field/modular.h"
#include "linbox/blackbox/diagonal.h"
#include "linbox/algorithms/rational-solver.h"
#include "linbox/randiter/random-prime.h"
#include <iostream>
#include "test-common.h"
#include "linbox/vector/stream.h"
#include "linbox/util/commentator.h"
using namespace LinBox;
/// Testing Nonsingular Random Diagonal solve.
template <class Ring, class Field, class Vector>
bool testRandomSolve (const Ring& R,
const Field& f,
LinBox::VectorStream<Vector>& stream1,
LinBox::VectorStream<Vector>& stream2)
{
std::ostringstream str;
commentator().start ("Testing Nonsingular Random Diagonal solve ","testNonsingularRandomDiagonalSolve", stream1.size());// "testNonsingularRandomMatrixSolve", stream1.m ());
bool ret = true;
bool iter_passed = true;
VectorDomain<Ring> VD (R);
Vector d(R), b(R), x(R), y(R);
VectorWrapper::ensureDim (d, stream1.n ());
VectorWrapper::ensureDim (b, stream1.n ());
VectorWrapper::ensureDim (x, stream1.n ());
VectorWrapper::ensureDim (y, stream1.n ());
int n = (int)d. size();
while (stream1 && stream2) {
commentator().startIteration ((unsigned)stream1.j ());
//ActivityState state = commentator().saveActivityState ();
iter_passed = true;
bool zeroEntry;
do {
stream1.next (d);
zeroEntry = false;
for (size_t i=0; i<stream1.n(); i++)
zeroEntry |= R.isZero(d[(size_t)i]);
} while (zeroEntry);
stream2.next (b);
std::ostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);
report << "Diagonal entries: ";
VD.write (report, d);
report << endl;
report << "Right-hand side: ";
VD.write (report, b);
report << endl;
//Diagonal<Ring> D(R, d);
BlasMatrix<Ring> D(R, n, n);
for(int i = 0; i < n; ++i) R.init (D[(size_t)i][(size_t)i], d[(size_t)i]);
typedef RationalSolver<Ring, Field, LinBox::RandomPrimeIterator> RSolver;
RSolver rsolver;
//std::vector<std::pair<typename Ring::Element, typename Ring::Element> > answer(n);
BlasVector<Ring> num(R,(size_t)n);
typename Ring::Element den;
SolverReturnStatus solveResult = rsolver.solve(num, den, D, b, 30); //often 5 primes are not enough
#if 0
typename Ring::Element lden;
R. init (lden, 1);
typename std::vector<std::pair<typename Ring::Element, typename Ring::Element> >::iterator p;
for (p = answer.begin(); p != answer.end(); ++ p)
R. lcm (lden, lden, p->second);
typename Vector::iterator p_x;
//typename Vector::iterator p_y;
#endif
if (solveResult == SS_OK) {
#if 0
for (p = answer.begin(), p_x = x. begin();
p != answer.end();
++ p, ++ p_x) {
R. mul (*p_x, p->first, lden);
R. divin (*p_x, p->second);
}
D. apply (y, x);
#endif
D. apply (y, num);
VD. mulin(b, den);
if (!VD.areEqual (y, b)) {
ret = iter_passed = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Computed solution is incorrect" << endl;
}
}
else {
ret = iter_passed = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Did not return OK solving status" << endl;
}
commentator().stop ("done");
commentator().progress ();
}
stream1.reset ();
stream2.reset ();
commentator().stop (MSG_STATUS (ret), (const char *) 0, "testNonsingularRandomDiagonalSolve");
return ret;
}
int main(int argc, char** argv)
{
bool pass = true;
static size_t n = 10;
static int iterations = 1;
static Argument args[] = {
{ 'n', "-n N", "Set order of test matrices to N.", TYPE_INT, &n},
{ 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations },
END_OF_ARGUMENTS
};
parseArguments (argc, argv, args);
typedef Modular<int32_t> Field;
// typedef Modular<double> Field;
typedef PID_integer Ring;
Ring R;
Field F(101);
RandomDenseStream<Ring> s1 (R, n, (unsigned int)iterations), s2 (R, n, (unsigned int)iterations);
if (!testRandomSolve(R, F, s1, s2)) pass = false;
return pass ? 0 : -1;
}
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s
// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:
<|endoftext|>
|
<commit_before>// Copyright Daniel Wallin 2008. Use, modification and distribution is
// subject to 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)
#ifndef LUABIND_FORMAT_SIGNATURE_081014_HPP
# define LUABIND_FORMAT_SIGNATURE_081014_HPP
# include <luabind/config.hpp>
# include <luabind/lua_include.hpp>
# include <luabind/typeid.hpp>
# include <boost/mpl/begin_end.hpp>
# include <boost/mpl/next.hpp>
# include <boost/mpl/size.hpp>
namespace luabind {
class object;
class argument;
template <class Base>
struct table;
} // namespace luabind
namespace luabind { namespace detail {
LUABIND_API std::string get_class_name(lua_State* L, type_id const& i);
template <class T>
struct type_to_string
{
static void get(lua_State* L)
{
lua_pushstring(L, get_class_name(L, typeid(T)).c_str());
}
};
template <class T>
struct type_to_string<T*>
{
static void get(lua_State* L)
{
type_to_string<T>::get(L);
lua_pushstring(L, "*");
lua_concat(L, 2);
}
};
template <class T>
struct type_to_string<T&>
{
static void get(lua_State* L)
{
type_to_string<T>::get(L);
lua_pushstring(L, "&");
lua_concat(L, 2);
}
};
template <class T>
struct type_to_string<T const>
{
static void get(lua_State* L)
{
type_to_string<T>::get(L);
lua_pushstring(L, " const");
lua_concat(L, 2);
}
};
# define LUABIND_TYPE_TO_STRING(x) \
template <> \
struct type_to_string<x> \
{ \
static void get(lua_State* L) \
{ \
lua_pushstring(L, #x); \
} \
};
# define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \
LUABIND_TYPE_TO_STRING(x) \
LUABIND_TYPE_TO_STRING(unsigned x)
LUABIND_INTEGRAL_TYPE_TO_STRING(char)
LUABIND_INTEGRAL_TYPE_TO_STRING(short)
LUABIND_INTEGRAL_TYPE_TO_STRING(int)
LUABIND_INTEGRAL_TYPE_TO_STRING(long)
LUABIND_TYPE_TO_STRING(void)
LUABIND_TYPE_TO_STRING(bool)
LUABIND_TYPE_TO_STRING(std::string)
LUABIND_TYPE_TO_STRING(lua_State)
LUABIND_TYPE_TO_STRING(luabind::object)
LUABIND_TYPE_TO_STRING(luabind::argument)
# undef LUABIND_INTEGRAL_TYPE_TO_STRING
# undef LUABIND_TYPE_TO_STRING
template <class Base>
struct type_to_string<table<Base> >
{
static void get(lua_State* L)
{
lua_pushstring(L, "table");
}
};
template <class End>
void format_signature_aux(lua_State*, bool, End, End)
{}
template <class Iter, class End>
void format_signature_aux(lua_State* L, bool first, Iter, End end)
{
if (!first)
lua_pushstring(L, ",");
type_to_string<typename Iter::type>::get(L);
format_signature_aux(L, false, typename mpl::next<Iter>::type(), end);
}
template <class Signature>
void format_signature(lua_State* L, char const* function, Signature)
{
typedef typename mpl::begin<Signature>::type first;
type_to_string<typename first::type>::get(L);
lua_pushstring(L, " ");
lua_pushstring(L, function);
lua_pushstring(L, "(");
format_signature_aux(
L
, true
, typename mpl::next<first>::type()
, typename mpl::end<Signature>::type()
);
lua_pushstring(L, ")");
lua_concat(L, mpl::size<Signature>() * 2 + 2);
}
}} // namespace luabind::detail
#endif // LUABIND_FORMAT_SIGNATURE_081014_HPP
<commit_msg>Fix GCC warning because mpl::size<> is long int.<commit_after>// Copyright Daniel Wallin 2008. Use, modification and distribution is
// subject to 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)
#ifndef LUABIND_FORMAT_SIGNATURE_081014_HPP
# define LUABIND_FORMAT_SIGNATURE_081014_HPP
# include <luabind/config.hpp>
# include <luabind/lua_include.hpp>
# include <luabind/typeid.hpp>
# include <boost/mpl/begin_end.hpp>
# include <boost/mpl/next.hpp>
# include <boost/mpl/size.hpp>
namespace luabind {
class object;
class argument;
template <class Base>
struct table;
} // namespace luabind
namespace luabind { namespace detail {
LUABIND_API std::string get_class_name(lua_State* L, type_id const& i);
template <class T>
struct type_to_string
{
static void get(lua_State* L)
{
lua_pushstring(L, get_class_name(L, typeid(T)).c_str());
}
};
template <class T>
struct type_to_string<T*>
{
static void get(lua_State* L)
{
type_to_string<T>::get(L);
lua_pushstring(L, "*");
lua_concat(L, 2);
}
};
template <class T>
struct type_to_string<T&>
{
static void get(lua_State* L)
{
type_to_string<T>::get(L);
lua_pushstring(L, "&");
lua_concat(L, 2);
}
};
template <class T>
struct type_to_string<T const>
{
static void get(lua_State* L)
{
type_to_string<T>::get(L);
lua_pushstring(L, " const");
lua_concat(L, 2);
}
};
# define LUABIND_TYPE_TO_STRING(x) \
template <> \
struct type_to_string<x> \
{ \
static void get(lua_State* L) \
{ \
lua_pushstring(L, #x); \
} \
};
# define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \
LUABIND_TYPE_TO_STRING(x) \
LUABIND_TYPE_TO_STRING(unsigned x)
LUABIND_INTEGRAL_TYPE_TO_STRING(char)
LUABIND_INTEGRAL_TYPE_TO_STRING(short)
LUABIND_INTEGRAL_TYPE_TO_STRING(int)
LUABIND_INTEGRAL_TYPE_TO_STRING(long)
LUABIND_TYPE_TO_STRING(void)
LUABIND_TYPE_TO_STRING(bool)
LUABIND_TYPE_TO_STRING(std::string)
LUABIND_TYPE_TO_STRING(lua_State)
LUABIND_TYPE_TO_STRING(luabind::object)
LUABIND_TYPE_TO_STRING(luabind::argument)
# undef LUABIND_INTEGRAL_TYPE_TO_STRING
# undef LUABIND_TYPE_TO_STRING
template <class Base>
struct type_to_string<table<Base> >
{
static void get(lua_State* L)
{
lua_pushstring(L, "table");
}
};
template <class End>
void format_signature_aux(lua_State*, bool, End, End)
{}
template <class Iter, class End>
void format_signature_aux(lua_State* L, bool first, Iter, End end)
{
if (!first)
lua_pushstring(L, ",");
type_to_string<typename Iter::type>::get(L);
format_signature_aux(L, false, typename mpl::next<Iter>::type(), end);
}
template <class Signature>
void format_signature(lua_State* L, char const* function, Signature)
{
typedef typename mpl::begin<Signature>::type first;
type_to_string<typename first::type>::get(L);
lua_pushstring(L, " ");
lua_pushstring(L, function);
lua_pushstring(L, "(");
format_signature_aux(
L
, true
, typename mpl::next<first>::type()
, typename mpl::end<Signature>::type()
);
lua_pushstring(L, ")");
lua_concat(L, static_cast<int>(mpl::size<Signature>()) * 2 + 2);
}
}} // namespace luabind::detail
#endif // LUABIND_FORMAT_SIGNATURE_081014_HPP
<|endoftext|>
|
<commit_before>#ifndef CLIENT_HPP
#define CLIENT_HPP
#include <map>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp/node/node.hpp>
#include <rclcpp/publisher/publisher.hpp>
#include <future>
#include <memory>
#include <chrono>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <genidlcpp/resolver.h>
#include <ccpp_dds_dcps.h>
#include <boost/interprocess/sync/interprocess_semaphore.hpp>
namespace rclcpp
{
namespace client
{
template <typename ROSService>
class Client
{
public:
typedef std::shared_ptr< std::promise<typename ROSService::Response::ConstPtr> > shared_promise;
typedef std::shared_ptr< Client<ROSService> > Ptr;
typedef std::shared_future<typename ROSService::Response::ConstPtr> shared_future;
Client(const std::string& client_id, typename rclcpp::publisher::Publisher<typename ROSService::Request>::Ptr publisher, rclcpp::node::Node *node) : client_id_(client_id), publisher_(publisher), node_(node), req_id_(0) {}
~Client() {}
void handle_response(typename ROSService::Response::ConstPtr res)
{
std::cout << "Got response" << std::endl;
shared_promise call_promise = this->pending_calls_[res->req_id];
this->pending_calls_.erase(res->req_id);
call_promise->set_value(res);
}
typename ROSService::Response::ConstPtr call(typename ROSService::Request &req)
{
shared_future f = this->async_call(req);
// NOTE The version (4.6) of GCC that ships with Ubuntu 12.04
// is broken, wait_for should return a std::future_status,
// according to the C++11 spec, not a bool as is GCC's case
std::future_status status;
do {
this->node_->spin_once();
status = f.wait_for(std::chrono::milliseconds(100));
} while (status != std::future_status::ready);
return f.get();
}
shared_future async_call(typename ROSService::Request &req) {
req.req_id = ++(this->req_id_);
req.client_id = client_id_;
shared_promise call_promise(new std::promise<typename ROSService::Response::ConstPtr>);
pending_calls_[req.req_id] = call_promise;
this->publisher_->publish(req);
return shared_future(call_promise->get_future());
}
private:
typename rclcpp::publisher::Publisher<typename ROSService::Request>::Ptr publisher_;
std::map<int, shared_promise> pending_calls_;
std::string client_id_;
int req_id_;
rclcpp::node::Node *node_;
};
}
}
#endif
<commit_msg>make client ctrl+c-able<commit_after>#ifndef CLIENT_HPP
#define CLIENT_HPP
#include <map>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp/node/node.hpp>
#include <rclcpp/publisher/publisher.hpp>
#include <future>
#include <memory>
#include <chrono>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <genidlcpp/resolver.h>
#include <ccpp_dds_dcps.h>
#include <boost/interprocess/sync/interprocess_semaphore.hpp>
namespace rclcpp
{
namespace client
{
template <typename ROSService>
class Client
{
public:
typedef std::shared_ptr< std::promise<typename ROSService::Response::ConstPtr> > shared_promise;
typedef std::shared_ptr< Client<ROSService> > Ptr;
typedef std::shared_future<typename ROSService::Response::ConstPtr> shared_future;
Client(const std::string& client_id, typename rclcpp::publisher::Publisher<typename ROSService::Request>::Ptr publisher, rclcpp::node::Node *node) : client_id_(client_id), publisher_(publisher), node_(node), req_id_(0) {}
~Client() {}
void handle_response(typename ROSService::Response::ConstPtr res)
{
std::cout << "Got response" << std::endl;
shared_promise call_promise = this->pending_calls_[res->req_id];
this->pending_calls_.erase(res->req_id);
call_promise->set_value(res);
}
typename ROSService::Response::ConstPtr call(typename ROSService::Request &req)
{
shared_future f = this->async_call(req);
// NOTE The version (4.6) of GCC that ships with Ubuntu 12.04
// is broken, wait_for should return a std::future_status,
// according to the C++11 spec, not a bool as is GCC's case
std::future_status status;
do {
this->node_->spin_once();
status = f.wait_for(std::chrono::milliseconds(100));
if (!this->node_->is_running())
{
throw std::exception();
}
} while (status != std::future_status::ready);
return f.get();
}
shared_future async_call(typename ROSService::Request &req) {
req.req_id = ++(this->req_id_);
req.client_id = client_id_;
shared_promise call_promise(new std::promise<typename ROSService::Response::ConstPtr>);
pending_calls_[req.req_id] = call_promise;
this->publisher_->publish(req);
return shared_future(call_promise->get_future());
}
private:
typename rclcpp::publisher::Publisher<typename ROSService::Request>::Ptr publisher_;
std::map<int, shared_promise> pending_calls_;
std::string client_id_;
int req_id_;
rclcpp::node::Node *node_;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <cstdio>
#include <random>
#if qPlatform_POSIX
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/ethtool.h>
#include <linux/sockios.h>
#elif qPlatform_Windows
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <Iphlpapi.h>
#include <netioapi.h>
#endif
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/Format.h"
#include "../../Containers/Collection.h"
#include "../../Containers/Mapping.h"
#include "../../Execution/ErrNoException.h"
#include "../../Execution/Finally.h"
#if qPlatform_Windows
#include "../../../Foundation/Execution/Platform/Windows/Exception.h"
#endif
#include "../../Execution/Synchronized.h"
#include "../../Memory/SmallStackBuffer.h"
#include "Socket.h"
#include "Interface.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
#if defined (_MSC_VER)
// support use of Iphlpapi - but better to reference here than in lib entry of project file cuz
// easiser to see/modularize (and only pulled in if this module is referenced)
#pragma comment (lib, "Iphlpapi.lib")
#endif
/*
********************************************************************************
**************************** Network::Interface ********************************
********************************************************************************
*/
const Configuration::EnumNames<Interface::Status> Interface::Stroika_Enum_Names(Status)
{
{ Interface::Status::eConnected, L"Connected" },
{ Interface::Status::eRunning, L"Running" },
};
const Configuration::EnumNames<Interface::Type> Interface::Stroika_Enum_Names(Type)
{
{ Interface::Type::eLoopback, L"Loopback" },
{ Interface::Type::eWiredEthernet, L"WiredEthernet" },
{ Interface::Type::eWIFI, L"WIFI" },
{ Interface::Type::eOther, L"Other" },
};
/*
********************************************************************************
************************** Network::GetInterfaces ******************************
********************************************************************************
*/
Traversal::Iterable<Interface> Network::GetInterfaces ()
{
Collection<Interface> result;
#if qPlatform_POSIX
auto getFlags = [] (int sd, const char* name) {
char buf[1024];
struct ifreq ifreq;
memset(&ifreq, 0, sizeof (ifreq));
strcpy (ifreq.ifr_name, name);
int r = ioctl (sd, SIOCGIFFLAGS, (char*)&ifreq);
Assert (r == 0);
return ifreq.ifr_flags;
};
struct ifreq ifreqs[64];
struct ifconf ifconf;
memset (&ifconf, 0, sizeof(ifconf));
ifconf.ifc_req = ifreqs;
ifconf.ifc_len = sizeof(ifreqs);
int sd = socket (PF_INET, SOCK_STREAM, 0);
Assert (sd >= 0);
Execution::Finally cleanup ([sd] () {
close (sd);
});
int r = ioctl (sd, SIOCGIFCONF, (char*)&ifconf);
Assert (r == 0);
for (int i = 0; i < ifconf.ifc_len / sizeof(struct ifreq); ++i) {
Interface newInterface;
String interfaceName { String::FromSDKString (ifreqs[i].ifr_name) };
newInterface.fInterfaceName = interfaceName;
newInterface.fInternalInterfaceID = interfaceName;
int flags = getFlags (sd, ifreqs[i].ifr_name);
if (flags & IFF_LOOPBACK) {
newInterface.fType = Interface::Type::eLoopback;
}
else {
// NYI
newInterface.fType = Interface::Type::eWiredEthernet; // WAY - not the right way to tell!
}
{
auto getSpeed = [] (int sd, const char* name) -> Optional<double> {
struct ifreq ifreq;
memset(&ifreq, 0, sizeof (ifreq));
strcpy (ifreq.ifr_name, name);
struct ethtool_cmd edata;
memset (&edata, 0, sizeof (edata));
ifreq.ifr_data = reinterpret_cast<caddr_t> (&edata);
edata.cmd = ETHTOOL_GSET;
int r = ioctl(sd, SIOCETHTOOL, &ifreq);
if (r != 0)
{
DbgTrace ("No speed for interface %s, errno=%d", name, errno);
return Optional<double> ();;
}
constexpr double kMegabit_ = 1000 * 1000;
DbgTrace ("ethtool_cmd_speed (&edata)=%d", ethtool_cmd_speed (&edata));
switch (ethtool_cmd_speed (&edata))
{
case SPEED_10:
return 10 * kMegabit_;
case SPEED_100:
return 100 * kMegabit_;
case SPEED_1000:
return 1000 * kMegabit_;
case SPEED_2500:
return 2500 * kMegabit_;
case SPEED_10000:
return 10000 * kMegabit_;
default:
return Optional<double> ();
}
};
newInterface.fTransmitSpeedBaud = getSpeed (sd, ifreqs[i].ifr_name);
newInterface.fReceiveLinkSpeedBaud = newInterface.fTransmitSpeedBaud;
}
{
Containers::Set<Interface::Status> status;
if (flags & IFF_RUNNING) {
// not right!!! But a start...
status.Add (Interface::Status::eConnected);
status.Add (Interface::Status::eRunning);
}
newInterface.fStatus = status;
}
newInterface.fBindings.Add (InternetAddress (((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr)); // @todo fix so works for ipv6 addresses as well!
result.Add (newInterface);
}
#elif qPlatform_Windows
static Synchronized<Mapping<pair<String, IF_INDEX>, String>> sIDMap_;
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
ULONG family = AF_UNSPEC; // Both IPv4 and IPv6 addresses
Memory::SmallStackBuffer<Byte> buf(0);
Again:
ULONG ulOutBufLen = static_cast<ULONG> (buf.GetSize ());
PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES> (buf.begin ());
DWORD dwRetVal = ::GetAdaptersAddresses (family, flags, nullptr, pAddresses, &ulOutBufLen);
if (dwRetVal == NO_ERROR) {
for (PIP_ADAPTER_ADDRESSES currAddresses = pAddresses; currAddresses != nullptr; currAddresses = currAddresses->Next) {
Interface newInterface;
newInterface.fAdapterName = String::FromNarrowSDKString (currAddresses->AdapterName);
{
auto l = sIDMap_.GetReference ();
auto key = pair<String, IF_INDEX> (*newInterface.fAdapterName, currAddresses->IfIndex);
auto o = l->Lookup (key);
if (o) {
newInterface.fInternalInterfaceID = *o;
}
else {
// @todo may not need random number stuff - maybe able to use IF_INDEX as unique key (docs not clear)
std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_int_distribution<int> uniform_dist(1, numeric_limits<int>::max ());
String newID = *newInterface.fAdapterName + Characters::Format (L"_%d", uniform_dist (e1));
newInterface.fInternalInterfaceID = newID;
l->Add (key, newID);
}
}
newInterface.fFriendlyName = currAddresses->FriendlyName;
newInterface.fDescription = currAddresses->Description;
switch (currAddresses->IfType) {
case IF_TYPE_SOFTWARE_LOOPBACK:
newInterface.fType = Interface::Type::eLoopback;
break;
case IF_TYPE_IEEE80211:
newInterface.fType = Interface::Type::eWIFI;
break;
case IF_TYPE_ETHERNET_CSMACD:
newInterface.fType = Interface::Type::eWiredEthernet;
break;
default:
newInterface.fType = Interface::Type::eOther;
break;
}
switch (currAddresses->OperStatus) {
case IfOperStatusUp:
newInterface.fStatus = Set<Interface::Status> ({Interface::Status::eConnected, Interface::Status::eRunning});
break;
case IfOperStatusDown:
newInterface.fStatus = Set<Interface::Status> ();
break;
default:
// Dont know how to interpret the other status states
break;
}
for (PIP_ADAPTER_UNICAST_ADDRESS pu = currAddresses->FirstUnicastAddress; pu != nullptr; pu = pu->Next) {
SocketAddress sa { pu->Address };
if (sa.IsInternetAddress ()) {
newInterface.fBindings.Add (sa.GetInternetAddress ());
}
}
for (PIP_ADAPTER_ANYCAST_ADDRESS pa = currAddresses->FirstAnycastAddress; pa != nullptr; pa = pa->Next) {
SocketAddress sa { pa->Address };
if (sa.IsInternetAddress ()) {
newInterface.fBindings.Add (sa.GetInternetAddress ());
}
}
for (PIP_ADAPTER_MULTICAST_ADDRESS pm = currAddresses->FirstMulticastAddress; pm != nullptr; pm = pm->Next) {
SocketAddress sa { pm->Address };
if (sa.IsInternetAddress ()) {
newInterface.fBindings.Add (sa.GetInternetAddress ());
}
}
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
newInterface.fTransmitSpeedBaud = currAddresses->TransmitLinkSpeed;
newInterface.fReceiveLinkSpeedBaud = currAddresses->ReceiveLinkSpeed;
#endif
result.Add (newInterface);
}
}
else if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
buf.GrowToSize (ulOutBufLen);
goto Again;
}
else if (dwRetVal == ERROR_NO_DATA) {
DbgTrace ("There are no network adapters with IPv4 enabled on the local system");
}
else {
Execution::Platform::Windows::Exception::DoThrow (dwRetVal);
}
#else
AssertNotImplemented ();
#endif
return result;
}
<commit_msg>Lose Synchronized<Mapping<pair<String, IF_INDEX>, String>> sIDMap_ stuff for windows - and just use adapatername as the fInternalInterfaceID<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <cstdio>
#include <random>
#if qPlatform_POSIX
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/ethtool.h>
#include <linux/sockios.h>
#elif qPlatform_Windows
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <Iphlpapi.h>
#include <netioapi.h>
#endif
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/Format.h"
#include "../../Containers/Collection.h"
#include "../../Containers/Mapping.h"
#include "../../Execution/ErrNoException.h"
#include "../../Execution/Finally.h"
#if qPlatform_Windows
#include "../../../Foundation/Execution/Platform/Windows/Exception.h"
#endif
#include "../../Execution/Synchronized.h"
#include "../../Memory/SmallStackBuffer.h"
#include "Socket.h"
#include "Interface.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
#if defined (_MSC_VER)
// support use of Iphlpapi - but better to reference here than in lib entry of project file cuz
// easiser to see/modularize (and only pulled in if this module is referenced)
#pragma comment (lib, "Iphlpapi.lib")
#endif
/*
********************************************************************************
**************************** Network::Interface ********************************
********************************************************************************
*/
const Configuration::EnumNames<Interface::Status> Interface::Stroika_Enum_Names(Status)
{
{ Interface::Status::eConnected, L"Connected" },
{ Interface::Status::eRunning, L"Running" },
};
const Configuration::EnumNames<Interface::Type> Interface::Stroika_Enum_Names(Type)
{
{ Interface::Type::eLoopback, L"Loopback" },
{ Interface::Type::eWiredEthernet, L"WiredEthernet" },
{ Interface::Type::eWIFI, L"WIFI" },
{ Interface::Type::eOther, L"Other" },
};
/*
********************************************************************************
************************** Network::GetInterfaces ******************************
********************************************************************************
*/
Traversal::Iterable<Interface> Network::GetInterfaces ()
{
Collection<Interface> result;
#if qPlatform_POSIX
auto getFlags = [] (int sd, const char* name) {
char buf[1024];
struct ifreq ifreq;
memset(&ifreq, 0, sizeof (ifreq));
strcpy (ifreq.ifr_name, name);
int r = ioctl (sd, SIOCGIFFLAGS, (char*)&ifreq);
Assert (r == 0);
return ifreq.ifr_flags;
};
struct ifreq ifreqs[64];
struct ifconf ifconf;
memset (&ifconf, 0, sizeof(ifconf));
ifconf.ifc_req = ifreqs;
ifconf.ifc_len = sizeof(ifreqs);
int sd = socket (PF_INET, SOCK_STREAM, 0);
Assert (sd >= 0);
Execution::Finally cleanup ([sd] () {
close (sd);
});
int r = ioctl (sd, SIOCGIFCONF, (char*)&ifconf);
Assert (r == 0);
for (int i = 0; i < ifconf.ifc_len / sizeof(struct ifreq); ++i) {
Interface newInterface;
String interfaceName { String::FromSDKString (ifreqs[i].ifr_name) };
newInterface.fInterfaceName = interfaceName;
newInterface.fInternalInterfaceID = interfaceName;
int flags = getFlags (sd, ifreqs[i].ifr_name);
if (flags & IFF_LOOPBACK) {
newInterface.fType = Interface::Type::eLoopback;
}
else {
// NYI
newInterface.fType = Interface::Type::eWiredEthernet; // WAY - not the right way to tell!
}
{
auto getSpeed = [] (int sd, const char* name) -> Optional<double> {
struct ifreq ifreq;
memset(&ifreq, 0, sizeof (ifreq));
strcpy (ifreq.ifr_name, name);
struct ethtool_cmd edata;
memset (&edata, 0, sizeof (edata));
ifreq.ifr_data = reinterpret_cast<caddr_t> (&edata);
edata.cmd = ETHTOOL_GSET;
int r = ioctl(sd, SIOCETHTOOL, &ifreq);
if (r != 0)
{
DbgTrace ("No speed for interface %s, errno=%d", name, errno);
return Optional<double> ();;
}
constexpr double kMegabit_ = 1000 * 1000;
DbgTrace ("ethtool_cmd_speed (&edata)=%d", ethtool_cmd_speed (&edata));
switch (ethtool_cmd_speed (&edata))
{
case SPEED_10:
return 10 * kMegabit_;
case SPEED_100:
return 100 * kMegabit_;
case SPEED_1000:
return 1000 * kMegabit_;
case SPEED_2500:
return 2500 * kMegabit_;
case SPEED_10000:
return 10000 * kMegabit_;
default:
return Optional<double> ();
}
};
newInterface.fTransmitSpeedBaud = getSpeed (sd, ifreqs[i].ifr_name);
newInterface.fReceiveLinkSpeedBaud = newInterface.fTransmitSpeedBaud;
}
{
Containers::Set<Interface::Status> status;
if (flags & IFF_RUNNING) {
// not right!!! But a start...
status.Add (Interface::Status::eConnected);
status.Add (Interface::Status::eRunning);
}
newInterface.fStatus = status;
}
newInterface.fBindings.Add (InternetAddress (((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr)); // @todo fix so works for ipv6 addresses as well!
result.Add (newInterface);
}
#elif qPlatform_Windows
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
ULONG family = AF_UNSPEC; // Both IPv4 and IPv6 addresses
Memory::SmallStackBuffer<Byte> buf(0);
Again:
ULONG ulOutBufLen = static_cast<ULONG> (buf.GetSize ());
PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES> (buf.begin ());
DWORD dwRetVal = ::GetAdaptersAddresses (family, flags, nullptr, pAddresses, &ulOutBufLen);
if (dwRetVal == NO_ERROR) {
for (PIP_ADAPTER_ADDRESSES currAddresses = pAddresses; currAddresses != nullptr; currAddresses = currAddresses->Next) {
Interface newInterface;
String adapterName { String::FromNarrowSDKString (currAddresses->AdapterName) };
newInterface.fAdapterName = adapterName;
newInterface.fInternalInterfaceID = adapterName;
newInterface.fFriendlyName = currAddresses->FriendlyName;
newInterface.fDescription = currAddresses->Description;
switch (currAddresses->IfType) {
case IF_TYPE_SOFTWARE_LOOPBACK:
newInterface.fType = Interface::Type::eLoopback;
break;
case IF_TYPE_IEEE80211:
newInterface.fType = Interface::Type::eWIFI;
break;
case IF_TYPE_ETHERNET_CSMACD:
newInterface.fType = Interface::Type::eWiredEthernet;
break;
default:
newInterface.fType = Interface::Type::eOther;
break;
}
switch (currAddresses->OperStatus) {
case IfOperStatusUp:
newInterface.fStatus = Set<Interface::Status> ({Interface::Status::eConnected, Interface::Status::eRunning});
break;
case IfOperStatusDown:
newInterface.fStatus = Set<Interface::Status> ();
break;
default:
// Dont know how to interpret the other status states
break;
}
for (PIP_ADAPTER_UNICAST_ADDRESS pu = currAddresses->FirstUnicastAddress; pu != nullptr; pu = pu->Next) {
SocketAddress sa { pu->Address };
if (sa.IsInternetAddress ()) {
newInterface.fBindings.Add (sa.GetInternetAddress ());
}
}
for (PIP_ADAPTER_ANYCAST_ADDRESS pa = currAddresses->FirstAnycastAddress; pa != nullptr; pa = pa->Next) {
SocketAddress sa { pa->Address };
if (sa.IsInternetAddress ()) {
newInterface.fBindings.Add (sa.GetInternetAddress ());
}
}
for (PIP_ADAPTER_MULTICAST_ADDRESS pm = currAddresses->FirstMulticastAddress; pm != nullptr; pm = pm->Next) {
SocketAddress sa { pm->Address };
if (sa.IsInternetAddress ()) {
newInterface.fBindings.Add (sa.GetInternetAddress ());
}
}
#if (NTDDI_VERSION >= NTDDI_LONGHORN)
newInterface.fTransmitSpeedBaud = currAddresses->TransmitLinkSpeed;
newInterface.fReceiveLinkSpeedBaud = currAddresses->ReceiveLinkSpeed;
#endif
result.Add (newInterface);
}
}
else if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
buf.GrowToSize (ulOutBufLen);
goto Again;
}
else if (dwRetVal == ERROR_NO_DATA) {
DbgTrace ("There are no network adapters with IPv4 enabled on the local system");
}
else {
Execution::Platform::Windows::Exception::DoThrow (dwRetVal);
}
#else
AssertNotImplemented ();
#endif
return result;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbSamplingRateCalculator.h"
#include "otbStringUtils.h"
#include "otbMacro.h"
#include <sstream>
#include <fstream>
#include <iterator>
#include "itksys/SystemTools.hxx"
namespace otb
{
bool
SamplingRateCalculator::TripletType::operator==(const SamplingRateCalculator::TripletType & triplet) const
{
return bool((Required == triplet.Required)||
(Tot == triplet.Tot)||
(Rate == triplet.Rate));
}
SamplingRateCalculator
::SamplingRateCalculator()
{
}
void
SamplingRateCalculator
::SetMinimumNbOfSamplesByClass(void)
{
unsigned long smallestNbofSamples = itk::NumericTraits<unsigned long>::max();
MapRateType::iterator it = m_RatesByClass.begin();
for (; it != m_RatesByClass.end() ; ++it)
{
if (smallestNbofSamples > it->second.Tot)
{
smallestNbofSamples = it->second.Tot;
}
}
// Check if there is an empty class
if (smallestNbofSamples == 0UL)
{
otbWarningMacro("There is an empty class, sample size is set to zero!");
}
this->SetNbOfSamplesAllClasses( smallestNbofSamples );
}
void
SamplingRateCalculator
::SetNbOfSamplesAllClasses(unsigned long dRequiredNbSamples)
{
MapRateType::iterator it = m_RatesByClass.begin();
for (; it != m_RatesByClass.end() ; ++it)
{
it->second.Required = dRequiredNbSamples;
this->UpdateRate(it->first);
}
}
void
SamplingRateCalculator
::SetNbOfSamplesByClass(const ClassCountMapType &required)
{
ClassCountMapType::const_iterator it = required.begin();
for (; it != required.end() ; ++it)
{
if (m_RatesByClass.count(it->first))
{
m_RatesByClass[it->first].Required = it->second;
this->UpdateRate(it->first);
}
else
{
TripletType triplet;
triplet.Tot = it->second;
triplet.Required = 0UL;
triplet.Rate = 0.0;
m_RatesByClass[it->first] = triplet;
}
}
}
void
SamplingRateCalculator
::SetAllSamples(void)
{
MapRateType::iterator it = m_RatesByClass.begin();
for (; it != m_RatesByClass.end() ; ++it)
{
it->second.Required = it->second.Tot;
it->second.Rate = 1.0;
}
}
void
SamplingRateCalculator
::Write(std::string filename)
{
std::ofstream file(filename.c_str(), std::ios::out | std::ios::trunc);
if (file)
{
itk::Indent indent(0);
this->PrintSelf(file,indent);
file.close();
}
else
{
itkExceptionMacro(<< " Couldn't open " << filename);
}
}
void
SamplingRateCalculator
::Read(std::string filename)
{
std::ifstream ifs(filename.c_str());
if (ifs)
{
this->ClearRates();
std::string line;
TripletType tpt;
std::string sep("");
while(!ifs.eof())
{
std::getline(ifs,line);
if (line.empty()) continue;
std::string::size_type pos = line.find_first_not_of(" \t");
if (pos != std::string::npos && line[pos] == '#') continue;
if (sep.size() == 0)
{
// Try to detect the separator
std::string separators("\t;,");
for (unsigned int k=0 ; k<separators.size() ; k++)
{
std::vector<itksys::String> words = itksys::SystemTools::SplitString(line,separators[k]);
if (words.size() == 4)
{
sep.push_back(separators[k]);
break;
}
}
if (sep.size() == 0) continue;
}
// parse the line
std::vector<itksys::String> parts = itksys::SystemTools::SplitString(line,sep[0]);
if (parts.size() == 4)
{
std::string::size_type pos1 = parts[0].find_first_not_of(" \t");
std::string::size_type pos2 = parts[0].find_last_not_of(" \t");
std::string::size_type pos3 = parts[1].find_first_not_of(" \t");
std::string::size_type pos4 = parts[1].find_last_not_of(" \t");
std::string::size_type pos5 = parts[2].find_first_not_of(" \t");
std::string::size_type pos6 = parts[2].find_last_not_of(" \t");
std::string::size_type pos7 = parts[3].find_first_not_of(" \t");
std::string::size_type pos8 = parts[3].find_last_not_of(" \t");
if (pos1 != std::string::npos && pos3 != std::string::npos &&
pos5 != std::string::npos && pos7 != std::string::npos)
{
std::string name = parts[0].substr(pos1, pos2 - pos1 + 1);
std::string val1 = parts[1].substr(pos3, pos4 - pos3 + 1);
std::string val2 = parts[2].substr(pos5, pos6 - pos5 + 1);
std::string val3 = parts[3].substr(pos7, pos8 - pos7 + 1);
tpt.Required = boost::lexical_cast<unsigned long>(val1);
tpt.Tot = boost::lexical_cast<unsigned long>(val2);
tpt.Rate = boost::lexical_cast<double>(val3);
m_RatesByClass[name] = tpt;
}
}
}
ifs.close();
}
else
{
itkExceptionMacro(<< " Couldn't open " << filename);
}
}
void
SamplingRateCalculator
::SetClassCount(const ClassCountMapType& map)
{
ClassCountMapType::const_iterator it = map.begin();
for (; it != map.end() ; ++it)
{
if (m_RatesByClass.count(it->first))
{
m_RatesByClass[it->first].Tot = it->second;
this->UpdateRate(it->first);
}
else
{
TripletType triplet;
triplet.Tot = it->second;
triplet.Required = 0UL;
triplet.Rate = 0.0;
m_RatesByClass[it->first] = triplet;
}
}
}
void
SamplingRateCalculator
::ClearRates(void)
{
m_RatesByClass.clear();
}
void
SamplingRateCalculator
::UpdateRate(const std::string &name)
{
if (m_RatesByClass[name].Tot)
{
m_RatesByClass[name].Rate = std::min(
static_cast<double>(m_RatesByClass[name].Required) /
static_cast<double>(m_RatesByClass[name].Tot),
1.0);
}
else
{
// Set to 0 as rate is undefined
m_RatesByClass[name].Rate = 0.0;
}
}
void
SamplingRateCalculator
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
os << indent << "#className requiredSamples totalSamples rate" << std::endl;
MapRateType::const_iterator itRates = m_RatesByClass.begin();
for(; itRates != m_RatesByClass.end(); ++itRates)
{
TripletType tpt=itRates->second;
os << indent << itRates->first << "\t" << tpt.Required << "\t" << tpt.Tot << "\t" << tpt.Rate << std::endl;
}
}
} // End namespace otb
<commit_msg>BUG: switch Tot and Required<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbSamplingRateCalculator.h"
#include "otbStringUtils.h"
#include "otbMacro.h"
#include <sstream>
#include <fstream>
#include <iterator>
#include "itksys/SystemTools.hxx"
namespace otb
{
bool
SamplingRateCalculator::TripletType::operator==(const SamplingRateCalculator::TripletType & triplet) const
{
return bool((Required == triplet.Required)||
(Tot == triplet.Tot)||
(Rate == triplet.Rate));
}
SamplingRateCalculator
::SamplingRateCalculator()
{
}
void
SamplingRateCalculator
::SetMinimumNbOfSamplesByClass(void)
{
unsigned long smallestNbofSamples = itk::NumericTraits<unsigned long>::max();
MapRateType::iterator it = m_RatesByClass.begin();
for (; it != m_RatesByClass.end() ; ++it)
{
if (smallestNbofSamples > it->second.Tot)
{
smallestNbofSamples = it->second.Tot;
}
}
// Check if there is an empty class
if (smallestNbofSamples == 0UL)
{
otbWarningMacro("There is an empty class, sample size is set to zero!");
}
this->SetNbOfSamplesAllClasses( smallestNbofSamples );
}
void
SamplingRateCalculator
::SetNbOfSamplesAllClasses(unsigned long dRequiredNbSamples)
{
MapRateType::iterator it = m_RatesByClass.begin();
for (; it != m_RatesByClass.end() ; ++it)
{
it->second.Required = dRequiredNbSamples;
this->UpdateRate(it->first);
}
}
void
SamplingRateCalculator
::SetNbOfSamplesByClass(const ClassCountMapType &required)
{
ClassCountMapType::const_iterator it = required.begin();
for (; it != required.end() ; ++it)
{
if (m_RatesByClass.count(it->first))
{
m_RatesByClass[it->first].Required = it->second;
this->UpdateRate(it->first);
}
else
{
TripletType triplet;
triplet.Tot = 0UL;
triplet.Required = it->second;
triplet.Rate = 0.0;
m_RatesByClass[it->first] = triplet;
}
}
}
void
SamplingRateCalculator
::SetAllSamples(void)
{
MapRateType::iterator it = m_RatesByClass.begin();
for (; it != m_RatesByClass.end() ; ++it)
{
it->second.Required = it->second.Tot;
it->second.Rate = 1.0;
}
}
void
SamplingRateCalculator
::Write(std::string filename)
{
std::ofstream file(filename.c_str(), std::ios::out | std::ios::trunc);
if (file)
{
itk::Indent indent(0);
this->PrintSelf(file,indent);
file.close();
}
else
{
itkExceptionMacro(<< " Couldn't open " << filename);
}
}
void
SamplingRateCalculator
::Read(std::string filename)
{
std::ifstream ifs(filename.c_str());
if (ifs)
{
this->ClearRates();
std::string line;
TripletType tpt;
std::string sep("");
while(!ifs.eof())
{
std::getline(ifs,line);
if (line.empty()) continue;
std::string::size_type pos = line.find_first_not_of(" \t");
if (pos != std::string::npos && line[pos] == '#') continue;
if (sep.size() == 0)
{
// Try to detect the separator
std::string separators("\t;,");
for (unsigned int k=0 ; k<separators.size() ; k++)
{
std::vector<itksys::String> words = itksys::SystemTools::SplitString(line,separators[k]);
if (words.size() == 4)
{
sep.push_back(separators[k]);
break;
}
}
if (sep.size() == 0) continue;
}
// parse the line
std::vector<itksys::String> parts = itksys::SystemTools::SplitString(line,sep[0]);
if (parts.size() == 4)
{
std::string::size_type pos1 = parts[0].find_first_not_of(" \t");
std::string::size_type pos2 = parts[0].find_last_not_of(" \t");
std::string::size_type pos3 = parts[1].find_first_not_of(" \t");
std::string::size_type pos4 = parts[1].find_last_not_of(" \t");
std::string::size_type pos5 = parts[2].find_first_not_of(" \t");
std::string::size_type pos6 = parts[2].find_last_not_of(" \t");
std::string::size_type pos7 = parts[3].find_first_not_of(" \t");
std::string::size_type pos8 = parts[3].find_last_not_of(" \t");
if (pos1 != std::string::npos && pos3 != std::string::npos &&
pos5 != std::string::npos && pos7 != std::string::npos)
{
std::string name = parts[0].substr(pos1, pos2 - pos1 + 1);
std::string val1 = parts[1].substr(pos3, pos4 - pos3 + 1);
std::string val2 = parts[2].substr(pos5, pos6 - pos5 + 1);
std::string val3 = parts[3].substr(pos7, pos8 - pos7 + 1);
tpt.Required = boost::lexical_cast<unsigned long>(val1);
tpt.Tot = boost::lexical_cast<unsigned long>(val2);
tpt.Rate = boost::lexical_cast<double>(val3);
m_RatesByClass[name] = tpt;
}
}
}
ifs.close();
}
else
{
itkExceptionMacro(<< " Couldn't open " << filename);
}
}
void
SamplingRateCalculator
::SetClassCount(const ClassCountMapType& map)
{
ClassCountMapType::const_iterator it = map.begin();
for (; it != map.end() ; ++it)
{
if (m_RatesByClass.count(it->first))
{
m_RatesByClass[it->first].Tot = it->second;
this->UpdateRate(it->first);
}
else
{
TripletType triplet;
triplet.Tot = it->second;
triplet.Required = 0UL;
triplet.Rate = 0.0;
m_RatesByClass[it->first] = triplet;
}
}
}
void
SamplingRateCalculator
::ClearRates(void)
{
m_RatesByClass.clear();
}
void
SamplingRateCalculator
::UpdateRate(const std::string &name)
{
if (m_RatesByClass[name].Tot)
{
m_RatesByClass[name].Rate = std::min(
static_cast<double>(m_RatesByClass[name].Required) /
static_cast<double>(m_RatesByClass[name].Tot),
1.0);
}
else
{
// Set to 0 as rate is undefined
m_RatesByClass[name].Rate = 0.0;
}
}
void
SamplingRateCalculator
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
os << indent << "#className requiredSamples totalSamples rate" << std::endl;
MapRateType::const_iterator itRates = m_RatesByClass.begin();
for(; itRates != m_RatesByClass.end(); ++itRates)
{
TripletType tpt=itRates->second;
os << indent << itRates->first << "\t" << tpt.Required << "\t" << tpt.Tot << "\t" << tpt.Rate << std::endl;
}
}
} // End namespace otb
<|endoftext|>
|
<commit_before>#include <cppunit/Portability.h>
#include <cppunit/Test.h>
#include <cppunit/TestPath.h>
#include <stdexcept>
CPPUNIT_NS_BEGIN
TestPath::TestPath()
{
}
TestPath::TestPath( Test *root )
{
add( root );
}
TestPath::TestPath( const TestPath &other,
int indexFirst,
int count )
{
int countAdjustment = 0;
if ( indexFirst < 0 )
{
countAdjustment = indexFirst;
indexFirst = 0;
}
if ( count < 0 )
count = other.getTestCount();
else
count += countAdjustment;
int index = indexFirst;
while ( count-- > 0 && index < other.getTestCount() )
add( other.getTestAt( index++ ) );
}
TestPath::TestPath( Test *searchRoot,
const std::string &pathAsString )
{
PathTestNames testNames;
Test *parentTest = findActualRoot( searchRoot, pathAsString, testNames );
add( parentTest );
for ( unsigned int index = 1; index < testNames.size(); ++index )
{
bool childFound = false;
for ( int childIndex =0; childIndex < parentTest->getChildTestCount(); ++childIndex )
{
if ( parentTest->getChildTestAt( childIndex )->getName() == testNames[index] )
{
childFound = true;
parentTest = parentTest->getChildTestAt( childIndex );
break;
}
}
if ( !childFound )
throw std::invalid_argument( "TestPath::TestPath(): failed to resolve test name <"+
testNames[index] + "> of path <" + pathAsString + ">" );
add( parentTest );
}
}
TestPath::TestPath( const TestPath &other )
: m_tests( other.m_tests )
{
}
TestPath::~TestPath()
{
}
TestPath &
TestPath::operator =( const TestPath &other )
{
if ( &other != this )
m_tests = other.m_tests;
return *this;
}
bool
TestPath::isValid() const
{
return getTestCount() > 0;
}
void
TestPath::add( Test *test )
{
m_tests.push_back( test );
}
void
TestPath::add( const TestPath &path )
{
for ( int index =0; index < path.getTestCount(); ++index )
add( path.getTestAt( index ) );
}
void
TestPath::insert( Test *test,
int index )
{
if ( index < 0 || index > getTestCount() )
throw std::out_of_range( "TestPath::insert(): index out of range" );
m_tests.insert( m_tests.begin() + index, test );
}
void
TestPath::insert( const TestPath &path,
int index )
{
int itemIndex = path.getTestCount() -1;
while ( itemIndex >= 0 )
insert( path.getTestAt( itemIndex-- ), index );
}
void
TestPath::removeTests()
{
while ( isValid() )
removeTest( 0 );
}
void
TestPath::removeTest( int index )
{
checkIndexValid( index );
m_tests.erase( m_tests.begin() + index );
}
void
TestPath::up()
{
checkIndexValid( 0 );
removeTest( getTestCount() -1 );
}
int
TestPath::getTestCount() const
{
return m_tests.size();
}
Test *
TestPath::getTestAt( int index ) const
{
checkIndexValid( index );
return m_tests[index];
}
Test *
TestPath::getChildTest() const
{
return getTestAt( getTestCount() -1 );
}
void
TestPath::checkIndexValid( int index ) const
{
if ( index < 0 || index >= getTestCount() )
throw std::out_of_range( "TestPath::checkIndexValid(): index out of range" );
}
std::string
TestPath::toString() const
{
std::string asString( "/" );
for ( int index =0; index < getTestCount(); ++index )
{
if ( index > 0 )
asString += '/';
asString += getTestAt(index)->getName();
}
return asString;
}
Test *
TestPath::findActualRoot( Test *searchRoot,
const std::string &pathAsString,
PathTestNames &testNames )
{
bool isRelative = splitPathString( pathAsString, testNames );
if ( isRelative && pathAsString.empty() )
return searchRoot;
if ( testNames.empty() )
throw std::invalid_argument( "TestPath::TestPath(): invalid root or root name in absolute path" );
Test *root = isRelative ? searchRoot->findTest( testNames[0] ) // throw if bad test name
: searchRoot;
if ( root->getName() != testNames[0] )
throw std::invalid_argument( "TestPath::TestPath(): searchRoot does not match path root name" );
return root;
}
bool
TestPath::splitPathString( const std::string &pathAsString,
PathTestNames &testNames )
{
bool isRelative = pathAsString.length() && pathAsString[0] != '/';
int index = (isRelative ? 0 : 1);
while ( true )
{
int separatorIndex = pathAsString.find( '/', index );
if ( separatorIndex >= 0 )
{
testNames.push_back( pathAsString.substr( index, separatorIndex - index ) );
index = separatorIndex + 1;
}
else
{
testNames.push_back( pathAsString.substr( index ) );
break;
}
}
return isRelative;
}
CPPUNIT_NS_END
<commit_msg>* src/cppunit/TestPath.cpp: bug #938753, array bound read in splitPathString() with substr if an empty string is passed.<commit_after>#include <cppunit/Portability.h>
#include <cppunit/Test.h>
#include <cppunit/TestPath.h>
#include <stdexcept>
CPPUNIT_NS_BEGIN
TestPath::TestPath()
{
}
TestPath::TestPath( Test *root )
{
add( root );
}
TestPath::TestPath( const TestPath &other,
int indexFirst,
int count )
{
int countAdjustment = 0;
if ( indexFirst < 0 )
{
countAdjustment = indexFirst;
indexFirst = 0;
}
if ( count < 0 )
count = other.getTestCount();
else
count += countAdjustment;
int index = indexFirst;
while ( count-- > 0 && index < other.getTestCount() )
add( other.getTestAt( index++ ) );
}
TestPath::TestPath( Test *searchRoot,
const std::string &pathAsString )
{
PathTestNames testNames;
Test *parentTest = findActualRoot( searchRoot, pathAsString, testNames );
add( parentTest );
for ( unsigned int index = 1; index < testNames.size(); ++index )
{
bool childFound = false;
for ( int childIndex =0; childIndex < parentTest->getChildTestCount(); ++childIndex )
{
if ( parentTest->getChildTestAt( childIndex )->getName() == testNames[index] )
{
childFound = true;
parentTest = parentTest->getChildTestAt( childIndex );
break;
}
}
if ( !childFound )
throw std::invalid_argument( "TestPath::TestPath(): failed to resolve test name <"+
testNames[index] + "> of path <" + pathAsString + ">" );
add( parentTest );
}
}
TestPath::TestPath( const TestPath &other )
: m_tests( other.m_tests )
{
}
TestPath::~TestPath()
{
}
TestPath &
TestPath::operator =( const TestPath &other )
{
if ( &other != this )
m_tests = other.m_tests;
return *this;
}
bool
TestPath::isValid() const
{
return getTestCount() > 0;
}
void
TestPath::add( Test *test )
{
m_tests.push_back( test );
}
void
TestPath::add( const TestPath &path )
{
for ( int index =0; index < path.getTestCount(); ++index )
add( path.getTestAt( index ) );
}
void
TestPath::insert( Test *test,
int index )
{
if ( index < 0 || index > getTestCount() )
throw std::out_of_range( "TestPath::insert(): index out of range" );
m_tests.insert( m_tests.begin() + index, test );
}
void
TestPath::insert( const TestPath &path,
int index )
{
int itemIndex = path.getTestCount() -1;
while ( itemIndex >= 0 )
insert( path.getTestAt( itemIndex-- ), index );
}
void
TestPath::removeTests()
{
while ( isValid() )
removeTest( 0 );
}
void
TestPath::removeTest( int index )
{
checkIndexValid( index );
m_tests.erase( m_tests.begin() + index );
}
void
TestPath::up()
{
checkIndexValid( 0 );
removeTest( getTestCount() -1 );
}
int
TestPath::getTestCount() const
{
return m_tests.size();
}
Test *
TestPath::getTestAt( int index ) const
{
checkIndexValid( index );
return m_tests[index];
}
Test *
TestPath::getChildTest() const
{
return getTestAt( getTestCount() -1 );
}
void
TestPath::checkIndexValid( int index ) const
{
if ( index < 0 || index >= getTestCount() )
throw std::out_of_range( "TestPath::checkIndexValid(): index out of range" );
}
std::string
TestPath::toString() const
{
std::string asString( "/" );
for ( int index =0; index < getTestCount(); ++index )
{
if ( index > 0 )
asString += '/';
asString += getTestAt(index)->getName();
}
return asString;
}
Test *
TestPath::findActualRoot( Test *searchRoot,
const std::string &pathAsString,
PathTestNames &testNames )
{
bool isRelative = splitPathString( pathAsString, testNames );
if ( isRelative && pathAsString.empty() )
return searchRoot;
if ( testNames.empty() )
throw std::invalid_argument( "TestPath::TestPath(): invalid root or root name in absolute path" );
Test *root = isRelative ? searchRoot->findTest( testNames[0] ) // throw if bad test name
: searchRoot;
if ( root->getName() != testNames[0] )
throw std::invalid_argument( "TestPath::TestPath(): searchRoot does not match path root name" );
return root;
}
bool
TestPath::splitPathString( const std::string &pathAsString,
PathTestNames &testNames )
{
if ( pathAsString.empty() )
return true;
bool isRelative = pathAsString[0] != '/';
int index = (isRelative ? 0 : 1);
while ( true )
{
int separatorIndex = pathAsString.find( '/', index );
if ( separatorIndex >= 0 )
{
testNames.push_back( pathAsString.substr( index, separatorIndex - index ) );
index = separatorIndex + 1;
}
else
{
testNames.push_back( pathAsString.substr( index ) );
break;
}
}
return isRelative;
}
CPPUNIT_NS_END
<|endoftext|>
|
<commit_before>// @(#)root/graf:$Id$
// Author: Rene Brun 12/05/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TVirtualPad.h"
#include "TMarker.h"
#include "TVirtualX.h"
#include "TMath.h"
#include "TPoint.h"
#include "TText.h"
#include "TClass.h"
ClassImp(TMarker)
//______________________________________________________________________________
//
// Manages Markers. Marker attributes are managed by TAttMarker.
// The list of standard ROOT markers is shown in this picture
//Begin_Html
/*
<img src="gif/markers.gif">
*/
//End_Html
//
//______________________________________________________________________________
TMarker::TMarker(): TObject(), TAttMarker()
{
// Marker default constructor.
fX = 0;
fY = 0;
}
//______________________________________________________________________________
TMarker::TMarker(Double_t x, Double_t y, Int_t marker)
:TObject(), TAttMarker()
{
// Marker normal constructor.
fX = x;
fY = y;
fMarkerStyle = marker;
}
//______________________________________________________________________________
TMarker::~TMarker()
{
// Marker default destructor.
}
//______________________________________________________________________________
TMarker::TMarker(const TMarker &marker) : TObject(marker), TAttMarker(marker)
{
// Marker copy constructor.
fX = 0;
fY = 0;
((TMarker&)marker).Copy(*this);
}
//______________________________________________________________________________
void TMarker::Copy(TObject &obj) const
{
// Copy this marker to marker.
TObject::Copy(obj);
TAttMarker::Copy(((TMarker&)obj));
((TMarker&)obj).fX = fX;
((TMarker&)obj).fY = fY;
}
//______________________________________________________________________________
void TMarker::DisplayMarkerTypes()
{
// Display the table of markers with their numbers.
TMarker *marker = new TMarker();
marker->SetMarkerSize(3);
TText *text = new TText();
text->SetTextFont(62);
text->SetTextAlign(22);
text->SetTextSize(0.1);
char atext[] = " ";
Double_t x = 0;
Double_t dx = 1/16.0;
for (Int_t i=1;i<16;i++) {
x += dx;
snprintf(atext,7,"%d",i);
marker->SetMarkerStyle(i);
marker->DrawMarker(x,.35);
text->DrawText(x,.17,atext);
snprintf(atext,7,"%d",i+19);
marker->SetMarkerStyle(i+19);
marker->DrawMarker(x,.8);
text->DrawText(x,.62,atext);
}
delete marker;
delete text;
}
//______________________________________________________________________________
Int_t TMarker::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to a marker.
//
// Compute the closest distance of approach from point px,py to this marker.
// The distance is computed in pixels units.
Int_t pxm, pym;
if (TestBit(kMarkerNDC)) {
pxm = gPad->UtoPixel(fX);
pym = gPad->VtoPixel(fY);
} else {
pxm = gPad->XtoAbsPixel(gPad->XtoPad(fX));
pym = gPad->YtoAbsPixel(gPad->YtoPad(fY));
}
Int_t dist = (Int_t)TMath::Sqrt((px-pxm)*(px-pxm) + (py-pym)*(py-pym));
//marker size = 1 is about 8 pixels
Int_t markerRadius = Int_t(4*fMarkerSize);
if (dist <= markerRadius) return 0;
if (dist > markerRadius+3) return 999;
return dist;
}
//______________________________________________________________________________
void TMarker::Draw(Option_t *option)
{
// Draw this marker with its current attributes.
AppendPad(option);
}
//______________________________________________________________________________
void TMarker::DrawMarker(Double_t x, Double_t y)
{
// Draw this marker with new coordinates.
TMarker *newmarker = new TMarker(x, y, 1);
TAttMarker::Copy(*newmarker);
newmarker->SetBit(kCanDelete);
newmarker->AppendPad();
}
//______________________________________________________________________________
void TMarker::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
// Execute action corresponding to one event.
//
// This member function is called when a marker is clicked with the locator
//
// If Left button is clicked on a marker, the marker is moved to
// a new position when the mouse button is released.
TPoint p;
static Int_t pxold, pyold;
if (!gPad->IsEditable()) return;
switch (event) {
case kButton1Down:
gVirtualX->SetTextColor(-1); // invalidate current text color (use xor mode)
TAttMarker::Modify(); //Change marker attributes only if necessary
// No break !!!
case kMouseMotion:
pxold = px; pyold = py;
gPad->SetCursor(kMove);
break;
case kButton1Motion:
p.fX = pxold; p.fY = pyold;
gVirtualX->DrawPolyMarker(1, &p);
p.fX = px; p.fY = py;
gVirtualX->DrawPolyMarker(1, &p);
pxold = px; pyold = py;
break;
case kButton1Up:
Double_t dpx, dpy, xp1,yp1;
if (TestBit(kMarkerNDC)) {
dpx = gPad->GetX2() - gPad->GetX1();
dpy = gPad->GetY2() - gPad->GetY1();
xp1 = gPad->GetX1();
yp1 = gPad->GetY1();
fX = (gPad->AbsPixeltoX(pxold)-xp1)/dpx;
fY = (gPad->AbsPixeltoY(pyold)-yp1)/dpy;
} else {
fX = gPad->PadtoX(gPad->AbsPixeltoX(px));
fY = gPad->PadtoY(gPad->AbsPixeltoY(py));
}
gPad->Modified(kTRUE);
gVirtualX->SetTextColor(-1);
break;
}
}
//______________________________________________________________________________
void TMarker::ls(Option_t *) const
{
// List this marker with its attributes.
TROOT::IndentLevel();
printf("Marker X=%f Y=%f marker type=%d\n",fX,fY,fMarkerStyle);
}
//______________________________________________________________________________
void TMarker::Paint(Option_t *)
{
// Paint this marker with its current attributes.
if (TestBit(kMarkerNDC)) {
Double_t u = gPad->GetX1() + fX*(gPad->GetX2()-gPad->GetX1());
Double_t v = gPad->GetY1() + fY*(gPad->GetY2()-gPad->GetY1());
PaintMarker(u,v);
} else {
PaintMarker(gPad->XtoPad(fX),gPad->YtoPad(fY));
}
}
//______________________________________________________________________________
void TMarker::PaintMarker(Double_t x, Double_t y)
{
// Draw this marker with new coordinates.
TAttMarker::Modify(); //Change line attributes only if necessary
gPad->PaintPolyMarker(-1,&x,&y,"");
}
//______________________________________________________________________________
void TMarker::PaintMarkerNDC(Double_t, Double_t)
{
// Draw this marker with new coordinates in NDC.
}
//______________________________________________________________________________
void TMarker::Print(Option_t *) const
{
// Dump this marker with its attributes.
printf("Marker X=%f Y=%f",fX,fY);
if (GetMarkerColor() != 1) printf(" Color=%d",GetMarkerColor());
if (GetMarkerStyle() != 1) printf(" MarkerStyle=%d",GetMarkerStyle());
if (GetMarkerSize() != 1) printf(" MarkerSize=%f",GetMarkerSize());
printf("\n");
}
//______________________________________________________________________________
void TMarker::SavePrimitive(std::ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
if (gROOT->ClassSaved(TMarker::Class())) {
out<<" ";
} else {
out<<" TMarker *";
}
out<<"marker = new TMarker("<<fX<<","<<fY<<","<<fMarkerStyle<<");"<<std::endl;
SaveMarkerAttributes(out,"marker",1,1,1);
out<<" marker->Draw();"<<std::endl;
}
//______________________________________________________________________________
void TMarker::SetNDC(Bool_t isNDC)
{
// Set NDC mode on if isNDC = kTRUE, off otherwise
ResetBit(kMarkerNDC);
if (isNDC) SetBit(kMarkerNDC);
}
//______________________________________________________________________________
void TMarker::Streamer(TBuffer &R__b)
{
// Stream an object of class TMarker.
if (R__b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
R__b.ReadClassBuffer(TMarker::Class(), this, R__v, R__s, R__c);
return;
}
//====process old versions before automatic schema evolution
TObject::Streamer(R__b);
TAttMarker::Streamer(R__b);
Float_t x,y;
R__b >> x; fX = x;
R__b >> y; fY = y;
//====end of old versions
} else {
R__b.WriteClassBuffer(TMarker::Class(),this);
}
}
<commit_msg>Removed the list of markers. The up to date one is in TAttMarker.<commit_after>// @(#)root/graf:$Id$
// Author: Rene Brun 12/05/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TVirtualPad.h"
#include "TMarker.h"
#include "TVirtualX.h"
#include "TMath.h"
#include "TPoint.h"
#include "TText.h"
#include "TClass.h"
ClassImp(TMarker)
//______________________________________________________________________________
//
// Manages Markers. Marker attributes are managed by TAttMarker.
//
//______________________________________________________________________________
TMarker::TMarker(): TObject(), TAttMarker()
{
// Marker default constructor.
fX = 0;
fY = 0;
}
//______________________________________________________________________________
TMarker::TMarker(Double_t x, Double_t y, Int_t marker)
:TObject(), TAttMarker()
{
// Marker normal constructor.
fX = x;
fY = y;
fMarkerStyle = marker;
}
//______________________________________________________________________________
TMarker::~TMarker()
{
// Marker default destructor.
}
//______________________________________________________________________________
TMarker::TMarker(const TMarker &marker) : TObject(marker), TAttMarker(marker)
{
// Marker copy constructor.
fX = 0;
fY = 0;
((TMarker&)marker).Copy(*this);
}
//______________________________________________________________________________
void TMarker::Copy(TObject &obj) const
{
// Copy this marker to marker.
TObject::Copy(obj);
TAttMarker::Copy(((TMarker&)obj));
((TMarker&)obj).fX = fX;
((TMarker&)obj).fY = fY;
}
//______________________________________________________________________________
void TMarker::DisplayMarkerTypes()
{
// Display the table of markers with their numbers.
TMarker *marker = new TMarker();
marker->SetMarkerSize(3);
TText *text = new TText();
text->SetTextFont(62);
text->SetTextAlign(22);
text->SetTextSize(0.1);
char atext[] = " ";
Double_t x = 0;
Double_t dx = 1/16.0;
for (Int_t i=1;i<16;i++) {
x += dx;
snprintf(atext,7,"%d",i);
marker->SetMarkerStyle(i);
marker->DrawMarker(x,.35);
text->DrawText(x,.17,atext);
snprintf(atext,7,"%d",i+19);
marker->SetMarkerStyle(i+19);
marker->DrawMarker(x,.8);
text->DrawText(x,.62,atext);
}
delete marker;
delete text;
}
//______________________________________________________________________________
Int_t TMarker::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to a marker.
//
// Compute the closest distance of approach from point px,py to this marker.
// The distance is computed in pixels units.
Int_t pxm, pym;
if (TestBit(kMarkerNDC)) {
pxm = gPad->UtoPixel(fX);
pym = gPad->VtoPixel(fY);
} else {
pxm = gPad->XtoAbsPixel(gPad->XtoPad(fX));
pym = gPad->YtoAbsPixel(gPad->YtoPad(fY));
}
Int_t dist = (Int_t)TMath::Sqrt((px-pxm)*(px-pxm) + (py-pym)*(py-pym));
//marker size = 1 is about 8 pixels
Int_t markerRadius = Int_t(4*fMarkerSize);
if (dist <= markerRadius) return 0;
if (dist > markerRadius+3) return 999;
return dist;
}
//______________________________________________________________________________
void TMarker::Draw(Option_t *option)
{
// Draw this marker with its current attributes.
AppendPad(option);
}
//______________________________________________________________________________
void TMarker::DrawMarker(Double_t x, Double_t y)
{
// Draw this marker with new coordinates.
TMarker *newmarker = new TMarker(x, y, 1);
TAttMarker::Copy(*newmarker);
newmarker->SetBit(kCanDelete);
newmarker->AppendPad();
}
//______________________________________________________________________________
void TMarker::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
// Execute action corresponding to one event.
//
// This member function is called when a marker is clicked with the locator
//
// If Left button is clicked on a marker, the marker is moved to
// a new position when the mouse button is released.
TPoint p;
static Int_t pxold, pyold;
if (!gPad->IsEditable()) return;
switch (event) {
case kButton1Down:
gVirtualX->SetTextColor(-1); // invalidate current text color (use xor mode)
TAttMarker::Modify(); //Change marker attributes only if necessary
// No break !!!
case kMouseMotion:
pxold = px; pyold = py;
gPad->SetCursor(kMove);
break;
case kButton1Motion:
p.fX = pxold; p.fY = pyold;
gVirtualX->DrawPolyMarker(1, &p);
p.fX = px; p.fY = py;
gVirtualX->DrawPolyMarker(1, &p);
pxold = px; pyold = py;
break;
case kButton1Up:
Double_t dpx, dpy, xp1,yp1;
if (TestBit(kMarkerNDC)) {
dpx = gPad->GetX2() - gPad->GetX1();
dpy = gPad->GetY2() - gPad->GetY1();
xp1 = gPad->GetX1();
yp1 = gPad->GetY1();
fX = (gPad->AbsPixeltoX(pxold)-xp1)/dpx;
fY = (gPad->AbsPixeltoY(pyold)-yp1)/dpy;
} else {
fX = gPad->PadtoX(gPad->AbsPixeltoX(px));
fY = gPad->PadtoY(gPad->AbsPixeltoY(py));
}
gPad->Modified(kTRUE);
gVirtualX->SetTextColor(-1);
break;
}
}
//______________________________________________________________________________
void TMarker::ls(Option_t *) const
{
// List this marker with its attributes.
TROOT::IndentLevel();
printf("Marker X=%f Y=%f marker type=%d\n",fX,fY,fMarkerStyle);
}
//______________________________________________________________________________
void TMarker::Paint(Option_t *)
{
// Paint this marker with its current attributes.
if (TestBit(kMarkerNDC)) {
Double_t u = gPad->GetX1() + fX*(gPad->GetX2()-gPad->GetX1());
Double_t v = gPad->GetY1() + fY*(gPad->GetY2()-gPad->GetY1());
PaintMarker(u,v);
} else {
PaintMarker(gPad->XtoPad(fX),gPad->YtoPad(fY));
}
}
//______________________________________________________________________________
void TMarker::PaintMarker(Double_t x, Double_t y)
{
// Draw this marker with new coordinates.
TAttMarker::Modify(); //Change line attributes only if necessary
gPad->PaintPolyMarker(-1,&x,&y,"");
}
//______________________________________________________________________________
void TMarker::PaintMarkerNDC(Double_t, Double_t)
{
// Draw this marker with new coordinates in NDC.
}
//______________________________________________________________________________
void TMarker::Print(Option_t *) const
{
// Dump this marker with its attributes.
printf("Marker X=%f Y=%f",fX,fY);
if (GetMarkerColor() != 1) printf(" Color=%d",GetMarkerColor());
if (GetMarkerStyle() != 1) printf(" MarkerStyle=%d",GetMarkerStyle());
if (GetMarkerSize() != 1) printf(" MarkerSize=%f",GetMarkerSize());
printf("\n");
}
//______________________________________________________________________________
void TMarker::SavePrimitive(std::ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
if (gROOT->ClassSaved(TMarker::Class())) {
out<<" ";
} else {
out<<" TMarker *";
}
out<<"marker = new TMarker("<<fX<<","<<fY<<","<<fMarkerStyle<<");"<<std::endl;
SaveMarkerAttributes(out,"marker",1,1,1);
out<<" marker->Draw();"<<std::endl;
}
//______________________________________________________________________________
void TMarker::SetNDC(Bool_t isNDC)
{
// Set NDC mode on if isNDC = kTRUE, off otherwise
ResetBit(kMarkerNDC);
if (isNDC) SetBit(kMarkerNDC);
}
//______________________________________________________________________________
void TMarker::Streamer(TBuffer &R__b)
{
// Stream an object of class TMarker.
if (R__b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
R__b.ReadClassBuffer(TMarker::Class(), this, R__v, R__s, R__c);
return;
}
//====process old versions before automatic schema evolution
TObject::Streamer(R__b);
TAttMarker::Streamer(R__b);
Float_t x,y;
R__b >> x; fX = x;
R__b >> y; fY = y;
//====end of old versions
} else {
R__b.WriteClassBuffer(TMarker::Class(),this);
}
}
<|endoftext|>
|
<commit_before>/**
* @file pointer.hpp
*
* @brief A wrapper class for host and/or device pointers, allowing
* easy access to CUDA's pointer attributes.
*
* @note at the moment, this class is not used by other sections of the API
* wrappers; specifically, freestanding functions and methods returning
* pointers return raw `T*`'s rather than `pointer_t<T>`'s.
* This may change in the future.
*
* @todo Consider allowing for storing attributes within the class,
* lazily (e.g. with an std::optional).
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_POINTER_HPP_
#define CUDA_API_WRAPPERS_POINTER_HPP_
#include <cuda/api/types.hpp>
#include <cuda/api/constants.hpp>
#include <cuda/api/error.hpp>
#include <cuda_runtime_api.h>
namespace cuda {
///@cond
template <bool AssumedCurrent> class device_t;
///@endcond
namespace memory {
/**
* @brief see @ref memory::host, @ref memory::device, @ref memory::managed
*/
enum type_t : std::underlying_type<cudaMemoryType>::type {
host_memory = cudaMemoryTypeHost,
device_memory = cudaMemoryTypeDevice,
#if CUDART_VERSION >= 10000
unregistered_memory = cudaMemoryTypeUnregistered,
managed_memory = cudaMemoryTypeManaged,
#else
unregistered_memory,
managed_memory,
#endif // CUDART_VERSION >= 10000
};
namespace pointer {
struct attributes_t : cudaPointerAttributes {
/**
* @brief indicates a choice memory space, management and access type -
* from among the options in @ref type_t .
*
* @return A value whose semantics are those introduced in CUDA 10.0,
* rather than those of CUDA 9 and earlier, where `type_t::device`
* actually signifies either device-only or `type_t::managed`.
*/
type_t memory_type() const
{
// TODO: For some strange reason, g++ 6.x claims that converting
// to the underlying type is a "narrowing conversion", and doesn't
// like some other conversions I've tried - so let's cast
// more violently instead
// Note: In CUDA v10.0, the semantics changed to what we're supporting
#if CUDART_VERSION >= 10000
return (type_t)cudaPointerAttributes::type;
#else // CUDART_VERSION < 10000
using utype = typename std::underlying_type<cudaMemoryType>::type;
if (((utype) memoryType == utype {type_t::device_memory}) and
cudaPointerAttributes::isManaged) {
return type_t::managed_memory;
}
return (type_t)(memoryType);
#endif // CUDART_VERSION >= 10000
}
};
} // namespace pointer
/**
* A convenience wrapper around a raw pointer "known" to the CUDA runtime
* and which thus has various kinds of associated information which this
* wrapper allows access to.
*/
template <typename T>
class pointer_t {
public: // getters and operators
/**
* @return Address of the pointed-to memory, regardless of which memory
* space it's in and whether or not it is accessible from the host
*/
T* get() const { return ptr_; }
operator T*() const { return ptr_; }
public: // other non-mutators
pointer::attributes_t attributes() const
{
pointer::attributes_t the_attributes;
auto status = cudaPointerGetAttributes (&the_attributes, ptr_);
throw_if_error(status, "Failed obtaining attributes of pointer " + cuda::detail::ptr_as_hex(ptr_));
return the_attributes;
}
device_t<detail::do_not_assume_device_is_current> device() const;
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_device() const { return attributes().devicePointer; }
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_host() const { return attributes().hostPointer; }
/**
* @returns For a mapped-memory pointer, returns the other side of the mapping,
* i.e. if this is the device pointer, returns the host pointer, otherwise
* returns the device pointer. For a managed-memory pointer, returns the
* single pointer usable on both device and host. In other cases returns `nullptr`.
*
* @note this relies on either the device and host pointers being `nullptr` in
* the case of a non-mapped pointer; and on the device and host pointers being
* identical to ptr_ for managed-memory pointers.
*/
pointer_t other_side_of_region_pair() const {
auto attrs = attributes();
#ifndef NDEBUG
assert(attrs.devicePointer == ptr_ or atts.hostPointer == ptr_);
#endif
return pointer_t { ptr_ == attrs.devicePointer ? attrs.hostPointer : ptr_ };
}
public: // constructors
pointer_t(T* ptr) noexcept : ptr_(ptr) { }
pointer_t(const pointer_t& other) noexcept = default;
pointer_t(pointer_t&& other) noexcept = default;
protected: // data members
T* const ptr_;
};
namespace pointer {
/**
* Wraps an existing pointer in a @ref pointer_t wrapper
*
* @param ptr a pointer - into either device or host memory -
* to be wrapped.
*/
template<typename T>
inline pointer_t<T> wrap(T* ptr) noexcept { return pointer_t<T>(ptr); }
} // namespace pointer
} // namespace memory
} // namespace cuda
#endif /* CUDA_API_WRAPPERS_POINTER_HPP_ */
<commit_msg>Compilation fix<commit_after>/**
* @file pointer.hpp
*
* @brief A wrapper class for host and/or device pointers, allowing
* easy access to CUDA's pointer attributes.
*
* @note at the moment, this class is not used by other sections of the API
* wrappers; specifically, freestanding functions and methods returning
* pointers return raw `T*`'s rather than `pointer_t<T>`'s.
* This may change in the future.
*
* @todo Consider allowing for storing attributes within the class,
* lazily (e.g. with an std::optional).
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_POINTER_HPP_
#define CUDA_API_WRAPPERS_POINTER_HPP_
#include <cuda/api/types.hpp>
#include <cuda/api/constants.hpp>
#include <cuda/api/error.hpp>
#include <cuda_runtime_api.h>
#ifndef NDEBUG
#include <cassert>
#endif
namespace cuda {
///@cond
template <bool AssumedCurrent> class device_t;
///@endcond
namespace memory {
/**
* @brief see @ref memory::host, @ref memory::device, @ref memory::managed
*/
enum type_t : std::underlying_type<cudaMemoryType>::type {
host_memory = cudaMemoryTypeHost,
device_memory = cudaMemoryTypeDevice,
#if CUDART_VERSION >= 10000
unregistered_memory = cudaMemoryTypeUnregistered,
managed_memory = cudaMemoryTypeManaged,
#else
unregistered_memory,
managed_memory,
#endif // CUDART_VERSION >= 10000
};
namespace pointer {
struct attributes_t : cudaPointerAttributes {
/**
* @brief indicates a choice memory space, management and access type -
* from among the options in @ref type_t .
*
* @return A value whose semantics are those introduced in CUDA 10.0,
* rather than those of CUDA 9 and earlier, where `type_t::device`
* actually signifies either device-only or `type_t::managed`.
*/
type_t memory_type() const
{
// TODO: For some strange reason, g++ 6.x claims that converting
// to the underlying type is a "narrowing conversion", and doesn't
// like some other conversions I've tried - so let's cast
// more violently instead
// Note: In CUDA v10.0, the semantics changed to what we're supporting
#if CUDART_VERSION >= 10000
return (type_t)cudaPointerAttributes::type;
#else // CUDART_VERSION < 10000
using utype = typename std::underlying_type<cudaMemoryType>::type;
if (((utype) memoryType == utype {type_t::device_memory}) and
cudaPointerAttributes::isManaged) {
return type_t::managed_memory;
}
return (type_t)(memoryType);
#endif // CUDART_VERSION >= 10000
}
};
} // namespace pointer
/**
* A convenience wrapper around a raw pointer "known" to the CUDA runtime
* and which thus has various kinds of associated information which this
* wrapper allows access to.
*/
template <typename T>
class pointer_t {
public: // getters and operators
/**
* @return Address of the pointed-to memory, regardless of which memory
* space it's in and whether or not it is accessible from the host
*/
T* get() const { return ptr_; }
operator T*() const { return ptr_; }
public: // other non-mutators
pointer::attributes_t attributes() const
{
pointer::attributes_t the_attributes;
auto status = cudaPointerGetAttributes (&the_attributes, ptr_);
throw_if_error(status, "Failed obtaining attributes of pointer " + cuda::detail::ptr_as_hex(ptr_));
return the_attributes;
}
device_t<detail::do_not_assume_device_is_current> device() const;
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_device() const { return attributes().devicePointer; }
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_host() const { return attributes().hostPointer; }
/**
* @returns For a mapped-memory pointer, returns the other side of the mapping,
* i.e. if this is the device pointer, returns the host pointer, otherwise
* returns the device pointer. For a managed-memory pointer, returns the
* single pointer usable on both device and host. In other cases returns `nullptr`.
*
* @note this relies on either the device and host pointers being `nullptr` in
* the case of a non-mapped pointer; and on the device and host pointers being
* identical to ptr_ for managed-memory pointers.
*/
pointer_t other_side_of_region_pair() const {
auto attrs = attributes();
#ifndef NDEBUG
assert(attrs.devicePointer == ptr_ or attrs.hostPointer == ptr_);
#endif
return pointer_t { ptr_ == attrs.devicePointer ? attrs.hostPointer : ptr_ };
}
public: // constructors
pointer_t(T* ptr) noexcept : ptr_(ptr) { }
pointer_t(const pointer_t& other) noexcept = default;
pointer_t(pointer_t&& other) noexcept = default;
protected: // data members
T* const ptr_;
};
namespace pointer {
/**
* Wraps an existing pointer in a @ref pointer_t wrapper
*
* @param ptr a pointer - into either device or host memory -
* to be wrapped.
*/
template<typename T>
inline pointer_t<T> wrap(T* ptr) noexcept { return pointer_t<T>(ptr); }
} // namespace pointer
} // namespace memory
} // namespace cuda
#endif /* CUDA_API_WRAPPERS_POINTER_HPP_ */
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <TClonesArray.h>
#include <THashList.h>
#include <THistManager.h>
#include "AliAnalysisUtils.h"
#include "AliAnalysisTaskEmcalMaxPatch.h"
#include "AliEMCalTriggerWeightHandler.h"
#include "AliEMCALTriggerPatchInfo.h"
#include "AliInputEventHandler.h"
#include "AliLog.h"
/// \cond CLASSIMP
ClassImp(EMCalTriggerPtAnalysis::AliAnalysisTaskEmcalMaxPatch)
/// \endcond
namespace EMCalTriggerPtAnalysis {
AliAnalysisTaskEmcalMaxPatch::AliAnalysisTaskEmcalMaxPatch() :
AliAnalysisTaskEmcal(),
fWeightHandler(nullptr),
fHistos(nullptr),
fSelectTrigger(AliVEvent::kINT7)
{
SetCaloTriggerPatchInfoName("EmcalTriggers");
}
AliAnalysisTaskEmcalMaxPatch::AliAnalysisTaskEmcalMaxPatch(const char *name) :
AliAnalysisTaskEmcal(name, kTRUE),
fWeightHandler(nullptr),
fHistos(nullptr),
fSelectTrigger(AliVEvent::kINT7)
{
SetCaloTriggerPatchInfoName("EmcalTriggers");
SetMakeGeneralHistograms(true);
}
AliAnalysisTaskEmcalMaxPatch::~AliAnalysisTaskEmcalMaxPatch() {
}
void AliAnalysisTaskEmcalMaxPatch::UserCreateOutputObjects(){
AliAnalysisTaskEmcal::UserCreateOutputObjects();
if(!fAliAnalysisUtils) fAliAnalysisUtils = new AliAnalysisUtils;
fHistos = new THistManager("histMaxPatch");
fHistos->CreateTH1("hTrueEventCount", "Maximum energy patch in the event", 1, 0.5, 1.5);
const std::map<std::string, std::string> triggers {
{"EGAOffline", "offline EGA"}, {"EJEOffline", "offline EJE"}, {"EGARecalc", "recalc EGA"},
{"EJERecalc", "recalc EJE"}, {"EG1Online", "online EG1"}, {"EG2Online", "online EG2"},
{"DG1Online", "online DG1"}, {"DG2Online", "online DG2"}, {"EJ1Online", "online EJ1"},
{"EJ2Online", "online EJ2"}, {"DJ1Online", "online DJ1"}, {"DJ2Online", "online DJ2"},
};
// Calibrated FEE energy
for(const auto &t : triggers)
fHistos->CreateTH1(Form("hPatchEnergyMax%s", t.first.c_str()), Form("Energy spectrum of the maximum %s patch", t.second.c_str()), 2000, 0., 200.);
// Online ADC counts
for(const auto &t : triggers)
fHistos->CreateTH1(Form("hPatchADCMax%s", t.first.c_str()), Form("ADC spectrum of the maximum %s patch", t.second.c_str()), 2049, -0.5, 2048.5);
// ADC vs energy
for(const auto &t : triggers)
fHistos->CreateTH2(Form("hPatchADCvsEnergyMax%s", t.first.c_str()), Form("ADC vs. Energy of the maximum %s patch", t.second.c_str()), 300, 0., 3000, 200, 0., 200.);
for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h);
PostData(1, fOutput);
}
Bool_t AliAnalysisTaskEmcalMaxPatch::IsEventSelected(){
AliDebugStream(2) << GetName() << ": Using custom event selection method" << std::endl;
if(!fTriggerPatchInfo){
AliErrorStream() << GetName() << ": Trigger patch container not found but required" << std::endl;
return false;
}
if(!(fInputHandler->IsEventSelected() & fSelectTrigger)) return false;
if(fTriggerPattern.Length()){
TString triggerstring = InputEvent()->GetFiredTriggerClasses();
if(!triggerstring.Contains(fTriggerPattern)) return false;
}
AliDebugStream(3) << GetName() << "Event is selected for the given trigger" << std::endl;
// Generall event quality cuts
// The vertex cut also contains cuts on the number
// of contributors and the position in z
AliDebugStream(3) << GetName() << ": Applying vertex selection" << std::endl;
if(fAliAnalysisUtils){
if(!fAliAnalysisUtils->IsVertexSelected2013pA(InputEvent())) return false;
if(fAliAnalysisUtils->IsPileUpEvent(InputEvent())) return false;
AliDebugStream(3) << GetName() << ": Vertex selection passed" << std::endl;
}
AliDebugStream(2) << GetName() << "Event selected" << std::endl;
return true;
}
Bool_t AliAnalysisTaskEmcalMaxPatch::Run(){
fHistos->FillTH1("hTrueEventCount", 1);
const AliEMCALTriggerPatchInfo *currentpatch(nullptr),
*maxOfflineEGA(nullptr),
*maxOfflineEJE(nullptr),
*maxRecalcEGA(nullptr),
*maxRecalcEJE(nullptr),
*maxOnlineEG1(nullptr),
*maxOnlineEG2(nullptr),
*maxOnlineDG1(nullptr),
*maxOnlineDG2(nullptr),
*maxOnlineEJ1(nullptr),
*maxOnlineEJ2(nullptr),
*maxOnlineDJ1(nullptr),
*maxOnlineDJ2(nullptr);
// Find the maximum patch for each cathegory
for(auto patchiter : *fTriggerPatchInfo){
currentpatch = static_cast<AliEMCALTriggerPatchInfo *>(patchiter);
// Offline patches - make cut on energy
if(currentpatch->IsOfflineSimple()){
if(currentpatch->IsGammaHighSimple()){
if(!maxOfflineEGA || currentpatch->GetPatchE() > maxOfflineEGA->GetPatchE())
maxOfflineEGA = currentpatch;
} else if(currentpatch->IsJetHighSimple()) {
if(!maxOfflineEJE || currentpatch->GetPatchE() > maxOfflineEJE->GetPatchE())
maxOfflineEJE = currentpatch;
}
}
// Recalc patches - make cut on FastOR ADC
if(currentpatch->IsRecalc()){
if(currentpatch->IsGammaHighRecalc()){
if(!maxRecalcEGA || currentpatch->GetADCAmp() > maxRecalcEGA->GetADCAmp())
maxRecalcEGA = currentpatch;
} else if(currentpatch->IsJetHighSimple()) {
if(!maxRecalcEJE || currentpatch->GetADCAmp() > maxRecalcEJE->GetADCAmp())
maxRecalcEJE = currentpatch;
}
}
// Online patches
if(currentpatch->IsGammaHigh() || currentpatch->IsGammaLow()){
if(currentpatch->IsEMCal()){
if(currentpatch->IsGammaHigh()){
if(!maxOnlineEG1 || currentpatch->GetADCAmp() > maxOnlineEG1->GetADCAmp())
maxOnlineEG1 = currentpatch;
}
if(currentpatch->IsGammaLow()){
if(!maxOnlineEG2 || currentpatch->GetADCAmp() > maxOnlineEG2->GetADCAmp())
maxOnlineEG2 = currentpatch;
}
} else {
if(currentpatch->IsGammaHigh()){
if(!maxOnlineDG1 || currentpatch->GetADCAmp() > maxOnlineDG1->GetADCAmp())
maxOnlineDG1 = currentpatch;
}
if(currentpatch->IsGammaLow()){
if(!maxOnlineDG2 || currentpatch->GetADCAmp() > maxOnlineDG2->GetADCAmp())
maxOnlineDG2 = currentpatch;
}
}
}
if(currentpatch->IsJetHigh() || currentpatch->IsJetLow()){
if(currentpatch->IsEMCal()){
if(currentpatch->IsJetHigh()){
if(!maxOnlineEJ1 || currentpatch->GetADCAmp() > maxOnlineEJ1->GetADCAmp())
maxOnlineEJ1 = currentpatch;
}
if(currentpatch->IsJetLow()){
if(!maxOnlineEJ2 || currentpatch->GetADCAmp() > maxOnlineEJ2->GetADCAmp())
maxOnlineEJ2 = currentpatch;
}
} else {
if(currentpatch->IsJetHigh()){
if(!maxOnlineDG1 || currentpatch->GetADCAmp() > maxOnlineDJ1->GetADCAmp())
maxOnlineDG1 = currentpatch;
}
if(currentpatch->IsJetLow()){
if(!maxOnlineDJ2 || currentpatch->GetADCAmp() > maxOnlineDJ2->GetADCAmp())
maxOnlineDJ2 = currentpatch;
}
}
}
}
std::function<void (const AliEMCALTriggerPatchInfo *, const std::string &)> FillHistos = [this](const AliEMCALTriggerPatchInfo * testpatch, const std::string & triggername){
fHistos->FillTH1(Form("hPatchEnergyMax%s", triggername.c_str()), testpatch ? testpatch->GetPatchE() : 0.);
fHistos->FillTH1(Form("hPatchADCMax%s", triggername.c_str()), testpatch ? testpatch->GetPatchE() : 0.);
fHistos->FillTH2(Form("hPatchADCvsEnergyMax%s", triggername.c_str()), testpatch ? testpatch->GetPatchE() : 0., testpatch ? testpatch->GetADCAmp() : 0);
};
FillHistos(maxOfflineEGA, "EGAOffline");
FillHistos(maxOfflineEJE, "EJEOffline");
FillHistos(maxRecalcEGA, "EGARecalc");
FillHistos(maxRecalcEJE, "EJERecalc");
FillHistos(maxOnlineEG1, "EG1Online");
FillHistos(maxOnlineEG2, "EG2Online");
FillHistos(maxOnlineDG1, "DG1Online");
FillHistos(maxOnlineDG2, "DG2Online");
FillHistos(maxOnlineEJ1, "EJ1Online");
FillHistos(maxOnlineEJ2, "EJ2Online");
FillHistos(maxOnlineDJ1, "DJ1Online");
FillHistos(maxOnlineDJ2, "DJ2Online");
return true;
}
} /* namespace EMCalTriggerPtAnalysis */
<commit_msg>Fixing ADC plot<commit_after>/**************************************************************************
* Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <TClonesArray.h>
#include <THashList.h>
#include <THistManager.h>
#include "AliAnalysisUtils.h"
#include "AliAnalysisTaskEmcalMaxPatch.h"
#include "AliEMCalTriggerWeightHandler.h"
#include "AliEMCALTriggerPatchInfo.h"
#include "AliInputEventHandler.h"
#include "AliLog.h"
/// \cond CLASSIMP
ClassImp(EMCalTriggerPtAnalysis::AliAnalysisTaskEmcalMaxPatch)
/// \endcond
namespace EMCalTriggerPtAnalysis {
AliAnalysisTaskEmcalMaxPatch::AliAnalysisTaskEmcalMaxPatch() :
AliAnalysisTaskEmcal(),
fWeightHandler(nullptr),
fHistos(nullptr),
fSelectTrigger(AliVEvent::kINT7)
{
SetCaloTriggerPatchInfoName("EmcalTriggers");
}
AliAnalysisTaskEmcalMaxPatch::AliAnalysisTaskEmcalMaxPatch(const char *name) :
AliAnalysisTaskEmcal(name, kTRUE),
fWeightHandler(nullptr),
fHistos(nullptr),
fSelectTrigger(AliVEvent::kINT7)
{
SetCaloTriggerPatchInfoName("EmcalTriggers");
SetMakeGeneralHistograms(true);
}
AliAnalysisTaskEmcalMaxPatch::~AliAnalysisTaskEmcalMaxPatch() {
}
void AliAnalysisTaskEmcalMaxPatch::UserCreateOutputObjects(){
AliAnalysisTaskEmcal::UserCreateOutputObjects();
if(!fAliAnalysisUtils) fAliAnalysisUtils = new AliAnalysisUtils;
fHistos = new THistManager("histMaxPatch");
fHistos->CreateTH1("hTrueEventCount", "Maximum energy patch in the event", 1, 0.5, 1.5);
const std::map<std::string, std::string> triggers {
{"EGAOffline", "offline EGA"}, {"EJEOffline", "offline EJE"}, {"EGARecalc", "recalc EGA"},
{"EJERecalc", "recalc EJE"}, {"EG1Online", "online EG1"}, {"EG2Online", "online EG2"},
{"DG1Online", "online DG1"}, {"DG2Online", "online DG2"}, {"EJ1Online", "online EJ1"},
{"EJ2Online", "online EJ2"}, {"DJ1Online", "online DJ1"}, {"DJ2Online", "online DJ2"},
};
// Calibrated FEE energy
for(const auto &t : triggers)
fHistos->CreateTH1(Form("hPatchEnergyMax%s", t.first.c_str()), Form("Energy spectrum of the maximum %s patch", t.second.c_str()), 2000, 0., 200.);
// Online ADC counts
for(const auto &t : triggers)
fHistos->CreateTH1(Form("hPatchADCMax%s", t.first.c_str()), Form("ADC spectrum of the maximum %s patch", t.second.c_str()), 2049, -0.5, 2048.5);
// ADC vs energy
for(const auto &t : triggers)
fHistos->CreateTH2(Form("hPatchADCvsEnergyMax%s", t.first.c_str()), Form("ADC vs. Energy of the maximum %s patch", t.second.c_str()), 300, 0., 3000, 200, 0., 200.);
for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h);
PostData(1, fOutput);
}
Bool_t AliAnalysisTaskEmcalMaxPatch::IsEventSelected(){
AliDebugStream(2) << GetName() << ": Using custom event selection method" << std::endl;
if(!fTriggerPatchInfo){
AliErrorStream() << GetName() << ": Trigger patch container not found but required" << std::endl;
return false;
}
if(!(fInputHandler->IsEventSelected() & fSelectTrigger)) return false;
if(fTriggerPattern.Length()){
TString triggerstring = InputEvent()->GetFiredTriggerClasses();
if(!triggerstring.Contains(fTriggerPattern)) return false;
}
AliDebugStream(3) << GetName() << "Event is selected for the given trigger" << std::endl;
// Generall event quality cuts
// The vertex cut also contains cuts on the number
// of contributors and the position in z
AliDebugStream(3) << GetName() << ": Applying vertex selection" << std::endl;
if(fAliAnalysisUtils){
if(!fAliAnalysisUtils->IsVertexSelected2013pA(InputEvent())) return false;
if(fAliAnalysisUtils->IsPileUpEvent(InputEvent())) return false;
AliDebugStream(3) << GetName() << ": Vertex selection passed" << std::endl;
}
AliDebugStream(2) << GetName() << "Event selected" << std::endl;
return true;
}
Bool_t AliAnalysisTaskEmcalMaxPatch::Run(){
fHistos->FillTH1("hTrueEventCount", 1);
const AliEMCALTriggerPatchInfo *currentpatch(nullptr),
*maxOfflineEGA(nullptr),
*maxOfflineEJE(nullptr),
*maxRecalcEGA(nullptr),
*maxRecalcEJE(nullptr),
*maxOnlineEG1(nullptr),
*maxOnlineEG2(nullptr),
*maxOnlineDG1(nullptr),
*maxOnlineDG2(nullptr),
*maxOnlineEJ1(nullptr),
*maxOnlineEJ2(nullptr),
*maxOnlineDJ1(nullptr),
*maxOnlineDJ2(nullptr);
// Find the maximum patch for each cathegory
for(auto patchiter : *fTriggerPatchInfo){
currentpatch = static_cast<AliEMCALTriggerPatchInfo *>(patchiter);
// Offline patches - make cut on energy
if(currentpatch->IsOfflineSimple()){
if(currentpatch->IsGammaHighSimple()){
if(!maxOfflineEGA || currentpatch->GetPatchE() > maxOfflineEGA->GetPatchE())
maxOfflineEGA = currentpatch;
} else if(currentpatch->IsJetHighSimple()) {
if(!maxOfflineEJE || currentpatch->GetPatchE() > maxOfflineEJE->GetPatchE())
maxOfflineEJE = currentpatch;
}
}
// Recalc patches - make cut on FastOR ADC
if(currentpatch->IsRecalc()){
if(currentpatch->IsGammaHighRecalc()){
if(!maxRecalcEGA || currentpatch->GetADCAmp() > maxRecalcEGA->GetADCAmp())
maxRecalcEGA = currentpatch;
} else if(currentpatch->IsJetHighSimple()) {
if(!maxRecalcEJE || currentpatch->GetADCAmp() > maxRecalcEJE->GetADCAmp())
maxRecalcEJE = currentpatch;
}
}
// Online patches
if(currentpatch->IsGammaHigh() || currentpatch->IsGammaLow()){
if(currentpatch->IsEMCal()){
if(currentpatch->IsGammaHigh()){
if(!maxOnlineEG1 || currentpatch->GetADCAmp() > maxOnlineEG1->GetADCAmp())
maxOnlineEG1 = currentpatch;
}
if(currentpatch->IsGammaLow()){
if(!maxOnlineEG2 || currentpatch->GetADCAmp() > maxOnlineEG2->GetADCAmp())
maxOnlineEG2 = currentpatch;
}
} else {
if(currentpatch->IsGammaHigh()){
if(!maxOnlineDG1 || currentpatch->GetADCAmp() > maxOnlineDG1->GetADCAmp())
maxOnlineDG1 = currentpatch;
}
if(currentpatch->IsGammaLow()){
if(!maxOnlineDG2 || currentpatch->GetADCAmp() > maxOnlineDG2->GetADCAmp())
maxOnlineDG2 = currentpatch;
}
}
}
if(currentpatch->IsJetHigh() || currentpatch->IsJetLow()){
if(currentpatch->IsEMCal()){
if(currentpatch->IsJetHigh()){
if(!maxOnlineEJ1 || currentpatch->GetADCAmp() > maxOnlineEJ1->GetADCAmp())
maxOnlineEJ1 = currentpatch;
}
if(currentpatch->IsJetLow()){
if(!maxOnlineEJ2 || currentpatch->GetADCAmp() > maxOnlineEJ2->GetADCAmp())
maxOnlineEJ2 = currentpatch;
}
} else {
if(currentpatch->IsJetHigh()){
if(!maxOnlineDG1 || currentpatch->GetADCAmp() > maxOnlineDJ1->GetADCAmp())
maxOnlineDG1 = currentpatch;
}
if(currentpatch->IsJetLow()){
if(!maxOnlineDJ2 || currentpatch->GetADCAmp() > maxOnlineDJ2->GetADCAmp())
maxOnlineDJ2 = currentpatch;
}
}
}
}
std::function<void (const AliEMCALTriggerPatchInfo *, const std::string &)> FillHistos = [this](const AliEMCALTriggerPatchInfo * testpatch, const std::string & triggername){
fHistos->FillTH1(Form("hPatchEnergyMax%s", triggername.c_str()), testpatch ? testpatch->GetPatchE() : 0.);
fHistos->FillTH1(Form("hPatchADCMax%s", triggername.c_str()), testpatch ? testpatch->GetADCAmp() : 0.);
fHistos->FillTH2(Form("hPatchADCvsEnergyMax%s", triggername.c_str()), testpatch ? testpatch->GetADCAmp() : 0, testpatch ? testpatch->GetPatchE() : 0.);
};
FillHistos(maxOfflineEGA, "EGAOffline");
FillHistos(maxOfflineEJE, "EJEOffline");
FillHistos(maxRecalcEGA, "EGARecalc");
FillHistos(maxRecalcEJE, "EJERecalc");
FillHistos(maxOnlineEG1, "EG1Online");
FillHistos(maxOnlineEG2, "EG2Online");
FillHistos(maxOnlineDG1, "DG1Online");
FillHistos(maxOnlineDG2, "DG2Online");
FillHistos(maxOnlineEJ1, "EJ1Online");
FillHistos(maxOnlineEJ2, "EJ2Online");
FillHistos(maxOnlineDJ1, "DJ1Online");
FillHistos(maxOnlineDJ2, "DJ2Online");
return true;
}
} /* namespace EMCalTriggerPtAnalysis */
<|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: documentlockfile.cxx,v $
*
* $Revision: 1.2 $
*
* 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_svtools.hxx"
#include <stdio.h>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/InsertCommandArgument.hpp>
#include <com/sun/star/ucb/NameClashException.hpp>
#include <com/sun/star/io/WrongFormatException.hpp>
#include <osl/time.h>
#include <osl/security.hxx>
#include <osl/socket.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <comphelper/processfactory.hxx>
#include <tools/urlobj.hxx>
#include <unotools/bootstrap.hxx>
#include <ucbhelper/content.hxx>
#include <svtools/useroptions.hxx>
#include <svtools/documentlockfile.hxx>
using namespace ::com::sun::star;
namespace svt {
sal_Bool DocumentLockFile::m_bAllowInteraction = sal_True;
// ----------------------------------------------------------------------
DocumentLockFile::DocumentLockFile( const ::rtl::OUString& aOrigURL, const uno::Reference< lang::XMultiServiceFactory >& xFactory )
: m_xFactory( xFactory )
{
if ( !m_xFactory.is() )
m_xFactory = ::comphelper::getProcessServiceFactory();
INetURLObject aDocURL( aOrigURL );
if ( aDocURL.HasError() )
throw lang::IllegalArgumentException();
::rtl::OUString aShareURLString = aDocURL.GetPartBeforeLastName();
aShareURLString += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".~lock." ) );
aShareURLString += aDocURL.GetName();
aShareURLString += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "#" ) );
m_aURL = INetURLObject( aShareURLString ).GetMainURL( INetURLObject::NO_DECODE );
}
// ----------------------------------------------------------------------
DocumentLockFile::~DocumentLockFile()
{
}
// ----------------------------------------------------------------------
void DocumentLockFile::WriteEntryToStream( uno::Sequence< ::rtl::OUString > aEntry, uno::Reference< io::XOutputStream > xOutput )
{
::rtl::OUStringBuffer aBuffer;
for ( sal_Int32 nEntryInd = 0; nEntryInd < aEntry.getLength(); nEntryInd++ )
{
aBuffer.append( EscapeCharacters( aEntry[nEntryInd] ) );
if ( nEntryInd < aEntry.getLength() - 1 )
aBuffer.append( (sal_Unicode)',' );
else
aBuffer.append( (sal_Unicode)';' );
}
::rtl::OString aStringData( ::rtl::OUStringToOString( aBuffer.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ) );
uno::Sequence< sal_Int8 > aData( (sal_Int8*)aStringData.getStr(), aStringData.getLength() );
xOutput->writeBytes( aData );
}
// ----------------------------------------------------------------------
sal_Bool DocumentLockFile::CreateOwnLockFile()
{
try
{
uno::Reference< io::XStream > xTempFile(
m_xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ) ),
uno::UNO_QUERY_THROW );
uno::Reference< io::XSeekable > xSeekable( xTempFile, uno::UNO_QUERY_THROW );
uno::Reference< io::XInputStream > xInput = xTempFile->getInputStream();
uno::Reference< io::XOutputStream > xOutput = xTempFile->getOutputStream();
if ( !xInput.is() || !xOutput.is() )
throw uno::RuntimeException();
uno::Sequence< ::rtl::OUString > aNewEntry = GenerateOwnEntry();
WriteEntryToStream( aNewEntry, xOutput );
xOutput->closeOutput();
xSeekable->seek( 0 );
uno::Reference < ::com::sun::star::ucb::XCommandEnvironment > xEnv;
::ucbhelper::Content aTargetContent( m_aURL, xEnv );
ucb::InsertCommandArgument aInsertArg;
aInsertArg.Data = xInput;
aInsertArg.ReplaceExisting = sal_False;
uno::Any aCmdArg;
aCmdArg <<= aInsertArg;
aTargetContent.executeCommand( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "insert" ) ), aCmdArg );
}
catch( ucb::NameClashException& )
{
return sal_False;
}
return sal_True;
}
// ----------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > DocumentLockFile::ParseEntry( const uno::Sequence< sal_Int8 >& aBuffer )
{
sal_Int32 nCurPos = 0;
uno::Sequence< ::rtl::OUString > aResult( LOCKFILE_ENTRYSIZE );
for ( int nInd = 0; nInd < LOCKFILE_ENTRYSIZE; nInd++ )
{
aResult[nInd] = ParseName( aBuffer, nCurPos );
if ( nCurPos >= aBuffer.getLength()
|| ( nInd < LOCKFILE_ENTRYSIZE - 1 && aBuffer[nCurPos++] != ',' )
|| ( nInd == LOCKFILE_ENTRYSIZE - 1 && aBuffer[nCurPos++] != ';' ) )
throw io::WrongFormatException();
}
return aResult;
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::ParseName( const uno::Sequence< sal_Int8 >& aBuffer, sal_Int32& o_nCurPos )
{
::rtl::OStringBuffer aResult;
sal_Bool bHaveName = sal_False;
sal_Bool bEscape = sal_False;
while( !bHaveName )
{
if ( o_nCurPos >= aBuffer.getLength() )
throw io::WrongFormatException();
if ( aBuffer[o_nCurPos] == ',' || aBuffer[o_nCurPos] == ';' )
bHaveName = sal_True;
else
{
if ( bEscape )
{
if ( aBuffer[o_nCurPos] == ',' || aBuffer[o_nCurPos] == ';' || aBuffer[o_nCurPos] == '\\' )
aResult.append( (sal_Char)aBuffer[o_nCurPos] );
else
throw io::WrongFormatException();
bEscape = sal_False;
}
else
{
if ( aBuffer[o_nCurPos] == '\\' )
bEscape = sal_True;
else
aResult.append( (sal_Char)aBuffer[o_nCurPos] );
}
o_nCurPos++;
}
}
return ::rtl::OStringToOUString( aResult.makeStringAndClear(), RTL_TEXTENCODING_UTF8 );
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::EscapeCharacters( const ::rtl::OUString& aSource )
{
::rtl::OUStringBuffer aBuffer;
const sal_Unicode* pStr = aSource.getStr();
for ( sal_Int32 nInd = 0; nInd < aSource.getLength() && pStr[nInd] != 0; nInd++ )
{
if ( pStr[nInd] == '\\' || pStr[nInd] == ';' || pStr[nInd] == ',' )
aBuffer.append( (sal_Unicode)'\\' );
aBuffer.append( pStr[nInd] );
}
return aBuffer.makeStringAndClear();
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::GetOOOUserName()
{
SvtUserOptions aUserOpt;
::rtl::OUString aName = aUserOpt.GetFirstName();
if ( aName.getLength() )
aName += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
aName += aUserOpt.GetLastName();
return aName;
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::GetCurrentLocalTime()
{
::rtl::OUString aTime;
TimeValue aSysTime;
if ( osl_getSystemTime( &aSysTime ) )
{
TimeValue aLocTime;
if ( osl_getLocalTimeFromSystemTime( &aSysTime, &aLocTime ) )
{
oslDateTime aDateTime;
if ( osl_getDateTimeFromTimeValue( &aLocTime, &aDateTime ) )
{
char pDateTime[20];
sprintf( pDateTime, "%02d.%02d.%4d %02d:%02d", aDateTime.Day, aDateTime.Month, aDateTime.Year, aDateTime.Hours, aDateTime.Minutes );
aTime = ::rtl::OUString::createFromAscii( pDateTime );
}
}
}
return aTime;
}
// ----------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > DocumentLockFile::GenerateOwnEntry()
{
uno::Sequence< ::rtl::OUString > aResult( LOCKFILE_ENTRYSIZE );
aResult[LOCKFILE_OOOUSERNAME_ID] = GetOOOUserName();
::osl::Security aSecurity;
aSecurity.getUserName( aResult[LOCKFILE_SYSUSERNAME_ID] );
aResult[LOCKFILE_LOCALHOST_ID] = ::osl::SocketAddr::getLocalHostname();
aResult[LOCKFILE_EDITTIME_ID] = GetCurrentLocalTime();
::utl::Bootstrap::locateUserInstallation( aResult[LOCKFILE_USERURL_ID] );
return aResult;
}
// ----------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > DocumentLockFile::GetLockData()
{
uno::Reference< io::XInputStream > xInput = OpenStream();
if ( !xInput.is() )
throw uno::RuntimeException();
const sal_Int32 nBufLen = 32000;
uno::Sequence< sal_Int8 > aBuffer( nBufLen );
sal_Int32 nRead = 0;
nRead = xInput->readBytes( aBuffer, nBufLen );
xInput->closeInput();
if ( nRead == nBufLen )
throw io::WrongFormatException();
return ParseEntry( aBuffer );
}
// ----------------------------------------------------------------------
uno::Reference< io::XInputStream > DocumentLockFile::OpenStream()
{
uno::Reference< lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSimpleFileAccess(
xFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess") ),
uno::UNO_QUERY_THROW );
return xSimpleFileAccess->openFileRead( m_aURL );
}
// ----------------------------------------------------------------------
void DocumentLockFile::RemoveFile()
{
// TODO/LATER: the removing is not atomar, is it possible in general to make it atomar?
uno::Sequence< ::rtl::OUString > aNewEntry = GenerateOwnEntry();
uno::Sequence< ::rtl::OUString > aFileData = GetLockData();
if ( aFileData.getLength() < LOCKFILE_ENTRYSIZE )
throw io::WrongFormatException();
if ( !aFileData[LOCKFILE_SYSUSERNAME_ID].equals( aNewEntry[LOCKFILE_SYSUSERNAME_ID] )
|| !aFileData[LOCKFILE_LOCALHOST_ID].equals( aNewEntry[LOCKFILE_LOCALHOST_ID] )
|| !aFileData[LOCKFILE_USERURL_ID].equals( aNewEntry[LOCKFILE_USERURL_ID] ) )
throw io::IOException(); // not the owner, access denied
uno::Reference< lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSimpleFileAccess(
xFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess") ),
uno::UNO_QUERY_THROW );
xSimpleFileAccess->kill( m_aURL );
}
} // namespace svt
<commit_msg>INTEGRATION: CWS fwk91 (1.2.88); FILE MERGED 2008/06/20 11:56:58 mav 1.2.88.1: #i87796# let the sharing- and lock-control files be hidden<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: documentlockfile.cxx,v $
*
* $Revision: 1.3 $
*
* 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_svtools.hxx"
#include <stdio.h>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/InsertCommandArgument.hpp>
#include <com/sun/star/ucb/NameClashException.hpp>
#include <com/sun/star/io/WrongFormatException.hpp>
#include <osl/time.h>
#include <osl/security.hxx>
#include <osl/socket.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <comphelper/processfactory.hxx>
#include <tools/urlobj.hxx>
#include <unotools/bootstrap.hxx>
#include <ucbhelper/content.hxx>
#include <svtools/useroptions.hxx>
#include <svtools/documentlockfile.hxx>
using namespace ::com::sun::star;
namespace svt {
sal_Bool DocumentLockFile::m_bAllowInteraction = sal_True;
// ----------------------------------------------------------------------
DocumentLockFile::DocumentLockFile( const ::rtl::OUString& aOrigURL, const uno::Reference< lang::XMultiServiceFactory >& xFactory )
: m_xFactory( xFactory )
{
if ( !m_xFactory.is() )
m_xFactory = ::comphelper::getProcessServiceFactory();
INetURLObject aDocURL( aOrigURL );
if ( aDocURL.HasError() )
throw lang::IllegalArgumentException();
::rtl::OUString aShareURLString = aDocURL.GetPartBeforeLastName();
aShareURLString += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".~lock." ) );
aShareURLString += aDocURL.GetName();
aShareURLString += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "#" ) );
m_aURL = INetURLObject( aShareURLString ).GetMainURL( INetURLObject::NO_DECODE );
}
// ----------------------------------------------------------------------
DocumentLockFile::~DocumentLockFile()
{
}
// ----------------------------------------------------------------------
void DocumentLockFile::WriteEntryToStream( uno::Sequence< ::rtl::OUString > aEntry, uno::Reference< io::XOutputStream > xOutput )
{
::rtl::OUStringBuffer aBuffer;
for ( sal_Int32 nEntryInd = 0; nEntryInd < aEntry.getLength(); nEntryInd++ )
{
aBuffer.append( EscapeCharacters( aEntry[nEntryInd] ) );
if ( nEntryInd < aEntry.getLength() - 1 )
aBuffer.append( (sal_Unicode)',' );
else
aBuffer.append( (sal_Unicode)';' );
}
::rtl::OString aStringData( ::rtl::OUStringToOString( aBuffer.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ) );
uno::Sequence< sal_Int8 > aData( (sal_Int8*)aStringData.getStr(), aStringData.getLength() );
xOutput->writeBytes( aData );
}
// ----------------------------------------------------------------------
sal_Bool DocumentLockFile::CreateOwnLockFile()
{
try
{
uno::Reference< io::XStream > xTempFile(
m_xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ) ),
uno::UNO_QUERY_THROW );
uno::Reference< io::XSeekable > xSeekable( xTempFile, uno::UNO_QUERY_THROW );
uno::Reference< io::XInputStream > xInput = xTempFile->getInputStream();
uno::Reference< io::XOutputStream > xOutput = xTempFile->getOutputStream();
if ( !xInput.is() || !xOutput.is() )
throw uno::RuntimeException();
uno::Sequence< ::rtl::OUString > aNewEntry = GenerateOwnEntry();
WriteEntryToStream( aNewEntry, xOutput );
xOutput->closeOutput();
xSeekable->seek( 0 );
uno::Reference < ::com::sun::star::ucb::XCommandEnvironment > xEnv;
::ucbhelper::Content aTargetContent( m_aURL, xEnv );
ucb::InsertCommandArgument aInsertArg;
aInsertArg.Data = xInput;
aInsertArg.ReplaceExisting = sal_False;
uno::Any aCmdArg;
aCmdArg <<= aInsertArg;
aTargetContent.executeCommand( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "insert" ) ), aCmdArg );
// try to let the file be hidden if possible
try {
aTargetContent.setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsHidden" ) ), uno::makeAny( sal_True ) );
} catch( uno::Exception& ) {}
}
catch( ucb::NameClashException& )
{
return sal_False;
}
return sal_True;
}
// ----------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > DocumentLockFile::ParseEntry( const uno::Sequence< sal_Int8 >& aBuffer )
{
sal_Int32 nCurPos = 0;
uno::Sequence< ::rtl::OUString > aResult( LOCKFILE_ENTRYSIZE );
for ( int nInd = 0; nInd < LOCKFILE_ENTRYSIZE; nInd++ )
{
aResult[nInd] = ParseName( aBuffer, nCurPos );
if ( nCurPos >= aBuffer.getLength()
|| ( nInd < LOCKFILE_ENTRYSIZE - 1 && aBuffer[nCurPos++] != ',' )
|| ( nInd == LOCKFILE_ENTRYSIZE - 1 && aBuffer[nCurPos++] != ';' ) )
throw io::WrongFormatException();
}
return aResult;
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::ParseName( const uno::Sequence< sal_Int8 >& aBuffer, sal_Int32& o_nCurPos )
{
::rtl::OStringBuffer aResult;
sal_Bool bHaveName = sal_False;
sal_Bool bEscape = sal_False;
while( !bHaveName )
{
if ( o_nCurPos >= aBuffer.getLength() )
throw io::WrongFormatException();
if ( aBuffer[o_nCurPos] == ',' || aBuffer[o_nCurPos] == ';' )
bHaveName = sal_True;
else
{
if ( bEscape )
{
if ( aBuffer[o_nCurPos] == ',' || aBuffer[o_nCurPos] == ';' || aBuffer[o_nCurPos] == '\\' )
aResult.append( (sal_Char)aBuffer[o_nCurPos] );
else
throw io::WrongFormatException();
bEscape = sal_False;
}
else
{
if ( aBuffer[o_nCurPos] == '\\' )
bEscape = sal_True;
else
aResult.append( (sal_Char)aBuffer[o_nCurPos] );
}
o_nCurPos++;
}
}
return ::rtl::OStringToOUString( aResult.makeStringAndClear(), RTL_TEXTENCODING_UTF8 );
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::EscapeCharacters( const ::rtl::OUString& aSource )
{
::rtl::OUStringBuffer aBuffer;
const sal_Unicode* pStr = aSource.getStr();
for ( sal_Int32 nInd = 0; nInd < aSource.getLength() && pStr[nInd] != 0; nInd++ )
{
if ( pStr[nInd] == '\\' || pStr[nInd] == ';' || pStr[nInd] == ',' )
aBuffer.append( (sal_Unicode)'\\' );
aBuffer.append( pStr[nInd] );
}
return aBuffer.makeStringAndClear();
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::GetOOOUserName()
{
SvtUserOptions aUserOpt;
::rtl::OUString aName = aUserOpt.GetFirstName();
if ( aName.getLength() )
aName += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
aName += aUserOpt.GetLastName();
return aName;
}
// ----------------------------------------------------------------------
::rtl::OUString DocumentLockFile::GetCurrentLocalTime()
{
::rtl::OUString aTime;
TimeValue aSysTime;
if ( osl_getSystemTime( &aSysTime ) )
{
TimeValue aLocTime;
if ( osl_getLocalTimeFromSystemTime( &aSysTime, &aLocTime ) )
{
oslDateTime aDateTime;
if ( osl_getDateTimeFromTimeValue( &aLocTime, &aDateTime ) )
{
char pDateTime[20];
sprintf( pDateTime, "%02d.%02d.%4d %02d:%02d", aDateTime.Day, aDateTime.Month, aDateTime.Year, aDateTime.Hours, aDateTime.Minutes );
aTime = ::rtl::OUString::createFromAscii( pDateTime );
}
}
}
return aTime;
}
// ----------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > DocumentLockFile::GenerateOwnEntry()
{
uno::Sequence< ::rtl::OUString > aResult( LOCKFILE_ENTRYSIZE );
aResult[LOCKFILE_OOOUSERNAME_ID] = GetOOOUserName();
::osl::Security aSecurity;
aSecurity.getUserName( aResult[LOCKFILE_SYSUSERNAME_ID] );
aResult[LOCKFILE_LOCALHOST_ID] = ::osl::SocketAddr::getLocalHostname();
aResult[LOCKFILE_EDITTIME_ID] = GetCurrentLocalTime();
::utl::Bootstrap::locateUserInstallation( aResult[LOCKFILE_USERURL_ID] );
return aResult;
}
// ----------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > DocumentLockFile::GetLockData()
{
uno::Reference< io::XInputStream > xInput = OpenStream();
if ( !xInput.is() )
throw uno::RuntimeException();
const sal_Int32 nBufLen = 32000;
uno::Sequence< sal_Int8 > aBuffer( nBufLen );
sal_Int32 nRead = 0;
nRead = xInput->readBytes( aBuffer, nBufLen );
xInput->closeInput();
if ( nRead == nBufLen )
throw io::WrongFormatException();
return ParseEntry( aBuffer );
}
// ----------------------------------------------------------------------
uno::Reference< io::XInputStream > DocumentLockFile::OpenStream()
{
uno::Reference< lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSimpleFileAccess(
xFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess") ),
uno::UNO_QUERY_THROW );
// the file can be opened readonly, no locking will be done
return xSimpleFileAccess->openFileRead( m_aURL );
}
// ----------------------------------------------------------------------
void DocumentLockFile::RemoveFile()
{
// TODO/LATER: the removing is not atomar, is it possible in general to make it atomar?
uno::Sequence< ::rtl::OUString > aNewEntry = GenerateOwnEntry();
uno::Sequence< ::rtl::OUString > aFileData = GetLockData();
if ( aFileData.getLength() < LOCKFILE_ENTRYSIZE )
throw io::WrongFormatException();
if ( !aFileData[LOCKFILE_SYSUSERNAME_ID].equals( aNewEntry[LOCKFILE_SYSUSERNAME_ID] )
|| !aFileData[LOCKFILE_LOCALHOST_ID].equals( aNewEntry[LOCKFILE_LOCALHOST_ID] )
|| !aFileData[LOCKFILE_USERURL_ID].equals( aNewEntry[LOCKFILE_USERURL_ID] ) )
throw io::IOException(); // not the owner, access denied
uno::Reference< lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSimpleFileAccess(
xFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess") ),
uno::UNO_QUERY_THROW );
xSimpleFileAccess->kill( m_aURL );
}
} // namespace svt
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <stdlib.h>
using namespace std;
void parse(char * line, vector<string> & input) {
char * pch;
pch = strtok (line, " \n");
while (pch!= NULL) {
// Ignore after comments
if (*pch == '#')
break;
// Check for && and ||
// Break input up
char * a = strstr(pch, "&&");
char * b = strstr(pch, "||");
char * c = strstr(pch, ";");
// If there are connectors, break up the string
// into parts and add them individually to the vector
if (a!=NULL || b!=NULL || c!=NULL) {
while (strlen(pch) != 0 ) {
// Checks for && and ||
if ((pch[0] == '&' && pch[1] == '&') ||
(pch[0] == '|' && pch[1] == '|')) {
string tmp;
tmp += *pch;
tmp += *(pch+1);
tmp[2] = '\0';
input.push_back(tmp);
memmove(pch, pch+2, strlen(pch) - 2);
pch[strlen(pch)-2] = '\0';
}
// Check for semicolons
else if (*pch == ';') {
input.push_back(";");
memmove(pch, pch+1, strlen(pch) -1);
pch[strlen(pch)-1] = '\0';
}
else {
string word;
int numletters = 0;
char *d = pch;
while (d!=a && d!=b && d!=c) {
if (*d == '\0')
break;
word += *d;
numletters++;
d++;
}
input.push_back(word);
memmove(pch, pch+numletters, strlen(pch) -numletters);
pch[strlen(pch)-numletters] = '\0';
}
a = strstr(pch, "&&");
b = strstr(pch, "||");
c = strstr(pch, ";");
}
}
// If no connectors, just add to vector
if (*pch != '\0' && *pch != '\n' && *pch != '#')
input.push_back(pch);
pch = strtok (NULL, " \n");
}
}
void execute(vector<string> & input, int start, int end) {
//Call execvp, based on which elements in the string vector to use
char * argv[5];
int i = 0;
for (i = 0; i <= (end - start); i++) {
argv[i] = new char[5];
}
for (i = 0; i < (end-start); i++) {
strcpy(argv[i], input[i+start].c_str());
}
argv[i] = NULL;
int status = execvp(argv[0], argv);
if (status == -1)
perror("execvp");
exit(1);
}
int main() {
vector<string> input;
int status=0;
// Get username
char * usrname = getlogin();
if (usrname == NULL){
perror ("getlogin");
exit(1);
}
// Get hostname
char hostname[20];
if (gethostname(hostname, sizeof hostname) ==-1) {
perror("gethostname");
exit(1);
}
// Main loop
while (1) {
status = 0;
if (input.size() != 0)
input.clear();
cout << usrname << "@" << hostname <<"$ ";
string string1;
getline(cin, string1);
char * line = new char [string1.length() + 1];
strcpy(line, string1.c_str());
parse(line, input);
delete line;
if (input.size() == 0)
continue;
if (strcmp(input[0].c_str(), "exit") == 0)
exit(0);
int pid=fork();
if (pid == -1)
perror ("fork");
int pid2;
if (pid == 0) {
int start = 0;
int end = input.size();
unsigned i;
loop:
end = input.size();
for (i = start; i < input.size(); i++) {
if (input[i] == ";" || input[i] == "&&" || input[i] == "||") {
string connector = input[i];
pid2 = fork();
if (pid2 == -1) {
perror("fork");
exit(1);
}
if (pid2!=0) {
if (-1 == wait(&status))
perror("wait");
if (connector == "&&" && status != 0)
exit(1);
if (connector == "||" && status == 0)
exit(0);
start = i + 1;
goto loop;
}
else {
end = i;
break;
}
}
}
execute(input, start, end);
}
else {
status = wait(NULL);
if (status == -1)
perror("wait");
}
}
return 0;
}
<commit_msg>updated rshell<commit_after>#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <stdlib.h>
using namespace std;
void parse(char * line, vector<string> & input) {
char * pch;
pch = strtok (line, " \n");
while (pch!= NULL) {
// Ignore after comments
if (*pch == '#')
break;
// Check for && and ||
// Break input up
char * a = strstr(pch, "&&");
char * b = strstr(pch, "||");
char * c = strstr(pch, ";");
// If there are connectors, break up the string
// into parts and add them individually to the vector
if (a!=NULL || b!=NULL || c!=NULL) {
while (strlen(pch) != 0 ) {
// Checks for && and ||
if ((pch[0] == '&' && pch[1] == '&') ||
(pch[0] == '|' && pch[1] == '|')) {
string tmp;
tmp += *pch;
tmp += *(pch+1);
tmp[2] = '\0';
input.push_back(tmp);
memmove(pch, pch+2, strlen(pch) - 2);
pch[strlen(pch)-2] = '\0';
}
// Check for semicolons
else if (*pch == ';') {
input.push_back(";");
memmove(pch, pch+1, strlen(pch) -1);
pch[strlen(pch)-1] = '\0';
}
else {
string word;
int numletters = 0;
char *d = pch;
while (d!=a && d!=b && d!=c) {
if (*d == '\0')
break;
word += *d;
numletters++;
d++;
}
input.push_back(word);
memmove(pch, pch+numletters, strlen(pch) -numletters);
pch[strlen(pch)-numletters] = '\0';
}
a = strstr(pch, "&&");
b = strstr(pch, "||");
c = strstr(pch, ";");
}
}
// If no connectors, just add to vector
if (*pch != '\0' && *pch != '\n' && *pch != '#')
input.push_back(pch);
pch = strtok (NULL, " \n");
}
}
void execute(vector<string> & input, int start, int end) {
//Call execvp, based on which elements in the string vector to use
char * argv[5];
int i = 0;
for (i = 0; i <= (end - start); i++) {
argv[i] = new char[5];
}
for (i = 0; i < (end-start); i++) {
strcpy(argv[i], input[i+start].c_str());
}
argv[i] = NULL;
int status = execvp(argv[0], argv);
if (status == -1)
perror("execvp");
exit(1);
}
int main() {
vector<string> input;
int status=0;
// Get username
char * usrname = getlogin();
if (usrname == NULL){
perror ("getlogin");
exit(1);
}
// Get hostname
char hostname[20];
if (gethostname(hostname, sizeof hostname) ==-1) {
perror("gethostname");
exit(1);
}
// Main loop
while (1) {
status = 0;
if (input.size() != 0)
input.clear();
cout << usrname << "@" << hostname <<"$ ";
string string1;
getline(cin, string1);
char * line = new char [string1.length() + 1];
strcpy(line, string1.c_str());
parse(line, input);
delete line;
if (input.size() == 0)
continue;
for (int i = 0; i < input.size(); i++)
if (strcmp(input[i].c_str(), "exit") == 0) exit(0);
int pid=fork();
if (pid == -1)
perror ("fork");
int pid2;
if (pid == 0) {
int start = 0;
int end = input.size();
unsigned i;
loop:
end = input.size();
for (i = start; i < input.size(); i++) {
if (input[i] == ";" || input[i] == "&&" || input[i] == "||") {
string connector = input[i];
pid2 = fork();
if (pid2 == -1) {
perror("fork");
exit(1);
}
if (pid2!=0) {
if (-1 == wait(&status))
perror("wait");
if (connector == "&&" && status != 0)
exit(1);
if (connector == "||" && status == 0)
exit(0);
start = i + 1;
goto loop;
}
else {
end = i;
break;
}
}
}
execute(input, start, end);
}
else {
status = wait(NULL);
if (status == -1)
perror("wait");
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace std;
/*
Usage: hadoop fs [generic options]
[-appendToFile <localsrc> ... <dst>]
[-cat [-ignoreCrc] <src> ...]
[-checksum <src> ...]
[-chgrp [-R] GROUP PATH...]
[-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]
[-chown [-R] [OWNER][:[GROUP]] PATH...]
[-copyFromLocal [-f] [-p] <localsrc> ... <dst>]
[-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-count [-q] <path> ...]
[-cp [-f] [-p] <src> ... <dst>]
[-createSnapshot <snapshotDir> [<snapshotName>]]
[-deleteSnapshot <snapshotDir> <snapshotName>]
[-df [-h] [<path> ...]]
[-du [-s] [-h] <path> ...]
[-expunge]
[-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-getfacl [-R] <path>]
[-getmerge [-nl] <src> <localdst>]
[-help [cmd ...]]
[-ls [-d] [-h] [-R] [<path> ...]]
[-mkdir [-p] <path> ...]
[-moveFromLocal <localsrc> ... <dst>]
[-moveToLocal <src> <localdst>]
[-mv <src> ... <dst>]
[-put [-f] [-p] <localsrc> ... <dst>]
[-renameSnapshot <snapshotDir> <oldName> <newName>]
[-rm [-f] [-r|-R] [-skipTrash] <src> ...]
[-rmdir [--ignore-fail-on-non-empty] <dir> ...]
[-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]]
[-setrep [-R] [-w] <rep> <path> ...]
[-stat [format] <path> ...]
[-tail [-f] <file>]
[-test -[defsz] <path>]
[-text [-ignoreCrc] <src> ...]
[-touchz <path> ...]
[-usage [cmd ...]]
*/
static const string constStrDecs =
"Usage: mdfs.client [generic options\n]"
" [-appendToFile <localsrc> ... <dst>\n]"
" [-cat [-ignoreCrc] <src> ...\n]"
" [-checksum <src> ...\n]"
" [-chgrp [-R] GROUP PATH...\n]"
" [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...\n]"
" [-chown [-R] [OWNER][:[GROUP]] PATH...\n]"
" [-copyFromLocal [-f] [-p] <localsrc> ... <dst>\n]"
" [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>\n]"
" [-count [-q] <path> ...\n]"
" [-cp [-f] [-p] <src> ... <dst>\n]"
" [-createSnapshot <snapshotDir> [<snapshotName>]\n]"
" [-deleteSnapshot <snapshotDir> <snapshotName>\n]"
" [-df [-h] [<path> ...]\n]"
" [-du [-s] [-h] <path> ...\n]"
" [-expunge\n]"
" [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>\n]"
" [-getfacl [-R] <path>\n]"
" [-getmerge [-nl] <src> <localdst>\n]"
" [-help [cmd ...]\n]"
" [-ls [-d] [-h] [-R] [<path> ...]\n]"
" [-mkdir [-p] <path> ...\n]"
" [-moveFromLocal <localsrc> ... <dst>\n]"
" [-moveToLocal <src> <localdst>\n]"
" [-mv <src> ... <dst>\n]"
" [-put [-f] [-p] <localsrc> ... <dst>\n]"
" [-renameSnapshot <snapshotDir> <oldName> <newName>\n]"
" [-rm [-f] [-r|-R] [-skipTrash] <src> ...\n]"
" [-rmdir [--ignore-fail-on-non-empty] <dir> ...\n]"
" [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]\n]"
" [-setrep [-R] [-w] <rep> <path> ...\n]"
" [-stat [format] <path> ...\n]"
" [-tail [-f] <file>\n]"
" [-test -[defsz] <path>\n]"
" [-text [-ignoreCrc] <src> ...\n]"
" [-touchz <path> ...\n]"
" [-usage [cmd ...]\n]"
;
int main(int ac,char*av[])
{
po::options_description opt(constStrDecs);
opt.add_options()
("help,h" , "")
(",appendToFile" , po::value<string>() ," <localsrc> ... <dst>")
;
po::variables_map vm;
try
{
po::store(po::parse_command_line(ac, av, opt), vm);
}
catch(const po::error_with_option_name& e)
{
std::cout << e.what() << std::endl;
}
po::notify(vm);
if (vm.count("help") || !vm.count("op"))
{
std::cout << opt << std::endl;
}
else
{
try
{
const std::string op = vm["op"].as<std::string>();
const int lhs = vm["lhs"].as<int>();
const int rhs = vm["rhs"].as<int>();
if (op == "add")
{
std::cout << lhs + rhs << std::endl;
}
if (op == "sub")
{
std::cout << lhs - rhs << std::endl;
}
}
catch(const boost::bad_any_cast& e)
{
std::cout << e.what() << std::endl;
}
}
return 0;
}
<commit_msg>add options<commit_after>#include <iostream>
#include <string>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace std;
/*
Usage: hadoop fs [generic options]
[-appendToFile <localsrc> ... <dst>]
[-cat [-ignoreCrc] <src> ...]
[-checksum <src> ...]
[-chgrp [-R] GROUP PATH...]
[-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]
[-chown [-R] [OWNER][:[GROUP]] PATH...]
[-copyFromLocal [-f] [-p] <localsrc> ... <dst>]
[-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-count [-q] <path> ...]
[-cp [-f] [-p] <src> ... <dst>]
[-createSnapshot <snapshotDir> [<snapshotName>]]
[-deleteSnapshot <snapshotDir> <snapshotName>]
[-df [-h] [<path> ...]]
[-du [-s] [-h] <path> ...]
[-expunge]
[-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-getfacl [-R] <path>]
[-getmerge [-nl] <src> <localdst>]
[-help [cmd ...]]
[-ls [-d] [-h] [-R] [<path> ...]]
[-mkdir [-p] <path> ...]
[-moveFromLocal <localsrc> ... <dst>]
[-moveToLocal <src> <localdst>]
[-mv <src> ... <dst>]
[-put [-f] [-p] <localsrc> ... <dst>]
[-renameSnapshot <snapshotDir> <oldName> <newName>]
[-rm [-f] [-r|-R] [-skipTrash] <src> ...]
[-rmdir [--ignore-fail-on-non-empty] <dir> ...]
[-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]]
[-setrep [-R] [-w] <rep> <path> ...]
[-stat [format] <path> ...]
[-tail [-f] <file>]
[-test -[defsz] <path>]
[-text [-ignoreCrc] <src> ...]
[-touchz <path> ...]
[-usage [cmd ...]]
*/
static const string constStrDecs =
"Usage: mdfs.client [generic options]\n"
" [-appendToFile <localsrc> ... <dst>]\n"
" [-cat [-ignoreCrc] <src> ...]\n"
" [-checksum <src> ...]\n"
" [-chgrp [-R] GROUP PATH...]\n"
" [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]\n"
" [-chown [-R] [OWNER][:[GROUP]] PATH...]\n"
" [-copyFromLocal [-f] [-p] <localsrc> ... <dst>]\n"
" [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]\n"
" [-count [-q] <path> ...]\n"
" [-cp [-f] [-p] <src> ... <dst>]\n"
" [-createSnapshot <snapshotDir> [<snapshotName>]]\n"
" [-deleteSnapshot <snapshotDir> <snapshotName>]\n"
" [-df [-h] [<path> ...]]\n"
" [-du [-s] [-h] <path> ...]\n"
" [-expunge]\n"
" [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]\n"
" [-getfacl [-R] <path>]\n"
" [-getmerge [-nl] <src> <localdst>]\n"
" [-help [cmd ...]]\n"
" [-ls [-d] [-h] [-R] [<path> ...]]\n"
" [-mkdir [-p] <path> ...]\n"
" [-moveFromLocal <localsrc> ... <dst>]\n"
" [-moveToLocal <src> <localdst>]\n"
" [-mv <src> ... <dst>]\n"
" [-put [-f] [-p] <localsrc> ... <dst>]\n"
" [-renameSnapshot <snapshotDir> <oldName> <newName>]\n"
" [-rm [-f] [-r|-R] [-skipTrash] <src> ...]\n"
" [-rmdir [--ignore-fail-on-non-empty] <dir> ...]\n"
" [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]]\n"
" [-setrep [-R] [-w] <rep> <path> ...]\n"
" [-stat [format] <path> ...]\n"
" [-tail [-f] <file>]\n"
" [-test -[defsz] <path>]\n"
" [-text [-ignoreCrc] <src> ...]\n"
" [-touchz <path> ...]\n"
" [-usage [cmd ...]]\n"
;
int main(int ac,char*av[])
{
po::options_description opt(constStrDecs);
opt.add_options()
("help,h" , "")
(",appendToFile" , po::value<string>() ," <localsrc> ... <dst>")
;
po::variables_map vm;
try
{
po::store(po::parse_command_line(ac, av, opt), vm);
}
catch(const po::error_with_option_name& e)
{
std::cout << e.what() << std::endl;
}
po::notify(vm);
if (vm.count("help") || !vm.count("op"))
{
std::cout << opt << std::endl;
}
else
{
try
{
const std::string op = vm["op"].as<std::string>();
const int lhs = vm["lhs"].as<int>();
const int rhs = vm["rhs"].as<int>();
if (op == "add")
{
std::cout << lhs + rhs << std::endl;
}
if (op == "sub")
{
std::cout << lhs - rhs << std::endl;
}
}
catch(const boost::bad_any_cast& e)
{
std::cout << e.what() << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef RPT_XMLCONTROLPROPERTY_HXX
#define RPT_XMLCONTROLPROPERTY_HXX
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlControlProperty.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-07-09 11:56:17 $
*
* 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_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_TIME_HPP_
#include <com/sun/star/util/Time.hpp>
#endif
namespace rptxml
{
class ORptFilter;
class OXMLControlProperty : public SvXMLImportContext
{
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xControl;
::com::sun::star::beans::PropertyValue m_aSetting;
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> m_aSequence;
OXMLControlProperty* m_pContainer;
::com::sun::star::uno::Type m_aPropType; // the type of the property the instance imports currently
sal_Bool m_bIsList;
ORptFilter& GetOwnImport();
::com::sun::star::uno::Any convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters);
OXMLControlProperty(const OXMLControlProperty&);
void operator =(const OXMLControlProperty&);
public:
OXMLControlProperty( ORptFilter& rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& rLName
,const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList
,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xControl
,OXMLControlProperty* _pContainer = NULL);
virtual ~OXMLControlProperty();
virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
virtual void Characters( const ::rtl::OUString& rChars );
/** adds value to property
@param _sValue
The value to add.
*/
void addValue(const ::rtl::OUString& _sValue);
private:
static ::com::sun::star::util::Time implGetTime(double _nValue);
static ::com::sun::star::util::Date implGetDate(double _nValue);
};
// -----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
#endif // RPT_XMLCONTROLPROPERTY_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.104); FILE MERGED 2008/04/01 15:23:37 thb 1.2.104.3: #i85898# Stripping all external header guards 2008/04/01 12:33:09 thb 1.2.104.2: #i85898# Stripping all external header guards 2008/03/31 13:32:07 rt 1.2.104.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: xmlControlProperty.hxx,v $
* $Revision: 1.3 $
*
* 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 RPT_XMLCONTROLPROPERTY_HXX
#define RPT_XMLCONTROLPROPERTY_HXX
#include <xmloff/xmlictxt.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/util/Date.hpp>
#include <com/sun/star/util/Time.hpp>
namespace rptxml
{
class ORptFilter;
class OXMLControlProperty : public SvXMLImportContext
{
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xControl;
::com::sun::star::beans::PropertyValue m_aSetting;
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> m_aSequence;
OXMLControlProperty* m_pContainer;
::com::sun::star::uno::Type m_aPropType; // the type of the property the instance imports currently
sal_Bool m_bIsList;
ORptFilter& GetOwnImport();
::com::sun::star::uno::Any convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters);
OXMLControlProperty(const OXMLControlProperty&);
void operator =(const OXMLControlProperty&);
public:
OXMLControlProperty( ORptFilter& rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& rLName
,const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList
,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xControl
,OXMLControlProperty* _pContainer = NULL);
virtual ~OXMLControlProperty();
virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
virtual void Characters( const ::rtl::OUString& rChars );
/** adds value to property
@param _sValue
The value to add.
*/
void addValue(const ::rtl::OUString& _sValue);
private:
static ::com::sun::star::util::Time implGetTime(double _nValue);
static ::com::sun::star::util::Date implGetDate(double _nValue);
};
// -----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
#endif // RPT_XMLCONTROLPROPERTY_HXX
<|endoftext|>
|
<commit_before>/* Rapicorn
* Copyright (C) 2008 Tim Janik
*
* 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.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#ifndef __RAPICORN_TESTUTILS_HH__
#define __RAPICORN_TESTUTILS_HH__
#include <rcore/rcore.hh>
// Test Macros
#define TTITLE(...) Rapicorn::Test::test_output (3, __VA_ARGS__)
#define TSTART(...) Rapicorn::Test::test_output (4, __VA_ARGS__)
#define TDONE() Rapicorn::Test::test_output (5, "%s", "")
#define TOUT(...) Rapicorn::Test::test_output (0, __VA_ARGS__)
#define TMSG(...) Rapicorn::Test::test_output (1, __VA_ARGS__)
#define TINFO(...) Rapicorn::Test::test_output (2, __VA_ARGS__)
#define TWARN(...) Rapicorn::Test::test_output (6, __VA_ARGS__)
#define TRUN(name, func) ({ TSTART (name); func(); TDONE(); })
#define TOK() do {} while (0) // printerr (".")
#define TCMP(a,cmp,b) TCMP_op (a,cmp,b,#a,#b,)
#define TCMPS(a,cmp,b) TCMP_op (a,cmp,b,#a,#b,Rapicorn::Test::_as_strptr)
#define TASSERT RAPICORN_ASSERT // TASSERT (condition)
#define TASSERT_EMPTY(str) do { const String &__s = str; if (__s.empty()) break; \
Rapicorn::debug_fatal (__FILE__, __LINE__, "error: %s", __s.c_str()); } while (0)
#define TCMP_op(a,cmp,b,sa,sb,cast) do { if (a cmp b) break; \
String __tassert_va = Rapicorn::Test::stringify_arg (cast (a), #a); \
String __tassert_vb = Rapicorn::Test::stringify_arg (cast (b), #b); \
Rapicorn::debug_fatal (__FILE__, __LINE__, \
"assertion failed: %s %s %s: %s %s %s", \
sa, #cmp, sb, __tassert_va.c_str(), #cmp, __tassert_vb.c_str()); \
} while (0)
namespace Rapicorn {
void init_core_test (const String &app_ident, int *argcp, char **argv, const StringVector &args = StringVector());
namespace Test {
/**
* Class for profiling benchmark tests.
* UseCase: Benchmarking function implementations, e.g. to compare sorting implementations.
*/
class Timer {
const double m_deadline;
vector<double> m_samples;
double m_test_duration;
int64 m_n_runs;
int64 loops_needed () const;
void reset ();
void submit (double elapsed, int64 repetitions);
static double bench_time ();
public:
/// Create a Timer() instance, specifying an optional upper bound for test durations.
explicit Timer (double deadline_in_secs = 0);
virtual ~Timer ();
int64 n_runs () const { return m_n_runs; } ///< Number of benchmark runs executed
double test_elapsed () const { return m_test_duration; } ///< Seconds spent in benchmark()
double min_elapsed () const; ///< Minimum time benchmarked for a @a callee() call.
double max_elapsed () const; ///< Maximum time benchmarked for a @a callee() call.
template<typename Callee>
double benchmark (Callee callee);
};
/**
* @param callee A callable function or object.
* Method to benchmark the execution time of @a callee.
* @returns Minimum runtime in seconds,
*/
template<typename Callee> double
Timer::benchmark (Callee callee)
{
reset();
for (int64 runs = loops_needed(); runs; runs = loops_needed())
{
int64 n = runs;
const double start = bench_time();
while (RAPICORN_LIKELY (n--))
callee();
const double stop = bench_time();
submit (stop - start, runs);
}
return min_elapsed();
}
// === test maintenance ===
int run (void); ///< Run all registered tests.
bool verbose (void); ///< Indicates whether tests should run verbosely.
bool logging (void); ///< Indicates whether only logging tests should be run.
bool slow (void); ///< Indicates whether only slow tests should be run.
bool ui_test (void); ///< Indicates execution of ui-thread tests.
void test_output (int kind, const char *format, ...) RAPICORN_PRINTF (2, 3);
void add_internal (const String &testname,
void (*test_func) (void*),
void *data);
void add (const String &funcname,
void (*test_func) (void));
template<typename D>
void add (const String &testname,
void (*test_func) (D*),
D *data)
{
add_internal (testname, (void(*)(void*)) test_func, (void*) data);
}
/// == Stringify Args ==
inline String stringify_arg (const char *a, const char *str_a) { return a ? string_to_cquote (a) : "(__null)"; }
template<class V> inline String stringify_arg (const V *a, const char *str_a) { return string_printf ("%p", a); }
template<class A> inline String stringify_arg (const A &a, const char *str_a) { return str_a; }
template<> inline String stringify_arg<float> (const float &a, const char *str_a) { return string_printf ("%.8g", a); }
template<> inline String stringify_arg<double> (const double &a, const char *str_a) { return string_printf ("%.17g", a); }
template<> inline String stringify_arg<bool> (const bool &a, const char *str_a) { return string_printf ("%u", a); }
template<> inline String stringify_arg<int8> (const int8 &a, const char *str_a) { return string_printf ("%d", a); }
template<> inline String stringify_arg<int16> (const int16 &a, const char *str_a) { return string_printf ("%d", a); }
template<> inline String stringify_arg<int32> (const int32 &a, const char *str_a) { return string_printf ("%d", a); }
template<> inline String stringify_arg<int64> (const int64 &a, const char *str_a) { return string_printf ("%lld", a); }
template<> inline String stringify_arg<uint8> (const uint8 &a, const char *str_a) { return string_printf ("0x%02x", a); }
template<> inline String stringify_arg<uint16> (const uint16 &a, const char *str_a) { return string_printf ("0x%04x", a); }
template<> inline String stringify_arg<uint32> (const uint32 &a, const char *str_a) { return string_printf ("0x%08x", a); }
template<> inline String stringify_arg<uint64> (const uint64 &a, const char *str_a) { return string_printf ("0x%08Lx", a); }
template<> inline String stringify_arg<String> (const String &a, const char *str_a) { return string_to_cquote (a); }
inline const char* _as_strptr (const char *s) { return s; } // implementation detail
class RegisterTest {
static void add_test (char kind, const String &testname, void (*test_func) (void*), void *data);
public:
RegisterTest (const char k, const String &testname, void (*test_func) (void))
{ add_test (k, testname, (void(*)(void*)) test_func, NULL); }
RegisterTest (const char k, const String &testname, void (*test_func) (ptrdiff_t), ptrdiff_t data)
{ add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }
template<typename D>
RegisterTest (const char k, const String &testname, void (*test_func) (D*), D *data)
{ add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }
typedef void (*TestTrigger) (void (*runner) (void));
static void test_set_trigger (TestTrigger func);
};
/// Register a standard test function for execution as unit test.
#define REGISTER_TEST(name, ...) static const Rapicorn::Test::RegisterTest \
RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('t', name, __VA_ARGS__)
/// Register a slow test function for execution as during slow unit testing.
#define REGISTER_SLOWTEST(name, ...) static const Rapicorn::Test::RegisterTest \
RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('s', name, __VA_ARGS__)
/// Register a logging test function for output recording and verification.
#define REGISTER_LOGTEST(name, ...) static const Rapicorn::Test::RegisterTest \
RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('l', name, __VA_ARGS__)
// == Deterministic random numbers for tests ===
char rand_bit (void); ///< Return a random bit.
int32 rand_int (void); ///< Return random int.
int32 rand_int_range (int32 begin, int32 end); ///< Return random int within range.
double test_rand_double (void); ///< Return random double.
double test_rand_double_range (double range_start, double range_end); ///< Return random double within range.
enum TrapFlags {
TRAP_INHERIT_STDIN = 1 << 0,
TRAP_SILENCE_STDOUT = 1 << 1,
TRAP_SILENCE_STDERR = 1 << 2,
TRAP_NO_FATAL_SYSLOG = 1 << 3,
};
bool trap_fork (uint64 usec_timeout, uint test_trap_flags);
bool trap_fork_silent ();
bool trap_timed_out ();
bool trap_passed ();
bool trap_aborted ();
String trap_stdout ();
String trap_stderr ();
} // Test
} // Rapicorn
#endif /* __RAPICORN_TESTUTILS_HH__ */
<commit_msg>RCORE: tests: provide TASSERT_AT to redirect assertion location information<commit_after>/* Rapicorn
* Copyright (C) 2008 Tim Janik
*
* 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.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#ifndef __RAPICORN_TESTUTILS_HH__
#define __RAPICORN_TESTUTILS_HH__
#include <rcore/rcore.hh>
// Test Macros
#define TTITLE(...) Rapicorn::Test::test_output (3, __VA_ARGS__)
#define TSTART(...) Rapicorn::Test::test_output (4, __VA_ARGS__)
#define TDONE() Rapicorn::Test::test_output (5, "%s", "")
#define TOUT(...) Rapicorn::Test::test_output (0, __VA_ARGS__)
#define TMSG(...) Rapicorn::Test::test_output (1, __VA_ARGS__)
#define TINFO(...) Rapicorn::Test::test_output (2, __VA_ARGS__)
#define TWARN(...) Rapicorn::Test::test_output (6, __VA_ARGS__)
#define TRUN(name, func) ({ TSTART (name); func(); TDONE(); })
#define TOK() do {} while (0) // printerr (".")
#define TCMP(a,cmp,b) TCMP_op (a,cmp,b,#a,#b,)
#define TCMPS(a,cmp,b) TCMP_op (a,cmp,b,#a,#b,Rapicorn::Test::_as_strptr)
#define TASSERT RAPICORN_ASSERT // TASSERT (condition)
#define TASSERT_AT(F,L,cond) do { if (RAPICORN_LIKELY (cond)) break; Rapicorn::debug_fassert (F, L, #cond); } while (0)
#define TASSERT_EMPTY(str) do { const String &__s = str; if (__s.empty()) break; \
Rapicorn::debug_fatal (__FILE__, __LINE__, "error: %s", __s.c_str()); } while (0)
#define TCMP_op(a,cmp,b,sa,sb,cast) do { if (a cmp b) break; \
String __tassert_va = Rapicorn::Test::stringify_arg (cast (a), #a); \
String __tassert_vb = Rapicorn::Test::stringify_arg (cast (b), #b); \
Rapicorn::debug_fatal (__FILE__, __LINE__, \
"assertion failed: %s %s %s: %s %s %s", \
sa, #cmp, sb, __tassert_va.c_str(), #cmp, __tassert_vb.c_str()); \
} while (0)
namespace Rapicorn {
void init_core_test (const String &app_ident, int *argcp, char **argv, const StringVector &args = StringVector());
namespace Test {
/**
* Class for profiling benchmark tests.
* UseCase: Benchmarking function implementations, e.g. to compare sorting implementations.
*/
class Timer {
const double m_deadline;
vector<double> m_samples;
double m_test_duration;
int64 m_n_runs;
int64 loops_needed () const;
void reset ();
void submit (double elapsed, int64 repetitions);
static double bench_time ();
public:
/// Create a Timer() instance, specifying an optional upper bound for test durations.
explicit Timer (double deadline_in_secs = 0);
virtual ~Timer ();
int64 n_runs () const { return m_n_runs; } ///< Number of benchmark runs executed
double test_elapsed () const { return m_test_duration; } ///< Seconds spent in benchmark()
double min_elapsed () const; ///< Minimum time benchmarked for a @a callee() call.
double max_elapsed () const; ///< Maximum time benchmarked for a @a callee() call.
template<typename Callee>
double benchmark (Callee callee);
};
/**
* @param callee A callable function or object.
* Method to benchmark the execution time of @a callee.
* @returns Minimum runtime in seconds,
*/
template<typename Callee> double
Timer::benchmark (Callee callee)
{
reset();
for (int64 runs = loops_needed(); runs; runs = loops_needed())
{
int64 n = runs;
const double start = bench_time();
while (RAPICORN_LIKELY (n--))
callee();
const double stop = bench_time();
submit (stop - start, runs);
}
return min_elapsed();
}
// === test maintenance ===
int run (void); ///< Run all registered tests.
bool verbose (void); ///< Indicates whether tests should run verbosely.
bool logging (void); ///< Indicates whether only logging tests should be run.
bool slow (void); ///< Indicates whether only slow tests should be run.
bool ui_test (void); ///< Indicates execution of ui-thread tests.
void test_output (int kind, const char *format, ...) RAPICORN_PRINTF (2, 3);
void add_internal (const String &testname,
void (*test_func) (void*),
void *data);
void add (const String &funcname,
void (*test_func) (void));
template<typename D>
void add (const String &testname,
void (*test_func) (D*),
D *data)
{
add_internal (testname, (void(*)(void*)) test_func, (void*) data);
}
/// == Stringify Args ==
inline String stringify_arg (const char *a, const char *str_a) { return a ? string_to_cquote (a) : "(__null)"; }
template<class V> inline String stringify_arg (const V *a, const char *str_a) { return string_printf ("%p", a); }
template<class A> inline String stringify_arg (const A &a, const char *str_a) { return str_a; }
template<> inline String stringify_arg<float> (const float &a, const char *str_a) { return string_printf ("%.8g", a); }
template<> inline String stringify_arg<double> (const double &a, const char *str_a) { return string_printf ("%.17g", a); }
template<> inline String stringify_arg<bool> (const bool &a, const char *str_a) { return string_printf ("%u", a); }
template<> inline String stringify_arg<int8> (const int8 &a, const char *str_a) { return string_printf ("%d", a); }
template<> inline String stringify_arg<int16> (const int16 &a, const char *str_a) { return string_printf ("%d", a); }
template<> inline String stringify_arg<int32> (const int32 &a, const char *str_a) { return string_printf ("%d", a); }
template<> inline String stringify_arg<int64> (const int64 &a, const char *str_a) { return string_printf ("%lld", a); }
template<> inline String stringify_arg<uint8> (const uint8 &a, const char *str_a) { return string_printf ("0x%02x", a); }
template<> inline String stringify_arg<uint16> (const uint16 &a, const char *str_a) { return string_printf ("0x%04x", a); }
template<> inline String stringify_arg<uint32> (const uint32 &a, const char *str_a) { return string_printf ("0x%08x", a); }
template<> inline String stringify_arg<uint64> (const uint64 &a, const char *str_a) { return string_printf ("0x%08Lx", a); }
template<> inline String stringify_arg<String> (const String &a, const char *str_a) { return string_to_cquote (a); }
inline const char* _as_strptr (const char *s) { return s; } // implementation detail
class RegisterTest {
static void add_test (char kind, const String &testname, void (*test_func) (void*), void *data);
public:
RegisterTest (const char k, const String &testname, void (*test_func) (void))
{ add_test (k, testname, (void(*)(void*)) test_func, NULL); }
RegisterTest (const char k, const String &testname, void (*test_func) (ptrdiff_t), ptrdiff_t data)
{ add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }
template<typename D>
RegisterTest (const char k, const String &testname, void (*test_func) (D*), D *data)
{ add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }
typedef void (*TestTrigger) (void (*runner) (void));
static void test_set_trigger (TestTrigger func);
};
/// Register a standard test function for execution as unit test.
#define REGISTER_TEST(name, ...) static const Rapicorn::Test::RegisterTest \
RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('t', name, __VA_ARGS__)
/// Register a slow test function for execution as during slow unit testing.
#define REGISTER_SLOWTEST(name, ...) static const Rapicorn::Test::RegisterTest \
RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('s', name, __VA_ARGS__)
/// Register a logging test function for output recording and verification.
#define REGISTER_LOGTEST(name, ...) static const Rapicorn::Test::RegisterTest \
RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('l', name, __VA_ARGS__)
// == Deterministic random numbers for tests ===
char rand_bit (void); ///< Return a random bit.
int32 rand_int (void); ///< Return random int.
int32 rand_int_range (int32 begin, int32 end); ///< Return random int within range.
double test_rand_double (void); ///< Return random double.
double test_rand_double_range (double range_start, double range_end); ///< Return random double within range.
enum TrapFlags {
TRAP_INHERIT_STDIN = 1 << 0,
TRAP_SILENCE_STDOUT = 1 << 1,
TRAP_SILENCE_STDERR = 1 << 2,
TRAP_NO_FATAL_SYSLOG = 1 << 3,
};
bool trap_fork (uint64 usec_timeout, uint test_trap_flags);
bool trap_fork_silent ();
bool trap_timed_out ();
bool trap_passed ();
bool trap_aborted ();
String trap_stdout ();
String trap_stderr ();
} // Test
} // Rapicorn
#endif /* __RAPICORN_TESTUTILS_HH__ */
<|endoftext|>
|
<commit_before>#include <trace_client/profile.h>
#if defined WIN32 || defined WIN64
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
namespace {
template<size_t N>
struct ThreadPool
{
enum { e_thread_count = N };
DWORD m_tids[e_thread_count];
HANDLE m_handles[e_thread_count];
ThreadPool () { memset(this, 0, sizeof(*this)); }
~ThreadPool () { Close(); }
void Create (DWORD (WINAPI * fn) (void *), void * ) {
for (size_t i = 0; i < e_thread_count; i++ )
m_handles[i] = CreateThread( NULL, 0, fn, 0, 0, &m_tids[i]);
}
void WaitForTerminate () { WaitForMultipleObjects(e_thread_count, m_handles, TRUE, INFINITE); }
void Close () {
for (size_t i = 0; i < e_thread_count; i++)
CloseHandle(m_handles[i]);
}
};
}
#elif defined __linux__
# include <pthread.h>
# include <cstring>
# include <cstdio>
# include <cstdlib>
# include <unistd.h>
# include <errno.h>
# include <ctype.h>
# ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
# endif
# define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
# define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int thread_num; /* Application-defined thread # */
char *argv_string; /* From command-line argument */
};
template<size_t N>
struct ThreadPool
{
enum { e_thread_count = N };
pthread_attr_t m_attr;
thread_info m_tinfo[e_thread_count];
ThreadPool () { memset(this, 0, sizeof(*this)); }
~ThreadPool () { Close(); }
void Create (void * (* fn) (void *), void * )
{
/* Initialize thread creation attributes */
int s = pthread_attr_init(&m_attr);
if (s != 0)
handle_error_en(s, "pthread_attr_init");
/*if (stack_size > 0)
{
s = pthread_attr_setstacksize(&m_attr, stack_size);
if (s != 0)
handle_error_en(s, "pthread_attr_setstacksize");
}*/
/* Create one thread for each command-line argument */
for (size_t t = 0; t < N; ++t)
{
m_tinfo[t].thread_num = t + 1;
//m_tinfo[t].argv_string = argv[optind + t];
pthread_attr_t m_attr;
pthread_attr_init(&m_attr);
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(t, &cpuset);
//CPU_SET(atoi(m_tinfo[t].argv_string), &cpuset);
pthread_attr_setaffinity_np(&m_attr, sizeof(cpuset), &cpuset);
/* The pthread_create() call stores the thread ID into corresponding element of m_tinfo[] */
s = pthread_create(&m_tinfo[t].thread_id, &m_attr, fn, &m_tinfo[t]);
if (s != 0)
handle_error_en(s, "pthread_create");
}
}
void WaitForTerminate ()
{
/* Destroy the thread attributes object, since it is no longer needed */
int s = pthread_attr_destroy(&m_attr);
if (s != 0)
handle_error_en(s, "pthread_attr_destroy");
/* Now join with each thread, and display its returned value */
for (size_t t = 0; t < N; t++)
{
void * res = 0;
s = pthread_join(m_tinfo[t].thread_id, &res);
if (s != 0)
handle_error_en(s, "pthread_join");
printf("Joined with thread %d; returned value was %s\n", m_tinfo[t].thread_num, (char *) res);
free(res); /* Free memory allocated by thread */
}
}
void Close ()
{
}
};
#endif
unsigned g_Quit = 0;
#if defined WIN32 || defined WIN64
DWORD WINAPI do_something ( LPVOID )
#elif defined __linux__
void * do_something ( void * )
#endif
{
static unsigned n = 0;
++n;
PROFILE_BGN("thread worker %u", n);
unsigned i = 0;
while (!g_Quit)
{
++i;
PROFILE_BGN("thread %u worker loop %u", n, i);
#if defined WIN32 || defined WIN64
Sleep(250);
#elif defined __linux__
usleep(250 * 1000);
#endif
PROFILE_END();
}
PROFILE_END();
return 0;
}
#if defined WIN32 || defined WIN64
//int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
int main ()
#elif defined __linux__
int main ()
#endif
{
PROFILE_APPNAME("Profiled_App");
PROFILE_CONNECT();
PROFILE_BGN("%s%u","main", 0);
ThreadPool<3> thr_pool;
thr_pool.Create(do_something, 0);
for (;;)
{
static size_t i = 0;
PROFILE_FRAME_BGN("frame %u", i);
++i;
#if defined WIN32 || defined WIN64
Sleep(1000);
#elif defined __linux__
usleep(1000 * 1000);
#endif
PROFILE_FRAME_END();
if (i == 6)
break;
}
g_Quit = 1;
thr_pool.WaitForTerminate();
PROFILE_END();
PROFILE_DISCONNECT();
}
<commit_msg>* minor fix<commit_after>#include <trace_client/profile.h>
#if defined WIN32 || defined WIN64
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
namespace {
template<size_t N>
struct ThreadPool
{
enum { e_thread_count = N };
DWORD m_tids[e_thread_count];
HANDLE m_handles[e_thread_count];
ThreadPool () { memset(this, 0, sizeof(*this)); }
~ThreadPool () { Close(); }
void Create (DWORD (WINAPI * fn) (void *), void * ) {
for (size_t i = 0; i < e_thread_count; i++ )
m_handles[i] = CreateThread( NULL, 0, fn, 0, 0, &m_tids[i]);
}
void WaitForTerminate () { WaitForMultipleObjects(e_thread_count, m_handles, TRUE, INFINITE); }
void Close () {
for (size_t i = 0; i < e_thread_count; i++)
CloseHandle(m_handles[i]);
}
};
}
#elif defined __linux__
# include <pthread.h>
# include <cstring>
# include <cstdio>
# include <cstdlib>
# include <unistd.h>
# include <errno.h>
# include <ctype.h>
# ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
# endif
# define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
# define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int thread_num; /* Application-defined thread # */
char *argv_string; /* From command-line argument */
};
template<size_t N>
struct ThreadPool
{
enum { e_thread_count = N };
pthread_attr_t m_attr;
thread_info m_tinfo[e_thread_count];
ThreadPool () { memset(this, 0, sizeof(*this)); }
~ThreadPool () { Close(); }
void Create (void * (* fn) (void *), void * )
{
/* Initialize thread creation attributes */
int s = pthread_attr_init(&m_attr);
if (s != 0)
handle_error_en(s, "pthread_attr_init");
/*if (stack_size > 0)
{
s = pthread_attr_setstacksize(&m_attr, stack_size);
if (s != 0)
handle_error_en(s, "pthread_attr_setstacksize");
}*/
/* Create one thread for each command-line argument */
for (size_t t = 0; t < N; ++t)
{
m_tinfo[t].thread_num = t + 1;
//m_tinfo[t].argv_string = argv[optind + t];
pthread_attr_t m_attr;
pthread_attr_init(&m_attr);
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(t, &cpuset);
//CPU_SET(atoi(m_tinfo[t].argv_string), &cpuset);
pthread_attr_setaffinity_np(&m_attr, sizeof(cpuset), &cpuset);
/* The pthread_create() call stores the thread ID into corresponding element of m_tinfo[] */
s = pthread_create(&m_tinfo[t].thread_id, &m_attr, fn, &m_tinfo[t]);
if (s != 0)
handle_error_en(s, "pthread_create");
}
}
void WaitForTerminate ()
{
/* Destroy the thread attributes object, since it is no longer needed */
int s = pthread_attr_destroy(&m_attr);
if (s != 0)
handle_error_en(s, "pthread_attr_destroy");
/* Now join with each thread, and display its returned value */
for (size_t t = 0; t < N; t++)
{
void * res = 0;
s = pthread_join(m_tinfo[t].thread_id, &res);
if (s != 0)
handle_error_en(s, "pthread_join");
printf("Joined with thread %d; returned value was %s\n", m_tinfo[t].thread_num, (char *) res);
free(res); /* Free memory allocated by thread */
}
}
void Close ()
{
}
};
#endif
unsigned g_Quit = 0;
#if defined WIN32 || defined WIN64
DWORD WINAPI do_something ( LPVOID )
#elif defined __linux__
void * do_something ( void * )
#endif
{
static unsigned n = 0;
int thr_n = n++;
PROFILE_BGN("thread worker %u", thr_n);
unsigned i = 0;
while (!g_Quit)
{
++i;
PROFILE_BGN("thread %u worker loop %u", thr_n, i);
#if defined WIN32 || defined WIN64
Sleep(250);
#elif defined __linux__
usleep(250 * 1000);
#endif
PROFILE_END();
}
PROFILE_END();
return 0;
}
#if defined WIN32 || defined WIN64
//int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
int main ()
#elif defined __linux__
int main ()
#endif
{
PROFILE_APPNAME("Profiled_App");
PROFILE_CONNECT();
PROFILE_BGN("%s%u","main", 0);
ThreadPool<3> thr_pool;
thr_pool.Create(do_something, 0);
for (;;)
{
static size_t i = 0;
PROFILE_FRAME_BGN("frame %u", i);
++i;
#if defined WIN32 || defined WIN64
Sleep(1000);
#elif defined __linux__
usleep(1000 * 1000);
#endif
PROFILE_FRAME_END();
if (i == 6)
break;
}
g_Quit = 1;
thr_pool.WaitForTerminate();
PROFILE_END();
PROFILE_DISCONNECT();
}
<|endoftext|>
|
<commit_before>/*-
* Copyright 2009 Colin Percival, 2011 ArtForz, 2011 pooler, 2013 Balthazar
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
#include <stdlib.h>
#include <stdint.h>
#include "scrypt.h"
#include "pbkdf2.h"
#include "util.h"
#include "net.h"
#define SCRYPT_BUFFER_SIZE (131072 + 63)
#if defined (OPTIMIZED_SALSA) && ( defined (__x86_64__) || defined (__i386__) || defined(__arm__) )
extern "C" void scrypt_core(unsigned int *X, unsigned int *V);
#else
// Generic scrypt_core implementation
static inline void xor_salsa8(unsigned int B[16], const unsigned int Bx[16])
{
unsigned int x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15;
int i;
x00 = (B[0] ^= Bx[0]);
x01 = (B[1] ^= Bx[1]);
x02 = (B[2] ^= Bx[2]);
x03 = (B[3] ^= Bx[3]);
x04 = (B[4] ^= Bx[4]);
x05 = (B[5] ^= Bx[5]);
x06 = (B[6] ^= Bx[6]);
x07 = (B[7] ^= Bx[7]);
x08 = (B[8] ^= Bx[8]);
x09 = (B[9] ^= Bx[9]);
x10 = (B[10] ^= Bx[10]);
x11 = (B[11] ^= Bx[11]);
x12 = (B[12] ^= Bx[12]);
x13 = (B[13] ^= Bx[13]);
x14 = (B[14] ^= Bx[14]);
x15 = (B[15] ^= Bx[15]);
for (i = 0; i < 8; i += 2) {
#define R(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
/* Operate on columns. */
x04 ^= R(x00+x12, 7); x09 ^= R(x05+x01, 7);
x14 ^= R(x10+x06, 7); x03 ^= R(x15+x11, 7);
x08 ^= R(x04+x00, 9); x13 ^= R(x09+x05, 9);
x02 ^= R(x14+x10, 9); x07 ^= R(x03+x15, 9);
x12 ^= R(x08+x04,13); x01 ^= R(x13+x09,13);
x06 ^= R(x02+x14,13); x11 ^= R(x07+x03,13);
x00 ^= R(x12+x08,18); x05 ^= R(x01+x13,18);
x10 ^= R(x06+x02,18); x15 ^= R(x11+x07,18);
/* Operate on rows. */
x01 ^= R(x00+x03, 7); x06 ^= R(x05+x04, 7);
x11 ^= R(x10+x09, 7); x12 ^= R(x15+x14, 7);
x02 ^= R(x01+x00, 9); x07 ^= R(x06+x05, 9);
x08 ^= R(x11+x10, 9); x13 ^= R(x12+x15, 9);
x03 ^= R(x02+x01,13); x04 ^= R(x07+x06,13);
x09 ^= R(x08+x11,13); x14 ^= R(x13+x12,13);
x00 ^= R(x03+x02,18); x05 ^= R(x04+x07,18);
x10 ^= R(x09+x08,18); x15 ^= R(x14+x13,18);
#undef R
}
B[0] += x00;
B[1] += x01;
B[2] += x02;
B[3] += x03;
B[4] += x04;
B[5] += x05;
B[6] += x06;
B[7] += x07;
B[8] += x08;
B[9] += x09;
B[10] += x10;
B[11] += x11;
B[12] += x12;
B[13] += x13;
B[14] += x14;
B[15] += x15;
}
static inline void scrypt_core(unsigned int *X, unsigned int *V)
{
unsigned int i, j, k;
for (i = 0; i < 1024; i++) {
memcpy(&V[i * 32], X, 128);
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
for (i = 0; i < 1024; i++) {
j = 32 * (X[16] & 1023);
for (k = 0; k < 32; k++)
X[k] ^= V[j + k];
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
}
#endif
/* cpu and memory intensive function to transform a 80 byte buffer into a 32 byte output
scratchpad size needs to be at least 63 + (128 * r * p) + (256 * r + 64) + (128 * r * N) bytes
r = 1, p = 1, N = 1024
*/
uint256 scrypt_nosalt(const void* input, size_t inputlen, void *scratchpad)
{
unsigned int *V;
unsigned int X[32];
uint256 result = 0;
V = (unsigned int *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
PBKDF2_SHA256((const uint8_t*)input, inputlen, (const uint8_t*)input, inputlen, 1, (uint8_t *)X, 128);
scrypt_core(X, V);
PBKDF2_SHA256((const uint8_t*)input, inputlen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32);
return result;
}
uint256 scrypt(const void* data, size_t datalen, const void* salt, size_t saltlen, void *scratchpad)
{
unsigned int *V;
unsigned int X[32];
uint256 result = 0;
V = (unsigned int *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
PBKDF2_SHA256((const uint8_t*)data, datalen, (const uint8_t*)salt, saltlen, 1, (uint8_t *)X, 128);
scrypt_core(X, V);
PBKDF2_SHA256((const uint8_t*)data, datalen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32);
return result;
}
uint256 scrypt_hash(const void* input, size_t inputlen)
{
unsigned char scratchpad[SCRYPT_BUFFER_SIZE];
return scrypt_nosalt(input, inputlen, scratchpad);
}
uint256 scrypt_salted_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen)
{
unsigned char scratchpad[SCRYPT_BUFFER_SIZE];
return scrypt(input, inputlen, salt, saltlen, scratchpad);
}
uint256 scrypt_salted_multiround_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen, const unsigned int nRounds)
{
uint256 resultHash = scrypt_salted_hash(input, inputlen, salt, saltlen);
uint256 transitionalHash = resultHash;
for(unsigned int i = 1; i < nRounds; i++)
{
resultHash = scrypt_salted_hash(input, inputlen, (const void*)&transitionalHash, 32);
transitionalHash = resultHash;
}
return resultHash;
}
uint256 scrypt_blockhash(const void* input)
{
unsigned char scratchpad[SCRYPT_BUFFER_SIZE];
return scrypt_nosalt(input, 80, scratchpad);
}
<commit_msg>Cleanup superfluous includes in scrypt.cpp<commit_after>/*-
* Copyright 2009 Colin Percival, 2011 ArtForz, 2011 pooler, 2013 Balthazar
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
#include <stdlib.h>
#include <stdint.h>
#include "scrypt.h"
#include "pbkdf2.h"
#define SCRYPT_BUFFER_SIZE (131072 + 63)
#if defined (OPTIMIZED_SALSA) && ( defined (__x86_64__) || defined (__i386__) || defined(__arm__) )
extern "C" void scrypt_core(unsigned int *X, unsigned int *V);
#else
// Generic scrypt_core implementation
static inline void xor_salsa8(unsigned int B[16], const unsigned int Bx[16])
{
unsigned int x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15;
int i;
x00 = (B[0] ^= Bx[0]);
x01 = (B[1] ^= Bx[1]);
x02 = (B[2] ^= Bx[2]);
x03 = (B[3] ^= Bx[3]);
x04 = (B[4] ^= Bx[4]);
x05 = (B[5] ^= Bx[5]);
x06 = (B[6] ^= Bx[6]);
x07 = (B[7] ^= Bx[7]);
x08 = (B[8] ^= Bx[8]);
x09 = (B[9] ^= Bx[9]);
x10 = (B[10] ^= Bx[10]);
x11 = (B[11] ^= Bx[11]);
x12 = (B[12] ^= Bx[12]);
x13 = (B[13] ^= Bx[13]);
x14 = (B[14] ^= Bx[14]);
x15 = (B[15] ^= Bx[15]);
for (i = 0; i < 8; i += 2) {
#define R(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
/* Operate on columns. */
x04 ^= R(x00+x12, 7); x09 ^= R(x05+x01, 7);
x14 ^= R(x10+x06, 7); x03 ^= R(x15+x11, 7);
x08 ^= R(x04+x00, 9); x13 ^= R(x09+x05, 9);
x02 ^= R(x14+x10, 9); x07 ^= R(x03+x15, 9);
x12 ^= R(x08+x04,13); x01 ^= R(x13+x09,13);
x06 ^= R(x02+x14,13); x11 ^= R(x07+x03,13);
x00 ^= R(x12+x08,18); x05 ^= R(x01+x13,18);
x10 ^= R(x06+x02,18); x15 ^= R(x11+x07,18);
/* Operate on rows. */
x01 ^= R(x00+x03, 7); x06 ^= R(x05+x04, 7);
x11 ^= R(x10+x09, 7); x12 ^= R(x15+x14, 7);
x02 ^= R(x01+x00, 9); x07 ^= R(x06+x05, 9);
x08 ^= R(x11+x10, 9); x13 ^= R(x12+x15, 9);
x03 ^= R(x02+x01,13); x04 ^= R(x07+x06,13);
x09 ^= R(x08+x11,13); x14 ^= R(x13+x12,13);
x00 ^= R(x03+x02,18); x05 ^= R(x04+x07,18);
x10 ^= R(x09+x08,18); x15 ^= R(x14+x13,18);
#undef R
}
B[0] += x00;
B[1] += x01;
B[2] += x02;
B[3] += x03;
B[4] += x04;
B[5] += x05;
B[6] += x06;
B[7] += x07;
B[8] += x08;
B[9] += x09;
B[10] += x10;
B[11] += x11;
B[12] += x12;
B[13] += x13;
B[14] += x14;
B[15] += x15;
}
static inline void scrypt_core(unsigned int *X, unsigned int *V)
{
unsigned int i, j, k;
for (i = 0; i < 1024; i++) {
memcpy(&V[i * 32], X, 128);
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
for (i = 0; i < 1024; i++) {
j = 32 * (X[16] & 1023);
for (k = 0; k < 32; k++)
X[k] ^= V[j + k];
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
}
#endif
/* cpu and memory intensive function to transform a 80 byte buffer into a 32 byte output
scratchpad size needs to be at least 63 + (128 * r * p) + (256 * r + 64) + (128 * r * N) bytes
r = 1, p = 1, N = 1024
*/
uint256 scrypt_nosalt(const void* input, size_t inputlen, void *scratchpad)
{
unsigned int *V;
unsigned int X[32];
uint256 result = 0;
V = (unsigned int *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
PBKDF2_SHA256((const uint8_t*)input, inputlen, (const uint8_t*)input, inputlen, 1, (uint8_t *)X, 128);
scrypt_core(X, V);
PBKDF2_SHA256((const uint8_t*)input, inputlen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32);
return result;
}
uint256 scrypt(const void* data, size_t datalen, const void* salt, size_t saltlen, void *scratchpad)
{
unsigned int *V;
unsigned int X[32];
uint256 result = 0;
V = (unsigned int *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
PBKDF2_SHA256((const uint8_t*)data, datalen, (const uint8_t*)salt, saltlen, 1, (uint8_t *)X, 128);
scrypt_core(X, V);
PBKDF2_SHA256((const uint8_t*)data, datalen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32);
return result;
}
uint256 scrypt_hash(const void* input, size_t inputlen)
{
unsigned char scratchpad[SCRYPT_BUFFER_SIZE];
return scrypt_nosalt(input, inputlen, scratchpad);
}
uint256 scrypt_salted_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen)
{
unsigned char scratchpad[SCRYPT_BUFFER_SIZE];
return scrypt(input, inputlen, salt, saltlen, scratchpad);
}
uint256 scrypt_salted_multiround_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen, const unsigned int nRounds)
{
uint256 resultHash = scrypt_salted_hash(input, inputlen, salt, saltlen);
uint256 transitionalHash = resultHash;
for(unsigned int i = 1; i < nRounds; i++)
{
resultHash = scrypt_salted_hash(input, inputlen, (const void*)&transitionalHash, 32);
transitionalHash = resultHash;
}
return resultHash;
}
uint256 scrypt_blockhash(const void* input)
{
unsigned char scratchpad[SCRYPT_BUFFER_SIZE];
return scrypt_nosalt(input, 80, scratchpad);
}
<|endoftext|>
|
<commit_before>#include "map/map2d.hpp"
#include "network/defaults.hpp"
#include "network/gameconnection.hpp"
#include "network/gameconnectionfactory.hpp"
#include <iostream>
using namespace Botventure;
int main(int argc, char* argv[]){
Map::Map2D map(10,10);
Poco::Net::TCPServer server(new Network::GameConnectionFactory<Network::GameConnection>(map), Network::Defaults::Port);
server.start();
std::string input;
while(std::cin >> input){
if(input.compare("exit\n")){
std::cout << "Shutting down server" << std::endl;
break;
}
}
}
<commit_msg>made exiting server work correctly<commit_after>#include "map/map2d.hpp"
#include "network/defaults.hpp"
#include "network/gameconnection.hpp"
#include "network/gameconnectionfactory.hpp"
#include <iostream>
using namespace Botventure;
int main(int argc, char* argv[]){
Map::Map2D map(10,10);
Poco::Net::TCPServer server(new Network::GameConnectionFactory<Network::GameConnection>(map), Network::Defaults::Port);
server.start();
std::string input;
while(std::cin >> input){
if(input.compare("exit") == 0){
std::cout << "Shutting down server" << std::endl;
break;
}
}
}
<|endoftext|>
|
<commit_before>#include "Body.h"
Body::Body()
{
m_center = Vec2<double>(0.0, 0.0);
m_max_radius = 0.0;
}
Body::Body(const Vec2<double> p_body...) : Body()
{
/*va_list args;
va_start(args, p_body);
do{
m_body.push_back(va_arg(args, Vec2<double>));
}while();*/
calculateCenter();
}
Body::~Body() {}
void Body::pushPoint(Vec2<double> point)
{
m_points.push_back(point);
calculateCenter();
}
std::vector< Vec2<double> >::iterator Body::start()
{
return m_points.begin();
}
std::vector< Vec2<double> >::iterator Body::end()
{
return m_points.end();
}
Vec2<double> Body::getCenter()
{
return m_center;
}
double Body::getMaxRadius()
{
return m_max_radius;
}
bool Body::inRangeWith(Body* that)
{
double delta_x = this->getCenter().x - that->getCenter().x;
double delta_y = this->getCenter().y - that->getCenter().y;
double distance = sqrt(pow(delta_x, 2) + pow(delta_y, 2));
double limit = this->getMaxRadius() + that->getMaxRadius();
std::cout << "Projectile Max Radius: " << this->getMaxRadius() << " -- ";
std::cout << "Ship Max Radius: " << that->getMaxRadius() << std::endl;
std::cout << "limit: (" << limit << ") -- ";
std::cout << "distance: (" << distance << ")" << std::endl;
if(distance < limit)
return true;
return false;
}
bool Body::collidesWith(Body* that)
{
/*
double angle = 0.0;
std::vector< Vec2<double> >::iterator it = that->start();
for(;it != that->end(); it++)
for(int i = 0; i < m_points.size(); i++)
{
if(i < m_points.size() - 1)
;//angle += atan((*it).y - m_points);
else
;//calculate angle between this point and the last
}
if(angle >= 360.0)
return true;
return false;
*/
return true;
}
void Body::calculateCenter()
{
m_center = Vec2<double>(0.0, 0.0);
m_max_radius = 0.0;
if(m_points.size() == 1)
m_center = m_points[0];
else if(m_points.size() > 1)
{
// calculate center
for(unsigned i = 0; i < m_points.size(); i++)
m_center += m_points[i];
m_center = m_center / m_points.size();
for(unsigned i = 0; i < m_points.size(); i++)
{
Vec2<double> temp = m_points[i];
temp = temp - m_center;
double magnitude = temp.magnitude();
if(magnitude > m_max_radius)
m_max_radius = magnitude;
}
}
}<commit_msg>Remove debugging code<commit_after>#include "Body.h"
Body::Body()
{
m_center = Vec2<double>(0.0, 0.0);
m_max_radius = 0.0;
}
Body::Body(const Vec2<double> p_body...) : Body()
{
/*va_list args;
va_start(args, p_body);
do{
m_body.push_back(va_arg(args, Vec2<double>));
}while();*/
calculateCenter();
}
Body::~Body() {}
void Body::pushPoint(Vec2<double> point)
{
m_points.push_back(point);
calculateCenter();
}
std::vector< Vec2<double> >::iterator Body::start()
{
return m_points.begin();
}
std::vector< Vec2<double> >::iterator Body::end()
{
return m_points.end();
}
Vec2<double> Body::getCenter()
{
return m_center;
}
double Body::getMaxRadius()
{
return m_max_radius;
}
bool Body::inRangeWith(Body* that)
{
double delta_x = this->getCenter().x - that->getCenter().x;
double delta_y = this->getCenter().y - that->getCenter().y;
double distance = sqrt(pow(delta_x, 2) + pow(delta_y, 2));
double limit = this->getMaxRadius() + that->getMaxRadius();
if(distance < limit)
return true;
return false;
}
bool Body::collidesWith(Body* that)
{
/*
double angle = 0.0;
std::vector< Vec2<double> >::iterator it = that->start();
for(;it != that->end(); it++)
for(int i = 0; i < m_points.size(); i++)
{
if(i < m_points.size() - 1)
;//angle += atan((*it).y - m_points);
else
;//calculate angle between this point and the last
}
if(angle >= 360.0)
return true;
return false;
*/
return true;
}
void Body::calculateCenter()
{
m_center = Vec2<double>(0.0, 0.0);
m_max_radius = 0.0;
if(m_points.size() == 1)
m_center = m_points[0];
else if(m_points.size() > 1)
{
// calculate center
for(unsigned i = 0; i < m_points.size(); i++)
m_center += m_points[i];
m_center = m_center / m_points.size();
for(unsigned i = 0; i < m_points.size(); i++)
{
Vec2<double> temp = m_points[i];
temp = temp - m_center;
double magnitude = temp.magnitude();
if(magnitude > m_max_radius)
m_max_radius = magnitude;
}
}
}<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.5 2000/02/06 07:47:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.4 2000/02/04 01:49:27 aruna1
* TreeWalker and NodeIterator changes
*
* Revision 1.3 2000/01/22 01:38:29 andyh
* Remove compiler warnings in DOM impl classes
*
* Revision 1.2 2000/01/05 01:16:08 andyh
* DOM Level 2 core, namespace support added.
*
* Revision 1.1.1.1 1999/11/09 01:09:02 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:44:20 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#ifndef DOM_NodeList_HEADER_GUARD_
#define DOM_NodeList_HEADER_GUARD_
#include <util/XML4CDefs.hpp>
#include <dom/DOM_Node.hpp>
class NodeListImpl;
/**
* The <code>NodeList</code> interface provides the abstraction of an ordered
* collection of nodes. NodeLists are created by DOM_Document::getElementsByTagName(),
* DOM_Node::getChildNodes(),
*
* <p>The items in the <code>NodeList</code> are accessible via an integral
* index, starting from 0.
*
* NodeLists are "live", in that any changes to the document tree are immediately
* reflected in any NodeLists that may have been created for that tree.
*/
class CDOM_EXPORT DOM_NodeList {
private:
NodeListImpl *fImpl;
public:
/** @name Constructors and assignment operator */
//@{
/**
* Default constructor for DOM_NodeList. The resulting object does not
* refer to an actual NodeList; it will compare == to 0, and is similar
* to a null object reference variable in Java. It may subsequently be
* assigned to refer to an actual NodeList.
*
*/
DOM_NodeList();
/**
* Copy constructor.
*
* @param other The object to be copied.
*/
DOM_NodeList(const DOM_NodeList &other);
/**
* Assignment operator.
*
* @param other The object to be copied.
*/
DOM_NodeList & operator = (const DOM_NodeList &other);
/**
* Assignment operator. This overloaded variant is provided for
* the sole purpose of setting a DOM_Node reference variable to
* zero. Nulling out a reference variable in this way will decrement
* the reference count on the underlying Node object that the variable
* formerly referenced. This effect is normally obtained when reference
* variable goes out of scope, but zeroing them can be useful for
* global instances, or for local instances that will remain in scope
* for an extended time, when the storage belonging to the underlying
* node needs to be reclaimed.
*
* @param val. Only a value of 0, or null, is allowed.
*/
DOM_NodeList & operator = (const DOM_NullPtr *val);
//@}
/** @name Destructor. */
//@{
/**
* Destructor for DOM_NodeList. The object being destroyed is the reference
* object, not the underlying NodeList node itself.
*
* <p>Like most other DOM types in this implementation, memory management
* of Node Lists is automatic. Instances of DOM_NodeList function
* as references to an underlying heap based implementation object,
* and should never be explicitly new-ed or deleted in application code, but
* should appear only as local variables or function parameters.
*/
~DOM_NodeList();
//@}
/** @name Comparison operators. */
//@{
/**
* Equality operator. Note that compares whether two node list
* variables refer to the same underlying node list. It does
* not compare the contents of the node lists themselves.
*/
bool operator == (const DOM_NodeList &other) const;
/**
* Equality operator. Note that compares whether two node list
* variables refer to the same underlying node list. It does
* not compare the contents of the node lists themselves.
*/
bool operator != (const DOM_NodeList &other) const;
bool operator == (const DOM_NullPtr *nullPtr) const;
bool operator != (const DOM_NullPtr *nullPtr) const;
//@}
/** @name Get functions. */
//@{
/**
* Returns the <code>index</code>th item in the collection.
*
* If <code>index</code> is greater than or equal to the number of nodes in
* the list, this returns <code>null</code>.
*
* @param index Index into the collection.
* @return The node at the <code>index</code>th position in the
* <code>NodeList</code>, or <code>null</code> if that is not a valid
* index.
*/
DOM_Node item(unsigned int index) const;
/**
* Returns the number of nodes in the list.
*
* The range of valid child node indices is 0 to <code>length-1</code> inclusive.
*/
unsigned int getLength() const;
//@}
protected:
DOM_NodeList(NodeListImpl *impl);
friend class DOM_Document;
friend class DOM_Element;
friend class DOM_Node;
};
#endif
<commit_msg>Added docs for equality operators<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.6 2000/02/10 20:38:46 abagchi
* Added docs for equality operators
*
* Revision 1.5 2000/02/06 07:47:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.4 2000/02/04 01:49:27 aruna1
* TreeWalker and NodeIterator changes
*
* Revision 1.3 2000/01/22 01:38:29 andyh
* Remove compiler warnings in DOM impl classes
*
* Revision 1.2 2000/01/05 01:16:08 andyh
* DOM Level 2 core, namespace support added.
*
* Revision 1.1.1.1 1999/11/09 01:09:02 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:44:20 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#ifndef DOM_NodeList_HEADER_GUARD_
#define DOM_NodeList_HEADER_GUARD_
#include <util/XML4CDefs.hpp>
#include <dom/DOM_Node.hpp>
class NodeListImpl;
/**
* The <code>NodeList</code> interface provides the abstraction of an ordered
* collection of nodes. NodeLists are created by DOM_Document::getElementsByTagName(),
* DOM_Node::getChildNodes(),
*
* <p>The items in the <code>NodeList</code> are accessible via an integral
* index, starting from 0.
*
* NodeLists are "live", in that any changes to the document tree are immediately
* reflected in any NodeLists that may have been created for that tree.
*/
class CDOM_EXPORT DOM_NodeList {
private:
NodeListImpl *fImpl;
public:
/** @name Constructors and assignment operator */
//@{
/**
* Default constructor for DOM_NodeList. The resulting object does not
* refer to an actual NodeList; it will compare == to 0, and is similar
* to a null object reference variable in Java. It may subsequently be
* assigned to refer to an actual NodeList.
*
*/
DOM_NodeList();
/**
* Copy constructor.
*
* @param other The object to be copied.
*/
DOM_NodeList(const DOM_NodeList &other);
/**
* Assignment operator.
*
* @param other The object to be copied.
*/
DOM_NodeList & operator = (const DOM_NodeList &other);
/**
* Assignment operator. This overloaded variant is provided for
* the sole purpose of setting a DOM_Node reference variable to
* zero. Nulling out a reference variable in this way will decrement
* the reference count on the underlying Node object that the variable
* formerly referenced. This effect is normally obtained when reference
* variable goes out of scope, but zeroing them can be useful for
* global instances, or for local instances that will remain in scope
* for an extended time, when the storage belonging to the underlying
* node needs to be reclaimed.
*
* @param val. Only a value of 0, or null, is allowed.
*/
DOM_NodeList & operator = (const DOM_NullPtr *val);
//@}
/** @name Destructor. */
//@{
/**
* Destructor for DOM_NodeList. The object being destroyed is the reference
* object, not the underlying NodeList node itself.
*
* <p>Like most other DOM types in this implementation, memory management
* of Node Lists is automatic. Instances of DOM_NodeList function
* as references to an underlying heap based implementation object,
* and should never be explicitly new-ed or deleted in application code, but
* should appear only as local variables or function parameters.
*/
~DOM_NodeList();
//@}
/** @name Comparison operators. */
//@{
/**
* Equality operator.
* Compares whether two node list
* variables refer to the same underlying node list. It does
* not compare the contents of the node lists themselves.
*
* @param other The value to be compared
* @return Returns true if node list refers to same underlying node list
*/
bool operator == (const DOM_NodeList &other) const;
/**
* Use this comparison operator to test whether a Node List reference
* is null.
*
* @param nullPtr The value to be compared, which must be 0 or null.
* @return Returns true if node list reference is null
*/
bool operator == (const DOM_NullPtr *nullPtr) const;
/**
* Inequality operator.
* Compares whether two node list
* variables refer to the same underlying node list. It does
* not compare the contents of the node lists themselves.
*
* @param other The value to be compared
* @return Returns true if node list refers to a different underlying node list
*/
bool operator != (const DOM_NodeList &other) const;
/**
* Use this comparison operator to test whether a Node List reference
* is not null.
*
* @param nullPtr The value to be compared, which must be 0 or null.
* @return Returns true if node list reference is not null
*/
bool operator != (const DOM_NullPtr *nullPtr) const;
//@}
/** @name Get functions. */
//@{
/**
* Returns the <code>index</code>th item in the collection.
*
* If <code>index</code> is greater than or equal to the number of nodes in
* the list, this returns <code>null</code>.
*
* @param index Index into the collection.
* @return The node at the <code>index</code>th position in the
* <code>NodeList</code>, or <code>null</code> if that is not a valid
* index.
*/
DOM_Node item(unsigned int index) const;
/**
* Returns the number of nodes in the list.
*
* The range of valid child node indices is 0 to <code>length-1</code> inclusive.
*/
unsigned int getLength() const;
//@}
protected:
DOM_NodeList(NodeListImpl *impl);
friend class DOM_Document;
friend class DOM_Element;
friend class DOM_Node;
};
#endif
<|endoftext|>
|
<commit_before>#include "encode_jpeg.h"
#include "common_png.h"
namespace vision {
namespace image {
#if !PNG_FOUND
torch::Tensor encode_png(const torch::Tensor& data, int64_t compression_level) {
TORCH_CHECK(
false, "encode_png: torchvision not compiled with libpng support");
}
#else
namespace {
struct torch_mem_encode {
char* buffer;
size_t size;
};
struct torch_png_error_mgr {
const char* pngLastErrorMsg; /* error messages */
jmp_buf setjmp_buffer; /* for return to caller */
};
using torch_png_error_mgr_ptr = torch_png_error_mgr*;
void torch_png_error(png_structp png_ptr, png_const_charp error_msg) {
/* png_ptr->err really points to a torch_png_error_mgr struct, so coerce
* pointer */
auto error_ptr = (torch_png_error_mgr_ptr)png_get_error_ptr(png_ptr);
/* Replace the error message on the error structure */
error_ptr->pngLastErrorMsg = error_msg;
/* Return control to the setjmp point */
longjmp(error_ptr->setjmp_buffer, 1);
}
void torch_png_write_data(
png_structp png_ptr,
png_bytep data,
png_size_t length) {
struct torch_mem_encode* p =
(struct torch_mem_encode*)png_get_io_ptr(png_ptr);
size_t nsize = p->size + length;
/* allocate or grow buffer */
if (p->buffer)
p->buffer = (char*)realloc(p->buffer, nsize);
else
p->buffer = (char*)malloc(nsize);
if (!p->buffer)
png_error(png_ptr, "Write Error");
/* copy new bytes to end of buffer */
memcpy(p->buffer + p->size, data, length);
p->size += length;
}
} // namespace
torch::Tensor encode_png(const torch::Tensor& data, int64_t compression_level) {
// Define compression structures and error handling
png_structp png_write;
png_infop info_ptr;
struct torch_png_error_mgr err_ptr;
// Define output buffer
struct torch_mem_encode buf_info;
buf_info.buffer = NULL;
buf_info.size = 0;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(err_ptr.setjmp_buffer)) {
/* If we get here, the PNG code has signaled an error.
* We need to clean up the PNG object and the buffer.
*/
if (info_ptr != NULL) {
png_destroy_info_struct(png_write, &info_ptr);
}
if (png_write != NULL) {
png_destroy_write_struct(&png_write, NULL);
}
if (buf_info.buffer != NULL) {
free(buf_info.buffer);
}
TORCH_CHECK(false, err_ptr.pngLastErrorMsg);
}
// Check that the compression level is between 0 and 9
TORCH_CHECK(
compression_level >= 0 && compression_level <= 9,
"Compression level should be between 0 and 9");
// Check that the input tensor is on CPU
TORCH_CHECK(data.device() == torch::kCPU, "Input tensor should be on CPU");
// Check that the input tensor dtype is uint8
TORCH_CHECK(data.dtype() == torch::kU8, "Input tensor dtype should be uint8");
// Check that the input tensor is 3-dimensional
TORCH_CHECK(data.dim() == 3, "Input data should be a 3-dimensional tensor");
// Get image info
int channels = data.size(0);
int height = data.size(1);
int width = data.size(2);
auto input = data.permute({1, 2, 0}).contiguous();
TORCH_CHECK(
channels == 1 || channels == 3,
"The number of channels should be 1 or 3, got: ",
channels);
// Initialize PNG structures
png_write = png_create_write_struct(
PNG_LIBPNG_VER_STRING, &err_ptr, torch_png_error, NULL);
info_ptr = png_create_info_struct(png_write);
// Define custom buffer output
png_set_write_fn(png_write, &buf_info, torch_png_write_data, NULL);
// Set output image information
auto color_type = PNG_COLOR_TYPE_GRAY ? channels == 1 : PNG_COLOR_TYPE_RGB;
png_set_IHDR(
png_write,
info_ptr,
width,
height,
8,
color_type,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
// Set image compression level
png_set_compression_level(png_write, compression_level);
// Write file header
png_write_info(png_write, info_ptr);
auto stride = width * channels;
auto ptr = input.data_ptr<uint8_t>();
// Encode PNG file
for (int y = 0; y < height; ++y) {
png_write_row(png_write, ptr);
ptr += stride;
}
// Write EOF
png_write_end(png_write, info_ptr);
// Destroy structures
png_destroy_write_struct(&png_write, &info_ptr);
torch::TensorOptions options = torch::TensorOptions{torch::kU8};
auto outTensor = torch::empty({(long)buf_info.size}, options);
// Copy memory from png buffer, since torch cannot get ownership of it via
// `from_blob`
auto outPtr = outTensor.data_ptr<uint8_t>();
std::memcpy(outPtr, buf_info.buffer, sizeof(uint8_t) * outTensor.numel());
free(buf_info.buffer);
return outTensor;
}
#endif
} // namespace image
} // namespace vision
<commit_msg>Fix ternary operator to decide to store an image in Grayscale or RGB (#3553)<commit_after>#include "encode_jpeg.h"
#include "common_png.h"
namespace vision {
namespace image {
#if !PNG_FOUND
torch::Tensor encode_png(const torch::Tensor& data, int64_t compression_level) {
TORCH_CHECK(
false, "encode_png: torchvision not compiled with libpng support");
}
#else
namespace {
struct torch_mem_encode {
char* buffer;
size_t size;
};
struct torch_png_error_mgr {
const char* pngLastErrorMsg; /* error messages */
jmp_buf setjmp_buffer; /* for return to caller */
};
using torch_png_error_mgr_ptr = torch_png_error_mgr*;
void torch_png_error(png_structp png_ptr, png_const_charp error_msg) {
/* png_ptr->err really points to a torch_png_error_mgr struct, so coerce
* pointer */
auto error_ptr = (torch_png_error_mgr_ptr)png_get_error_ptr(png_ptr);
/* Replace the error message on the error structure */
error_ptr->pngLastErrorMsg = error_msg;
/* Return control to the setjmp point */
longjmp(error_ptr->setjmp_buffer, 1);
}
void torch_png_write_data(
png_structp png_ptr,
png_bytep data,
png_size_t length) {
struct torch_mem_encode* p =
(struct torch_mem_encode*)png_get_io_ptr(png_ptr);
size_t nsize = p->size + length;
/* allocate or grow buffer */
if (p->buffer)
p->buffer = (char*)realloc(p->buffer, nsize);
else
p->buffer = (char*)malloc(nsize);
if (!p->buffer)
png_error(png_ptr, "Write Error");
/* copy new bytes to end of buffer */
memcpy(p->buffer + p->size, data, length);
p->size += length;
}
} // namespace
torch::Tensor encode_png(const torch::Tensor& data, int64_t compression_level) {
// Define compression structures and error handling
png_structp png_write;
png_infop info_ptr;
struct torch_png_error_mgr err_ptr;
// Define output buffer
struct torch_mem_encode buf_info;
buf_info.buffer = NULL;
buf_info.size = 0;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(err_ptr.setjmp_buffer)) {
/* If we get here, the PNG code has signaled an error.
* We need to clean up the PNG object and the buffer.
*/
if (info_ptr != NULL) {
png_destroy_info_struct(png_write, &info_ptr);
}
if (png_write != NULL) {
png_destroy_write_struct(&png_write, NULL);
}
if (buf_info.buffer != NULL) {
free(buf_info.buffer);
}
TORCH_CHECK(false, err_ptr.pngLastErrorMsg);
}
// Check that the compression level is between 0 and 9
TORCH_CHECK(
compression_level >= 0 && compression_level <= 9,
"Compression level should be between 0 and 9");
// Check that the input tensor is on CPU
TORCH_CHECK(data.device() == torch::kCPU, "Input tensor should be on CPU");
// Check that the input tensor dtype is uint8
TORCH_CHECK(data.dtype() == torch::kU8, "Input tensor dtype should be uint8");
// Check that the input tensor is 3-dimensional
TORCH_CHECK(data.dim() == 3, "Input data should be a 3-dimensional tensor");
// Get image info
int channels = data.size(0);
int height = data.size(1);
int width = data.size(2);
auto input = data.permute({1, 2, 0}).contiguous();
TORCH_CHECK(
channels == 1 || channels == 3,
"The number of channels should be 1 or 3, got: ",
channels);
// Initialize PNG structures
png_write = png_create_write_struct(
PNG_LIBPNG_VER_STRING, &err_ptr, torch_png_error, NULL);
info_ptr = png_create_info_struct(png_write);
// Define custom buffer output
png_set_write_fn(png_write, &buf_info, torch_png_write_data, NULL);
// Set output image information
auto color_type = channels == 1 ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_RGB;
png_set_IHDR(
png_write,
info_ptr,
width,
height,
8,
color_type,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
// Set image compression level
png_set_compression_level(png_write, compression_level);
// Write file header
png_write_info(png_write, info_ptr);
auto stride = width * channels;
auto ptr = input.data_ptr<uint8_t>();
// Encode PNG file
for (int y = 0; y < height; ++y) {
png_write_row(png_write, ptr);
ptr += stride;
}
// Write EOF
png_write_end(png_write, info_ptr);
// Destroy structures
png_destroy_write_struct(&png_write, &info_ptr);
torch::TensorOptions options = torch::TensorOptions{torch::kU8};
auto outTensor = torch::empty({(long)buf_info.size}, options);
// Copy memory from png buffer, since torch cannot get ownership of it via
// `from_blob`
auto outPtr = outTensor.data_ptr<uint8_t>();
std::memcpy(outPtr, buf_info.buffer, sizeof(uint8_t) * outTensor.numel());
free(buf_info.buffer);
return outTensor;
}
#endif
} // namespace image
} // namespace vision
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <map>
#include <qi/atomic.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/make_shared.hpp>
#include <qitype/signal.hpp>
#include <qitype/genericvalue.hpp>
#include <qitype/genericobject.hpp>
#include "object_p.hpp"
#include "signal_p.hpp"
qiLogCategory("qitype.signal");
namespace qi {
SignalSubscriber::SignalSubscriber(qi::ObjectPtr target, unsigned int method)
: weakLock(0), threadingModel(MetaCallType_Direct), target(new qi::ObjectWeakPtr(target)), method(method), enabled(true)
{ // The slot has its own threading model: be synchronous
}
SignalSubscriber::SignalSubscriber(GenericFunction func, MetaCallType model, detail::WeakLock* lock)
: handler(func), weakLock(lock), threadingModel(model), target(0), method(0), enabled(true)
{
}
SignalSubscriber::~SignalSubscriber()
{
delete target;
delete weakLock;
}
SignalSubscriber::SignalSubscriber(const SignalSubscriber& b)
: weakLock(0), target(0)
{
*this = b;
}
void SignalSubscriber::operator=(const SignalSubscriber& b)
{
source = b.source;
linkId = b.linkId;
handler = b.handler;
weakLock = b.weakLock?b.weakLock->clone():0;
threadingModel = b.threadingModel;
target = b.target?new ObjectWeakPtr(*b.target):0;
method = b.method;
enabled = b.enabled;
}
static qi::Atomic<int> linkUid = 1;
void SignalBase::setCallType(MetaCallType callType)
{
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
_p->defaultCallType = callType;
}
void SignalBase::operator()(
qi::AutoGenericValuePtr p1,
qi::AutoGenericValuePtr p2,
qi::AutoGenericValuePtr p3,
qi::AutoGenericValuePtr p4,
qi::AutoGenericValuePtr p5,
qi::AutoGenericValuePtr p6,
qi::AutoGenericValuePtr p7,
qi::AutoGenericValuePtr p8)
{
qi::AutoGenericValuePtr* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8};
std::vector<qi::GenericValuePtr> params;
for (unsigned i = 0; i < 8; ++i)
if (vals[i]->value)
params.push_back(*vals[i]);
// Signature construction
std::string signature = "(";
for (unsigned i=0; i< params.size(); ++i)
signature += params[i].signature();
signature += ")";
if (signature != _p->signature)
{
qiLogError() << "Dropping emit: signature mismatch: " << signature <<" " << _p->signature;
return;
}
trigger(params, _p->defaultCallType);
}
void SignalBase::trigger(const GenericFunctionParameters& params, MetaCallType callType)
{
MetaCallType mct = callType;
if (!_p)
return;
if (mct == qi::MetaCallType_Auto)
mct = _p->defaultCallType;
SignalSubscriberMap copy;
{
boost::recursive_mutex::scoped_lock sl(_p->mutex);
copy = _p->subscriberMap;
}
SignalSubscriberMap::iterator i;
for (i = copy.begin(); i != copy.end(); ++i)
{
qiLogDebug() << (void*)this << " Invoking signal subscriber";
SignalSubscriberPtr s = i->second; // hold s alive
s->call(params, mct);
}
qiLogDebug() << (void*)this << " done invoking signal subscribers";
}
class FunctorCall
{
public:
FunctorCall(GenericFunctionParameters* params, SignalSubscriberPtr* sub)
: params(params)
, sub(sub)
{
}
FunctorCall(const FunctorCall& b)
{
*this = b;
}
void operator=(const FunctorCall& b)
{
params = b.params;
sub = b.sub;
}
void operator() ()
{
try
{
{
SignalSubscriberPtr s;
boost::mutex::scoped_lock sl((*sub)->mutex);
// verify-enabled-then-register-active op must be locked
if (!(*sub)->enabled)
{
s = *sub; // delay destruction until after we leave the scoped_lock
delete sub;
params->destroy();
delete params;
return;
}
(*sub)->addActive(false);
} // end mutex-protected scope
(*sub)->handler(*params);
}
catch(const std::exception& e)
{
qiLogVerbose() << "Exception caught from signal subscriber: " << e.what();
}
catch (...) {
qiLogVerbose() << "Unknown exception caught from signal subscriber";
}
(*sub)->removeActive(true);
params->destroy();
delete params;
if ((*sub)->weakLock)
(*sub)->weakLock->unlock();
delete sub;
}
public:
GenericFunctionParameters* params;
SignalSubscriberPtr* sub;
};
void SignalSubscriber::call(const GenericFunctionParameters& args, MetaCallType callType)
{
// this is held alive by caller
if (handler)
{
// Try to acquire weakLock, for both the sync and async cases
if (weakLock)
{
bool locked = weakLock->tryLock();
if (!locked)
{
source->disconnect(linkId);
return;
}
}
bool async = true;
if (threadingModel != MetaCallType_Auto)
async = (threadingModel == MetaCallType_Queued);
else if (callType != MetaCallType_Auto)
async = (callType == MetaCallType_Queued);
qiLogDebug() << "subscriber call async=" << async <<" ct " << callType <<" tm " << threadingModel;
if (async)
{
GenericFunctionParameters* copy = new GenericFunctionParameters(args.copy());
// We will check enabled when we will be scheduled in the target
// thread, and we hold this SignalSubscriber alive, so no need to
// explicitly track the asynccall
getDefaultThreadPoolEventLoop()->post(FunctorCall(copy, new SignalSubscriberPtr(shared_from_this())));
}
else
{
// verify-enabled-then-register-active op must be locked
{
boost::mutex::scoped_lock sl(mutex);
if (!enabled)
return;
addActive(false);
}
//do not throw
handler(args);
if (weakLock)
weakLock->unlock();
removeActive(true);
}
}
else if (target)
{
ObjectPtr lockedTarget = target->lock();
if (!lockedTarget)
{
source->disconnect(linkId);
}
else // no need to keep anything locked, whatever happens this is not used
lockedTarget->metaPost(method, args);
}
}
//check if we are called from the same thread that triggered us.
//in that case, do not wait.
void SignalSubscriber::waitForInactive()
{
boost::thread::id tid = boost::this_thread::get_id();
while (true)
{
{
boost::mutex::scoped_lock sl(mutex);
if (activeThreads.empty())
return;
// There cannot be two activeThreads entry for the same tid
// because activeThreads is not set at the post() stage
if (activeThreads.size() == 1
&& *activeThreads.begin() == tid)
{ // One active callback in this thread, means above us in call stack
// So we cannot wait for it
return;
}
}
os::msleep(1); // FIXME too long use a condition
}
}
void SignalSubscriber::addActive(bool acquireLock, boost::thread::id id)
{
if (acquireLock)
{
boost::mutex::scoped_lock sl(mutex);
activeThreads.push_back(id);
}
else
activeThreads.push_back(id);
}
void SignalSubscriber::removeActive(bool acquireLock, boost::thread::id id)
{
boost::mutex::scoped_lock sl(mutex, boost::defer_lock_t());
if (acquireLock)
sl.lock();
for (unsigned i=0; i<activeThreads.size(); ++i)
{
if (activeThreads[i] == id)
{ // fast remove by swapping with last and then pop_back
activeThreads[i] = activeThreads[activeThreads.size() - 1];
activeThreads.pop_back();
}
}
}
SignalSubscriber& SignalBase::connect(GenericFunction callback, MetaCallType model)
{
return connect(SignalSubscriber(callback, model));
}
SignalSubscriber& SignalBase::connect(qi::ObjectPtr o, unsigned int slot)
{
return connect(SignalSubscriber(o, slot));
}
SignalSubscriber& SignalBase::connect(const SignalSubscriber& src)
{
qiLogDebug() << (void*)this << " connecting new subscriber";
static SignalSubscriber invalid;
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
// Check arity. Does not require to acquire weakLock.
int sigArity = Signature(signature()).begin().children().size();
int subArity = -1;
if (src.handler)
{
if (src.handler.functionType() == dynamicFunctionType())
goto proceed; // no arity checking is possible
subArity = src.handler.argumentsType().size();
}
else if (src.target)
{
ObjectPtr locked = src.target->lock();
if (!locked)
{
qiLogVerbose() << "connecting a dead slot (weak ptr out)";
return invalid;
}
const MetaMethod* ms = locked->metaObject().method(src.method);
if (!ms)
{
qiLogWarning() << "Method " << src.method <<" not found, proceeding anyway";
goto proceed;
}
else
subArity = Signature(ms->parametersSignature()).size();
}
if (sigArity != subArity)
{
qiLogWarning() << "Subscriber has incorrect arity (expected "
<< sigArity << " , got " << subArity <<")";
return invalid;
}
proceed:
boost::recursive_mutex::scoped_lock sl(_p->mutex);
Link res = ++linkUid;
SignalSubscriberPtr s = boost::make_shared<SignalSubscriber>(src);
s->linkId = res;
s->source = this;
bool first = _p->subscriberMap.empty();
_p->subscriberMap[res] = s;
if (first && _p->onSubscribers)
_p->onSubscribers(true);
return *s.get();
}
bool SignalBase::disconnectAll() {
if (_p)
return _p->reset();
return false;
}
SignalBase::SignalBase(const std::string& sig, OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
_p->signature = sig;
}
SignalBase::SignalBase(OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
}
SignalBase::SignalBase(const SignalBase& b)
{
(*this) = b;
}
SignalBase& SignalBase::operator=(const SignalBase& b)
{
if (!b._p)
{
const_cast<SignalBase&>(b)._p = boost::make_shared<SignalBasePrivate>();
}
_p = b._p;
return *this;
}
std::string SignalBase::signature() const
{
return _p ? _p->signature : "";
}
void SignalBase::_setSignature(const std::string& s)
{
_p->signature = s;
}
bool SignalBasePrivate::disconnect(const SignalBase::Link& l)
{
SignalSubscriberPtr s;
// Acquire signal mutex
boost::recursive_mutex::scoped_lock sigLock(mutex);
SignalSubscriberMap::iterator it = subscriberMap.find(l);
if (it == subscriberMap.end())
return false;
s = it->second;
// Remove from map (but SignalSubscriber object still good)
subscriberMap.erase(it);
// Acquire subscriber mutex before releasing mutex
boost::mutex::scoped_lock subLock(s->mutex);
// Release signal mutex
sigLock.release()->unlock();
// Ensure no call on subscriber occurrs once this function returns
s->enabled = false;
if (subscriberMap.empty() && onSubscribers)
onSubscribers(false);
if ( s->activeThreads.empty()
|| (s->activeThreads.size() == 1
&& *s->activeThreads.begin() == boost::this_thread::get_id()))
{ // One active callback in this thread, means above us in call stack
// So we cannot trash s right now
return true;
}
// More than one active callback, or one in a state that prevent us
// from knowing in which thread it will run
subLock.release()->unlock();
s->waitForInactive();
return true;
}
bool SignalBase::disconnect(const Link &link) {
if (!_p)
return false;
else
return _p->disconnect(link);
}
SignalBase::~SignalBase()
{
if (!_p)
return;
_p->onSubscribers = OnSubscribers();
boost::shared_ptr<SignalBasePrivate> p(_p);
_p.reset();
SignalSubscriberMap::iterator i;
std::vector<Link> links;
for (i = p->subscriberMap.begin(); i!= p->subscriberMap.end(); ++i)
{
links.push_back(i->first);
}
for (unsigned i=0; i<links.size(); ++i)
p->disconnect(links[i]);
}
std::vector<SignalSubscriber> SignalBase::subscribers()
{
std::vector<SignalSubscriber> res;
if (!_p)
return res;
boost::recursive_mutex::scoped_lock sl(_p->mutex);
SignalSubscriberMap::iterator i;
for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i)
res.push_back(*i->second);
return res;
}
bool SignalBasePrivate::reset() {
bool ret = true;
boost::recursive_mutex::scoped_lock sl(mutex);
SignalSubscriberMap::iterator it = subscriberMap.begin();
while (it != subscriberMap.end()) {
bool b = disconnect(it->first);
if (!b)
ret = false;
it = subscriberMap.begin();
}
return ret;
}
QITYPE_API const SignalBase::Link SignalBase::invalidLink = ((unsigned int)-1);
}
<commit_msg>Signal: add a missing important debug message.<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <map>
#include <qi/atomic.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/make_shared.hpp>
#include <qitype/signal.hpp>
#include <qitype/genericvalue.hpp>
#include <qitype/genericobject.hpp>
#include "object_p.hpp"
#include "signal_p.hpp"
qiLogCategory("qitype.signal");
namespace qi {
SignalSubscriber::SignalSubscriber(qi::ObjectPtr target, unsigned int method)
: weakLock(0), threadingModel(MetaCallType_Direct), target(new qi::ObjectWeakPtr(target)), method(method), enabled(true)
{ // The slot has its own threading model: be synchronous
}
SignalSubscriber::SignalSubscriber(GenericFunction func, MetaCallType model, detail::WeakLock* lock)
: handler(func), weakLock(lock), threadingModel(model), target(0), method(0), enabled(true)
{
}
SignalSubscriber::~SignalSubscriber()
{
delete target;
delete weakLock;
}
SignalSubscriber::SignalSubscriber(const SignalSubscriber& b)
: weakLock(0), target(0)
{
*this = b;
}
void SignalSubscriber::operator=(const SignalSubscriber& b)
{
source = b.source;
linkId = b.linkId;
handler = b.handler;
weakLock = b.weakLock?b.weakLock->clone():0;
threadingModel = b.threadingModel;
target = b.target?new ObjectWeakPtr(*b.target):0;
method = b.method;
enabled = b.enabled;
}
static qi::Atomic<int> linkUid = 1;
void SignalBase::setCallType(MetaCallType callType)
{
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
_p->defaultCallType = callType;
}
void SignalBase::operator()(
qi::AutoGenericValuePtr p1,
qi::AutoGenericValuePtr p2,
qi::AutoGenericValuePtr p3,
qi::AutoGenericValuePtr p4,
qi::AutoGenericValuePtr p5,
qi::AutoGenericValuePtr p6,
qi::AutoGenericValuePtr p7,
qi::AutoGenericValuePtr p8)
{
qi::AutoGenericValuePtr* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8};
std::vector<qi::GenericValuePtr> params;
for (unsigned i = 0; i < 8; ++i)
if (vals[i]->value)
params.push_back(*vals[i]);
// Signature construction
std::string signature = "(";
for (unsigned i=0; i< params.size(); ++i)
signature += params[i].signature();
signature += ")";
if (signature != _p->signature)
{
qiLogError() << "Dropping emit: signature mismatch: " << signature <<" " << _p->signature;
return;
}
trigger(params, _p->defaultCallType);
}
void SignalBase::trigger(const GenericFunctionParameters& params, MetaCallType callType)
{
MetaCallType mct = callType;
if (!_p)
return;
if (mct == qi::MetaCallType_Auto)
mct = _p->defaultCallType;
SignalSubscriberMap copy;
{
boost::recursive_mutex::scoped_lock sl(_p->mutex);
copy = _p->subscriberMap;
}
qiLogDebug() << (void*)this << " Invoking signal subscribers: " << copy.size();
SignalSubscriberMap::iterator i;
for (i = copy.begin(); i != copy.end(); ++i)
{
qiLogDebug() << (void*)this << " Invoking signal subscriber";
SignalSubscriberPtr s = i->second; // hold s alive
s->call(params, mct);
}
qiLogDebug() << (void*)this << " done invoking signal subscribers";
}
class FunctorCall
{
public:
FunctorCall(GenericFunctionParameters* params, SignalSubscriberPtr* sub)
: params(params)
, sub(sub)
{
}
FunctorCall(const FunctorCall& b)
{
*this = b;
}
void operator=(const FunctorCall& b)
{
params = b.params;
sub = b.sub;
}
void operator() ()
{
try
{
{
SignalSubscriberPtr s;
boost::mutex::scoped_lock sl((*sub)->mutex);
// verify-enabled-then-register-active op must be locked
if (!(*sub)->enabled)
{
s = *sub; // delay destruction until after we leave the scoped_lock
delete sub;
params->destroy();
delete params;
return;
}
(*sub)->addActive(false);
} // end mutex-protected scope
(*sub)->handler(*params);
}
catch(const std::exception& e)
{
qiLogVerbose() << "Exception caught from signal subscriber: " << e.what();
}
catch (...) {
qiLogVerbose() << "Unknown exception caught from signal subscriber";
}
(*sub)->removeActive(true);
params->destroy();
delete params;
if ((*sub)->weakLock)
(*sub)->weakLock->unlock();
delete sub;
}
public:
GenericFunctionParameters* params;
SignalSubscriberPtr* sub;
};
void SignalSubscriber::call(const GenericFunctionParameters& args, MetaCallType callType)
{
// this is held alive by caller
if (handler)
{
// Try to acquire weakLock, for both the sync and async cases
if (weakLock)
{
bool locked = weakLock->tryLock();
if (!locked)
{
source->disconnect(linkId);
return;
}
}
bool async = true;
if (threadingModel != MetaCallType_Auto)
async = (threadingModel == MetaCallType_Queued);
else if (callType != MetaCallType_Auto)
async = (callType == MetaCallType_Queued);
qiLogDebug() << "subscriber call async=" << async <<" ct " << callType <<" tm " << threadingModel;
if (async)
{
GenericFunctionParameters* copy = new GenericFunctionParameters(args.copy());
// We will check enabled when we will be scheduled in the target
// thread, and we hold this SignalSubscriber alive, so no need to
// explicitly track the asynccall
getDefaultThreadPoolEventLoop()->post(FunctorCall(copy, new SignalSubscriberPtr(shared_from_this())));
}
else
{
// verify-enabled-then-register-active op must be locked
{
boost::mutex::scoped_lock sl(mutex);
if (!enabled)
return;
addActive(false);
}
//do not throw
handler(args);
if (weakLock)
weakLock->unlock();
removeActive(true);
}
}
else if (target)
{
ObjectPtr lockedTarget = target->lock();
if (!lockedTarget)
{
source->disconnect(linkId);
}
else // no need to keep anything locked, whatever happens this is not used
lockedTarget->metaPost(method, args);
}
}
//check if we are called from the same thread that triggered us.
//in that case, do not wait.
void SignalSubscriber::waitForInactive()
{
boost::thread::id tid = boost::this_thread::get_id();
while (true)
{
{
boost::mutex::scoped_lock sl(mutex);
if (activeThreads.empty())
return;
// There cannot be two activeThreads entry for the same tid
// because activeThreads is not set at the post() stage
if (activeThreads.size() == 1
&& *activeThreads.begin() == tid)
{ // One active callback in this thread, means above us in call stack
// So we cannot wait for it
return;
}
}
os::msleep(1); // FIXME too long use a condition
}
}
void SignalSubscriber::addActive(bool acquireLock, boost::thread::id id)
{
if (acquireLock)
{
boost::mutex::scoped_lock sl(mutex);
activeThreads.push_back(id);
}
else
activeThreads.push_back(id);
}
void SignalSubscriber::removeActive(bool acquireLock, boost::thread::id id)
{
boost::mutex::scoped_lock sl(mutex, boost::defer_lock_t());
if (acquireLock)
sl.lock();
for (unsigned i=0; i<activeThreads.size(); ++i)
{
if (activeThreads[i] == id)
{ // fast remove by swapping with last and then pop_back
activeThreads[i] = activeThreads[activeThreads.size() - 1];
activeThreads.pop_back();
}
}
}
SignalSubscriber& SignalBase::connect(GenericFunction callback, MetaCallType model)
{
return connect(SignalSubscriber(callback, model));
}
SignalSubscriber& SignalBase::connect(qi::ObjectPtr o, unsigned int slot)
{
return connect(SignalSubscriber(o, slot));
}
SignalSubscriber& SignalBase::connect(const SignalSubscriber& src)
{
qiLogDebug() << (void*)this << " connecting new subscriber";
static SignalSubscriber invalid;
if (!_p)
{
_p = boost::make_shared<SignalBasePrivate>();
}
// Check arity. Does not require to acquire weakLock.
int sigArity = Signature(signature()).begin().children().size();
int subArity = -1;
if (src.handler)
{
if (src.handler.functionType() == dynamicFunctionType())
goto proceed; // no arity checking is possible
subArity = src.handler.argumentsType().size();
}
else if (src.target)
{
ObjectPtr locked = src.target->lock();
if (!locked)
{
qiLogVerbose() << "connecting a dead slot (weak ptr out)";
return invalid;
}
const MetaMethod* ms = locked->metaObject().method(src.method);
if (!ms)
{
qiLogWarning() << "Method " << src.method <<" not found, proceeding anyway";
goto proceed;
}
else
subArity = Signature(ms->parametersSignature()).size();
}
if (sigArity != subArity)
{
qiLogWarning() << "Subscriber has incorrect arity (expected "
<< sigArity << " , got " << subArity <<")";
return invalid;
}
proceed:
boost::recursive_mutex::scoped_lock sl(_p->mutex);
Link res = ++linkUid;
SignalSubscriberPtr s = boost::make_shared<SignalSubscriber>(src);
s->linkId = res;
s->source = this;
bool first = _p->subscriberMap.empty();
_p->subscriberMap[res] = s;
if (first && _p->onSubscribers)
_p->onSubscribers(true);
return *s.get();
}
bool SignalBase::disconnectAll() {
if (_p)
return _p->reset();
return false;
}
SignalBase::SignalBase(const std::string& sig, OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
_p->signature = sig;
}
SignalBase::SignalBase(OnSubscribers onSubscribers)
: _p(new SignalBasePrivate)
{
_p->onSubscribers = onSubscribers;
}
SignalBase::SignalBase(const SignalBase& b)
{
(*this) = b;
}
SignalBase& SignalBase::operator=(const SignalBase& b)
{
if (!b._p)
{
const_cast<SignalBase&>(b)._p = boost::make_shared<SignalBasePrivate>();
}
_p = b._p;
return *this;
}
std::string SignalBase::signature() const
{
return _p ? _p->signature : "";
}
void SignalBase::_setSignature(const std::string& s)
{
_p->signature = s;
}
bool SignalBasePrivate::disconnect(const SignalBase::Link& l)
{
SignalSubscriberPtr s;
// Acquire signal mutex
boost::recursive_mutex::scoped_lock sigLock(mutex);
SignalSubscriberMap::iterator it = subscriberMap.find(l);
if (it == subscriberMap.end())
return false;
s = it->second;
// Remove from map (but SignalSubscriber object still good)
subscriberMap.erase(it);
// Acquire subscriber mutex before releasing mutex
boost::mutex::scoped_lock subLock(s->mutex);
// Release signal mutex
sigLock.release()->unlock();
// Ensure no call on subscriber occurrs once this function returns
s->enabled = false;
if (subscriberMap.empty() && onSubscribers)
onSubscribers(false);
if ( s->activeThreads.empty()
|| (s->activeThreads.size() == 1
&& *s->activeThreads.begin() == boost::this_thread::get_id()))
{ // One active callback in this thread, means above us in call stack
// So we cannot trash s right now
return true;
}
// More than one active callback, or one in a state that prevent us
// from knowing in which thread it will run
subLock.release()->unlock();
s->waitForInactive();
return true;
}
bool SignalBase::disconnect(const Link &link) {
if (!_p)
return false;
else
return _p->disconnect(link);
}
SignalBase::~SignalBase()
{
if (!_p)
return;
_p->onSubscribers = OnSubscribers();
boost::shared_ptr<SignalBasePrivate> p(_p);
_p.reset();
SignalSubscriberMap::iterator i;
std::vector<Link> links;
for (i = p->subscriberMap.begin(); i!= p->subscriberMap.end(); ++i)
{
links.push_back(i->first);
}
for (unsigned i=0; i<links.size(); ++i)
p->disconnect(links[i]);
}
std::vector<SignalSubscriber> SignalBase::subscribers()
{
std::vector<SignalSubscriber> res;
if (!_p)
return res;
boost::recursive_mutex::scoped_lock sl(_p->mutex);
SignalSubscriberMap::iterator i;
for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i)
res.push_back(*i->second);
return res;
}
bool SignalBasePrivate::reset() {
bool ret = true;
boost::recursive_mutex::scoped_lock sl(mutex);
SignalSubscriberMap::iterator it = subscriberMap.begin();
while (it != subscriberMap.end()) {
bool b = disconnect(it->first);
if (!b)
ret = false;
it = subscriberMap.begin();
}
return ret;
}
QITYPE_API const SignalBase::Link SignalBase::invalidLink = ((unsigned int)-1);
}
<|endoftext|>
|
<commit_before>//=============================================================================
//File Name: OurRobot.cpp
//Description: Main robot class in which all robot sensors and devices are
// declared
//Author: FRC Team 3512, Spartatroniks
//=============================================================================
#include "OurRobot.hpp"
#include "DriverStationDisplay.hpp"
float ScaleZ( Joystick& stick) {
return floorf( 500.f * ( 1.f - stick.GetZ() ) / 2.f ) / 500.f; // CONSTANT^-1 is step value (now 1/500)
}
DriverStationDisplay* OurRobot::driverStation = DriverStationDisplay::getInstance();
OurRobot::OurRobot() :
mainCompressor( 1 , 6 ),
mainDrive( 3 , 4 , 1 , 2 ),
driveStick1( 1 ),
driveStick2( 2 ),
turretStick( 3 ),
lift( 7 ),
shooterMotorLeft( 7 ),
shooterMotorRight( 6 ),
rotateMotor( 5 ),
pinLock( 3 ),
hammer( 2 ),
shifter( 1 ),
shooterEncoder( 6 ),
turretKinect( "10.35.12.6" , 5614 ), // on-board computer's IP address and port
pidControl()
{
mainDrive.SetExpiration( 1.f ); // let motors run for 1 second uncontrolled before shutting them down
pidControl.Initialize( &shooterEncoder , &shooterMotorLeft , &shooterMotorRight );
shooterIsManual = false;
isShooting = false;
isAutoAiming = false;
}
void OurRobot::DS_PrintOut() {
/* ===== Print to Driver Station LCD =====
* Packs the following variables:
*
* unsigned int: shooter RPM
* bool: shooter RPM control is manual
* unsigned int: turret ScaleZ
* bool: turret is locked on
* unsigned char: Kinect is online
* bool: isShooting
* bool: isAutoAiming
* unsigned int: distance to target
*/
driverStation->clear();
*driverStation << static_cast<unsigned int>(60.f / ( 16.f * shooterEncoder.GetPeriod() ) * 100000.f);
*driverStation << shooterIsManual;
// floats don't work so " * 10000" saves some precision in a UINT
*driverStation << static_cast<unsigned int>(ScaleZ(turretStick) * 100000.f);
*driverStation << static_cast<bool>( fabs( turretKinect.getPixelOffset() ) < TurretKinect::pxlDeadband
&& turretKinect.getOnlineStatus() == sf::Socket::Done );
*driverStation << static_cast<unsigned char>( turretKinect.getOnlineStatus() );
*driverStation << isShooting;
*driverStation << isAutoAiming;
*driverStation << turretKinect.getDistance();
driverStation->sendToDS();
/* ====================================== */
}
START_ROBOT_CLASS(OurRobot);
<commit_msg>Added information to DriverStationDisplay packet for driver and changed order of data in packet<commit_after>//=============================================================================
//File Name: OurRobot.cpp
//Description: Main robot class in which all robot sensors and devices are
// declared
//Author: FRC Team 3512, Spartatroniks
//=============================================================================
#include "OurRobot.hpp"
#include "DriverStationDisplay.hpp"
float ScaleZ( Joystick& stick) {
return floorf( 500.f * ( 1.f - stick.GetZ() ) / 2.f ) / 500.f; // CONSTANT^-1 is step value (now 1/500)
}
DriverStationDisplay* OurRobot::driverStation = DriverStationDisplay::getInstance();
OurRobot::OurRobot() :
mainCompressor( 1 , 6 ),
mainDrive( 3 , 4 , 1 , 2 ),
driveStick1( 1 ),
driveStick2( 2 ),
turretStick( 3 ),
lift( 7 ),
shooterMotorLeft( 7 ),
shooterMotorRight( 6 ),
rotateMotor( 5 ),
pinLock( 3 ),
hammer( 2 ),
shifter( 1 ),
shooterEncoder( 6 ),
turretKinect( "10.35.12.6" , 5614 ), // on-board computer's IP address and port
pidControl()
{
mainDrive.SetExpiration( 1.f ); // let motors run for 1 second uncontrolled before shutting them down
pidControl.Initialize( &shooterEncoder , &shooterMotorLeft , &shooterMotorRight );
shooterIsManual = false;
isShooting = false;
isAutoAiming = false;
}
void OurRobot::DS_PrintOut() {
/* ===== Print to Driver Station LCD =====
* Packs the following variables:
*
* unsigned int: drive1 ScaleZ
* unsigned int: drive2 ScaleZ
* unsigned int: turret ScaleZ
* bool: drivetrain is in high gear
* bool: is hammer mechanism deployed
* unsigned int: shooter RPM
* bool: shooter RPM control is manual
* bool: isShooting
* bool: isAutoAiming
* bool: turret is locked on
* unsigned char: Kinect is online
* unsigned int: distance to target
*/
// floats don't work so " * 100000" saves some precision in a UINT
driverStation->clear();
*driverStation << static_cast<unsigned int>(ScaleZ(driveStick1) * 100000.f);
*driverStation << static_cast<unsigned int>(ScaleZ(driveStick2) * 100000.f);
*driverStation << static_cast<unsigned int>(ScaleZ(turretStick) * 100000.f);
*driverStation << shifter.Get();
*driverStation << hammer.Get();
*driverStation << static_cast<unsigned int>(60.f / ( 16.f * shooterEncoder.GetPeriod() ) * 100000.f);
*driverStation << shooterIsManual;
*driverStation << isShooting;
*driverStation << isAutoAiming;
*driverStation << static_cast<bool>( fabs( turretKinect.getPixelOffset() ) < TurretKinect::pxlDeadband
&& turretKinect.getOnlineStatus() == sf::Socket::Done );
*driverStation << static_cast<unsigned char>( turretKinect.getOnlineStatus() );
*driverStation << turretKinect.getDistance();
driverStation->sendToDS();
/* ====================================== */
}
START_ROBOT_CLASS(OurRobot);
<|endoftext|>
|
<commit_before>#include <iostream> // std::cin, std::cout
#include <sstream>
#include <tuple>
#include <string>
#include <regex>
#include <cmath>
#include "PEG.hpp"
using namespace std;
using namespace peg;
// regex parser builder
auto operator ""_r(const char* s, std::size_t) {
string str = s;
regex re(str[0] != '^' ? "^" + str : str);
return [re](auto input, auto end) -> decltype(resolve(string(), input)) {
regex_iterator<string::const_iterator> re_it(input, end, re), re_end;
if (re_it != re_end) {
auto str = re_it->str();
std::advance(input, re_it->str().size());
return resolve(str, input);
} else {
return reject();
}
};
}
// declare parser combinators
using Input = std::string::const_iterator;
Rule<Input, string> NUMBER = R"([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)"_r,
ADD = R"(\+)"_r,
SUB = R"(\-)"_r,
MUL = R"(\*)"_r,
DIV = R"(\/)"_r,
L_PAREN = R"(\()"_r,
R_PAREN = R"(\))"_r;
Rule<Input, optional<string>> SPACE_OPT = opt(R"([ \r\t\n]+)"_r);
Rule<Input, double> Number, Primary, Unary, Term, Expr;
// initialize parser & define rules
void init_parser() {
Number = NUMBER >> [](auto x) {
return stod(x);
};
Primary = Number
| (L_PAREN, SPACE_OPT, Expr, SPACE_OPT, R_PAREN) >> [](auto x) {
return get<2>(x);
}
;
Unary = (ADD | SUB, SPACE_OPT, Unary) >> [](auto t) {
return get<0>(t) == "+" ? get<2>(t) : - get<2>(t);
}
| Primary
;
Term = (Unary, SPACE_OPT, MUL | DIV, SPACE_OPT, Term) >> [](auto t) {
return get<2>(t) == "*" ?
get<0>(t) * get<4>(t) : get<0>(t) / get<4>(t);
}
| Unary
;
Expr = (Term, SPACE_OPT, ADD | SUB, SPACE_OPT, Expr) >> [](auto t) {
return get<2>(t) == "+" ?
get<0>(t) + get<4>(t) : get<0>(t) - get<4>(t);
}
| Term
;
}
int main () {
// initialize parser
init_parser();
// expression
string expr = "12 + (-5 - - - (5 + 12 / 3) / 3)";
// parse
auto parse_result = Expr(expr.cbegin(), expr.cend());
double ans = parse_result ? parse_result->first : NAN;;
// print result
cout << ans << endl;
return 0;
}
<commit_msg>Update test.cpp<commit_after>#include <iostream> // std::cin, std::cout
#include <sstream>
#include <tuple>
#include <string>
#include <regex>
#include <cmath>
#include "PEG.hpp"
using namespace std;
using namespace peg;
// regex parser builder
auto operator ""_r(const char* s, std::size_t) {
string str = s;
regex re(str[0] != '^' ? "^" + str : str);
return [re](auto input, auto end) -> decltype(resolve(string(), input)) {
regex_iterator<string::const_iterator> re_it(input, end, re), re_end;
if (re_it != re_end) {
auto str = re_it->str();
std::advance(input, re_it->str().size());
return resolve(str, input);
} else {
return reject();
}
};
}
// declare parser combinators
using Input = std::string::const_iterator;
Rule<Input, string> NUMBER = R"([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)"_r,
ADD = R"(\+)"_r,
SUB = R"(\-)"_r,
MUL = R"(\*)"_r,
DIV = R"(\/)"_r,
L_PAREN = R"(\()"_r,
R_PAREN = R"(\))"_r;
Rule<Input, optional<string>> SPACE_OPT = opt(R"([ \r\t\n]+)"_r);
Rule<Input, double> Number, Primary, Unary, Term, Expr;
// initialize parser & define rules
void init_parser() {
Number = NUMBER >> [](auto x) {
return stod(x);
};
Primary = Number
| (L_PAREN, SPACE_OPT, Expr, SPACE_OPT, R_PAREN) >> [](auto x) {
return get<2>(x);
}
;
Unary = (ADD | SUB, SPACE_OPT, Unary) >> [](auto t) {
return get<0>(t) == "+" ? get<2>(t) : - get<2>(t);
}
| Primary
;
Term = (Unary, SPACE_OPT, MUL | DIV, SPACE_OPT, Term) >> [](auto t) {
return get<2>(t) == "*" ?
get<0>(t) * get<4>(t) : get<0>(t) / get<4>(t);
}
| Unary
;
Expr = (Term, SPACE_OPT, ADD | SUB, SPACE_OPT, Expr) >> [](auto t) {
return get<2>(t) == "+" ?
get<0>(t) + get<4>(t) : get<0>(t) - get<4>(t);
}
| Term
;
}
int main () {
// initialize parser
init_parser();
// expression
string expr = "12 + (-5 - - - (5 + 12 / 3) / 3)";
// parse
auto parse_result = Expr(expr.cbegin(), expr.cend());
double ans = parse_result ? parse_result->first : NAN;
// print result
cout << ans << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include <cfenv>
#include <cfloat>
#include <inttypes.h>
#define HAS_FEATURE_AVX 1
#define HAS_FEATURE_AVX512 0
#define ADDRESS_SIZE_BITS 64
#include "remill/Arch/X86/Runtime/State.h"
#include "mcsema/Arch/X86/Runtime/Registers.h"
extern "C" {
// enum : size_t {
// kStackSize = 1UL << 20UL
// };
// struct alignas(16) Stack {
// uint8_t bytes[kStackSize]; // 1 MiB.
// };
// __thread State __mcsema_reg_state;
// __thread Stack __mcsema_stack;
// State *__mcsema_get_reg_state(void) {
// return &__mcsema_reg_state;
// }
// uint8_t *__mcsema_get_stack(void) {
// return &(__mcsema_stack.bytes[kStackSize - 16UL]);
// }
Memory *__remill_sync_hyper_call(
State &state, Memory *mem, SyncHyperCall::Name call) {
auto eax = state.gpr.rax.dword;
auto ebx = state.gpr.rbx.dword;
auto ecx = state.gpr.rcx.dword;
auto edx = state.gpr.rdx.dword;
switch (call) {
case SyncHyperCall::kX86CPUID:
state.gpr.rax.aword = 0;
state.gpr.rbx.aword = 0;
state.gpr.rcx.aword = 0;
state.gpr.rdx.aword = 0;
asm volatile(
"cpuid"
: "=a"(state.gpr.rax.dword),
"=b"(state.gpr.rbx.dword),
"=c"(state.gpr.rcx.dword),
"=d"(state.gpr.rdx.dword)
: "a"(eax),
"b"(ebx),
"c"(ecx),
"d"(edx)
);
break;
case SyncHyperCall::kX86ReadTSC:
state.gpr.rax.aword = 0;
state.gpr.rdx.aword = 0;
asm volatile(
"rdtsc"
: "=a"(state.gpr.rax.dword),
"=d"(state.gpr.rdx.dword)
);
break;
case SyncHyperCall::kX86ReadTSCP:
state.gpr.rax.aword = 0;
state.gpr.rcx.aword = 0;
state.gpr.rdx.aword = 0;
asm volatile(
"rdtscp"
: "=a"(state.gpr.rax.dword),
"=c"(state.gpr.rcx.dword),
"=d"(state.gpr.rdx.dword)
);
break;
default:
__builtin_unreachable();
}
return mem;
}
Memory *__mcsema_reg_tracer(State &state, addr_t, Memory *memory) {
const char *format = nullptr;
if (sizeof(void *) == 8) {
fprintf(
stderr,
"RIP=%" PRIx64 ",RAX=%" PRIx64 ",RBX=%" PRIx64
",RCX=%" PRIx64 ",RDX=%" PRIx64 ",RSI=%" PRIx64
",RDI=%" PRIx64 ",RBP=%" PRIx64 ",RSP=%" PRIx64
",R8=%" PRIx64 ",R9=%" PRIx64 ",R10=%" PRIx64
",R11=%" PRIx64 ",R12=%" PRIx64 ",R13=%" PRIx64
",R14=%" PRIx64 ",R15=%" PRIx64 "\n",
state.RIP, state.RAX, state.RBX, state.RCX, state.RDX, state.RSI,
state.RDI, state.RBP, state.RSP, state.R8, state.R9, state.R10,
state.R11, state.R12, state.R13, state.R14, state.R15);
} else {
fprintf(
stderr,
"EIP=%" PRIx32 ",EAX=%" PRIx32 ",EBX=%" PRIx32
",ECX=%" PRIx32 ",EDX=%" PRIx32 ",ESI=%" PRIx32
",EDI=%" PRIx32 ",ESP=%" PRIx32 ",EBP=%" PRIx32 "\n",
state.EIP, state.EAX, state.EBX, state.ECX, state.EDX, state.ESI,
state.EDI, state.EBP, state.ESP);
}
return memory;
}
// Memory read intrinsics.
uint8_t __remill_read_memory_8(Memory *, addr_t addr) {
return *reinterpret_cast<uint8_t *>(addr);
}
uint16_t __remill_read_memory_16(Memory *, addr_t addr) {
return *reinterpret_cast<uint16_t *>(addr);
}
uint32_t __remill_read_memory_32(Memory *, addr_t addr) {
return *reinterpret_cast<uint32_t *>(addr);
}
uint64_t __remill_read_memory_64(Memory *, addr_t addr) {
return *reinterpret_cast<uint64_t *>(addr);
}
// Memory write intrinsics.
Memory *__remill_write_memory_8(
Memory * memory, addr_t addr, uint8_t val) {
*reinterpret_cast<uint8_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_16(
Memory * memory, addr_t addr, uint16_t val) {
*reinterpret_cast<uint16_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_32(
Memory * memory, addr_t addr, uint32_t val) {
*reinterpret_cast<uint32_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_64(
Memory * memory, addr_t addr, uint64_t val) {
*reinterpret_cast<uint64_t *>(addr) = val;
return memory;
}
float32_t __remill_read_memory_f32(
Memory *, addr_t addr, float32_t val) {
return *reinterpret_cast<float32_t *>(addr);
}
float64_t __remill_read_memory_f64(
Memory *, addr_t addr, float64_t val) {
return *reinterpret_cast<float64_t *>(addr);
}
float64_t __remill_read_memory_f80(Memory *, addr_t addr) {
return static_cast<float64_t>(*reinterpret_cast<long double *>(addr));
}
Memory *__remill_write_memory_f32(
Memory * memory, addr_t addr, float32_t val) {
*reinterpret_cast<float32_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_f64(
Memory * memory, addr_t addr, float64_t val) {
*reinterpret_cast<float64_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_f80(
Memory * memory, addr_t addr, float64_t val) {
*reinterpret_cast<long double *>(addr) = static_cast<long double>(val);
return memory;
}
// Memory barriers types, see: http://g.oswego.edu/dl/jmm/cookbook.html
Memory *__remill_barrier_load_load(Memory * memory) {
return memory;
}
Memory *__remill_barrier_load_store(Memory * memory) {
return memory;
}
Memory *__remill_barrier_store_load(Memory * memory) {
return memory;
}
Memory *__remill_barrier_store_store(Memory * memory) {
return memory;
}
// Atomic operations. The address/size are hints, but the granularity of the
// access can be bigger. These have implicit StoreLoad semantics.
Memory *__remill_atomic_begin(Memory * memory) {
return memory;
}
Memory *__remill_atomic_end(Memory * memory) {
return memory;
}
int __remill_fpu_exception_test_and_clear(int read_mask, int clear_mask) {
auto except = std::fetestexcept(read_mask);
std::feclearexcept(clear_mask);
return except;
}
} // extern C
<commit_msg>Atomic intrinsic support (#360)<commit_after>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include <cfenv>
#include <cfloat>
#include <inttypes.h>
#define HAS_FEATURE_AVX 1
#define HAS_FEATURE_AVX512 0
#define ADDRESS_SIZE_BITS 64
#include "remill/Arch/X86/Runtime/State.h"
#include "mcsema/Arch/X86/Runtime/Registers.h"
extern "C" {
// enum : size_t {
// kStackSize = 1UL << 20UL
// };
// struct alignas(16) Stack {
// uint8_t bytes[kStackSize]; // 1 MiB.
// };
// __thread State __mcsema_reg_state;
// __thread Stack __mcsema_stack;
// State *__mcsema_get_reg_state(void) {
// return &__mcsema_reg_state;
// }
// uint8_t *__mcsema_get_stack(void) {
// return &(__mcsema_stack.bytes[kStackSize - 16UL]);
// }
Memory *__remill_sync_hyper_call(
State &state, Memory *mem, SyncHyperCall::Name call) {
auto eax = state.gpr.rax.dword;
auto ebx = state.gpr.rbx.dword;
auto ecx = state.gpr.rcx.dword;
auto edx = state.gpr.rdx.dword;
switch (call) {
case SyncHyperCall::kX86CPUID:
state.gpr.rax.aword = 0;
state.gpr.rbx.aword = 0;
state.gpr.rcx.aword = 0;
state.gpr.rdx.aword = 0;
asm volatile(
"cpuid"
: "=a"(state.gpr.rax.dword),
"=b"(state.gpr.rbx.dword),
"=c"(state.gpr.rcx.dword),
"=d"(state.gpr.rdx.dword)
: "a"(eax),
"b"(ebx),
"c"(ecx),
"d"(edx)
);
break;
case SyncHyperCall::kX86ReadTSC:
state.gpr.rax.aword = 0;
state.gpr.rdx.aword = 0;
asm volatile(
"rdtsc"
: "=a"(state.gpr.rax.dword),
"=d"(state.gpr.rdx.dword)
);
break;
case SyncHyperCall::kX86ReadTSCP:
state.gpr.rax.aword = 0;
state.gpr.rcx.aword = 0;
state.gpr.rdx.aword = 0;
asm volatile(
"rdtscp"
: "=a"(state.gpr.rax.dword),
"=c"(state.gpr.rcx.dword),
"=d"(state.gpr.rdx.dword)
);
break;
default:
__builtin_unreachable();
}
return mem;
}
Memory *__mcsema_reg_tracer(State &state, addr_t, Memory *memory) {
const char *format = nullptr;
if (sizeof(void *) == 8) {
fprintf(
stderr,
"RIP=%" PRIx64 ",RAX=%" PRIx64 ",RBX=%" PRIx64
",RCX=%" PRIx64 ",RDX=%" PRIx64 ",RSI=%" PRIx64
",RDI=%" PRIx64 ",RBP=%" PRIx64 ",RSP=%" PRIx64
",R8=%" PRIx64 ",R9=%" PRIx64 ",R10=%" PRIx64
",R11=%" PRIx64 ",R12=%" PRIx64 ",R13=%" PRIx64
",R14=%" PRIx64 ",R15=%" PRIx64 "\n",
state.RIP, state.RAX, state.RBX, state.RCX, state.RDX, state.RSI,
state.RDI, state.RBP, state.RSP, state.R8, state.R9, state.R10,
state.R11, state.R12, state.R13, state.R14, state.R15);
} else {
fprintf(
stderr,
"EIP=%" PRIx32 ",EAX=%" PRIx32 ",EBX=%" PRIx32
",ECX=%" PRIx32 ",EDX=%" PRIx32 ",ESI=%" PRIx32
",EDI=%" PRIx32 ",ESP=%" PRIx32 ",EBP=%" PRIx32 "\n",
state.EIP, state.EAX, state.EBX, state.ECX, state.EDX, state.ESI,
state.EDI, state.EBP, state.ESP);
}
return memory;
}
// Memory read intrinsics.
uint8_t __remill_read_memory_8(Memory *, addr_t addr) {
return *reinterpret_cast<uint8_t *>(addr);
}
uint16_t __remill_read_memory_16(Memory *, addr_t addr) {
return *reinterpret_cast<uint16_t *>(addr);
}
uint32_t __remill_read_memory_32(Memory *, addr_t addr) {
return *reinterpret_cast<uint32_t *>(addr);
}
uint64_t __remill_read_memory_64(Memory *, addr_t addr) {
return *reinterpret_cast<uint64_t *>(addr);
}
// Memory write intrinsics.
Memory *__remill_write_memory_8(
Memory * memory, addr_t addr, uint8_t val) {
*reinterpret_cast<uint8_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_16(
Memory * memory, addr_t addr, uint16_t val) {
*reinterpret_cast<uint16_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_32(
Memory * memory, addr_t addr, uint32_t val) {
*reinterpret_cast<uint32_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_64(
Memory * memory, addr_t addr, uint64_t val) {
*reinterpret_cast<uint64_t *>(addr) = val;
return memory;
}
float32_t __remill_read_memory_f32(
Memory *, addr_t addr, float32_t val) {
return *reinterpret_cast<float32_t *>(addr);
}
float64_t __remill_read_memory_f64(
Memory *, addr_t addr, float64_t val) {
return *reinterpret_cast<float64_t *>(addr);
}
float64_t __remill_read_memory_f80(Memory *, addr_t addr) {
return static_cast<float64_t>(*reinterpret_cast<long double *>(addr));
}
Memory *__remill_write_memory_f32(
Memory * memory, addr_t addr, float32_t val) {
*reinterpret_cast<float32_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_f64(
Memory * memory, addr_t addr, float64_t val) {
*reinterpret_cast<float64_t *>(addr) = val;
return memory;
}
Memory *__remill_write_memory_f80(
Memory * memory, addr_t addr, float64_t val) {
*reinterpret_cast<long double *>(addr) = static_cast<long double>(val);
return memory;
}
// Memory barriers types, see: http://g.oswego.edu/dl/jmm/cookbook.html
Memory *__remill_barrier_load_load(Memory * memory) {
return memory;
}
Memory *__remill_barrier_load_store(Memory * memory) {
return memory;
}
Memory *__remill_barrier_store_load(Memory * memory) {
return memory;
}
Memory *__remill_barrier_store_store(Memory * memory) {
return memory;
}
// Atomic operations. The address/size are hints, but the granularity of the
// access can be bigger. These have implicit StoreLoad semantics.
Memory *__remill_atomic_begin(Memory * memory) {
return memory;
}
Memory *__remill_atomic_end(Memory * memory) {
return memory;
}
Memory *__remill_compare_exchange_memory_8(
Memory *memory, addr_t addr, uint8_t &expected, uint8_t desired) {
expected = __sync_val_compare_and_swap(
reinterpret_cast<uint8_t *>(addr), expected, desired);
return memory;
}
Memory *__remill_compare_exchange_memory_16(
Memory *memory, addr_t addr, uint16_t &expected, uint16_t desired) {
expected = __sync_val_compare_and_swap(
reinterpret_cast<uint16_t *>(addr), expected, desired);
return memory;
}
Memory *__remill_compare_exchange_memory_32(
Memory *memory, addr_t addr, uint32_t &expected, uint32_t desired) {
expected = __sync_val_compare_and_swap(
reinterpret_cast<uint32_t *>(addr), expected, desired);
return memory;
}
Memory *__remill_compare_exchange_memory_64(
Memory *memory, addr_t addr, uint64_t &expected, uint64_t desired) {
expected = __sync_val_compare_and_swap(
reinterpret_cast<uint64_t *>(addr), expected, desired);
return memory;
}
#ifdef _GXX_EXPERIMENTAL_CXX0X__
Memory *__remill_compare_exchange_memory_128(
Memory *memory, addr_t addr, uint128_t &expected, uint128_t &desired) {
expected = __sync_val_compare_and_swap(
reinterpret_cast<uint128_t *>(addr), expected, desired);
return memory;
}
#endif
Memory *__remill_fetch_and_add_8(
Memory *memory, addr_t addr, uint8_t &value) {
value = __sync_fetch_and_add(reinterpret_cast<uint8_t*>(addr), value);
return memory;
}
Memory *__remill_fetch_and_add_16(
Memory *memory, addr_t addr, uint16_t &value) {
value = __sync_fetch_and_add(reinterpret_cast<uint16_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_add_32(
Memory *memory, addr_t addr, uint32_t &value) {
value = __sync_fetch_and_add(reinterpret_cast<uint32_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_add_64(
Memory *memory, addr_t addr, uint64_t &value) {
value = __sync_fetch_and_add(reinterpret_cast<uint64_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_sub_8(
Memory *memory, addr_t addr, uint8_t &value) {
value = __sync_fetch_and_sub(reinterpret_cast<uint8_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_sub_16(
Memory *memory, addr_t addr, uint16_t &value) {
value = __sync_fetch_and_sub(reinterpret_cast<uint16_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_sub_32(
Memory *memory, addr_t addr, uint32_t &value) {
value = __sync_fetch_and_sub(reinterpret_cast<uint32_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_sub_64(
Memory *memory, addr_t addr, uint64_t &value) {
value = __sync_fetch_and_sub(reinterpret_cast<uint64_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_or_8(
Memory *memory, addr_t addr, uint8_t &value) {
value = __sync_fetch_and_or(reinterpret_cast<uint8_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_or_16(
Memory *memory, addr_t addr, uint16_t &value) {
value = __sync_fetch_and_or(reinterpret_cast<uint16_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_or_32(
Memory *memory, addr_t addr, uint32_t &value) {
value = __sync_fetch_and_or(reinterpret_cast<uint32_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_or_64(
Memory *memory, addr_t addr, uint64_t &value) {
value = __sync_fetch_and_or(reinterpret_cast<uint64_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_and_8(
Memory *memory, addr_t addr, uint8_t &value) {
value = __sync_fetch_and_and(reinterpret_cast<uint8_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_and_16(
Memory *memory, addr_t addr, uint16_t &value) {
value = __sync_fetch_and_and(reinterpret_cast<uint16_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_and_32(
Memory *memory, addr_t addr, uint32_t &value) {
value = __sync_fetch_and_and(reinterpret_cast<uint32_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_and_64(
Memory *memory, addr_t addr, uint64_t &value) {
value = __sync_fetch_and_and(reinterpret_cast<uint64_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_xor_8(
Memory *memory, addr_t addr, uint8_t &value) {
value = __sync_fetch_and_xor(reinterpret_cast<uint8_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_xor_16(
Memory *memory, addr_t addr, uint16_t &value) {
value = __sync_fetch_and_xor(reinterpret_cast<uint16_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_xor_32(
Memory *memory, addr_t addr, uint32_t &value) {
value = __sync_fetch_and_xor(reinterpret_cast<uint32_t *>(addr), value);
return memory;
}
Memory *__remill_fetch_and_xor_64(
Memory *memory, addr_t addr, uint64_t &value) {
value = __sync_fetch_and_xor(reinterpret_cast<uint64_t *>(addr), value);
return memory;
}
int __remill_fpu_exception_test_and_clear(int read_mask, int clear_mask) {
auto except = std::fetestexcept(read_mask);
std::feclearexcept(clear_mask);
return except;
}
} // extern C
<|endoftext|>
|
<commit_before>
#include <hx/CFFI.h>
#include "common/ByteArray.h"
#include "snow_core.h"
#include "snow_io.h"
#include <string>
namespace snow {
// --- ByteArray -----------------------------------------------------
AutoGCRoot *gByteArrayCreate = 0;
AutoGCRoot *gByteArrayLen = 0;
AutoGCRoot *gByteArrayResize = 0;
AutoGCRoot *gByteArrayBytes = 0;
value snow_byte_array_init(value inFactory, value inLen, value inResize, value inBytes) {
gByteArrayCreate = new AutoGCRoot(inFactory);
gByteArrayLen = new AutoGCRoot(inLen);
gByteArrayResize = new AutoGCRoot(inResize);
gByteArrayBytes = new AutoGCRoot(inBytes);
return alloc_null();
} DEFINE_PRIM(snow_byte_array_init,4);
ByteArray::ByteArray() : mValue(0) {}
ByteArray::ByteArray(const ByteArray &inRHS) : mValue(inRHS.mValue) { }
ByteArray::ByteArray(value inValue) : mValue(inValue) { }
ByteArray::ByteArray(int inSize) {
mValue = val_call1(gByteArrayCreate->get(), alloc_int(inSize) );
}
ByteArray::ByteArray(const QuickVec<uint8> &inData) {
mValue = val_call1(gByteArrayCreate->get(), alloc_int(inData.size()) );
uint8 *bytes = Bytes();
if (bytes) {
memcpy(bytes, &inData[0], inData.size() );
}
}
void ByteArray::Resize(int inSize) {
val_call2(gByteArrayResize->get(), mValue, alloc_int(inSize) );
}
int ByteArray::Size() const {
return val_int( val_call1(gByteArrayLen->get(), mValue ));
}
const unsigned char *ByteArray::Bytes() const {
value bytes = val_call1(gByteArrayBytes->get(),mValue);
if (val_is_string(bytes)) {
return (unsigned char *)val_string(bytes);
}
buffer buf = val_to_buffer(bytes);
if (buf==0) {
val_throw(alloc_string("Bad ByteArray"));
}
return (unsigned char *)buffer_data(buf);
}
unsigned char *ByteArray::Bytes() {
value bytes = val_call1(gByteArrayBytes->get(), mValue);
if (val_is_string(bytes)) {
return (unsigned char *)val_string(bytes);
}
buffer buf = val_to_buffer(bytes);
if (buf == 0) {
val_throw(alloc_string("Bad ByteArray"));
}
return (unsigned char *)buffer_data(buf);
}
// --------------------
int ByteArray::ToFile(const OSChar *inFilename, const ByteArray array) {
snow::io::iosrc* file = snow::io::iosrc_fromfile(inFilename, "wb");
if(!file) {
snow::log(1, "/ snow / ByteArray::ToFile cannot open file for writing %s\n", inFilename );
//0 means nothing was written
return 0;
}
int res = snow::io::write( file, array.Bytes() , 1, array.Size() );
snow::io::close(file);
return res;
} //ToFile
ByteArray ByteArray::FromFile(const OSChar *inFilename) {
snow::io::iosrc* file = snow::io::iosrc_fromfile(inFilename, "rb");
if(!file) {
snow::log(1, "/ snow / ByteArray::FromFile cannot open file for reading %s\n", inFilename );
return ByteArray();
}
//determine the length
snow::io::seek(file, 0, snow_seek_end);
int len = snow::io::tell(file);
snow::io::seek(file, 0, snow_seek_set);
//create a bytearray of the file size
ByteArray result(len);
//read the data into the buffer
int status = snow::io::read(file, result.Bytes(), len, 1);
//close the file
snow::io::close(file);
return result;
} //FromFile
} //snow namespace
<commit_msg>cleanup<commit_after>#include <hx/CFFI.h>
/*
Portions adapted from https://github.com/haxenme/nme/
*/
#include "common/ByteArray.h"
#include "snow_core.h"
#include "snow_io.h"
#include <string>
namespace snow {
// --- ByteArray -----------------------------------------------------
AutoGCRoot *gByteArrayCreate = 0;
AutoGCRoot *gByteArrayLen = 0;
AutoGCRoot *gByteArrayResize = 0;
AutoGCRoot *gByteArrayBytes = 0;
value snow_byte_array_init(value inFactory, value inLen, value inResize, value inBytes) {
gByteArrayCreate = new AutoGCRoot(inFactory);
gByteArrayLen = new AutoGCRoot(inLen);
gByteArrayResize = new AutoGCRoot(inResize);
gByteArrayBytes = new AutoGCRoot(inBytes);
return alloc_null();
} DEFINE_PRIM(snow_byte_array_init,4);
ByteArray::ByteArray() : mValue(0) {}
ByteArray::ByteArray(const ByteArray &inRHS) : mValue(inRHS.mValue) { }
ByteArray::ByteArray(value inValue) : mValue(inValue) { }
ByteArray::ByteArray(int inSize) {
mValue = val_call1(gByteArrayCreate->get(), alloc_int(inSize) );
}
ByteArray::ByteArray(const QuickVec<uint8> &inData) {
mValue = val_call1(gByteArrayCreate->get(), alloc_int(inData.size()) );
uint8 *bytes = Bytes();
if (bytes) {
memcpy(bytes, &inData[0], inData.size() );
}
}
void ByteArray::Resize(int inSize) {
val_call2(gByteArrayResize->get(), mValue, alloc_int(inSize) );
}
int ByteArray::Size() const {
return val_int( val_call1(gByteArrayLen->get(), mValue ));
}
const unsigned char *ByteArray::Bytes() const {
value bytes = val_call1(gByteArrayBytes->get(),mValue);
if (val_is_string(bytes)) {
return (unsigned char *)val_string(bytes);
}
buffer buf = val_to_buffer(bytes);
if (buf==0) {
val_throw(alloc_string("Bad ByteArray"));
}
return (unsigned char *)buffer_data(buf);
}
unsigned char *ByteArray::Bytes() {
value bytes = val_call1(gByteArrayBytes->get(), mValue);
if (val_is_string(bytes)) {
return (unsigned char *)val_string(bytes);
}
buffer buf = val_to_buffer(bytes);
if (buf == 0) {
val_throw(alloc_string("Bad ByteArray"));
}
return (unsigned char *)buffer_data(buf);
}
// --------------------
int ByteArray::ToFile(const OSChar *inFilename, const ByteArray array) {
snow::io::iosrc* file = snow::io::iosrc_fromfile(inFilename, "wb");
if(!file) {
snow::log(1, "/ snow / ByteArray::ToFile cannot open file for writing %s\n", inFilename );
//0 means nothing was written
return 0;
}
int res = snow::io::write( file, array.Bytes() , 1, array.Size() );
snow::io::close(file);
return res;
} //ToFile
ByteArray ByteArray::FromFile(const OSChar *inFilename) {
snow::io::iosrc* file = snow::io::iosrc_fromfile(inFilename, "rb");
if(!file) {
snow::log(1, "/ snow / ByteArray::FromFile cannot open file for reading %s\n", inFilename );
return ByteArray();
}
//determine the length
snow::io::seek(file, 0, snow_seek_end);
int len = snow::io::tell(file);
snow::io::seek(file, 0, snow_seek_set);
//create a bytearray of the file size
ByteArray result(len);
//read the data into the buffer
int status = snow::io::read(file, result.Bytes(), len, 1);
//close the file
snow::io::close(file);
return result;
} //FromFile
} //snow namespace
<|endoftext|>
|
<commit_before>#line 2 "togo/core/parser/types.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Parser types.
@ingroup lib_core_types
@ingroup lib_core_parser
*/
#pragma once
#include <togo/core/config.hpp>
#include <togo/core/types.hpp>
#include <togo/core/utility/types.hpp>
#include <togo/core/utility/traits.hpp>
#include <togo/core/memory/types.hpp>
#include <togo/core/collection/types.hpp>
#include <togo/core/string/types.hpp>
namespace togo {
/**
@addtogroup lib_core_parser
@{
*/
// Forward declarations
namespace parser {
struct Parser;
} // namespace parser
namespace parse_state {
struct ParsePosition;
struct ParseState;
enum class ParseResultCode : unsigned;
} // namespace parse_state
namespace parser {
/// Parser type.
enum class ParserType : unsigned {
Undefined,
// intangible
Nothing,
Empty,
Head,
Tail,
// values
Char,
CharRange,
String,
Bounded,
// series
Any,
All,
// branch
Ref,
// call
Func,
// conditional_call
Close,
};
static constexpr unsigned const c_num_types = unsigned_cast(ParserType::Close) + 1;
/// Parser modifiers.
///
/// These are executed in order of definition.
enum class ParserModifier : unsigned {
/// No modifiers.
none = 0,
/// Report no_match instead of failure.
maybe = 1 << 0,
/// Suppress results.
test = 1 << 1,
/// Suppress results and produce a slice for the parsed segment.
flatten = 1 << 2,
/// One or more.
repeat = 1 << 3,
/// Zero or more.
repeat_or_none = 1 << 4,
};
using PMod = ParserModifier;
/// Parse function type.
using parse_func_type = parse_state::ParseResultCode (
Parser const* p,
parse_state::ParseState& s,
parse_state::ParsePosition const& from
);
/// Parser data.
template<ParserType, typename = void> struct ParserData;
#define PARSER_TRAIT_TYPE(name_) \
template<ParserType T> struct name_ { \
static constexpr bool const value = false
PARSER_TRAIT_TYPE(is_value)
|| T == ParserType::Char
|| T == ParserType::CharRange
|| T == ParserType::String
;};
PARSER_TRAIT_TYPE(is_series)
|| T == ParserType::All
|| T == ParserType::Any
;};
PARSER_TRAIT_TYPE(is_branch)
|| T == ParserType::Ref
;};
PARSER_TRAIT_TYPE(is_conditional_call)
|| T == ParserType::Close
;};
#undef PARSER_TRAIT_TYPE
/// Undefined.
using Undefined = ParserData<ParserType::Undefined>;
/// Match nothing (always succeeds).
using Nothing = ParserData<ParserType::Nothing>;
/// Match an empty input.
using Empty = ParserData<ParserType::Empty>;
/// Match the beginning of the input.
using Head = ParserData<ParserType::Head>;
/// Match the end of the input.
using Tail = ParserData<ParserType::Tail>;
/// Match a single character.
using Char = ParserData<ParserType::Char>;
/// Match a character range.
using CharRange = ParserData<ParserType::CharRange>;
/// Match a string.
using String = ParserData<ParserType::String>;
/// Match a bounded parser.
using Bounded = ParserData<ParserType::Bounded>;
/// Match any in a series.
using Any = ParserData<ParserType::Any>;
/// Match all in a series.
using All = ParserData<ParserType::All>;
/// Match another parser after modifiers.
using Ref = ParserData<ParserType::Ref>;
/// Call a parse function.
using Func = ParserData<ParserType::Func>;
/// Match a parser and call a function if it succeeds.
using Close = ParserData<ParserType::Close>;
template<> struct ParserData<ParserType::Undefined> {};
template<> struct ParserData<ParserType::Nothing> {};
template<> struct ParserData<ParserType::Empty> {};
template<> struct ParserData<ParserType::Head> {};
template<> struct ParserData<ParserType::Tail> {};
template<>
struct ParserData<ParserType::Char> {
signed c;
};
template<>
struct ParserData<ParserType::CharRange> {
signed b;
signed e;
};
template<>
struct ParserData<ParserType::String> {
StringRef s;
};
template<>
struct ParserData<ParserType::Bounded> {
signed opener;
signed closer;
Parser const* p;
ParserData(char opener, char closer, Parser const& p);
ParserData(Allocator& a, char opener, char closer, Parser&& p);
};
template<ParserType T>
struct ParserData<T, enable_if<is_series<T>::value>> {
unsigned num;
Parser const** p;
template<class... P>
ParserData(Allocator& a, P&&... p);
};
template<ParserType T>
struct ParserData<T, enable_if<is_branch<T>::value>> {
Parser const* p;
ParserData(Parser const& p);
ParserData(Allocator& a, Parser&& p);
};
template<>
struct ParserData<ParserType::Func> {
parse_func_type* f;
void* userdata;
ParserData(parse_func_type* f);
ParserData(parse_func_type* f, void* userdata);
ParserData(void* userdata, parse_func_type* f);
};
template<ParserType T>
struct ParserData<T, enable_if<is_conditional_call<T>::value>> {
parse_func_type* f;
Parser const* p;
ParserData(parse_func_type* f);
ParserData(parse_func_type* f, Parser const& p);
ParserData(Parser const& p, parse_func_type* f);
ParserData(Allocator& a, parse_func_type* f, Parser&& p);
ParserData(Allocator& a, Parser&& p, parse_func_type* f);
};
/// Parser.
struct Parser {
// {u16 type; u16 modifiers;}
u32 properties;
hash32 name_hash;
StringRef name;
union Storage {
Char Char;
CharRange CharRange;
String String;
Bounded Bounded;
Any Any;
All All;
Ref Ref;
Func Func;
Close Close;
Storage(no_init_tag) {}
Storage(parser::Undefined&&) {}
Storage(parser::Nothing&&) {}
Storage(parser::Empty&&) {}
Storage(parser::Head&&) {}
Storage(parser::Tail&&) {}
Storage(parser::Char&& d) : Char(rvalue_ref(d)) {}
Storage(parser::CharRange&& d) : CharRange(rvalue_ref(d)) {}
Storage(parser::String&& d) : String(rvalue_ref(d)) {}
Storage(parser::Bounded&& d) : Bounded(rvalue_ref(d)) {}
Storage(parser::Any&& d) : Any(rvalue_ref(d)) {}
Storage(parser::All&& d) : All(rvalue_ref(d)) {}
Storage(parser::Ref&& d) : Ref(rvalue_ref(d)) {}
Storage(parser::Func&& d) : Func(rvalue_ref(d)) {}
Storage(parser::Close&& d) : Close(rvalue_ref(d)) {}
} s;
/// Construct named Undefined parser.
Parser(StringRef name);
/// Construct unnamed Undefined parser.
Parser();
/// Construct named parser with modifiers.
template<ParserType T>
Parser(StringRef name, ParserModifier mods, ParserData<T>&& d);
/// Construct named parser.
template<ParserType T>
Parser(StringRef name, ParserData<T>&& d);
/// Construct unnamed parser with modifiers.
template<ParserType T>
Parser(ParserModifier mods, ParserData<T>&& d);
/// Construct unnamed parser.
template<ParserType T>
Parser(ParserData<T>&& d);
};
/// sizeof(Parser) * num.
inline constexpr unsigned sizeof_n(unsigned num = 1) {
return sizeof(Parser) * num;
}
/// The allocation size of a series parser (e.g., Any).
inline constexpr unsigned sizeof_series(unsigned num_ref, unsigned num_inplace = 0) {
return sizeof(Parser*) * (num_ref + num_inplace) + sizeof_n(num_inplace);
}
/// FixedAllocator helper.
template<
unsigned num_ref,
unsigned num_inplace = 0,
unsigned num = 0
>
using FixedParserAllocator = FixedAllocator<0
+ sizeof_series(num_ref, num_inplace)
+ sizeof_n(num)
>;
/// Predefined parsers.
struct PDef {
/// [ \t\n\r]+ :t => nothing
static Parser const whitespace;
/// <whitespace>? => nothing
static Parser const whitespace_maybe;
/// "null" => null
static Parser const null;
/// (true|false) => bool
static Parser const boolean;
/// [\-+] => char
static Parser const sign;
/// <sign>? => char
static Parser const sign_maybe;
/// [0-9] => char
static Parser const digit_dec;
/// <digit_dec>+ => slice
static Parser const digits_dec;
/// [0-9a-fA-F] => char
static Parser const digit_hex;
/// <digit_hex>+ => slice
static Parser const digits_hex;
/// [0-7] => char
static Parser const digit_oct;
/// <digit_oct>+ => slice
static Parser const digits_oct;
/// <digits> => u64
static Parser const u64_dec;
/// 0[xX]<hex_digits> => u64
static Parser const u64_hex;
/// 0<oct_digits> => u64
static Parser const u64_oct;
/// (<u64_dec>|<u64_hex>|<u64_oct>) => u64
static Parser const u64_any;
/// <sign_maybe><u64_dec> => s64
static Parser const s64_dec;
/// (<s64_dec>|<u64_hex>|<u64_oct>) => s64
static Parser const s64_any;
/// <sign_maybe><digits>\.<digits> => f64
static Parser const f64_basic;
/// <f64_basic>([eE]<sign_maybe><digits>)? => f64
static Parser const f64_exp;
};
} // namespace parser
namespace parse_state {
/// Parse result code.
enum class ParseResultCode : unsigned {
fail,
ok,
no_match,
};
static constexpr unsigned const c_num_result_codes = unsigned_cast(ParseResultCode::no_match) + 1;
/// Whether a result code is fail-y.
inline constexpr bool operator!(ParseResultCode rc) {
return rc == ParseResultCode::fail;
}
/// Parse position.
struct ParsePosition {
char const* p;
u32_fast i;
};
struct Slice {
char const* b;
char const* e;
};
/// Parse result.
struct ParseResult {
enum Type : unsigned {
type_null,
type_bool,
type_char,
type_s64,
type_u64,
type_f64,
type_pointer,
type_slice,
type_user_base,
};
Type type;
union {
bool b;
char c;
s64 i;
u64 u;
f64 f;
void const* p;
Slice s;
};
ParseResult() = default;
~ParseResult() = default;
ParseResult(null_tag const) : type(type_null) {}
ParseResult(bool b) : type(type_bool), b(b) {}
ParseResult(char c) : type(type_char), c(c) {}
ParseResult(s64 i) : type(type_s64), i(i) {}
ParseResult(u64 u) : type(type_u64), u(u) {}
ParseResult(f64 f) : type(type_f64), f(f) {}
ParseResult(void const* p) : type(type_pointer), p(p) {}
ParseResult(char const* b, char const* e) : type(type_slice), s{b, e} {}
};
/// Parse error.
struct ParseError {
/// Line where the error occurred.
unsigned line;
/// Column where the error occurred.
unsigned column;
/// Result code.
ParseResultCode result_code;
/// Error message.
FixedArray<char, 512> message;
};
/// Parse state.
struct ParseState {
char const* p;
char const* b;
char const* e;
char const* t;
Array<ParseResult> results;
unsigned suppress_results;
unsigned suppress_errors;
unsigned line;
unsigned column;
ParseError* error;
void* userdata;
ParseState(
Allocator& allocator,
ParseError* error = nullptr,
void* userdata = nullptr
)
: p(nullptr)
, b(nullptr)
, e(nullptr)
, t(nullptr)
, results(allocator)
, suppress_results(0)
, suppress_errors(0)
, line(0)
, column(0)
, error(error)
, userdata(userdata)
{}
};
} // namespace parse_state
/** @} */ // end of doc-group lib_core_parser
/** @cond INTERNAL */
template<> struct enable_enum_bitwise_ops<parser::ParserModifier> : true_type {};
/** @endcond */ // INTERNAL
using parser::Undefined;
using parser::Nothing;
using parser::Empty;
using parser::Head;
using parser::Tail;
using parser::Char;
using parser::CharRange;
using parser::String;
using parser::Bounded;
using parser::Any;
using parser::All;
using parser::Ref;
using parser::Func;
using parser::Close;
using parser::ParserType;
using parser::ParserModifier;
using parser::PMod;
using parser::Parser;
using parser::FixedParserAllocator;
using parse_state::ParseResultCode;
using parse_state::ParseResult;
using parse_state::ParsePosition;
using parse_state::ParseError;
using parse_state::ParseState;
using parser::PDef;
} // namespace togo
<commit_msg>lib/core/parser: added helpful ParseResult ctors.<commit_after>#line 2 "togo/core/parser/types.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Parser types.
@ingroup lib_core_types
@ingroup lib_core_parser
*/
#pragma once
#include <togo/core/config.hpp>
#include <togo/core/types.hpp>
#include <togo/core/utility/types.hpp>
#include <togo/core/utility/traits.hpp>
#include <togo/core/memory/types.hpp>
#include <togo/core/collection/types.hpp>
#include <togo/core/string/types.hpp>
namespace togo {
/**
@addtogroup lib_core_parser
@{
*/
// Forward declarations
namespace parser {
struct Parser;
} // namespace parser
namespace parse_state {
struct ParsePosition;
struct ParseState;
enum class ParseResultCode : unsigned;
} // namespace parse_state
namespace parser {
/// Parser type.
enum class ParserType : unsigned {
Undefined,
// intangible
Nothing,
Empty,
Head,
Tail,
// values
Char,
CharRange,
String,
Bounded,
// series
Any,
All,
// branch
Ref,
// call
Func,
// conditional_call
Close,
};
static constexpr unsigned const c_num_types = unsigned_cast(ParserType::Close) + 1;
/// Parser modifiers.
///
/// These are executed in order of definition.
enum class ParserModifier : unsigned {
/// No modifiers.
none = 0,
/// Report no_match instead of failure.
maybe = 1 << 0,
/// Suppress results.
test = 1 << 1,
/// Suppress results and produce a slice for the parsed segment.
flatten = 1 << 2,
/// One or more.
repeat = 1 << 3,
/// Zero or more.
repeat_or_none = 1 << 4,
};
using PMod = ParserModifier;
/// Parse function type.
using parse_func_type = parse_state::ParseResultCode (
Parser const* p,
parse_state::ParseState& s,
parse_state::ParsePosition const& from
);
/// Parser data.
template<ParserType, typename = void> struct ParserData;
#define PARSER_TRAIT_TYPE(name_) \
template<ParserType T> struct name_ { \
static constexpr bool const value = false
PARSER_TRAIT_TYPE(is_value)
|| T == ParserType::Char
|| T == ParserType::CharRange
|| T == ParserType::String
;};
PARSER_TRAIT_TYPE(is_series)
|| T == ParserType::All
|| T == ParserType::Any
;};
PARSER_TRAIT_TYPE(is_branch)
|| T == ParserType::Ref
;};
PARSER_TRAIT_TYPE(is_conditional_call)
|| T == ParserType::Close
;};
#undef PARSER_TRAIT_TYPE
/// Undefined.
using Undefined = ParserData<ParserType::Undefined>;
/// Match nothing (always succeeds).
using Nothing = ParserData<ParserType::Nothing>;
/// Match an empty input.
using Empty = ParserData<ParserType::Empty>;
/// Match the beginning of the input.
using Head = ParserData<ParserType::Head>;
/// Match the end of the input.
using Tail = ParserData<ParserType::Tail>;
/// Match a single character.
using Char = ParserData<ParserType::Char>;
/// Match a character range.
using CharRange = ParserData<ParserType::CharRange>;
/// Match a string.
using String = ParserData<ParserType::String>;
/// Match a bounded parser.
using Bounded = ParserData<ParserType::Bounded>;
/// Match any in a series.
using Any = ParserData<ParserType::Any>;
/// Match all in a series.
using All = ParserData<ParserType::All>;
/// Match another parser after modifiers.
using Ref = ParserData<ParserType::Ref>;
/// Call a parse function.
using Func = ParserData<ParserType::Func>;
/// Match a parser and call a function if it succeeds.
using Close = ParserData<ParserType::Close>;
template<> struct ParserData<ParserType::Undefined> {};
template<> struct ParserData<ParserType::Nothing> {};
template<> struct ParserData<ParserType::Empty> {};
template<> struct ParserData<ParserType::Head> {};
template<> struct ParserData<ParserType::Tail> {};
template<>
struct ParserData<ParserType::Char> {
signed c;
};
template<>
struct ParserData<ParserType::CharRange> {
signed b;
signed e;
};
template<>
struct ParserData<ParserType::String> {
StringRef s;
};
template<>
struct ParserData<ParserType::Bounded> {
signed opener;
signed closer;
Parser const* p;
ParserData(char opener, char closer, Parser const& p);
ParserData(Allocator& a, char opener, char closer, Parser&& p);
};
template<ParserType T>
struct ParserData<T, enable_if<is_series<T>::value>> {
unsigned num;
Parser const** p;
template<class... P>
ParserData(Allocator& a, P&&... p);
};
template<ParserType T>
struct ParserData<T, enable_if<is_branch<T>::value>> {
Parser const* p;
ParserData(Parser const& p);
ParserData(Allocator& a, Parser&& p);
};
template<>
struct ParserData<ParserType::Func> {
parse_func_type* f;
void* userdata;
ParserData(parse_func_type* f);
ParserData(parse_func_type* f, void* userdata);
ParserData(void* userdata, parse_func_type* f);
};
template<ParserType T>
struct ParserData<T, enable_if<is_conditional_call<T>::value>> {
parse_func_type* f;
Parser const* p;
ParserData(parse_func_type* f);
ParserData(parse_func_type* f, Parser const& p);
ParserData(Parser const& p, parse_func_type* f);
ParserData(Allocator& a, parse_func_type* f, Parser&& p);
ParserData(Allocator& a, Parser&& p, parse_func_type* f);
};
/// Parser.
struct Parser {
// {u16 type; u16 modifiers;}
u32 properties;
hash32 name_hash;
StringRef name;
union Storage {
Char Char;
CharRange CharRange;
String String;
Bounded Bounded;
Any Any;
All All;
Ref Ref;
Func Func;
Close Close;
Storage(no_init_tag) {}
Storage(parser::Undefined&&) {}
Storage(parser::Nothing&&) {}
Storage(parser::Empty&&) {}
Storage(parser::Head&&) {}
Storage(parser::Tail&&) {}
Storage(parser::Char&& d) : Char(rvalue_ref(d)) {}
Storage(parser::CharRange&& d) : CharRange(rvalue_ref(d)) {}
Storage(parser::String&& d) : String(rvalue_ref(d)) {}
Storage(parser::Bounded&& d) : Bounded(rvalue_ref(d)) {}
Storage(parser::Any&& d) : Any(rvalue_ref(d)) {}
Storage(parser::All&& d) : All(rvalue_ref(d)) {}
Storage(parser::Ref&& d) : Ref(rvalue_ref(d)) {}
Storage(parser::Func&& d) : Func(rvalue_ref(d)) {}
Storage(parser::Close&& d) : Close(rvalue_ref(d)) {}
} s;
/// Construct named Undefined parser.
Parser(StringRef name);
/// Construct unnamed Undefined parser.
Parser();
/// Construct named parser with modifiers.
template<ParserType T>
Parser(StringRef name, ParserModifier mods, ParserData<T>&& d);
/// Construct named parser.
template<ParserType T>
Parser(StringRef name, ParserData<T>&& d);
/// Construct unnamed parser with modifiers.
template<ParserType T>
Parser(ParserModifier mods, ParserData<T>&& d);
/// Construct unnamed parser.
template<ParserType T>
Parser(ParserData<T>&& d);
};
/// sizeof(Parser) * num.
inline constexpr unsigned sizeof_n(unsigned num = 1) {
return sizeof(Parser) * num;
}
/// The allocation size of a series parser (e.g., Any).
inline constexpr unsigned sizeof_series(unsigned num_ref, unsigned num_inplace = 0) {
return sizeof(Parser*) * (num_ref + num_inplace) + sizeof_n(num_inplace);
}
/// FixedAllocator helper.
template<
unsigned num_ref,
unsigned num_inplace = 0,
unsigned num = 0
>
using FixedParserAllocator = FixedAllocator<0
+ sizeof_series(num_ref, num_inplace)
+ sizeof_n(num)
>;
/// Predefined parsers.
struct PDef {
/// [ \t\n\r]+ :t => nothing
static Parser const whitespace;
/// <whitespace>? => nothing
static Parser const whitespace_maybe;
/// "null" => null
static Parser const null;
/// (true|false) => bool
static Parser const boolean;
/// [\-+] => char
static Parser const sign;
/// <sign>? => char
static Parser const sign_maybe;
/// [0-9] => char
static Parser const digit_dec;
/// <digit_dec>+ => slice
static Parser const digits_dec;
/// [0-9a-fA-F] => char
static Parser const digit_hex;
/// <digit_hex>+ => slice
static Parser const digits_hex;
/// [0-7] => char
static Parser const digit_oct;
/// <digit_oct>+ => slice
static Parser const digits_oct;
/// <digits> => u64
static Parser const u64_dec;
/// 0[xX]<hex_digits> => u64
static Parser const u64_hex;
/// 0<oct_digits> => u64
static Parser const u64_oct;
/// (<u64_dec>|<u64_hex>|<u64_oct>) => u64
static Parser const u64_any;
/// <sign_maybe><u64_dec> => s64
static Parser const s64_dec;
/// (<s64_dec>|<u64_hex>|<u64_oct>) => s64
static Parser const s64_any;
/// <sign_maybe><digits>\.<digits> => f64
static Parser const f64_basic;
/// <f64_basic>([eE]<sign_maybe><digits>)? => f64
static Parser const f64_exp;
};
} // namespace parser
namespace parse_state {
/// Parse result code.
enum class ParseResultCode : unsigned {
fail,
ok,
no_match,
};
static constexpr unsigned const c_num_result_codes = unsigned_cast(ParseResultCode::no_match) + 1;
/// Whether a result code is fail-y.
inline constexpr bool operator!(ParseResultCode rc) {
return rc == ParseResultCode::fail;
}
/// Parse position.
struct ParsePosition {
char const* p;
u32_fast i;
};
struct Slice {
char const* b;
char const* e;
};
/// Parse result.
struct ParseResult {
enum Type : unsigned {
type_null,
type_bool,
type_char,
type_s64,
type_u64,
type_f64,
type_pointer,
type_slice,
type_user_base,
};
Type type;
union {
bool b;
char c;
s64 i;
u64 u;
f64 f;
void const* p;
Slice s;
};
ParseResult() = default;
~ParseResult() = default;
ParseResult(Type type) : type(type) {}
ParseResult(Type type, void const* p) : type(type), p(p) {}
ParseResult(null_tag const) : type(type_null) {}
ParseResult(bool b) : type(type_bool), b(b) {}
ParseResult(char c) : type(type_char), c(c) {}
ParseResult(s32 i) : type(type_s64), i(i) {}
ParseResult(s64 i) : type(type_s64), i(i) {}
ParseResult(u32 u) : type(type_u64), u(u) {}
ParseResult(u64 u) : type(type_u64), u(u) {}
ParseResult(f32 f) : type(type_f64), f(f) {}
ParseResult(f64 f) : type(type_f64), f(f) {}
ParseResult(void const* p) : type(type_pointer), p(p) {}
ParseResult(char const* b, char const* e) : type(type_slice), s{b, e} {}
};
/// Parse error.
struct ParseError {
/// Line where the error occurred.
unsigned line;
/// Column where the error occurred.
unsigned column;
/// Result code.
ParseResultCode result_code;
/// Error message.
FixedArray<char, 512> message;
};
/// Parse state.
struct ParseState {
char const* p;
char const* b;
char const* e;
char const* t;
Array<ParseResult> results;
unsigned suppress_results;
unsigned suppress_errors;
unsigned line;
unsigned column;
ParseError* error;
void* userdata;
ParseState(
Allocator& allocator,
ParseError* error = nullptr,
void* userdata = nullptr
)
: p(nullptr)
, b(nullptr)
, e(nullptr)
, t(nullptr)
, results(allocator)
, suppress_results(0)
, suppress_errors(0)
, line(0)
, column(0)
, error(error)
, userdata(userdata)
{}
};
} // namespace parse_state
/** @} */ // end of doc-group lib_core_parser
/** @cond INTERNAL */
template<> struct enable_enum_bitwise_ops<parser::ParserModifier> : true_type {};
/** @endcond */ // INTERNAL
using parser::Undefined;
using parser::Nothing;
using parser::Empty;
using parser::Head;
using parser::Tail;
using parser::Char;
using parser::CharRange;
using parser::String;
using parser::Bounded;
using parser::Any;
using parser::All;
using parser::Ref;
using parser::Func;
using parser::Close;
using parser::ParserType;
using parser::ParserModifier;
using parser::PMod;
using parser::Parser;
using parser::FixedParserAllocator;
using parse_state::ParseResultCode;
using parse_state::ParseResult;
using parse_state::ParsePosition;
using parse_state::ParseError;
using parse_state::ParseState;
using parser::PDef;
} // namespace togo
<|endoftext|>
|
<commit_before>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "local_socket.h"
#include "pathname.h"
#include <array> /* for std::array */
#include <cassert> /* for assert() */
#include <cerrno> /* for errno */
#include <cstring> /* for std::memset(), std::strlen() */
#include <fcntl.h> /* for F_*, fcntl() */
#include <stdexcept> /* for std::logic_error */
#include <sys/socket.h> /* for AF_LOCAL, CMSG_*, connect(), recvmsg(), send(), socket() */
#include <sys/un.h> /* for struct sockaddr_un */
#include <system_error> /* for std::system_error */
using namespace posix;
local_socket
local_socket::connect(const pathname& pathname) {
assert(!pathname.empty());
int sockfd;
if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
switch (errno) {
case EMFILE: /* Too many open files */
case ENFILE: /* Too many open files in system */
case ENOMEM: /* Cannot allocate memory in kernel */
throw std::system_error(errno, std::system_category()); // FIXME
default:
throw std::system_error(errno, std::system_category());
}
}
local_socket socket = local_socket(sockfd);
struct sockaddr_un addr;
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path, pathname.c_str()); // TODO: check bounds
const socklen_t addrlen = sizeof(addr.sun_family) + std::strlen(addr.sun_path);
retry:
if (::connect(sockfd, reinterpret_cast<struct sockaddr*>(&addr), addrlen) == -1) {
switch (errno) {
case EINTR: /* Interrupted system call */
goto retry;
default:
throw std::system_error(errno, std::system_category());
}
}
return socket;
}
void
local_socket::send(const std::string& string) {
return send(string.c_str(), string.size());
}
void
local_socket::send(const void* const data) {
assert(data != nullptr);
return send(data, std::strlen(reinterpret_cast<const char*>(data)));
}
void
local_socket::send(const void* const data,
const std::size_t size) {
assert(data != nullptr);
(void)data, (void)size; // TODO
}
void
local_socket::send(const descriptor& descriptor) {
(void)descriptor; // TODO
}
descriptor
local_socket::recvfd() {
descriptor result;
/* The control buffer must be large enough to hold a single frame of
* cmsghdr ancillary data: */
std::array<std::uint8_t, CMSG_SPACE(sizeof(int))> cmsg_buffer;
static_assert(sizeof(struct cmsghdr) <= cmsg_buffer.size(),
"sizeof(struct cmsghdr) > cmsg_buffer.size()");
static_assert(CMSG_SPACE(sizeof(int)) <= cmsg_buffer.size(),
"CMSG_SPACE(sizeof(int)) > cmsg_buffer.size()");
static_assert(CMSG_LEN(sizeof(int)) <= cmsg_buffer.size(),
"CMSG_LEN(sizeof(int)) > cmsg_buffer.size()");
/* Linux and Solaris require there to be at least 1 byte of actual data: */
std::array<std::uint8_t, 1> data_buffer;
struct iovec iov;
std::memset(&iov, 0, sizeof(iov));
iov.iov_base = data_buffer.data();
iov.iov_len = data_buffer.size();
struct msghdr msg;
std::memset(&msg, 0, sizeof(msghdr));
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg_buffer.data();
msg.msg_controllen = cmsg_buffer.size();
int flags = 0;
#ifdef MSG_CMSG_CLOEXEC
flags |= MSG_CMSG_CLOEXEC; /* Linux only */
#endif
retry:
const ssize_t rc = ::recvmsg(fd(), &msg, flags);
if (rc == -1) {
switch (errno) {
case EINTR: /* Interrupted system call */
goto retry;
case ENOMEM: /* Cannot allocate memory in kernel */
throw std::system_error(errno, std::system_category()); // FIXME
default:
throw std::system_error(errno, std::system_category());
}
}
const struct cmsghdr* const cmsg = CMSG_FIRSTHDR(&msg);
if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
if (cmsg->cmsg_level != SOL_SOCKET) {
throw std::logic_error("invalid cmsg_level");
}
if (cmsg->cmsg_type != SCM_RIGHTS) {
throw std::logic_error("invalid cmsg_type");
}
result.assign(*reinterpret_cast<const int*>(CMSG_DATA(cmsg)));
}
#ifndef MSG_CMSG_CLOEXEC
result.fcntl(F_SETFD, result.fcntl(F_GETFD) | FD_CLOEXEC);
#endif
return result;
}
<commit_msg>Implemented the posix::local_socket#send(data, size) method.<commit_after>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "local_socket.h"
#include "pathname.h"
#include <array> /* for std::array */
#include <cassert> /* for assert() */
#include <cerrno> /* for errno */
#include <cstdint> /* for std::uint8_t */
#include <cstring> /* for std::memset(), std::strlen() */
#include <fcntl.h> /* for F_*, fcntl() */
#include <stdexcept> /* for std::logic_error */
#include <sys/socket.h> /* for AF_LOCAL, CMSG_*, connect(), recvmsg(), send(), socket() */
#include <sys/un.h> /* for struct sockaddr_un */
#include <system_error> /* for std::system_error */
using namespace posix;
local_socket
local_socket::connect(const pathname& pathname) {
assert(!pathname.empty());
int sockfd;
if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
switch (errno) {
case EMFILE: /* Too many open files */
case ENFILE: /* Too many open files in system */
case ENOMEM: /* Cannot allocate memory in kernel */
throw std::system_error(errno, std::system_category()); // FIXME
default:
throw std::system_error(errno, std::system_category());
}
}
local_socket socket = local_socket(sockfd);
struct sockaddr_un addr;
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path, pathname.c_str()); // TODO: check bounds
const socklen_t addrlen = sizeof(addr.sun_family) + std::strlen(addr.sun_path);
retry:
if (::connect(sockfd, reinterpret_cast<struct sockaddr*>(&addr), addrlen) == -1) {
switch (errno) {
case EINTR: /* Interrupted system call */
goto retry;
default:
throw std::system_error(errno, std::system_category());
}
}
return socket;
}
void
local_socket::send(const std::string& string) {
return send(string.c_str(), string.size());
}
void
local_socket::send(const void* const data) {
assert(data != nullptr);
return send(data, std::strlen(reinterpret_cast<const char*>(data)));
}
void
local_socket::send(const void* const data,
const std::size_t size) {
assert(data != nullptr);
std::size_t sent = 0;
while (sent < size) {
const ssize_t rc = ::send(fd(), reinterpret_cast<const std::uint8_t*>(data) + sent, size - sent, 0);
if (rc == -1) {
switch (errno) {
case EINTR: /* Interrupted system call */
continue;
case ENOMEM: /* Cannot allocate memory in kernel */
throw std::system_error(errno, std::system_category()); // FIXME
default:
throw std::system_error(errno, std::system_category());
}
}
sent += rc;
}
}
void
local_socket::send(const descriptor& descriptor) {
(void)descriptor; // TODO
}
descriptor
local_socket::recvfd() {
descriptor result;
/* The control buffer must be large enough to hold a single frame of
* cmsghdr ancillary data: */
std::array<std::uint8_t, CMSG_SPACE(sizeof(int))> cmsg_buffer;
static_assert(sizeof(struct cmsghdr) <= cmsg_buffer.size(),
"sizeof(struct cmsghdr) > cmsg_buffer.size()");
static_assert(CMSG_SPACE(sizeof(int)) <= cmsg_buffer.size(),
"CMSG_SPACE(sizeof(int)) > cmsg_buffer.size()");
static_assert(CMSG_LEN(sizeof(int)) <= cmsg_buffer.size(),
"CMSG_LEN(sizeof(int)) > cmsg_buffer.size()");
/* Linux and Solaris require there to be at least 1 byte of actual data: */
std::array<std::uint8_t, 1> data_buffer;
struct iovec iov;
std::memset(&iov, 0, sizeof(iov));
iov.iov_base = data_buffer.data();
iov.iov_len = data_buffer.size();
struct msghdr msg;
std::memset(&msg, 0, sizeof(msghdr));
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg_buffer.data();
msg.msg_controllen = cmsg_buffer.size();
int flags = 0;
#ifdef MSG_CMSG_CLOEXEC
flags |= MSG_CMSG_CLOEXEC; /* Linux only */
#endif
retry:
const ssize_t rc = ::recvmsg(fd(), &msg, flags);
if (rc == -1) {
switch (errno) {
case EINTR: /* Interrupted system call */
goto retry;
case ENOMEM: /* Cannot allocate memory in kernel */
throw std::system_error(errno, std::system_category()); // FIXME
default:
throw std::system_error(errno, std::system_category());
}
}
const struct cmsghdr* const cmsg = CMSG_FIRSTHDR(&msg);
if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
if (cmsg->cmsg_level != SOL_SOCKET) {
throw std::logic_error("invalid cmsg_level");
}
if (cmsg->cmsg_type != SCM_RIGHTS) {
throw std::logic_error("invalid cmsg_type");
}
result.assign(*reinterpret_cast<const int*>(CMSG_DATA(cmsg)));
}
#ifndef MSG_CMSG_CLOEXEC
result.fcntl(F_SETFD, result.fcntl(F_GETFD) | FD_CLOEXEC);
#endif
return result;
}
<|endoftext|>
|
<commit_before>/// Synchronization mechanism used to signal one or more other threads.
// Usually, one thread signals an event, while one or more other threads wait for an event to become signaled.
// Note: event userdata are copyable/sharable between threads.
// @module event
#include "Event.h"
#include "Poco/Exception.h"
LUA_API int luaopen_poco_event(lua_State* L)
{
return LuaPoco::loadConstructor(L, LuaPoco::EventUserdata::Event);
}
namespace LuaPoco
{
const char* POCO_EVENT_METATABLE_NAME = "Poco.Event.metatable";
EventUserdata::EventUserdata(bool autoReset) :
mEvent(new Poco::Event(autoReset))
{
}
EventUserdata::EventUserdata(const Poco::SharedPtr<Poco::Event>& fm) :
mEvent(fm)
{
}
EventUserdata::~EventUserdata()
{
}
bool EventUserdata::copyToState(lua_State *L)
{
EventUserdata* eud = new(lua_newuserdata(L, sizeof *eud)) EventUserdata(mEvent);
setupPocoUserdata(L, eud, POCO_EVENT_METATABLE_NAME);
return true;
}
// register metatable for this class
bool EventUserdata::registerEvent(lua_State* L)
{
struct UserdataMethod methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "set", set },
{ "tryWait", tryWait },
{ "wait", wait },
{ "reset", reset },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_EVENT_METATABLE_NAME, methods);
return true;
}
/// create a new event userdata.
// @bool[opt] autoReset optional boolean indicating if the event should auto reset after wait() succesfully returns.
// [default = true]
// @return userdata or nil. (error)
// @return error message.
// @function new
int EventUserdata::Event(lua_State* L)
{
int rv = 0;
int firstArg = lua_istable(L, 1) ? 2 : 1;
bool autoReset = true;
if (lua_gettop(L) > 0)
{
luaL_checktype(L, firstArg, LUA_TBOOLEAN);
autoReset = lua_toboolean(L, firstArg);
}
try
{
EventUserdata* eud = new(lua_newuserdata(L, sizeof *eud)) EventUserdata(autoReset);
setupPocoUserdata(L, eud, POCO_EVENT_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
///
// @type event
// metamethod infrastructure
int EventUserdata::metamethod__tostring(lua_State* L)
{
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
lua_pushfstring(L, "Poco.Event (%p)", static_cast<void*>(eud));
return 1;
}
// userdata methods
/// Signals the event.
// If autoReset is true, only one thread waiting for the event can resume execution. If autoReset is false, all waiting threads can resume execution.
// @function set
int EventUserdata::set(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
try
{
eud->mEvent->set();
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
/// Attempts to wait for the event.
// @int ms number of milliseconds to try to wait for the event.
// @return boolean returning true if event was signaled or false if a timeout occured.
// @function tryWait
int EventUserdata::tryWait(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
long ms = luaL_checkinteger(L, 2);
try
{
bool result = false;
result = eud->mEvent->tryWait(ms);
lua_pushboolean(L, result);
rv = 1;
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
/// Waits for the event to become signaled.
// @function wait
int EventUserdata::wait(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
try
{
eud->mEvent->wait();
lua_pushboolean(L, 1);
rv = 1;
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
/// Resets the event to unsignaled state.
// @function reset
int EventUserdata::reset(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
try
{
eud->mEvent->reset();
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
} // LuaPoco
<commit_msg>bug fix for Event.<commit_after>/// Synchronization mechanism used to signal one or more other threads.
// Usually, one thread signals an event, while one or more other threads wait for an event to become signaled.
// Note: event userdata are copyable/sharable between threads.
// @module event
#include "Event.h"
#include "Poco/Exception.h"
LUA_API int luaopen_poco_event(lua_State* L)
{
return LuaPoco::loadConstructor(L, LuaPoco::EventUserdata::Event);
}
namespace LuaPoco
{
const char* POCO_EVENT_METATABLE_NAME = "Poco.Event.metatable";
EventUserdata::EventUserdata(bool autoReset) :
mEvent(new Poco::Event(autoReset))
{
}
EventUserdata::EventUserdata(const Poco::SharedPtr<Poco::Event>& fm) :
mEvent(fm)
{
}
EventUserdata::~EventUserdata()
{
}
bool EventUserdata::copyToState(lua_State *L)
{
EventUserdata* eud = new(lua_newuserdata(L, sizeof *eud)) EventUserdata(mEvent);
setupPocoUserdata(L, eud, POCO_EVENT_METATABLE_NAME);
return true;
}
// register metatable for this class
bool EventUserdata::registerEvent(lua_State* L)
{
struct UserdataMethod methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "set", set },
{ "tryWait", tryWait },
{ "wait", wait },
{ "reset", reset },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_EVENT_METATABLE_NAME, methods);
return true;
}
/// create a new event userdata.
// @bool[opt] autoReset optional boolean indicating if the event should auto reset after wait() succesfully returns.
// [default = true]
// @return userdata or nil. (error)
// @return error message.
// @function new
int EventUserdata::Event(lua_State* L)
{
int rv = 0;
int firstArg = lua_istable(L, 1) ? 2 : 1;
bool autoReset = true;
if (lua_gettop(L) > firstArg)
{
luaL_checktype(L, firstArg, LUA_TBOOLEAN);
autoReset = lua_toboolean(L, firstArg);
}
try
{
EventUserdata* eud = new(lua_newuserdata(L, sizeof *eud)) EventUserdata(autoReset);
setupPocoUserdata(L, eud, POCO_EVENT_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
///
// @type event
// metamethod infrastructure
int EventUserdata::metamethod__tostring(lua_State* L)
{
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
lua_pushfstring(L, "Poco.Event (%p)", static_cast<void*>(eud));
return 1;
}
// userdata methods
/// Signals the event.
// If autoReset is true, only one thread waiting for the event can resume execution. If autoReset is false, all waiting threads can resume execution.
// @function set
int EventUserdata::set(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
try
{
eud->mEvent->set();
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
/// Attempts to wait for the event.
// @int ms number of milliseconds to try to wait for the event.
// @return boolean returning true if event was signaled or false if a timeout occured.
// @function tryWait
int EventUserdata::tryWait(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
long ms = luaL_checkinteger(L, 2);
try
{
bool result = false;
result = eud->mEvent->tryWait(ms);
lua_pushboolean(L, result);
rv = 1;
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
/// Waits for the event to become signaled.
// @function wait
int EventUserdata::wait(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
try
{
eud->mEvent->wait();
lua_pushboolean(L, 1);
rv = 1;
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
/// Resets the event to unsignaled state.
// @function reset
int EventUserdata::reset(lua_State* L)
{
int rv = 0;
EventUserdata* eud = checkPrivateUserdata<EventUserdata>(L, 1);
try
{
eud->mEvent->reset();
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
lua_error(L);
}
catch (...)
{
pushUnknownException(L);
lua_error(L);
}
return rv;
}
} // LuaPoco
<|endoftext|>
|
<commit_before>#include "lusolving.h"
namespace BuiltInFunctions {
namespace EquationSolving {
namespace {
LuSolving instance;
}
RpnOperand LuSolving::calculate(Function::FunctionCalculator *calculator, QList<RpnOperand> actualArguments)
{
m_calculator = calculator;
QList<QList<Number> > coefficients = RpnVector::toTwoDimensional(actualArguments[0].value.value<RpnVector>());
QList<Number> result = findSolution(coefficients);
return RpnOperand(RpnOperandVector, QVariant::fromValue(RpnVector::fromOneDimensional(result)));
}
QList<RpnArgument> LuSolving::requiredArguments()
{
QList<RpnArgument> arguments;
arguments << RpnArgument(RpnOperandVector);
return arguments;
}
QList<Number> LuSolving::findSolution(QList<QList<Number> > coefficients)
{
QList<QList<Number> > workingMatrix = extractWorkingMatrix(coefficients);
QList<Number> freeCoefficients = extractFreeCoefficients(coefficients);
QList<QList<Number> > LuMatrix = decompose(workingMatrix).first();
QList<QList<Number> > shiftMatrix = decompose(workingMatrix).last();
// Forward substitution
QList<Number> forwardSubstitutionResult = emptyVector(freeCoefficients.size());
for (int i = 0; i < LuMatrix.size(); i++) {
// Find sum
Number sum = 0;
for (int j = 0; j < i; j++) {
sum += LuMatrix.at(i).at(j) * forwardSubstitutionResult.at(j);
}
forwardSubstitutionResult[i] =
MathUtils::multiplyVectorByVectorScalar(freeCoefficients, shiftMatrix.at(i)) - sum;
}
// Back substitution
QList<Number> backSubstitutionResult = emptyVector(freeCoefficients.size());
for (int i = LuMatrix.size() - 1; i >= 0; i--) {
// Find sum
Number sum = 0;
for (int j = i + 1; j < LuMatrix.size(); j++) {
sum += LuMatrix.at(i).at(j) * backSubstitutionResult.at(j);
}
backSubstitutionResult[i] = (forwardSubstitutionResult.at(i) - sum) / LuMatrix.at(i).at(i);
}
return backSubstitutionResult;
}
QList<QList<Number> > LuSolving::extractWorkingMatrix(QList<QList<Number> > coefficients)
{
QList<QList<Number> > result = coefficients;
QMutableListIterator<QList<Number> > i(result);
while (i.hasNext()) {
i.next().removeLast();
}
return result;
}
QList<Number> LuSolving::extractFreeCoefficients(QList<QList<Number> > coefficients)
{
QList<Number> result;
foreach (QList<Number> row, coefficients) {
result << row.last();
}
return result;
}
QList<QList<QList<Number> > > LuSolving::decompose(QList<QList<Number> > matrix)
{
QList<RpnOperand> functionArguments;
RpnOperand argument = RpnOperand(RpnOperandVector, QVariant::fromValue(RpnVector::fromTwoDimensional(matrix)));
functionArguments << argument;
// Use PLU decomposition
RpnOperand result = m_calculator->calculate("plu", functionArguments);
return RpnVector::toThreeDimensional(result.value.value<RpnVector>());
}
QList<Number> LuSolving::emptyVector(int size)
{
QList<Number> result;
for (int i = 0; i < size; i++) {
result << 0.0;
}
return result;
}
} // namespace
} // namespace
<commit_msg>Fix for new method name.<commit_after>#include "lusolving.h"
namespace BuiltInFunctions {
namespace EquationSolving {
namespace {
LuSolving instance;
}
RpnOperand LuSolving::calculate(Function::FunctionCalculator *calculator, QList<RpnOperand> actualArguments)
{
m_calculator = calculator;
QList<QList<Number> > coefficients = RpnVector::toTwoDimensional(actualArguments[0].value.value<RpnVector>());
QList<Number> result = findSolution(coefficients);
return RpnOperand(RpnOperandVector, QVariant::fromValue(RpnVector::fromOneDimensional(result)));
}
QList<RpnArgument> LuSolving::requiredArguments()
{
QList<RpnArgument> arguments;
arguments << RpnArgument(RpnOperandVector);
return arguments;
}
QList<Number> LuSolving::findSolution(QList<QList<Number> > coefficients)
{
QList<QList<Number> > workingMatrix = extractWorkingMatrix(coefficients);
QList<Number> freeCoefficients = extractFreeCoefficients(coefficients);
QList<QList<Number> > LuMatrix = decompose(workingMatrix).first();
QList<QList<Number> > shiftMatrix = decompose(workingMatrix).last();
// Forward substitution
QList<Number> forwardSubstitutionResult = emptyVector(freeCoefficients.size());
for (int i = 0; i < LuMatrix.size(); i++) {
// Find sum
Number sum = 0;
for (int j = 0; j < i; j++) {
sum += LuMatrix.at(i).at(j) * forwardSubstitutionResult.at(j);
}
forwardSubstitutionResult[i] =
MathUtils::multiplyVectorByVectorScalar(freeCoefficients, shiftMatrix.at(i)) - sum;
}
// Back substitution
QList<Number> backSubstitutionResult = emptyVector(freeCoefficients.size());
for (int i = LuMatrix.size() - 1; i >= 0; i--) {
// Find sum
Number sum = 0;
for (int j = i + 1; j < LuMatrix.size(); j++) {
sum += LuMatrix.at(i).at(j) * backSubstitutionResult.at(j);
}
backSubstitutionResult[i] = (forwardSubstitutionResult.at(i) - sum) / LuMatrix.at(i).at(i);
}
return backSubstitutionResult;
}
QList<QList<Number> > LuSolving::extractWorkingMatrix(QList<QList<Number> > coefficients)
{
QList<QList<Number> > result = coefficients;
QMutableListIterator<QList<Number> > i(result);
while (i.hasNext()) {
i.next().removeLast();
}
return result;
}
QList<Number> LuSolving::extractFreeCoefficients(QList<QList<Number> > coefficients)
{
QList<Number> result;
foreach (QList<Number> row, coefficients) {
result << row.last();
}
return result;
}
QList<QList<QList<Number> > > LuSolving::decompose(QList<QList<Number> > matrix)
{
QList<RpnOperand> functionArguments;
RpnOperand argument = RpnOperand(RpnOperandVector, QVariant::fromValue(RpnVector::fromTwoDimensional(matrix)));
functionArguments << argument;
// Use PLU decomposition
RpnOperand result = m_calculator->calculate("matrix_plu", functionArguments);
return RpnVector::toThreeDimensional(result.value.value<RpnVector>());
}
QList<Number> LuSolving::emptyVector(int size)
{
QList<Number> result;
for (int i = 0; i < size; i++) {
result << 0.0;
}
return result;
}
} // namespace
} // namespace
<|endoftext|>
|
<commit_before>//===------------------------- string.cpp ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define _LIBCPP_EXTERN_TEMPLATE(...) extern template __VA_ARGS__;
#include "string"
#include "cstdlib"
#include "cwchar"
#include "cerrno"
#include "limits"
#include "stdexcept"
#ifdef _LIBCPP_MSVCRT
#include "support/win32/support.h"
#endif // _LIBCPP_MSVCRT
#include <stdio.h>
_LIBCPP_BEGIN_NAMESPACE_STD
template class __basic_string_common<true>;
template class basic_string<char>;
template class basic_string<wchar_t>;
template
string
operator+<char, char_traits<char>, allocator<char> >(char const*, string const&);
namespace
{
template<typename T>
inline
void throw_helper( const string& msg )
{
#ifndef _LIBCPP_NO_EXCEPTIONS
throw T( msg );
#else
printf("%s\n", msg.c_str());
abort();
#endif
}
inline
void throw_from_string_out_of_range( const string& func )
{
throw_helper<out_of_range>(func + ": out of range");
}
inline
void throw_from_string_invalid_arg( const string& func )
{
throw_helper<invalid_argument>(func + ": no conversion");
}
// as_integer
template<typename V, typename S, typename F>
inline
V
as_integer_helper(const string& func, const S& str, size_t* idx, int base, F f)
{
typename S::value_type* ptr;
const typename S::value_type* const p = str.c_str();
typename remove_reference<decltype(errno)>::type errno_save = errno;
errno = 0;
V r = f(p, &ptr, base);
swap(errno, errno_save);
if (errno_save == ERANGE)
throw_from_string_out_of_range(func);
if (ptr == p)
throw_from_string_invalid_arg(func);
if (idx)
*idx = static_cast<size_t>(ptr - p);
return r;
}
template<typename V, typename S>
inline
V
as_integer(const string& func, const S& s, size_t* idx, int base);
// string
template<>
inline
int
as_integer(const string& func, const string& s, size_t* idx, int base )
{
// Use long as no Stantard string to integer exists.
long r = as_integer_helper<long>( func, s, idx, base, strtol );
if (r < numeric_limits<int>::min() || numeric_limits<int>::max() < r)
throw_from_string_out_of_range(func);
return static_cast<int>(r);
}
template<>
inline
long
as_integer(const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<long>( func, s, idx, base, strtol );
}
template<>
inline
unsigned long
as_integer( const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long>( func, s, idx, base, strtoul );
}
template<>
inline
long long
as_integer( const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<long long>( func, s, idx, base, strtoll );
}
template<>
inline
unsigned long long
as_integer( const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long long>( func, s, idx, base, strtoull );
}
// wstring
template<>
inline
int
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
// Use long as no Stantard string to integer exists.
long r = as_integer_helper<long>( func, s, idx, base, wcstol );
if (r < numeric_limits<int>::min() || numeric_limits<int>::max() < r)
throw_from_string_out_of_range(func);
return static_cast<int>(r);
}
template<>
inline
long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<long>( func, s, idx, base, wcstol );
}
template<>
inline
unsigned long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long>( func, s, idx, base, wcstoul );
}
template<>
inline
long long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<long long>( func, s, idx, base, wcstoll );
}
template<>
inline
unsigned long long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long long>( func, s, idx, base, wcstoull );
}
// as_float
template<typename V, typename S, typename F>
inline
V
as_float_helper(const string& func, const S& str, size_t* idx, F f )
{
typename S::value_type* ptr;
const typename S::value_type* const p = str.c_str();
typename remove_reference<decltype(errno)>::type errno_save = errno;
errno = 0;
V r = f(p, &ptr);
swap(errno, errno_save);
if (errno_save == ERANGE)
throw_from_string_out_of_range(func);
if (ptr == p)
throw_from_string_invalid_arg(func);
if (idx)
*idx = static_cast<size_t>(ptr - p);
return r;
}
template<typename V, typename S>
inline
V as_float( const string& func, const S& s, size_t* idx = nullptr );
template<>
inline
float
as_float( const string& func, const string& s, size_t* idx )
{
return as_float_helper<float>( func, s, idx, strtof );
}
template<>
inline
double
as_float(const string& func, const string& s, size_t* idx )
{
return as_float_helper<double>( func, s, idx, strtod );
}
template<>
inline
long double
as_float( const string& func, const string& s, size_t* idx )
{
return as_float_helper<long double>( func, s, idx, strtold );
}
template<>
inline
float
as_float( const string& func, const wstring& s, size_t* idx )
{
return as_float_helper<float>( func, s, idx, wcstof );
}
template<>
inline
double
as_float( const string& func, const wstring& s, size_t* idx )
{
return as_float_helper<double>( func, s, idx, wcstod );
}
template<>
inline
long double
as_float( const string& func, const wstring& s, size_t* idx )
{
return as_float_helper<long double>( func, s, idx, wcstold );
}
} // unnamed namespace
int
stoi(const string& str, size_t* idx, int base)
{
return as_integer<int>( "stoi", str, idx, base );
}
int
stoi(const wstring& str, size_t* idx, int base)
{
return as_integer<int>( "stoi", str, idx, base );
}
long
stol(const string& str, size_t* idx, int base)
{
return as_integer<long>( "stol", str, idx, base );
}
long
stol(const wstring& str, size_t* idx, int base)
{
return as_integer<long>( "stol", str, idx, base );
}
unsigned long
stoul(const string& str, size_t* idx, int base)
{
return as_integer<unsigned long>( "stoul", str, idx, base );
}
unsigned long
stoul(const wstring& str, size_t* idx, int base)
{
return as_integer<unsigned long>( "stoul", str, idx, base );
}
long long
stoll(const string& str, size_t* idx, int base)
{
return as_integer<long long>( "stoll", str, idx, base );
}
long long
stoll(const wstring& str, size_t* idx, int base)
{
return as_integer<long long>( "stoll", str, idx, base );
}
unsigned long long
stoull(const string& str, size_t* idx, int base)
{
return as_integer<unsigned long long>( "stoull", str, idx, base );
}
unsigned long long
stoull(const wstring& str, size_t* idx, int base)
{
return as_integer<unsigned long long>( "stoull", str, idx, base );
}
float
stof(const string& str, size_t* idx)
{
return as_float<float>( "stof", str, idx );
}
float
stof(const wstring& str, size_t* idx)
{
return as_float<float>( "stof", str, idx );
}
double
stod(const string& str, size_t* idx)
{
return as_float<double>( "stod", str, idx );
}
double
stod(const wstring& str, size_t* idx)
{
return as_float<double>( "stod", str, idx );
}
long double
stold(const string& str, size_t* idx)
{
return as_float<long double>( "stold", str, idx );
}
long double
stold(const wstring& str, size_t* idx)
{
return as_float<long double>( "stold", str, idx );
}
// to_string
namespace
{
// as_string
template<typename S, typename P, typename V >
inline
S
as_string(P sprintf_like, S s, const typename S::value_type* fmt, V a)
{
typedef typename S::size_type size_type;
size_type available = s.size();
while (true)
{
int status = sprintf_like(&s[0], available + 1, fmt, a);
if ( status >= 0 )
{
size_type used = static_cast<size_type>(status);
if ( used <= available )
{
s.resize( used );
break;
}
available = used; // Assume this is advice of how much space we need.
}
else
available = available * 2 + 1;
s.resize(available);
}
return s;
}
template <class S, class V, bool = is_floating_point<V>::value>
struct initial_string;
template <class V, bool b>
struct initial_string<string, V, b>
{
string
operator()() const
{
string s;
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, false>
{
wstring
operator()() const
{
const size_t n = (numeric_limits<unsigned long long>::digits / 3)
+ ((numeric_limits<unsigned long long>::digits % 3) != 0)
+ 1;
wstring s(n, wchar_t());
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, true>
{
wstring
operator()() const
{
wstring s(20, wchar_t());
s.resize(s.capacity());
return s;
}
};
typedef int (*wide_printf)(wchar_t* __restrict, size_t, const wchar_t*__restrict, ...);
inline
wide_printf
get_swprintf()
{
#ifndef _LIBCPP_MSVCRT
return swprintf;
#else
return static_cast<int (__cdecl*)(wchar_t* __restrict, size_t, const wchar_t*__restrict, ...)>(swprintf);
#endif
}
} // unnamed namespace
string to_string(int val)
{
return as_string(snprintf, initial_string<string, int>()(), "%d", val);
}
string to_string(unsigned val)
{
return as_string(snprintf, initial_string<string, unsigned>()(), "%u", val);
}
string to_string(long val)
{
return as_string(snprintf, initial_string<string, long>()(), "%ld", val);
}
string to_string(unsigned long val)
{
return as_string(snprintf, initial_string<string, unsigned long>()(), "%lu", val);
}
string to_string(long long val)
{
return as_string(snprintf, initial_string<string, long long>()(), "%lld", val);
}
string to_string(unsigned long long val)
{
return as_string(snprintf, initial_string<string, unsigned long long>()(), "%llu", val);
}
string to_string(float val)
{
return as_string(snprintf, initial_string<string, float>()(), "%f", val);
}
string to_string(double val)
{
return as_string(snprintf, initial_string<string, double>()(), "%f", val);
}
string to_string(long double val)
{
return as_string(snprintf, initial_string<string, long double>()(), "%Lf", val);
}
wstring to_wstring(int val)
{
return as_string(get_swprintf(), initial_string<wstring, int>()(), L"%d", val);
}
wstring to_wstring(unsigned val)
{
return as_string(get_swprintf(), initial_string<wstring, unsigned>()(), L"%u", val);
}
wstring to_wstring(long val)
{
return as_string(get_swprintf(), initial_string<wstring, long>()(), L"%ld", val);
}
wstring to_wstring(unsigned long val)
{
return as_string(get_swprintf(), initial_string<wstring, unsigned long>()(), L"%lu", val);
}
wstring to_wstring(long long val)
{
return as_string(get_swprintf(), initial_string<wstring, long long>()(), L"%lld", val);
}
wstring to_wstring(unsigned long long val)
{
return as_string(get_swprintf(), initial_string<wstring, unsigned long long>()(), L"%llu", val);
}
wstring to_wstring(float val)
{
return as_string(get_swprintf(), initial_string<wstring, float>()(), L"%f", val);
}
wstring to_wstring(double val)
{
return as_string(get_swprintf(), initial_string<wstring, double>()(), L"%f", val);
}
wstring to_wstring(long double val)
{
return as_string(get_swprintf(), initial_string<wstring, long double>()(), L"%Lf", val);
}
_LIBCPP_END_NAMESPACE_STD
<commit_msg>Fix typo.<commit_after>//===------------------------- string.cpp ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define _LIBCPP_EXTERN_TEMPLATE(...) extern template __VA_ARGS__;
#include "string"
#include "cstdlib"
#include "cwchar"
#include "cerrno"
#include "limits"
#include "stdexcept"
#ifdef _LIBCPP_MSVCRT
#include "support/win32/support.h"
#endif // _LIBCPP_MSVCRT
#include <stdio.h>
_LIBCPP_BEGIN_NAMESPACE_STD
template class __basic_string_common<true>;
template class basic_string<char>;
template class basic_string<wchar_t>;
template
string
operator+<char, char_traits<char>, allocator<char> >(char const*, string const&);
namespace
{
template<typename T>
inline
void throw_helper( const string& msg )
{
#ifndef _LIBCPP_NO_EXCEPTIONS
throw T( msg );
#else
printf("%s\n", msg.c_str());
abort();
#endif
}
inline
void throw_from_string_out_of_range( const string& func )
{
throw_helper<out_of_range>(func + ": out of range");
}
inline
void throw_from_string_invalid_arg( const string& func )
{
throw_helper<invalid_argument>(func + ": no conversion");
}
// as_integer
template<typename V, typename S, typename F>
inline
V
as_integer_helper(const string& func, const S& str, size_t* idx, int base, F f)
{
typename S::value_type* ptr;
const typename S::value_type* const p = str.c_str();
typename remove_reference<decltype(errno)>::type errno_save = errno;
errno = 0;
V r = f(p, &ptr, base);
swap(errno, errno_save);
if (errno_save == ERANGE)
throw_from_string_out_of_range(func);
if (ptr == p)
throw_from_string_invalid_arg(func);
if (idx)
*idx = static_cast<size_t>(ptr - p);
return r;
}
template<typename V, typename S>
inline
V
as_integer(const string& func, const S& s, size_t* idx, int base);
// string
template<>
inline
int
as_integer(const string& func, const string& s, size_t* idx, int base )
{
// Use long as no Standard string to integer exists.
long r = as_integer_helper<long>( func, s, idx, base, strtol );
if (r < numeric_limits<int>::min() || numeric_limits<int>::max() < r)
throw_from_string_out_of_range(func);
return static_cast<int>(r);
}
template<>
inline
long
as_integer(const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<long>( func, s, idx, base, strtol );
}
template<>
inline
unsigned long
as_integer( const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long>( func, s, idx, base, strtoul );
}
template<>
inline
long long
as_integer( const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<long long>( func, s, idx, base, strtoll );
}
template<>
inline
unsigned long long
as_integer( const string& func, const string& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long long>( func, s, idx, base, strtoull );
}
// wstring
template<>
inline
int
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
// Use long as no Stantard string to integer exists.
long r = as_integer_helper<long>( func, s, idx, base, wcstol );
if (r < numeric_limits<int>::min() || numeric_limits<int>::max() < r)
throw_from_string_out_of_range(func);
return static_cast<int>(r);
}
template<>
inline
long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<long>( func, s, idx, base, wcstol );
}
template<>
inline
unsigned long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long>( func, s, idx, base, wcstoul );
}
template<>
inline
long long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<long long>( func, s, idx, base, wcstoll );
}
template<>
inline
unsigned long long
as_integer( const string& func, const wstring& s, size_t* idx, int base )
{
return as_integer_helper<unsigned long long>( func, s, idx, base, wcstoull );
}
// as_float
template<typename V, typename S, typename F>
inline
V
as_float_helper(const string& func, const S& str, size_t* idx, F f )
{
typename S::value_type* ptr;
const typename S::value_type* const p = str.c_str();
typename remove_reference<decltype(errno)>::type errno_save = errno;
errno = 0;
V r = f(p, &ptr);
swap(errno, errno_save);
if (errno_save == ERANGE)
throw_from_string_out_of_range(func);
if (ptr == p)
throw_from_string_invalid_arg(func);
if (idx)
*idx = static_cast<size_t>(ptr - p);
return r;
}
template<typename V, typename S>
inline
V as_float( const string& func, const S& s, size_t* idx = nullptr );
template<>
inline
float
as_float( const string& func, const string& s, size_t* idx )
{
return as_float_helper<float>( func, s, idx, strtof );
}
template<>
inline
double
as_float(const string& func, const string& s, size_t* idx )
{
return as_float_helper<double>( func, s, idx, strtod );
}
template<>
inline
long double
as_float( const string& func, const string& s, size_t* idx )
{
return as_float_helper<long double>( func, s, idx, strtold );
}
template<>
inline
float
as_float( const string& func, const wstring& s, size_t* idx )
{
return as_float_helper<float>( func, s, idx, wcstof );
}
template<>
inline
double
as_float( const string& func, const wstring& s, size_t* idx )
{
return as_float_helper<double>( func, s, idx, wcstod );
}
template<>
inline
long double
as_float( const string& func, const wstring& s, size_t* idx )
{
return as_float_helper<long double>( func, s, idx, wcstold );
}
} // unnamed namespace
int
stoi(const string& str, size_t* idx, int base)
{
return as_integer<int>( "stoi", str, idx, base );
}
int
stoi(const wstring& str, size_t* idx, int base)
{
return as_integer<int>( "stoi", str, idx, base );
}
long
stol(const string& str, size_t* idx, int base)
{
return as_integer<long>( "stol", str, idx, base );
}
long
stol(const wstring& str, size_t* idx, int base)
{
return as_integer<long>( "stol", str, idx, base );
}
unsigned long
stoul(const string& str, size_t* idx, int base)
{
return as_integer<unsigned long>( "stoul", str, idx, base );
}
unsigned long
stoul(const wstring& str, size_t* idx, int base)
{
return as_integer<unsigned long>( "stoul", str, idx, base );
}
long long
stoll(const string& str, size_t* idx, int base)
{
return as_integer<long long>( "stoll", str, idx, base );
}
long long
stoll(const wstring& str, size_t* idx, int base)
{
return as_integer<long long>( "stoll", str, idx, base );
}
unsigned long long
stoull(const string& str, size_t* idx, int base)
{
return as_integer<unsigned long long>( "stoull", str, idx, base );
}
unsigned long long
stoull(const wstring& str, size_t* idx, int base)
{
return as_integer<unsigned long long>( "stoull", str, idx, base );
}
float
stof(const string& str, size_t* idx)
{
return as_float<float>( "stof", str, idx );
}
float
stof(const wstring& str, size_t* idx)
{
return as_float<float>( "stof", str, idx );
}
double
stod(const string& str, size_t* idx)
{
return as_float<double>( "stod", str, idx );
}
double
stod(const wstring& str, size_t* idx)
{
return as_float<double>( "stod", str, idx );
}
long double
stold(const string& str, size_t* idx)
{
return as_float<long double>( "stold", str, idx );
}
long double
stold(const wstring& str, size_t* idx)
{
return as_float<long double>( "stold", str, idx );
}
// to_string
namespace
{
// as_string
template<typename S, typename P, typename V >
inline
S
as_string(P sprintf_like, S s, const typename S::value_type* fmt, V a)
{
typedef typename S::size_type size_type;
size_type available = s.size();
while (true)
{
int status = sprintf_like(&s[0], available + 1, fmt, a);
if ( status >= 0 )
{
size_type used = static_cast<size_type>(status);
if ( used <= available )
{
s.resize( used );
break;
}
available = used; // Assume this is advice of how much space we need.
}
else
available = available * 2 + 1;
s.resize(available);
}
return s;
}
template <class S, class V, bool = is_floating_point<V>::value>
struct initial_string;
template <class V, bool b>
struct initial_string<string, V, b>
{
string
operator()() const
{
string s;
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, false>
{
wstring
operator()() const
{
const size_t n = (numeric_limits<unsigned long long>::digits / 3)
+ ((numeric_limits<unsigned long long>::digits % 3) != 0)
+ 1;
wstring s(n, wchar_t());
s.resize(s.capacity());
return s;
}
};
template <class V>
struct initial_string<wstring, V, true>
{
wstring
operator()() const
{
wstring s(20, wchar_t());
s.resize(s.capacity());
return s;
}
};
typedef int (*wide_printf)(wchar_t* __restrict, size_t, const wchar_t*__restrict, ...);
inline
wide_printf
get_swprintf()
{
#ifndef _LIBCPP_MSVCRT
return swprintf;
#else
return static_cast<int (__cdecl*)(wchar_t* __restrict, size_t, const wchar_t*__restrict, ...)>(swprintf);
#endif
}
} // unnamed namespace
string to_string(int val)
{
return as_string(snprintf, initial_string<string, int>()(), "%d", val);
}
string to_string(unsigned val)
{
return as_string(snprintf, initial_string<string, unsigned>()(), "%u", val);
}
string to_string(long val)
{
return as_string(snprintf, initial_string<string, long>()(), "%ld", val);
}
string to_string(unsigned long val)
{
return as_string(snprintf, initial_string<string, unsigned long>()(), "%lu", val);
}
string to_string(long long val)
{
return as_string(snprintf, initial_string<string, long long>()(), "%lld", val);
}
string to_string(unsigned long long val)
{
return as_string(snprintf, initial_string<string, unsigned long long>()(), "%llu", val);
}
string to_string(float val)
{
return as_string(snprintf, initial_string<string, float>()(), "%f", val);
}
string to_string(double val)
{
return as_string(snprintf, initial_string<string, double>()(), "%f", val);
}
string to_string(long double val)
{
return as_string(snprintf, initial_string<string, long double>()(), "%Lf", val);
}
wstring to_wstring(int val)
{
return as_string(get_swprintf(), initial_string<wstring, int>()(), L"%d", val);
}
wstring to_wstring(unsigned val)
{
return as_string(get_swprintf(), initial_string<wstring, unsigned>()(), L"%u", val);
}
wstring to_wstring(long val)
{
return as_string(get_swprintf(), initial_string<wstring, long>()(), L"%ld", val);
}
wstring to_wstring(unsigned long val)
{
return as_string(get_swprintf(), initial_string<wstring, unsigned long>()(), L"%lu", val);
}
wstring to_wstring(long long val)
{
return as_string(get_swprintf(), initial_string<wstring, long long>()(), L"%lld", val);
}
wstring to_wstring(unsigned long long val)
{
return as_string(get_swprintf(), initial_string<wstring, unsigned long long>()(), L"%llu", val);
}
wstring to_wstring(float val)
{
return as_string(get_swprintf(), initial_string<wstring, float>()(), L"%f", val);
}
wstring to_wstring(double val)
{
return as_string(get_swprintf(), initial_string<wstring, double>()(), L"%f", val);
}
wstring to_wstring(long double val)
{
return as_string(get_swprintf(), initial_string<wstring, long double>()(), L"%Lf", val);
}
_LIBCPP_END_NAMESPACE_STD
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_CORE_MSGPACK_OBSERVER_HPP
#define MJOLNIR_CORE_MSGPACK_OBSERVER_HPP
#include <mjolnir/util/macro.hpp>
#include <mjolnir/core/ObserverBase.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/Unit.hpp>
#include <fstream>
#include <iomanip>
namespace mjolnir
{
// Serialize System into MsgPack format that is equivalent to the following JSON
// In the current implementation, the order should be preserved.
// fixmap<3> {
// "boundary" : fixmap<2>{"lower": [real, real, real],
// "upper": [real, real, real]}
// or nil,
// "particles" : array<N>[
// fixmap<6>{
// "mass" : real,
// "position": [real, real, real],
// "velocity": [real, real, real],
// "force" : [real, real, real],
// "name" : string,
// "group" : string,
// }, ...
// ]
// "attributres" : map<N>{"temperature": real, ...},
// }
template<typename traitsT>
class MsgPackObserver final : public ObserverBase<traitsT>
{
public:
using base_type = ObserverBase<traitsT>;
using traits_type = typename base_type::traits_type;
using real_type = typename base_type::real_type;
using coordinate_type = typename base_type::coordinate_type;
using system_type = typename base_type::system_type;
using forcefield_type = typename base_type::forcefield_type;
// system attribute container type. map-like class.
using attribute_type = typename system_type::attribute_type;
public:
explicit MsgPackObserver(const std::string& filename_prefix)
: base_type(), prefix_(filename_prefix),
filename_(filename_prefix + std::string(".msg"))
{}
~MsgPackObserver() override {}
void initialize(const std::size_t, const real_type,
const system_type&, const forcefield_type&) override
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
MJOLNIR_LOG_NOTICE("checkpoint file is ", filename_);
// check the specified file can be opened.
// Here, it does not clear the content.
std::ofstream ofs(filename_, std::ios_base::app);
if(!ofs.good())
{
MJOLNIR_LOG_ERROR("file open error: ", filename_);
throw std::runtime_error("file open error");
}
ofs.close();
return;
}
void update(const std::size_t, const real_type,
const system_type&, const forcefield_type&) override
{
return; // do nothing.
}
void output(const std::size_t, const real_type,
const system_type& sys, const forcefield_type&) override
{
// 0b'1000'0011
// 0x 8 3
constexpr std::uint8_t fixmap3_code = 0x83;
// ---------------------------------------------------------------------
// clear buffer before writing to it.
this->buffer_.clear();
this->buffer_.push_back(fixmap3_code);
auto buffer_iterator = std::back_inserter(buffer_);
// ---------------------------------------------------------------------
// write boundary condition.
to_msgpack("boundary", buffer_iterator);
to_msgpack(sys.boundary(), buffer_iterator);
// ---------------------------------------------------------------------
// append particles
to_msgpack("particles", buffer_iterator);
const auto num_particles = sys.size();
if(num_particles < 16)
{
// 0b'1001'0000
// 0x 9 0
std::uint8_t fixarray_code = num_particles;
fixarray_code |= std::uint8_t(0x90);
buffer_.push_back(fixarray_code);
}
else if(num_particles < 65536)
{
const std::uint16_t size = num_particles;
buffer_.push_back(std::uint8_t(0xdc));
to_big_endian(size, buffer_iterator);
}
else
{
const std::uint32_t size = num_particles;
buffer_.push_back(std::uint8_t(0xdd));
to_big_endian(size, buffer_iterator);
}
constexpr std::uint8_t fixmap6_code = 0x86;
for(std::size_t i=0; i<sys.size(); ++i)
{
buffer_.push_back(fixmap6_code);
to_msgpack("mass", buffer_iterator);
to_msgpack(sys.mass(i), buffer_iterator);
to_msgpack("position", buffer_iterator);
to_msgpack(sys.position(i), buffer_iterator);
to_msgpack("velocity", buffer_iterator);
to_msgpack(sys.velocity(i), buffer_iterator);
to_msgpack("force", buffer_iterator);
to_msgpack(sys.force(i), buffer_iterator);
to_msgpack("name", buffer_iterator);
to_msgpack(sys.name(i), buffer_iterator);
to_msgpack("group", buffer_iterator);
to_msgpack(sys.group(i), buffer_iterator);
}
// ---------------------------------------------------------------------
// write attributes list
to_msgpack("attributes", buffer_iterator);
to_msgpack(sys.attributes(), buffer_iterator);
// -------------------------------------------------------------------
// overwrite .msg file by the current status
std::ofstream ofs(filename_);
if(!ofs.good())
{
throw std::runtime_error("file open error: " + filename_);
}
ofs.write(reinterpret_cast<const char*>(buffer_.data()),buffer_.size());
ofs.close();
return;
}
void finalize(const std::size_t step, const real_type t,
const system_type& sys, const forcefield_type& ff) override
{
this->output(step, t, sys, ff);
return;
}
std::string const& prefix() const noexcept override {return prefix_;}
private:
template<typename OutputIterator>
void to_msgpack(const std::string& str, OutputIterator& out)
{
constexpr std::uint8_t str8_code = 0xd9;
constexpr std::uint8_t str16_code = 0xda;
constexpr std::uint8_t str32_code = 0xdb;
// add a byte tag and length
if(str.size() < 32)
{
// 0b'1010'0000
// 0x a 0
std::uint8_t fixstr_code = str.size();
fixstr_code |= std::uint8_t(0xa0);
*out = fixstr_code; ++out;
}
else if(str.size() <= 0xFF)
{
const std::uint8_t size = str.size();
*out = str8_code; ++out;
*out = size; ++out;
}
else if(str.size() <= 0xFFFF)
{
const std::uint16_t size = str.size();
*out = str16_code; ++out;
to_big_endian(size, out);
}
else
{
const std::uint32_t size = str.size();
*out = str32_code; ++out;
to_big_endian(size, out);
}
// write string body
for(const std::uint8_t c : str)
{
*out = c; ++out;
}
return ;
}
template<typename OutputIterator>
void to_msgpack(const float& x, OutputIterator& out)
{
constexpr std::uint8_t f32_code = 0xca;
*out = f32_code; ++out;
to_big_endian(x, out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const double& x, OutputIterator& out)
{
constexpr std::uint8_t f64_code = 0xcb;
*out = f64_code; ++out;
to_big_endian(x, out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const coordinate_type& v, OutputIterator& out)
{
// [float, float, float]
// fixmap (3)
// 0b'1001'0011
// 0x 9 3
constexpr std::uint8_t fixarray3_code = 0x93;
*out = fixarray3_code; ++out;
to_msgpack(math::X(v), out);
to_msgpack(math::Y(v), out);
to_msgpack(math::Z(v), out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const UnlimitedBoundary<real_type, coordinate_type>&,
OutputIterator& out)
{
// UnlimitedBoundary is represented as nil
*out = std::uint8_t(0xc0); ++out;
return ;
}
template<typename OutputIterator>
void to_msgpack(
const CuboidalPeriodicBoundary<real_type, coordinate_type>& boundary,
OutputIterator& out)
{
constexpr std::uint8_t fixmap2_t = 0x82;
*out = fixmap2_t; ++out;
to_msgpack("lower", out);
to_msgpack(boundary.lower_bound(), out);
to_msgpack("upper", out);
to_msgpack(boundary.upper_bound(), out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const attribute_type& attr, OutputIterator& out)
{
constexpr std::uint8_t map16_code = 0xde;
constexpr std::uint8_t map32_code = 0xdf;
if(attr.size() < 16)
{
std::uint8_t fixmap_code = attr.size();
fixmap_code |= std::uint8_t(0x80);
*out = fixmap_code; ++out;
}
else if(attr.size() < 65536)
{
const std::uint16_t size = attr.size();
*out = map16_code; ++out;
to_big_endian(size, out);
}
else
{
const std::uint32_t size = attr.size();
*out = map32_code; ++out;
to_big_endian(size, out);
}
for(const auto& keyval : attr)
{
// string -> real
to_msgpack(keyval.first, out);
to_msgpack(keyval.second, out);
}
return ;
}
template<typename T, typename OutputIterator>
void to_big_endian(const T& val, OutputIterator& dst)
{
const char* src = reinterpret_cast<const char*>(std::addressof(val));
#if defined(MJOLNIR_WITH_LITTLE_ENDIAN)
// If the architecture uses little endian, we need to reverse bytes.
std::reverse_copy(src, src + sizeof(T), dst);
#elif defined(MJOLNIR_WITH_BIG_ENDIAN)
// If the architecture uses big endian, we don't need to do anything.
std::copy(src, src + sizeof(T), dst);
#else
# error "Unknown platform."
#endif
return ;
}
private:
std::string prefix_;
std::string filename_;
std::vector<std::uint8_t> buffer_;
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class MsgPackObserver<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class MsgPackObserver<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class MsgPackObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class MsgPackObserver<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif // MJOLNIR_CORE_MSGPACK_OBSERVER_HPP
<commit_msg>refactor: use just +, not a bit operator<commit_after>#ifndef MJOLNIR_CORE_MSGPACK_OBSERVER_HPP
#define MJOLNIR_CORE_MSGPACK_OBSERVER_HPP
#include <mjolnir/util/macro.hpp>
#include <mjolnir/core/ObserverBase.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/Unit.hpp>
#include <fstream>
#include <iomanip>
namespace mjolnir
{
// Serialize System into MsgPack format that is equivalent to the following JSON
// In the current implementation, the order should be preserved.
// fixmap<3> {
// "boundary" : fixmap<2>{"lower": [real, real, real],
// "upper": [real, real, real]}
// or nil,
// "particles" : array<N>[
// fixmap<6>{
// "mass" : real,
// "position": [real, real, real],
// "velocity": [real, real, real],
// "force" : [real, real, real],
// "name" : string,
// "group" : string,
// }, ...
// ]
// "attributres" : map<N>{"temperature": real, ...},
// }
template<typename traitsT>
class MsgPackObserver final : public ObserverBase<traitsT>
{
public:
using base_type = ObserverBase<traitsT>;
using traits_type = typename base_type::traits_type;
using real_type = typename base_type::real_type;
using coordinate_type = typename base_type::coordinate_type;
using system_type = typename base_type::system_type;
using forcefield_type = typename base_type::forcefield_type;
// system attribute container type. map-like class.
using attribute_type = typename system_type::attribute_type;
public:
explicit MsgPackObserver(const std::string& filename_prefix)
: base_type(), prefix_(filename_prefix),
filename_(filename_prefix + std::string(".msg"))
{}
~MsgPackObserver() override {}
void initialize(const std::size_t, const real_type,
const system_type&, const forcefield_type&) override
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
MJOLNIR_LOG_NOTICE("checkpoint file is ", filename_);
// check the specified file can be opened.
// Here, it does not clear the content.
std::ofstream ofs(filename_, std::ios_base::app);
if(!ofs.good())
{
MJOLNIR_LOG_ERROR("file open error: ", filename_);
throw std::runtime_error("file open error");
}
ofs.close();
return;
}
void update(const std::size_t, const real_type,
const system_type&, const forcefield_type&) override
{
return; // do nothing.
}
void output(const std::size_t, const real_type,
const system_type& sys, const forcefield_type&) override
{
// 0b'1000'0011
// 0x 8 3
constexpr std::uint8_t fixmap3_code = 0x83;
// ---------------------------------------------------------------------
// clear buffer before writing to it.
this->buffer_.clear();
this->buffer_.push_back(fixmap3_code);
auto buffer_iterator = std::back_inserter(buffer_);
// ---------------------------------------------------------------------
// write boundary condition.
to_msgpack("boundary", buffer_iterator);
to_msgpack(sys.boundary(), buffer_iterator);
// ---------------------------------------------------------------------
// append particles
to_msgpack("particles", buffer_iterator);
const auto num_particles = sys.size();
if(num_particles < 16)
{
// 0b'1001'0000
// 0x 9 0
buffer_.push_back(std::uint8_t(num_particles) + std::uint8_t(0x90));
}
else if(num_particles < 65536)
{
const std::uint16_t size = num_particles;
buffer_.push_back(std::uint8_t(0xdc));
to_big_endian(size, buffer_iterator);
}
else
{
const std::uint32_t size = num_particles;
buffer_.push_back(std::uint8_t(0xdd));
to_big_endian(size, buffer_iterator);
}
constexpr std::uint8_t fixmap6_code = 0x86;
for(std::size_t i=0; i<sys.size(); ++i)
{
buffer_.push_back(fixmap6_code);
to_msgpack("mass", buffer_iterator);
to_msgpack(sys.mass(i), buffer_iterator);
to_msgpack("position", buffer_iterator);
to_msgpack(sys.position(i), buffer_iterator);
to_msgpack("velocity", buffer_iterator);
to_msgpack(sys.velocity(i), buffer_iterator);
to_msgpack("force", buffer_iterator);
to_msgpack(sys.force(i), buffer_iterator);
to_msgpack("name", buffer_iterator);
to_msgpack(sys.name(i), buffer_iterator);
to_msgpack("group", buffer_iterator);
to_msgpack(sys.group(i), buffer_iterator);
}
// ---------------------------------------------------------------------
// write attributes list
to_msgpack("attributes", buffer_iterator);
to_msgpack(sys.attributes(), buffer_iterator);
// -------------------------------------------------------------------
// overwrite .msg file by the current status
std::ofstream ofs(filename_);
if(!ofs.good())
{
throw std::runtime_error("file open error: " + filename_);
}
ofs.write(reinterpret_cast<const char*>(buffer_.data()),buffer_.size());
ofs.close();
return;
}
void finalize(const std::size_t step, const real_type t,
const system_type& sys, const forcefield_type& ff) override
{
this->output(step, t, sys, ff);
return;
}
std::string const& prefix() const noexcept override {return prefix_;}
private:
template<typename OutputIterator>
void to_msgpack(const std::string& str, OutputIterator& out)
{
constexpr std::uint8_t str8_code = 0xd9;
constexpr std::uint8_t str16_code = 0xda;
constexpr std::uint8_t str32_code = 0xdb;
// add a byte tag and length
if(str.size() < 32)
{
// 0b'1010'0000
// 0x a 0
*out = (std::uint8_t(str.size()) + std::uint8_t(0xa0)); ++out;
}
else if(str.size() <= 0xFF)
{
const std::uint8_t size = str.size();
*out = str8_code; ++out;
*out = size; ++out;
}
else if(str.size() <= 0xFFFF)
{
const std::uint16_t size = str.size();
*out = str16_code; ++out;
to_big_endian(size, out);
}
else
{
const std::uint32_t size = str.size();
*out = str32_code; ++out;
to_big_endian(size, out);
}
// write string body
for(const std::uint8_t c : str)
{
*out = c; ++out;
}
return ;
}
template<typename OutputIterator>
void to_msgpack(const float& x, OutputIterator& out)
{
constexpr std::uint8_t f32_code = 0xca;
*out = f32_code; ++out;
to_big_endian(x, out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const double& x, OutputIterator& out)
{
constexpr std::uint8_t f64_code = 0xcb;
*out = f64_code; ++out;
to_big_endian(x, out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const coordinate_type& v, OutputIterator& out)
{
// [float, float, float]
// fixmap (3)
// 0b'1001'0011
// 0x 9 3
constexpr std::uint8_t fixarray3_code = 0x93;
*out = fixarray3_code; ++out;
to_msgpack(math::X(v), out);
to_msgpack(math::Y(v), out);
to_msgpack(math::Z(v), out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const UnlimitedBoundary<real_type, coordinate_type>&,
OutputIterator& out)
{
// UnlimitedBoundary is represented as nil
*out = std::uint8_t(0xc0); ++out;
return ;
}
template<typename OutputIterator>
void to_msgpack(
const CuboidalPeriodicBoundary<real_type, coordinate_type>& boundary,
OutputIterator& out)
{
constexpr std::uint8_t fixmap2_t = 0x82;
*out = fixmap2_t; ++out;
to_msgpack("lower", out);
to_msgpack(boundary.lower_bound(), out);
to_msgpack("upper", out);
to_msgpack(boundary.upper_bound(), out);
return ;
}
template<typename OutputIterator>
void to_msgpack(const attribute_type& attr, OutputIterator& out)
{
constexpr std::uint8_t map16_code = 0xde;
constexpr std::uint8_t map32_code = 0xdf;
if(attr.size() < 16)
{
*out = (std::uint8_t(attr.size()) + std::uint8_t(0x80)); ++out;
}
else if(attr.size() < 65536)
{
const std::uint16_t size = attr.size();
*out = map16_code; ++out;
to_big_endian(size, out);
}
else
{
const std::uint32_t size = attr.size();
*out = map32_code; ++out;
to_big_endian(size, out);
}
for(const auto& keyval : attr)
{
// string -> real
to_msgpack(keyval.first, out);
to_msgpack(keyval.second, out);
}
return ;
}
template<typename T, typename OutputIterator>
void to_big_endian(const T& val, OutputIterator& dst)
{
const char* src = reinterpret_cast<const char*>(std::addressof(val));
#if defined(MJOLNIR_WITH_LITTLE_ENDIAN)
// If the architecture uses little endian, we need to reverse bytes.
std::reverse_copy(src, src + sizeof(T), dst);
#elif defined(MJOLNIR_WITH_BIG_ENDIAN)
// If the architecture uses big endian, we don't need to do anything.
std::copy(src, src + sizeof(T), dst);
#else
# error "Unknown platform."
#endif
return ;
}
private:
std::string prefix_;
std::string filename_;
std::vector<std::uint8_t> buffer_;
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class MsgPackObserver<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class MsgPackObserver<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class MsgPackObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class MsgPackObserver<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif // MJOLNIR_CORE_MSGPACK_OBSERVER_HPP
<|endoftext|>
|
<commit_before>#include <node.h>
#include <./gpio_functions.h>
using namespace v8;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
int result = lightLED();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world" + result));
}
void init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(addon, init)<commit_msg>add new module<commit_after>#include <node.h>
#include <gpio_functions.h>
using namespace v8;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
int result = lightLED();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world" + result));
}
void init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(addon, init)<|endoftext|>
|
<commit_before>/***************************************************************************
system.cpp - class System
-------------------
begin : 2003/07/11
copyright : (C) 2003 by Michael CATANZARITI
email : mcatan@free.fr
***************************************************************************/
/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the LICENSE.txt file. *
***************************************************************************/
#include <log4cxx/helpers/system.h>
#if defined(HAVE_FTIME)
#include <sys/timeb.h>
#endif
#if defined(HAVE_GETTIMEOFDAY)
#include <sys/time.h>
#endif
#include <time.h>
#include <log4cxx/helpers/properties.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
int64_t System::currentTimeMillis()
{
#if defined(HAVE_GETTIMEOFDAY)
timeval tp;
::gettimeofday(&tp, 0);
return ((int64_t)tp.tv_sec * 1000) + (int64_t)(tp.tv_usec / 1000);
#elif defined(HAVE_FTIME)
struct timeb tp;
::ftime(&tp);
time_t time1 = time(0);
return ((int64_t)tp.time * 1000) + (int64_t)tp.millitm;
#else
return (int64_t)::time(0) * 1000;
#endif
}
String System::getProperty(const String& key)
{
if (key.empty())
{
throw IllegalArgumentException(_T("key is empty"));
}
USES_CONVERSION;
char * value = ::getenv(T2A(key.c_str()));
if (value == 0)
{
return String();
}
else
{
return A2T(value);
}
}
void System::setProperty(const String& key, const String& value)
{
if (key.empty())
{
throw IllegalArgumentException(_T("key is empty"));
}
String strEnv = key + _T("=") + value;
USES_CONVERSION;
::putenv((char *)T2A(strEnv.c_str()));
}
void System::setProperties(const Properties& props)
{
std::vector<String> propertyNames = props.propertyNames();
for (std::vector<String>::iterator it = propertyNames.begin();
it != propertyNames.end(); it++)
{
const String& propertyName = *it;
setProperty(propertyName, props.getProperty(propertyName));
}
}
<commit_msg>fixed Linux glibc specific bug<commit_after>/***************************************************************************
system.cpp - class System
-------------------
begin : 2003/07/11
copyright : (C) 2003 by Michael CATANZARITI
email : mcatan@free.fr
***************************************************************************/
/***************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* *
* This software is published under the terms of the Apache Software *
* License version 1.1, a copy of which has been included with this *
* distribution in the LICENSE.txt file. *
***************************************************************************/
#include <log4cxx/helpers/system.h>
#if defined(HAVE_FTIME)
#include <sys/timeb.h>
#endif
#if defined(HAVE_GETTIMEOFDAY)
#include <sys/time.h>
#endif
#include <time.h>
#include <log4cxx/helpers/properties.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
int64_t System::currentTimeMillis()
{
#if defined(HAVE_GETTIMEOFDAY)
timeval tp;
::gettimeofday(&tp, 0);
return ((int64_t)tp.tv_sec * 1000) + (int64_t)(tp.tv_usec / 1000);
#elif defined(HAVE_FTIME)
struct timeb tp;
::ftime(&tp);
time_t time1 = time(0);
return ((int64_t)tp.time * 1000) + (int64_t)tp.millitm;
#else
return (int64_t)::time(0) * 1000;
#endif
}
String System::getProperty(const String& key)
{
if (key.empty())
{
throw IllegalArgumentException(_T("key is empty"));
}
USES_CONVERSION;
char * value = ::getenv(T2A(key.c_str()));
if (value == 0)
{
return String();
}
else
{
return A2T(value);
}
}
void System::setProperty(const String& key, const String& value)
{
if (key.empty())
{
throw IllegalArgumentException(_T("key is empty"));
}
#ifdef WIN32
String strEnv = key + _T("=") + value;
USES_CONVERSION;
::putenv((char *)T2A(strEnv.c_str()));
#else
/* wARNING !
We don't use putenv with glibc, because it doesn't make
a copy of the string, but try to keep the pointer
cf. man 3 putenv.
*/
USES_CONVERSION;
std::string name = T2A(key.c_str());
std::string val = T2A(value.c_str());
::setenv(name.c_str(), val.c_str(), 1);
#endif
}
void System::setProperties(const Properties& props)
{
std::vector<String> propertyNames = props.propertyNames();
for (std::vector<String>::iterator it = propertyNames.begin();
it != propertyNames.end(); it++)
{
const String& propertyName = *it;
setProperty(propertyName, props.getProperty(propertyName));
}
}
<|endoftext|>
|
<commit_before>#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"
#include "syntax-highlighter-helper.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("Grabber");
app.setApplicationVersion(VERSION);
app.setOrganizationName("Bionus");
app.setOrganizationDomain("bionus.fr.cr");
qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper");
// Copy settings files to writable directory
const QStringList toCopy { "sites/", "themes/", "webservices/" };
for (const QString &tgt : toCopy) {
const QString from = savePath(tgt, true, false);
const QString to = savePath(tgt, true, true);
if (!QDir(to).exists() && QDir(from).exists()) {
copyRecursively(from, to);
}
}
const QUrl url(QStringLiteral("qrc:/main-screen.qml"));
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
Profile profile(savePath());
MainScreen mainScreen(&profile);
engine.rootContext()->setContextProperty("backend", &mainScreen);
engine.load(url);
return app.exec();
}
<commit_msg>Set proper ownership on C++ backend<commit_after>#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"
#include "syntax-highlighter-helper.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("Grabber");
app.setApplicationVersion(VERSION);
app.setOrganizationName("Bionus");
app.setOrganizationDomain("bionus.fr.cr");
qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper");
// Copy settings files to writable directory
const QStringList toCopy { "sites/", "themes/", "webservices/" };
for (const QString &tgt : toCopy) {
const QString from = savePath(tgt, true, false);
const QString to = savePath(tgt, true, true);
if (!QDir(to).exists() && QDir(from).exists()) {
copyRecursively(from, to);
}
}
const QUrl url(QStringLiteral("qrc:/main-screen.qml"));
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
Profile profile(savePath());
MainScreen mainScreen(&profile, &engine);
engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);
engine.rootContext()->setContextProperty("backend", &mainScreen);
engine.load(url);
return app.exec();
}
<|endoftext|>
|
<commit_before>// JSON private
#include "json/json_serialize.h"
// public
#include <disir/disir.h>
// standard
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
#include <string>
using namespace dio;
ConfigWriter::ConfigWriter (struct disir_instance *disir)
: JsonIO (disir)
{
m_contextConfig = NULL;
}
ConfigWriter::~ConfigWriter ()
{
if (m_contextConfig)
{
dc_putcontext (&m_contextConfig);
}
}
enum disir_status
ConfigWriter::serialize (struct disir_config *config, std::ostream& stream)
{
enum disir_status status;
Json::StyledWriter writer;
std::string outputJson;
status = DISIR_STATUS_OK;
// Retrieving the config's context object
m_contextConfig = dc_config_getcontext (config);
if (m_contextConfig == NULL )
{
disir_error_set (m_disir, "could not retrieve cconfig context object");
return DISIR_STATUS_INTERNAL_ERROR;
}
status = set_config_version (m_contextConfig, m_configRoot);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = _serialize_context (m_contextConfig, m_configRoot[ATTRIBUTE_KEY_CONFIG]);
if (status != DISIR_STATUS_OK)
{
goto end;
}
stream << writer.writeOrdered (m_configRoot);
end:
dc_putcontext (&m_contextConfig);
return status;
}
enum disir_status
ConfigWriter::serialize (struct disir_config *config, std::string& output)
{
enum disir_status status;
Json::StyledWriter writer;
std::string outputJson;
// Retrieving the config's context object
m_contextConfig = dc_config_getcontext (config);
if (m_contextConfig == NULL )
{
disir_error_set (m_disir, "could not retrieve cconfig context object");
return DISIR_STATUS_INTERNAL_ERROR;
}
status = set_config_version (m_contextConfig, m_configRoot);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = _serialize_context (m_contextConfig, m_configRoot[ATTRIBUTE_KEY_CONFIG]);
if (status != DISIR_STATUS_OK)
{
goto end;
}
output = writer.writeOrdered (m_configRoot);
end:
dc_putcontext (&m_contextConfig);
return status;
}
enum disir_status
ConfigWriter::set_config_version (struct disir_context *context_config, Json::Value& root)
{
struct disir_version version;
enum disir_status status;
char buf[500];
char *temp;
status = dc_get_version (context_config, &version);
if (status != DISIR_STATUS_OK)
{
disir_error_set (m_disir, "Could not read config version: (%s)",
disir_status_string (status));
return status;
}
temp = dc_version_string ((char *)buf, (int32_t)500, &version);
if (temp == NULL)
{
disir_error_set (m_disir, "Error retrieving semantic version string");
return DISIR_STATUS_INTERNAL_ERROR;
}
root[ATTRIBUTE_KEY_VERSION] = buf;
return status;
}
// Mapping child node (section) to key (section name)
enum disir_status
ConfigWriter::set_section_keyname (struct disir_context *context, Json::Value& parent,
Json::Value& sectionVal)
{
std::string name;
enum disir_status status;
status = get_context_key (context, name);
if (status != DISIR_STATUS_OK)
{
// logged
return status;
}
serialize_duplicate_entries (parent, sectionVal, name);
return status;
}
enum disir_status
ConfigWriter::get_context_key (struct disir_context *context, std::string& key)
{
const char *name;
int32_t size;
enum disir_status status;
status = dc_get_name (context, &name, &size);
if (status != DISIR_STATUS_OK) {
// Should not happen
disir_error_set (m_disir, "Disir returned an error from dc_get_name: %s",
disir_status_string (status));
return status;
}
key = std::string (name, size);
return status;
}
void
ConfigWriter::serialize_duplicate_entries (Json::Value& parent,
Json::Value& child, const std::string name)
{
Json::Value entries;
if (parent[name].isArray())
{
parent[name].append (child);
}
else if (parent[name].isNull() == false)
{
entries = Json::arrayValue;
entries.append (parent[name]);
entries.append (child);
child = entries;
parent[name] = child;
}
else
{
parent[name] = child;
}
}
// Wraps libdisir dc_get_value to handle arbitrary value sizes
enum disir_status
ConfigWriter::set_keyval (struct disir_context *context, std::string name, Json::Value& node)
{
enum disir_status status;
enum disir_value_type type;
int32_t size;
double floatval;
int64_t intval;
const char *stringval;
uint8_t boolval;
std::string buf;
Json::Value keyval;
status = dc_get_value_type (context, &type);
if (status != DISIR_STATUS_OK)
{
disir_error_set (m_disir, "Could not obtain context_value_type (%s)",
disir_status_string (status));
return status;
}
switch (type) {
case DISIR_VALUE_TYPE_STRING:
status = dc_get_value_string (context, &stringval, &size);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = stringval;
break;
case DISIR_VALUE_TYPE_INTEGER:
status = dc_get_value_integer (context, &intval);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = (Json::Int64)intval;
break;
case DISIR_VALUE_TYPE_FLOAT:
status = dc_get_value_float (context, &floatval);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = floatval;
break;
case DISIR_VALUE_TYPE_BOOLEAN:
status = dc_get_value_boolean (context, &boolval);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = !!boolval;
break;
case DISIR_VALUE_TYPE_ENUM:
status = dc_get_value_enum (context, &stringval, NULL);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = stringval;
break;
case DISIR_VALUE_TYPE_UNKNOWN:
// If type is not know, we mark it
// as unkwnown
keyval = dc_value_type_string (context);
break;
default:
// HUH? Type not supported?
disir_error_set (m_disir, "Got an unsupported disir value type: %s",
dc_value_type_string (context));
break;
}
serialize_duplicate_entries (node, keyval, name);
return status;
error:
disir_error_set (m_disir, "Unable to fetch value from keyval with name: %s and type %s",
name.c_str(), dc_value_type_string (context));
return status;
}
enum disir_status
ConfigWriter::serialize_keyval (struct disir_context *context, Json::Value& node)
{
enum disir_status status;
std::string name;
status = get_context_key (context, name);
if (status != DISIR_STATUS_OK)
{
return status;
}
return set_keyval (context, name, node);
}
enum disir_status
ConfigWriter::_serialize_context (struct disir_context *parent_context, Json::Value& parent)
{
struct disir_collection *collection;
struct disir_context *child_context;
enum disir_status status;
child_context = NULL;
status = dc_get_elements (parent_context, &collection);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = DISIR_STATUS_OK;
while (dc_collection_next (collection, &child_context)
!= DISIR_STATUS_EXHAUSTED)
{
// per-iteration such that child values
// never have old references to pre-marshaled
// context objects
Json::Value child;
switch (dc_context_type (child_context))
{
case DISIR_CONTEXT_SECTION:
// Initialize child to an empty object, that way we indicate
// in the serialized configuration that this section exists,
// it just didnt have any children
child = Json::objectValue;
status = _serialize_context (child_context, child);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = set_section_keyname (child_context, parent, child);
if (status != DISIR_STATUS_OK)
{
// logged
return status;
}
break;
case DISIR_CONTEXT_KEYVAL:
status = serialize_keyval (child_context, parent);
if (status != DISIR_STATUS_OK)
{
goto end;
}
break;
default:
break;
}
dc_putcontext (&child_context);
}
end:
if (child_context)
{
dc_putcontext (&child_context);
}
dc_collection_finished (&collection);
return status;
}
<commit_msg>fix: serializing disir_config with no elements writes null to file<commit_after>// JSON private
#include "json/json_serialize.h"
// public
#include <disir/disir.h>
// standard
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
#include <string>
using namespace dio;
ConfigWriter::ConfigWriter (struct disir_instance *disir)
: JsonIO (disir)
{
m_contextConfig = NULL;
}
ConfigWriter::~ConfigWriter ()
{
if (m_contextConfig)
{
dc_putcontext (&m_contextConfig);
}
}
enum disir_status
ConfigWriter::serialize (struct disir_config *config, std::ostream& stream)
{
enum disir_status status;
Json::StyledWriter writer;
std::string outputJson;
status = DISIR_STATUS_OK;
// Retrieving the config's context object
m_contextConfig = dc_config_getcontext (config);
if (m_contextConfig == NULL )
{
disir_error_set (m_disir, "could not retrieve cconfig context object");
return DISIR_STATUS_INTERNAL_ERROR;
}
status = set_config_version (m_contextConfig, m_configRoot);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = _serialize_context (m_contextConfig, m_configRoot[ATTRIBUTE_KEY_CONFIG]);
if (status != DISIR_STATUS_OK)
{
goto end;
}
if (m_configRoot[ATTRIBUTE_KEY_CONFIG].empty())
{
m_configRoot[ATTRIBUTE_KEY_CONFIG] = Json::objectValue;
}
stream << writer.writeOrdered (m_configRoot);
end:
dc_putcontext (&m_contextConfig);
return status;
}
enum disir_status
ConfigWriter::serialize (struct disir_config *config, std::string& output)
{
enum disir_status status;
Json::StyledWriter writer;
std::string outputJson;
// Retrieving the config's context object
m_contextConfig = dc_config_getcontext (config);
if (m_contextConfig == NULL )
{
disir_error_set (m_disir, "could not retrieve cconfig context object");
return DISIR_STATUS_INTERNAL_ERROR;
}
status = set_config_version (m_contextConfig, m_configRoot);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = _serialize_context (m_contextConfig, m_configRoot[ATTRIBUTE_KEY_CONFIG]);
if (status != DISIR_STATUS_OK)
{
goto end;
}
if (m_configRoot[ATTRIBUTE_KEY_CONFIG].empty())
{
m_configRoot[ATTRIBUTE_KEY_CONFIG] = Json::objectValue;
}
output = writer.writeOrdered (m_configRoot);
end:
dc_putcontext (&m_contextConfig);
return status;
}
enum disir_status
ConfigWriter::set_config_version (struct disir_context *context_config, Json::Value& root)
{
struct disir_version version;
enum disir_status status;
char buf[500];
char *temp;
status = dc_get_version (context_config, &version);
if (status != DISIR_STATUS_OK)
{
disir_error_set (m_disir, "Could not read config version: (%s)",
disir_status_string (status));
return status;
}
temp = dc_version_string ((char *)buf, (int32_t)500, &version);
if (temp == NULL)
{
disir_error_set (m_disir, "Error retrieving semantic version string");
return DISIR_STATUS_INTERNAL_ERROR;
}
root[ATTRIBUTE_KEY_VERSION] = buf;
return status;
}
// Mapping child node (section) to key (section name)
enum disir_status
ConfigWriter::set_section_keyname (struct disir_context *context, Json::Value& parent,
Json::Value& sectionVal)
{
std::string name;
enum disir_status status;
status = get_context_key (context, name);
if (status != DISIR_STATUS_OK)
{
// logged
return status;
}
serialize_duplicate_entries (parent, sectionVal, name);
return status;
}
enum disir_status
ConfigWriter::get_context_key (struct disir_context *context, std::string& key)
{
const char *name;
int32_t size;
enum disir_status status;
status = dc_get_name (context, &name, &size);
if (status != DISIR_STATUS_OK) {
// Should not happen
disir_error_set (m_disir, "Disir returned an error from dc_get_name: %s",
disir_status_string (status));
return status;
}
key = std::string (name, size);
return status;
}
void
ConfigWriter::serialize_duplicate_entries (Json::Value& parent,
Json::Value& child, const std::string name)
{
Json::Value entries;
if (parent[name].isArray())
{
parent[name].append (child);
}
else if (parent[name].isNull() == false)
{
entries = Json::arrayValue;
entries.append (parent[name]);
entries.append (child);
child = entries;
parent[name] = child;
}
else
{
parent[name] = child;
}
}
// Wraps libdisir dc_get_value to handle arbitrary value sizes
enum disir_status
ConfigWriter::set_keyval (struct disir_context *context, std::string name, Json::Value& node)
{
enum disir_status status;
enum disir_value_type type;
int32_t size;
double floatval;
int64_t intval;
const char *stringval;
uint8_t boolval;
std::string buf;
Json::Value keyval;
status = dc_get_value_type (context, &type);
if (status != DISIR_STATUS_OK)
{
disir_error_set (m_disir, "Could not obtain context_value_type (%s)",
disir_status_string (status));
return status;
}
switch (type) {
case DISIR_VALUE_TYPE_STRING:
status = dc_get_value_string (context, &stringval, &size);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = stringval;
break;
case DISIR_VALUE_TYPE_INTEGER:
status = dc_get_value_integer (context, &intval);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = (Json::Int64)intval;
break;
case DISIR_VALUE_TYPE_FLOAT:
status = dc_get_value_float (context, &floatval);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = floatval;
break;
case DISIR_VALUE_TYPE_BOOLEAN:
status = dc_get_value_boolean (context, &boolval);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = !!boolval;
break;
case DISIR_VALUE_TYPE_ENUM:
status = dc_get_value_enum (context, &stringval, NULL);
if (status != DISIR_STATUS_OK)
{
goto error;
}
keyval = stringval;
break;
case DISIR_VALUE_TYPE_UNKNOWN:
// If type is not know, we mark it
// as unkwnown
keyval = dc_value_type_string (context);
break;
default:
// HUH? Type not supported?
disir_error_set (m_disir, "Got an unsupported disir value type: %s",
dc_value_type_string (context));
break;
}
serialize_duplicate_entries (node, keyval, name);
return status;
error:
disir_error_set (m_disir, "Unable to fetch value from keyval with name: %s and type %s",
name.c_str(), dc_value_type_string (context));
return status;
}
enum disir_status
ConfigWriter::serialize_keyval (struct disir_context *context, Json::Value& node)
{
enum disir_status status;
std::string name;
status = get_context_key (context, name);
if (status != DISIR_STATUS_OK)
{
return status;
}
return set_keyval (context, name, node);
}
enum disir_status
ConfigWriter::_serialize_context (struct disir_context *parent_context, Json::Value& parent)
{
struct disir_collection *collection;
struct disir_context *child_context;
enum disir_status status;
child_context = NULL;
status = dc_get_elements (parent_context, &collection);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = DISIR_STATUS_OK;
while (dc_collection_next (collection, &child_context)
!= DISIR_STATUS_EXHAUSTED)
{
// per-iteration such that child values
// never have old references to pre-marshaled
// context objects
Json::Value child;
switch (dc_context_type (child_context))
{
case DISIR_CONTEXT_SECTION:
// Initialize child to an empty object, that way we indicate
// in the serialized configuration that this section exists,
// it just didnt have any children
child = Json::objectValue;
status = _serialize_context (child_context, child);
if (status != DISIR_STATUS_OK)
{
goto end;
}
status = set_section_keyname (child_context, parent, child);
if (status != DISIR_STATUS_OK)
{
// logged
return status;
}
break;
case DISIR_CONTEXT_KEYVAL:
status = serialize_keyval (child_context, parent);
if (status != DISIR_STATUS_OK)
{
goto end;
}
break;
default:
break;
}
dc_putcontext (&child_context);
}
end:
if (child_context)
{
dc_putcontext (&child_context);
}
dc_collection_finished (&collection);
return status;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/DataArray.hpp>
#include <nix/hdf5/FeatureHDF5.hpp>
using namespace std;
using namespace nix;
using namespace nix::base;
using namespace nix::hdf5;
string nix::hdf5::linkTypeToString(LinkType link_type) {
static vector<string> type_names = {"tagged", "untagged", "indexed"};
return type_names[static_cast<int>(link_type)];
}
LinkType nix::hdf5::linkTypeFromString(const string &str) {
if (str == "tagged")
return LinkType::Tagged;
else if (str == "untagged")
return LinkType::Untagged;
else if (str == "indexed")
return LinkType::Indexed;
else
throw runtime_error("Unable to create a LinkType from the string: " + str);
}
FeatureHDF5::FeatureHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group)
: EntityHDF5(file, group), block(block)
{
}
FeatureHDF5::FeatureHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group,
const string &id, DataArray data, LinkType link_type)
: FeatureHDF5(file, block, group, id, data, link_type, util::getTime())
{
}
FeatureHDF5::FeatureHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group,
const string &id, DataArray data, LinkType link_type, time_t time)
: EntityHDF5(file, group, id, time), block(block)
{
linkType(link_type);
// TODO: the line below currently throws an exception if the DataArray
// is not in block - to consider if we prefer copying it to the block
this->data(data.id());
}
void FeatureHDF5::linkType(LinkType link_type) {
// linkTypeToString will generate an error if link_type is invalid
group().setAttr("link_type", linkTypeToString(link_type));
forceUpdatedAt();
}
void FeatureHDF5::data(const std::string &data_array_id) {
if (data_array_id.empty()) {
throw EmptyString("data DataArray id");
}
else {
if (!block->hasDataArray(data_array_id)) {
throw runtime_error("FeatureHDF5::data: cannot set Feature data because referenced DataArray does not exist!");
} else {
group().setAttr("data", data_array_id);
forceUpdatedAt();
}
}
}
shared_ptr<IDataArray> FeatureHDF5::data() const {
shared_ptr<IDataArray> da;
if (group().hasAttr("data")) {
string dataId;
group().getAttr("data", dataId);
if (block->hasDataArray(dataId)) {
da = block->getDataArray(dataId);
} else {
throw std::runtime_error("Data array not found by id in Block");
}
}
return da;
}
LinkType FeatureHDF5::linkType() const {
if (group().hasAttr("link_type")) {
string link_type;
group().getAttr("link_type", link_type);
return linkTypeFromString(link_type);
} else {
throw MissingAttr("data");
}
}
FeatureHDF5::~FeatureHDF5() {}
<commit_msg>Implemented refs as links for FeatureHDF5::data<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/DataArray.hpp>
#include <nix/DataArray.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/FeatureHDF5.hpp>
using namespace std;
using namespace nix;
using namespace nix::base;
using namespace nix::hdf5;
string nix::hdf5::linkTypeToString(LinkType link_type) {
static vector<string> type_names = {"tagged", "untagged", "indexed"};
return type_names[static_cast<int>(link_type)];
}
LinkType nix::hdf5::linkTypeFromString(const string &str) {
if (str == "tagged")
return LinkType::Tagged;
else if (str == "untagged")
return LinkType::Untagged;
else if (str == "indexed")
return LinkType::Indexed;
else
throw runtime_error("Unable to create a LinkType from the string: " + str);
}
FeatureHDF5::FeatureHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group)
: EntityHDF5(file, group), block(block)
{
}
FeatureHDF5::FeatureHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group,
const string &id, DataArray data, LinkType link_type)
: FeatureHDF5(file, block, group, id, data, link_type, util::getTime())
{
}
FeatureHDF5::FeatureHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group,
const string &id, DataArray data, LinkType link_type, time_t time)
: EntityHDF5(file, group, id, time), block(block)
{
linkType(link_type);
// TODO: the line below currently throws an exception if the DataArray
// is not in block - to consider if we prefer copying it to the block
this->data(data.id());
}
void FeatureHDF5::linkType(LinkType link_type) {
// linkTypeToString will generate an error if link_type is invalid
group().setAttr("link_type", linkTypeToString(link_type));
forceUpdatedAt();
}
void FeatureHDF5::data(const std::string &data_array_id) {
if (data_array_id.empty())
throw EmptyString("data(id)");
if (!block->hasDataArray(data_array_id))
throw std::runtime_error("FeatureHDF5::data: DataArray not found in block!");
if (group().hasGroup("data"))
group().removeGroup("data");
auto target = dynamic_pointer_cast<DataArrayHDF5>(block->getDataArray(data_array_id));
group().createLink(target->group(), "data");
forceUpdatedAt();
}
shared_ptr<IDataArray> FeatureHDF5::data() const {
shared_ptr<IDataArray> da;
if (group().hasGroup("data")) {
Group other_group = group().openGroup("data", false);
da = make_shared<DataArrayHDF5>(file(), block, other_group);
}
return da;
}
LinkType FeatureHDF5::linkType() const {
if (group().hasAttr("link_type")) {
string link_type;
group().getAttr("link_type", link_type);
return linkTypeFromString(link_type);
} else {
throw MissingAttr("data");
}
}
FeatureHDF5::~FeatureHDF5() {}
<|endoftext|>
|
<commit_before>/*
* cpptest libcaca++ rendering test
* Copyright (c) 2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
* All Rights Reserved
*
* $Id$
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Do What The Fuck You Want To
* Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
#include <iostream>
#include <cucul++.h>
#include <caca++.h>
using namespace std;
static char const *pig[]= {
" ",
" _ ",
" _._ _..._ .-', _.._(`)) ",
" '-. ` ' /-._.-' ',/ ",
" ) \ '. ",
" / _ _ | \\ ",
" | a a / | ",
" \ .-. ; " ,
" '-('' ).-' ,' ; ",
" '-; | .' ",
" \\ \\ / ",
" | 7 .__ _.-\\ \\ ",
" | | | ``/ /` / ",
" jgs /,_| | /,_/ / ",
" /,_/ '`-' ",
" ",
NULL
};
int main(int argc, char *argv[])
{
Cucul *qq;
Caca *kk;
Event ev;
int x = 0, y = 0, ix = 1, iy = 1;
try {
qq = new Cucul();
}
catch (int e) {
cerr << "Error while initializing cucul (" << e << ")" << endl;
return -1;
}
try {
kk = new Caca(qq);
}
catch(int e) {
cerr << "Error while attaching cucul to caca (" << e << ")" << endl;
return -1;
}
kk->set_delay(20000);
while(!kk->get_event(ev.CACA_EVENT_KEY_PRESS, &ev, 0)) {
/* Draw pig */
qq->set_color(CUCUL_COLOR_LIGHTMAGENTA, CUCUL_COLOR_BLACK);
for(int i = 0; pig[i]; i++)
qq->putstr(x, y+i, (char*)pig[i]);
/* printf works */
qq->set_color(CUCUL_COLOR_LIGHTBLUE, CUCUL_COLOR_BLACK);
qq->printf(30,15, "Powered by libcaca %s", VERSION);
/* Blit */
kk->display();
x+=ix;
y+=iy;
if(x>=(qq->get_width()-35) || x<0 )
ix=-ix;
if(y>=(qq->get_height()-15) || y<0 )
iy=-iy;
}
delete kk;
delete qq;
return 0;
}
<commit_msg> * Compilation fix in cpptest.cpp.<commit_after>/*
* cpptest libcaca++ rendering test
* Copyright (c) 2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
* All Rights Reserved
*
* $Id$
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Do What The Fuck You Want To
* Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
#include <iostream>
#include <cucul++.h>
#include <caca++.h>
using namespace std;
static char const *pig[]= {
" ",
" _ ",
" _._ _..._ .-', _.._(`)) ",
" '-. ` ' /-._.-' ',/ ",
" ) \\ '. ",
" / _ _ | \\ ",
" | a a / | ",
" \\ .-. ; " ,
" '-('' ).-' ,' ; ",
" '-; | .' ",
" \\ \\ / ",
" | 7 .__ _.-\\ \\ ",
" | | | ``/ /` / ",
" jgs /,_| | /,_/ / ",
" /,_/ '`-' ",
" ",
NULL
};
int main(int argc, char *argv[])
{
Cucul *qq;
Caca *kk;
Event ev;
int x = 0, y = 0, ix = 1, iy = 1;
try {
qq = new Cucul();
}
catch (int e) {
cerr << "Error while initializing cucul (" << e << ")" << endl;
return -1;
}
try {
kk = new Caca(qq);
}
catch(int e) {
cerr << "Error while attaching cucul to caca (" << e << ")" << endl;
return -1;
}
kk->set_delay(20000);
while(!kk->get_event(ev.CACA_EVENT_KEY_PRESS, &ev, 0)) {
/* Draw pig */
qq->set_color(CUCUL_COLOR_LIGHTMAGENTA, CUCUL_COLOR_BLACK);
for(int i = 0; pig[i]; i++)
qq->putstr(x, y+i, (char*)pig[i]);
/* printf works */
qq->set_color(CUCUL_COLOR_LIGHTBLUE, CUCUL_COLOR_BLACK);
qq->printf(30,15, "Powered by libcaca %s", VERSION);
/* Blit */
kk->display();
x+=ix;
y+=iy;
if(x>=(qq->get_width()-35) || x<0 )
ix=-ix;
if(y>=(qq->get_height()-15) || y<0 )
iy=-iy;
}
delete kk;
delete qq;
return 0;
}
<|endoftext|>
|
<commit_before>#include "ghost/timing.h"
#include "ghost/util.h"
#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <numeric>
#include <algorithm>
using namespace std;
typedef struct
{
/**
* @brief User-defined callback function to compute a region's performance.
*/
ghost_compute_performance_func_t perfFunc;
/**
* @brief Argument to perfFunc.
*/
void *perfFuncArg;
/**
* @brief The unit of performance.
*/
const char *perfUnit;
}
ghost_timing_perfFunc_t;
/**
* @brief Region timing accumulator
*/
typedef struct
{
/**
* @brief The runtimes of this region.
*/
vector<double> times;
/**
* @brief The last start time of this region.
*/
double start;
vector<ghost_timing_perfFunc_t> perfFuncs;
}
ghost_timing_region_accu_t;
static map<string,ghost_timing_region_accu_t> timings;
void ghost_timing_tick(const char *tag)
{
double start = 0.;
ghost_timing_wc(&start);
timings[tag].start = start;
}
void ghost_timing_tock(const char *tag)
{
double end;
ghost_timing_wc(&end);
ghost_timing_region_accu_t *ti = &timings[string(tag)];
ti->times.push_back(end-ti->start);
}
void ghost_timing_set_perfFunc(const char *prefix, const char *tag, ghost_compute_performance_func_t func, void *arg, size_t sizeofarg, const char *unit)
{
if (!tag) {
WARNING_LOG("Empty tag! This should not have happened...");
return;
}
ghost_timing_perfFunc_t pf;
pf.perfFunc = func;
pf.perfUnit = unit;
ghost_timing_region_accu_t region;
if (prefix) {
const char *fulltag = (string(prefix)+"->"+string(tag)).c_str();
region = timings[fulltag];
} else {
region = timings[tag];
}
for (std::vector<ghost_timing_perfFunc_t>::iterator it = region.perfFuncs.begin();
it !=region.perfFuncs.end(); ++it) {
if (it->perfFunc == func && !strcmp(it->perfUnit,unit)) {
return;
}
}
ghost_malloc((void **)&(pf.perfFuncArg),sizeofarg);
memcpy(pf.perfFuncArg,arg,sizeofarg);
region.perfFuncs.push_back(pf);
}
ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag)
{
ghost_timing_region_accu_t ti = timings[string(tag)];
if (!ti.times.size()) {
*ri = NULL;
return GHOST_SUCCESS;
}
ghost_error_t ret = GHOST_SUCCESS;
GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret);
(*ri)->nCalls = ti.times.size();
(*ri)->minTime = *min_element(ti.times.begin(),ti.times.end());
(*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end());
(*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.);
(*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls;
if ((*ri)->nCalls > 10) {
(*ri)->skip10avgTime = accumulate(ti.times.begin()+10,ti.times.end(),0.)/((*ri)->nCalls-10);
} else {
(*ri)->skip10avgTime = 0.;
}
GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret);
memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double));
goto out;
err:
ERROR_LOG("Freeing region info");
if (*ri) {
free((*ri)->times); (*ri)->times = NULL;
}
free(*ri); (*ri) = NULL;
out:
return ret;
}
void ghost_timing_region_destroy(ghost_timing_region_t * ri)
{
if (ri) {
free(ri->times); ri->times = NULL;
}
free(ri);
}
ghost_error_t ghost_timing_summarystring(char **str)
{
stringstream buffer;
map<string,ghost_timing_region_accu_t>::iterator iter;
vector<ghost_timing_perfFunc_t>::iterator pf_iter;
size_t maxRegionLen = 0;
size_t maxCallsLen = 0;
size_t maxUnitLen = 0;
stringstream tmp;
for (iter = timings.begin(); iter != timings.end(); ++iter) {
int regLen = 0;
for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
if (pf_iter->perfUnit) {
tmp << iter->first.length();
maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen);
regLen = strlen(pf_iter->perfUnit);
tmp.str("");
}
}
tmp << regLen+iter->first.length();
maxRegionLen = max(regLen+iter->first.length(),maxRegionLen);
tmp.str("");
tmp << iter->second.times.size();
maxCallsLen = max(maxCallsLen,tmp.str().length());
tmp.str("");
}
if (maxCallsLen < 5) {
maxCallsLen = 5;
}
buffer << left << setw(maxRegionLen+4) << "Region" << right << " | ";
buffer << setw(maxCallsLen+3) << "Calls | ";
buffer << " t_min | ";
buffer << " t_max | ";
buffer << " t_avg | ";
buffer << " t_s10 | ";
buffer << " t_acc" << endl;
buffer << string(maxRegionLen+maxCallsLen+7+5*11,'-') << endl;
buffer.precision(2);
for (iter = timings.begin(); iter != timings.end(); ++iter) {
ghost_timing_region_t *region = NULL;
ghost_timing_region_create(®ion,iter->first.c_str());
if (region) {
buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) <<
region->nCalls << " | " <<
region->minTime << " | " <<
region->maxTime << " | " <<
region->avgTime << " | " <<
region->skip10avgTime << " | " <<
region->accTime << endl;
ghost_timing_region_destroy(region);
}
}
int printed = 0;
buffer.precision(2);
for (iter = timings.begin(); iter != timings.end(); ++iter) {
if (!printed) {
buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | ";
buffer << setw(maxCallsLen+3) << "Calls | ";
buffer << " P_max | ";
buffer << " P_min | ";
buffer << " P_avg | ";
buffer << "P_skip10" << endl;;
buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl;
}
printed = 1;
ghost_timing_region_t *region = NULL;
ghost_timing_region_create(®ion,iter->first.c_str());
if (region) {
for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
ghost_compute_performance_func_t pf = pf_iter->perfFunc;
void *pfa = pf_iter->perfFuncArg;
double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.;
int err = pf(&P_min,region->maxTime,pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
err = pf(&P_max,region->minTime,pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
err = pf(&P_avg,region->avgTime,pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
if (region->nCalls > 10) {
err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
}
buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first <<
right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) <<
region->nCalls << " | " <<
P_max << " | " <<
P_min << " | " <<
P_avg << " | " <<
P_skip10 << endl;
}
ghost_timing_region_destroy(region);
}
}
// clear all timings to prevent memory leaks
for (iter = timings.begin(); iter != timings.end(); ++iter) {
for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
if( pf_iter->perfFuncArg != NULL )
free(pf_iter->perfFuncArg);
pf_iter->perfFuncArg = NULL;
}
}
timings.clear();
GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1));
strcpy(*str,buffer.str().c_str());
return GHOST_SUCCESS;
}
<commit_msg>what a shitty bug...<commit_after>#include "ghost/timing.h"
#include "ghost/util.h"
#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <numeric>
#include <algorithm>
using namespace std;
typedef struct
{
/**
* @brief User-defined callback function to compute a region's performance.
*/
ghost_compute_performance_func_t perfFunc;
/**
* @brief Argument to perfFunc.
*/
void *perfFuncArg;
/**
* @brief The unit of performance.
*/
const char *perfUnit;
}
ghost_timing_perfFunc_t;
/**
* @brief Region timing accumulator
*/
typedef struct
{
/**
* @brief The runtimes of this region.
*/
vector<double> times;
/**
* @brief The last start time of this region.
*/
double start;
vector<ghost_timing_perfFunc_t> perfFuncs;
}
ghost_timing_region_accu_t;
static map<string,ghost_timing_region_accu_t> timings;
void ghost_timing_tick(const char *tag)
{
double start = 0.;
ghost_timing_wc(&start);
timings[tag].start = start;
}
void ghost_timing_tock(const char *tag)
{
double end;
ghost_timing_wc(&end);
ghost_timing_region_accu_t *ti = &timings[string(tag)];
ti->times.push_back(end-ti->start);
}
void ghost_timing_set_perfFunc(const char *prefix, const char *tag, ghost_compute_performance_func_t func, void *arg, size_t sizeofarg, const char *unit)
{
if (!tag) {
WARNING_LOG("Empty tag! This should not have happened...");
return;
}
ghost_timing_perfFunc_t pf;
pf.perfFunc = func;
pf.perfUnit = unit;
ghost_timing_region_accu_t *region;
if (prefix) {
const char *fulltag = (string(prefix)+"->"+string(tag)).c_str();
region = &timings[fulltag];
} else {
region = &timings[tag];
}
for (std::vector<ghost_timing_perfFunc_t>::iterator it = region->perfFuncs.begin();
it !=region->perfFuncs.end(); ++it) {
if (it->perfFunc == func && !strcmp(it->perfUnit,unit)) {
return;
}
}
ghost_malloc((void **)&(pf.perfFuncArg),sizeofarg);
memcpy(pf.perfFuncArg,arg,sizeofarg);
region->perfFuncs.push_back(pf);
}
ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag)
{
ghost_timing_region_accu_t ti = timings[string(tag)];
if (!ti.times.size()) {
*ri = NULL;
return GHOST_SUCCESS;
}
ghost_error_t ret = GHOST_SUCCESS;
GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret);
(*ri)->nCalls = ti.times.size();
(*ri)->minTime = *min_element(ti.times.begin(),ti.times.end());
(*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end());
(*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.);
(*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls;
if ((*ri)->nCalls > 10) {
(*ri)->skip10avgTime = accumulate(ti.times.begin()+10,ti.times.end(),0.)/((*ri)->nCalls-10);
} else {
(*ri)->skip10avgTime = 0.;
}
GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret);
memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double));
goto out;
err:
ERROR_LOG("Freeing region info");
if (*ri) {
free((*ri)->times); (*ri)->times = NULL;
}
free(*ri); (*ri) = NULL;
out:
return ret;
}
void ghost_timing_region_destroy(ghost_timing_region_t * ri)
{
if (ri) {
free(ri->times); ri->times = NULL;
}
free(ri);
}
ghost_error_t ghost_timing_summarystring(char **str)
{
stringstream buffer;
map<string,ghost_timing_region_accu_t>::iterator iter;
vector<ghost_timing_perfFunc_t>::iterator pf_iter;
size_t maxRegionLen = 0;
size_t maxCallsLen = 0;
size_t maxUnitLen = 0;
stringstream tmp;
for (iter = timings.begin(); iter != timings.end(); ++iter) {
int regLen = 0;
for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
if (pf_iter->perfUnit) {
tmp << iter->first.length();
maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen);
regLen = strlen(pf_iter->perfUnit);
tmp.str("");
}
}
tmp << regLen+iter->first.length();
maxRegionLen = max(regLen+iter->first.length(),maxRegionLen);
tmp.str("");
tmp << iter->second.times.size();
maxCallsLen = max(maxCallsLen,tmp.str().length());
tmp.str("");
}
if (maxCallsLen < 5) {
maxCallsLen = 5;
}
buffer << left << setw(maxRegionLen+4) << "Region" << right << " | ";
buffer << setw(maxCallsLen+3) << "Calls | ";
buffer << " t_min | ";
buffer << " t_max | ";
buffer << " t_avg | ";
buffer << " t_s10 | ";
buffer << " t_acc" << endl;
buffer << string(maxRegionLen+maxCallsLen+7+5*11,'-') << endl;
buffer.precision(2);
for (iter = timings.begin(); iter != timings.end(); ++iter) {
ghost_timing_region_t *region = NULL;
ghost_timing_region_create(®ion,iter->first.c_str());
if (region) {
buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) <<
region->nCalls << " | " <<
region->minTime << " | " <<
region->maxTime << " | " <<
region->avgTime << " | " <<
region->skip10avgTime << " | " <<
region->accTime << endl;
ghost_timing_region_destroy(region);
}
}
int printed = 0;
buffer.precision(2);
for (iter = timings.begin(); iter != timings.end(); ++iter) {
if (!printed) {
buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | ";
buffer << setw(maxCallsLen+3) << "Calls | ";
buffer << " P_max | ";
buffer << " P_min | ";
buffer << " P_avg | ";
buffer << "P_skip10" << endl;;
buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl;
}
printed = 1;
ghost_timing_region_t *region = NULL;
ghost_timing_region_create(®ion,iter->first.c_str());
if (region) {
for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
ghost_compute_performance_func_t pf = pf_iter->perfFunc;
void *pfa = pf_iter->perfFuncArg;
double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.;
int err = pf(&P_min,region->maxTime,pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
err = pf(&P_max,region->minTime,pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
err = pf(&P_avg,region->avgTime,pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
if (region->nCalls > 10) {
err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa);
if (err) {
ERROR_LOG("Error in calling performance computation callback!");
}
}
buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first <<
right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) <<
region->nCalls << " | " <<
P_max << " | " <<
P_min << " | " <<
P_avg << " | " <<
P_skip10 << endl;
}
ghost_timing_region_destroy(region);
}
}
// clear all timings to prevent memory leaks
for (iter = timings.begin(); iter != timings.end(); ++iter) {
for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
if( pf_iter->perfFuncArg != NULL )
free(pf_iter->perfFuncArg);
pf_iter->perfFuncArg = NULL;
}
}
timings.clear();
GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1));
strcpy(*str,buffer.str().c_str());
return GHOST_SUCCESS;
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: logical8.cc,v 1.17 2002/10/07 22:51:57 kevinlawton Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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 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
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#define LOG_THIS BX_CPU_THIS_PTR
void
BX_CPU_C::XOR_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 ^ op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 ^ op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_XOR8);
}
void
BX_CPU_C::XOR_GbEb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op2 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op2);
}
result = op1 ^ op2;
BX_WRITE_8BIT_REGx(i->nnn(), i->extend8bitL(), result);
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_XOR8);
}
void
BX_CPU_C::XOR_ALIb(bxInstruction_c *i)
{
Bit8u op1, op2, sum;
op1 = AL;
op2 = i->Ib();
sum = op1 ^ op2;
AL = sum;
SET_FLAGS_OSZAPC_8(op1, op2, sum, BX_INSTR_XOR8);
}
void
BX_CPU_C::XOR_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 ^ op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 ^ op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_XOR8);
}
void
BX_CPU_C::OR_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 | op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 | op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
}
void
BX_CPU_C::NOT_Eb(bxInstruction_c *i)
{
Bit8u op1_8, result_8;
if (i->modC0()) {
op1_8 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result_8 = ~op1_8;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result_8);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1_8);
result_8 = ~op1_8;
Write_RMW_virtual_byte(result_8);
}
}
void
BX_CPU_C::OR_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 | op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 | op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
}
void
BX_CPU_C::OR_GbEb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op2 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op2);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmOr8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 | op2;
#endif
BX_WRITE_8BIT_REGx(i->nnn(), i->extend8bitL(), result);
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
#endif
}
void
BX_CPU_C::OR_ALIb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = AL;
op2 = i->Ib();
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmOr8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 | op2;
#endif
AL = result;
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, sum, BX_INSTR_OR8);
#endif
}
void
BX_CPU_C::AND_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
Write_RMW_virtual_byte(result);
}
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::AND_GbEb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op2 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op2);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
BX_WRITE_8BIT_REGx(i->nnn(), i->extend8bitL(), result);
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::AND_ALIb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = AL;
op2 = i->Ib();
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
AL = result;
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::AND_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
Write_RMW_virtual_byte(result);
}
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::TEST_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op1);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmTest8(op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
Bit8u result;
result = op1 & op2;
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_TEST8);
#endif
}
void
BX_CPU_C::TEST_ALIb(bxInstruction_c *i)
{
Bit8u op2, op1;
op1 = AL;
op2 = i->Ib();
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmTest8(op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
Bit8u result;
result = op1 & op2;
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_TEST8);
#endif
}
void
BX_CPU_C::TEST_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op1);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmTest8(op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
Bit8u result;
result = op1 & op2;
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_TEST8);
#endif
}
<commit_msg>- in OR_ALIb the local variable "sum" was changed to "result" but the non-host-asm line at the end still said "sum". Fixed.<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: logical8.cc,v 1.18 2002/10/11 13:50:14 bdenney Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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 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
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#define LOG_THIS BX_CPU_THIS_PTR
void
BX_CPU_C::XOR_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 ^ op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 ^ op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_XOR8);
}
void
BX_CPU_C::XOR_GbEb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op2 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op2);
}
result = op1 ^ op2;
BX_WRITE_8BIT_REGx(i->nnn(), i->extend8bitL(), result);
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_XOR8);
}
void
BX_CPU_C::XOR_ALIb(bxInstruction_c *i)
{
Bit8u op1, op2, sum;
op1 = AL;
op2 = i->Ib();
sum = op1 ^ op2;
AL = sum;
SET_FLAGS_OSZAPC_8(op1, op2, sum, BX_INSTR_XOR8);
}
void
BX_CPU_C::XOR_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 ^ op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 ^ op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_XOR8);
}
void
BX_CPU_C::OR_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 | op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 | op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
}
void
BX_CPU_C::NOT_Eb(bxInstruction_c *i)
{
Bit8u op1_8, result_8;
if (i->modC0()) {
op1_8 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result_8 = ~op1_8;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result_8);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1_8);
result_8 = ~op1_8;
Write_RMW_virtual_byte(result_8);
}
}
void
BX_CPU_C::OR_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
result = op1 | op2;
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
result = op1 | op2;
Write_RMW_virtual_byte(result);
}
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
}
void
BX_CPU_C::OR_GbEb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op2 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op2);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmOr8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 | op2;
#endif
BX_WRITE_8BIT_REGx(i->nnn(), i->extend8bitL(), result);
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
#endif
}
void
BX_CPU_C::OR_ALIb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = AL;
op2 = i->Ib();
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmOr8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 | op2;
#endif
AL = result;
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_OR8);
#endif
}
void
BX_CPU_C::AND_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
Write_RMW_virtual_byte(result);
}
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::AND_GbEb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op2 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op2);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
BX_WRITE_8BIT_REGx(i->nnn(), i->extend8bitL(), result);
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::AND_ALIb(bxInstruction_c *i)
{
Bit8u op1, op2, result;
op1 = AL;
op2 = i->Ib();
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
AL = result;
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::AND_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1, result;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
BX_WRITE_8BIT_REGx(i->rm(), i->extend8bitL(), result);
}
else {
read_RMW_virtual_byte(i->seg(), RMAddr(i), &op1);
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmAnd8(result, op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
result = op1 & op2;
#endif
Write_RMW_virtual_byte(result);
}
#if !(defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_AND8);
#endif
}
void
BX_CPU_C::TEST_EbGb(bxInstruction_c *i)
{
Bit8u op2, op1;
op2 = BX_READ_8BIT_REGx(i->nnn(),i->extend8bitL());
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op1);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmTest8(op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
Bit8u result;
result = op1 & op2;
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_TEST8);
#endif
}
void
BX_CPU_C::TEST_ALIb(bxInstruction_c *i)
{
Bit8u op2, op1;
op1 = AL;
op2 = i->Ib();
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmTest8(op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
Bit8u result;
result = op1 & op2;
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_TEST8);
#endif
}
void
BX_CPU_C::TEST_EbIb(bxInstruction_c *i)
{
Bit8u op2, op1;
op2 = i->Ib();
if (i->modC0()) {
op1 = BX_READ_8BIT_REGx(i->rm(),i->extend8bitL());
}
else {
read_virtual_byte(i->seg(), RMAddr(i), &op1);
}
#if (defined(__i386__) && defined(__GNUC__) && BX_SupportHostAsms)
Bit32u flags32;
asmTest8(op1, op2, flags32);
setEFlagsOSZAPC(flags32);
#else
Bit8u result;
result = op1 & op2;
SET_FLAGS_OSZAPC_8(op1, op2, result, BX_INSTR_TEST8);
#endif
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "CoreDefines.h"
#include "OgreRenderingModule.h"
#include "Renderer.h"
#include "LoggingFunctions.h"
#include "CAVEStereoModule.h"
#include "CAVEManager.h"
#include "CAVESettingsWidget.h"
#include "StereoController.h"
#include "StereoWidget.h"
#include "MemoryLeakCheck.h"
namespace CAVEStereo
{
CAVEStereoModule::CAVEStereoModule() :
IModule("CAVEStereo"),
stereo_(0),
cave_(0)
{
}
CAVEStereoModule::~CAVEStereoModule()
{
SAFE_DELETE(stereo_);
SAFE_DELETE(cave_);
}
void CAVEStereoModule::Initialize()
{
OgreRenderer::OgreRenderingModule *renderingModule = framework_->GetModule<OgreRenderer::OgreRenderingModule>();
if (!renderingModule)
{
LogError("CAVEStereoModule: Could not acquire OgreRenderingModule for Renderer!");
return;
}
OgreRenderer::RendererPtr renderer = renderingModule->GetRenderer();
if (renderer.get())
{
stereo_ = new StereoController(renderer.get(), this);
cave_ = new CAVEManager(renderer);
stereo_->InitializeUi();
cave_->InitializeUi();
}
else
LogError("CAVEStereoModule: Renderer is null on startup, what now!");
}
QVector<Ogre::RenderWindow*> CAVEStereoModule::GetCAVERenderWindows()
{
return cave_->GetExternalWindows();
}
void CAVEStereoModule::ShowStereoscopyWindow()
{
stereo_->GetStereoWidget()->show();
}
void CAVEStereoModule::ShowCaveWindow()
{
cave_->GetCaveWidget()->show();
}
}
extern "C"
{
DLLEXPORT void TundraPluginMain(Framework *fw)
{
Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
IModule *module = new CAVEStereo::CAVEStereoModule();
fw->RegisterModule(module);
}
}
<commit_msg>stereomodule image saving: add forwarder funcs in the module qobject, apparently got lost in cherry-picking from tundra1 earlier<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "CoreDefines.h"
#include "OgreRenderingModule.h"
#include "Renderer.h"
#include "LoggingFunctions.h"
#include "CAVEStereoModule.h"
#include "CAVEManager.h"
#include "CAVESettingsWidget.h"
#include "StereoController.h"
#include "StereoWidget.h"
#include "MemoryLeakCheck.h"
namespace CAVEStereo
{
CAVEStereoModule::CAVEStereoModule() :
IModule("CAVEStereo"),
stereo_(0),
cave_(0)
{
}
CAVEStereoModule::~CAVEStereoModule()
{
SAFE_DELETE(stereo_);
SAFE_DELETE(cave_);
}
void CAVEStereoModule::Initialize()
{
OgreRenderer::OgreRenderingModule *renderingModule = framework_->GetModule<OgreRenderer::OgreRenderingModule>();
if (!renderingModule)
{
LogError("CAVEStereoModule: Could not acquire OgreRenderingModule for Renderer!");
return;
}
OgreRenderer::RendererPtr renderer = renderingModule->GetRenderer();
if (renderer.get())
{
stereo_ = new StereoController(renderer.get(), this);
cave_ = new CAVEManager(renderer);
stereo_->InitializeUi();
cave_->InitializeUi();
}
else
LogError("CAVEStereoModule: Renderer is null on startup, what now!");
}
QVector<Ogre::RenderWindow*> CAVEStereoModule::GetCAVERenderWindows()
{
return cave_->GetExternalWindows();
}
void CAVEStereoModule::ShowStereoscopyWindow()
{
stereo_->GetStereoWidget()->show();
}
void CAVEStereoModule::ShowCaveWindow()
{
cave_->GetCaveWidget()->show();
}
void CAVEStereoModule::TakeScreenshots(QString path, QString filename)
{
stereo_->TakeScreenshots(path, filename);
}
void CAVEStereoModule::EnableStereo(QString tech_type, qreal eye_dist, qreal focal_l, qreal offset, qreal scrn_width)
{
stereo_->EnableStereo(tech_type, eye_dist, focal_l, offset, scrn_width);
}
}
extern "C"
{
DLLEXPORT void TundraPluginMain(Framework *fw)
{
Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
IModule *module = new CAVEStereo::CAVEStereoModule();
fw->RegisterModule(module);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_SUBMINOR 13
#define RMI4UPDATE_GETOPTS "hfd:t:pclv"
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< std::hex << rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
if (rc != UPDATE_SUCCESS)
{
device.Reset();
return 1;
}
return 0;
}
<commit_msg>Print firmware version in decimal instead of hex<commit_after>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_SUBMINOR 13
#define RMI4UPDATE_GETOPTS "hfd:t:pclv"
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
if (rc != UPDATE_SUCCESS)
{
device.Reset();
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(0) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
std::list<tcp::endpoint> cs;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!i->second->is_local()) continue;
// don't send out peers that we haven't successfully connected to
if (i->second->connecting()) continue;
cs.push_back(i->first);
}
std::list<tcp::endpoint> added_peers, dropped_peers;
std::set_difference(cs.begin(), cs.end(), m_old_peers.begin()
, m_old_peers.end(), std::back_inserter(added_peers));
std::set_difference(m_old_peers.begin(), m_old_peers.end()
, cs.begin(), cs.end(), std::back_inserter(dropped_peers));
m_old_peers = cs;
unsigned int num_peers = max_peer_entries;
std::string pla, pld, plf;
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
// TODO: use random selection in case added_peers.size() > num_peers
for (std::list<tcp::endpoint>::const_iterator i = added_peers.begin()
, end(added_peers.end());i != end; ++i)
{
if (!i->address().is_v4()) continue;
detail::write_endpoint(*i, pla_out);
// no supported flags to set yet
// 0x01 - peer supports encryption
detail::write_uint8(0, plf_out);
if (--num_peers == 0) break;
}
num_peers = max_peer_entries;
// TODO: use random selection in case dropped_peers.size() > num_peers
for (std::list<tcp::endpoint>::const_iterator i = dropped_peers.begin()
, end(dropped_peers.end());i != end; ++i)
{
if (!i->address().is_v4()) continue;
detail::write_endpoint(*i, pld_out);
if (--num_peers == 0) break;
}
entry pex(entry::dictionary_t);
pex["added"] = pla;
pex["dropped"] = pld;
pex["added.f"] = plf;
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::list<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(0)
, m_message_index(0)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
entry const& messages = h["m"];
if (entry const* index = messages.find_key(extension_name))
{
m_message_index = index->integer();
return true;
}
else
{
m_message_index = 0;
return false;
}
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
throw protocol_error("ut peer exchange message larger than 500 kB");
if (body.left() < length) return true;
// in case we are a seed we do not use the peers
// from the pex message to prevent us from
// overloading ourself
if (m_torrent.is_seed()) return true;
entry Pex = bdecode(body.begin, body.end);
entry* PeerList = Pex.find_key("added");
if (!PeerList) return true;
std::string const& peers = PeerList->string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
peer_id pid;
pid.clear();
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
if (!m_torrent.connection_for(adr)) p.peer_from_tracker(adr, pid);
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
send_ut_peer_list();
m_1_minute = 0;
}
private:
void send_ut_peer_list()
{
std::vector<char>& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
assert(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<commit_msg>fixed typo<commit_after>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(0) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
std::list<tcp::endpoint> cs;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!i->second->is_local()) continue;
// don't send out peers that we haven't successfully connected to
if (i->second->is_connecting()) continue;
cs.push_back(i->first);
}
std::list<tcp::endpoint> added_peers, dropped_peers;
std::set_difference(cs.begin(), cs.end(), m_old_peers.begin()
, m_old_peers.end(), std::back_inserter(added_peers));
std::set_difference(m_old_peers.begin(), m_old_peers.end()
, cs.begin(), cs.end(), std::back_inserter(dropped_peers));
m_old_peers = cs;
unsigned int num_peers = max_peer_entries;
std::string pla, pld, plf;
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
// TODO: use random selection in case added_peers.size() > num_peers
for (std::list<tcp::endpoint>::const_iterator i = added_peers.begin()
, end(added_peers.end());i != end; ++i)
{
if (!i->address().is_v4()) continue;
detail::write_endpoint(*i, pla_out);
// no supported flags to set yet
// 0x01 - peer supports encryption
detail::write_uint8(0, plf_out);
if (--num_peers == 0) break;
}
num_peers = max_peer_entries;
// TODO: use random selection in case dropped_peers.size() > num_peers
for (std::list<tcp::endpoint>::const_iterator i = dropped_peers.begin()
, end(dropped_peers.end());i != end; ++i)
{
if (!i->address().is_v4()) continue;
detail::write_endpoint(*i, pld_out);
if (--num_peers == 0) break;
}
entry pex(entry::dictionary_t);
pex["added"] = pla;
pex["dropped"] = pld;
pex["added.f"] = plf;
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::list<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(0)
, m_message_index(0)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
entry const& messages = h["m"];
if (entry const* index = messages.find_key(extension_name))
{
m_message_index = index->integer();
return true;
}
else
{
m_message_index = 0;
return false;
}
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
throw protocol_error("ut peer exchange message larger than 500 kB");
if (body.left() < length) return true;
// in case we are a seed we do not use the peers
// from the pex message to prevent us from
// overloading ourself
if (m_torrent.is_seed()) return true;
entry Pex = bdecode(body.begin, body.end);
entry* PeerList = Pex.find_key("added");
if (!PeerList) return true;
std::string const& peers = PeerList->string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
peer_id pid;
pid.clear();
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
if (!m_torrent.connection_for(adr)) p.peer_from_tracker(adr, pid);
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
send_ut_peer_list();
m_1_minute = 0;
}
private:
void send_ut_peer_list()
{
std::vector<char>& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
assert(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <deque>
#include "caf/byte_buffer.hpp"
#include "caf/fwd.hpp"
#include "caf/logger.hpp"
#include "caf/net/endpoint_manager.hpp"
#include "caf/net/fwd.hpp"
#include "caf/net/receive_policy.hpp"
#include "caf/net/stream_socket.hpp"
#include "caf/net/transport_base.hpp"
#include "caf/net/transport_worker.hpp"
#include "caf/sec.hpp"
#include "caf/span.hpp"
namespace caf::net {
template <class Application>
using stream_transport_base
= transport_base<stream_transport<Application>, transport_worker<Application>,
stream_socket, Application, unit_t>;
/// Implements a stream_transport that manages a stream socket.
template <class Application>
class stream_transport : public stream_transport_base<Application> {
public:
// -- member types -----------------------------------------------------------
using application_type = Application;
using worker_type = transport_worker<application_type>;
using super = stream_transport_base<application_type>;
using id_type = typename super::id_type;
using write_queue_type = std::deque<std::pair<bool, byte_buffer>>;
// -- constructors, destructors, and assignment operators --------------------
stream_transport(stream_socket handle, application_type application)
: super(handle, std::move(application)),
written_(0),
read_threshold_(1024),
collected_(0),
max_(1024),
rd_flag_(net::receive_policy_flag::exactly) {
CAF_ASSERT(handle != invalid_socket);
if (auto err = nodelay(handle, true))
CAF_LOG_ERROR("nodelay failed: " << err);
}
// -- member functions -------------------------------------------------------
bool handle_read_event(endpoint_manager&) override {
CAF_LOG_TRACE(CAF_ARG2("handle", this->handle().id));
for (size_t reads = 0; reads < this->max_consecutive_reads_; ++reads) {
auto buf = this->read_buf_.data() + collected_;
size_t len = read_threshold_ - collected_;
CAF_LOG_DEBUG(CAF_ARG2("missing", len));
auto num_bytes = read(this->handle_, make_span(buf, len));
CAF_LOG_DEBUG(CAF_ARG(len) << CAF_ARG2("handle", this->handle().id)
<< CAF_ARG(num_bytes));
// Update state.
if (num_bytes > 0) {
collected_ += num_bytes;
if (collected_ >= read_threshold_) {
if (auto err = this->next_layer_.handle_data(
*this, make_span(this->read_buf_))) {
CAF_LOG_ERROR("handle_data failed: " << CAF_ARG(err));
return false;
}
this->prepare_next_read();
}
} else if (num_bytes == 0) {
auto err = sec::socket_disconnected;
CAF_LOG_DEBUG("read failed" << CAF_ARG(err));
this->next_layer_.handle_error(err);
return false;
} else if (!last_socket_error_is_temporary()) {
auto err = sec::socket_operation_failed;
CAF_LOG_DEBUG("read failed" << CAF_ARG(err));
this->next_layer_.handle_error(err);
return false;
}
}
return true;
}
bool handle_write_event(endpoint_manager& manager) override {
CAF_LOG_TRACE(CAF_ARG2("handle", this->handle_.id)
<< CAF_ARG2("queue-size", write_queue_.size()));
auto drain_write_queue = [this]() -> error_code<sec> {
// Helper function to sort empty buffers back into the right caches.
auto recycle = [this]() {
auto& front = this->write_queue_.front();
auto& is_header = front.first;
auto& buf = front.second;
written_ = 0;
buf.clear();
if (is_header) {
if (this->header_bufs_.size() < this->header_bufs_.capacity())
this->header_bufs_.emplace_back(std::move(buf));
} else if (this->payload_bufs_.size()
< this->payload_bufs_.capacity()) {
this->payload_bufs_.emplace_back(std::move(buf));
}
write_queue_.pop_front();
};
// Write buffers from the write_queue_ for as long as possible.
while (!write_queue_.empty()) {
auto& buf = write_queue_.front().second;
CAF_ASSERT(!buf.empty());
auto data = buf.data() + written_;
auto len = buf.size() - written_;
auto num_bytes = write(this->handle(), make_span(data, len));
if (num_bytes > 0) {
CAF_LOG_DEBUG(CAF_ARG(this->handle_.id) << CAF_ARG(num_bytes));
written_ += num_bytes;
if (written_ >= static_cast<ptrdiff_t>(buf.size())) {
recycle();
written_ = 0;
}
} else if (num_bytes == 0) {
auto err = sec::socket_disconnected;
CAF_LOG_DEBUG("send failed" << CAF_ARG(err));
this->next_layer_.handle_error(err);
return err;
} else if (!last_socket_error_is_temporary()) {
auto err = sec::socket_operation_failed;
CAF_LOG_DEBUG("send failed" << CAF_ARG(err));
this->next_layer_.handle_error(err);
return err;
}
}
return none;
};
auto fetch_next_message = [&] {
if (auto msg = manager.next_message()) {
this->next_layer_.write_message(*this, std::move(msg));
return true;
}
return false;
};
do {
if (auto err = drain_write_queue())
return err == sec::unavailable_or_would_block;
} while (fetch_next_message());
CAF_ASSERT(write_queue_.empty());
return false;
}
void write_packet(id_type, span<byte_buffer*> buffers) override {
CAF_LOG_TRACE("");
CAF_ASSERT(!buffers.empty());
if (this->write_queue_.empty())
this->manager().register_writing();
// By convention, the first buffer is a header buffer. Every other buffer is
// a payload buffer.
auto i = buffers.begin();
this->write_queue_.emplace_back(true, std::move(*(*i++)));
while (i != buffers.end())
this->write_queue_.emplace_back(false, std::move(*(*i++)));
}
void configure_read(receive_policy::config cfg) override {
rd_flag_ = cfg.first;
max_ = cfg.second;
prepare_next_read();
}
private:
// -- utility functions ------------------------------------------------------
void prepare_next_read() {
collected_ = 0;
switch (rd_flag_) {
case net::receive_policy_flag::exactly:
if (this->read_buf_.size() != max_)
this->read_buf_.resize(max_);
read_threshold_ = max_;
break;
case net::receive_policy_flag::at_most:
if (this->read_buf_.size() != max_)
this->read_buf_.resize(max_);
read_threshold_ = 1;
break;
case net::receive_policy_flag::at_least: {
// read up to 10% more, but at least allow 100 bytes more
auto max_size = max_ + std::max<size_t>(100, max_ / 10);
if (this->read_buf_.size() != max_size)
this->read_buf_.resize(max_size);
read_threshold_ = max_;
break;
}
}
}
write_queue_type write_queue_;
ptrdiff_t written_;
ptrdiff_t read_threshold_;
ptrdiff_t collected_;
size_t max_;
receive_policy_flag rd_flag_;
};
} // namespace caf::net
<commit_msg>Integrate review feedback<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <deque>
#include "caf/byte_buffer.hpp"
#include "caf/fwd.hpp"
#include "caf/logger.hpp"
#include "caf/net/endpoint_manager.hpp"
#include "caf/net/fwd.hpp"
#include "caf/net/receive_policy.hpp"
#include "caf/net/stream_socket.hpp"
#include "caf/net/transport_base.hpp"
#include "caf/net/transport_worker.hpp"
#include "caf/sec.hpp"
#include "caf/span.hpp"
namespace caf::net {
template <class Application>
using stream_transport_base
= transport_base<stream_transport<Application>, transport_worker<Application>,
stream_socket, Application, unit_t>;
/// Implements a stream_transport that manages a stream socket.
template <class Application>
class stream_transport : public stream_transport_base<Application> {
public:
// -- member types -----------------------------------------------------------
using application_type = Application;
using worker_type = transport_worker<application_type>;
using super = stream_transport_base<application_type>;
using id_type = typename super::id_type;
using write_queue_type = std::deque<std::pair<bool, byte_buffer>>;
// -- constructors, destructors, and assignment operators --------------------
stream_transport(stream_socket handle, application_type application)
: super(handle, std::move(application)),
written_(0),
read_threshold_(1024),
collected_(0),
max_(1024),
rd_flag_(net::receive_policy_flag::exactly) {
CAF_ASSERT(handle != invalid_socket);
if (auto err = nodelay(handle, true))
CAF_LOG_ERROR("nodelay failed: " << err);
}
// -- member functions -------------------------------------------------------
bool handle_read_event(endpoint_manager&) override {
CAF_LOG_TRACE(CAF_ARG2("handle", this->handle().id));
auto fail = [this](sec err) {
CAF_LOG_DEBUG("read failed" << CAF_ARG(err));
this->next_layer_.handle_error(err);
return false;
};
for (size_t reads = 0; reads < this->max_consecutive_reads_; ++reads) {
auto buf = this->read_buf_.data() + collected_;
size_t len = read_threshold_ - collected_;
CAF_LOG_DEBUG(CAF_ARG2("missing", len));
auto num_bytes = read(this->handle_, make_span(buf, len));
CAF_LOG_DEBUG(CAF_ARG(len) << CAF_ARG2("handle", this->handle().id)
<< CAF_ARG(num_bytes));
// Update state.
if (num_bytes > 0) {
collected_ += num_bytes;
if (collected_ >= read_threshold_) {
if (auto err = this->next_layer_.handle_data(
*this, make_span(this->read_buf_))) {
CAF_LOG_ERROR("handle_data failed: " << CAF_ARG(err));
return false;
}
this->prepare_next_read();
}
} else if (num_bytes < 0) {
// Try again later on temporary errors such as EWOULDBLOCK and
// stop reading on the socket on hard errors.
return last_socket_error_is_temporary()
? true
: fail(sec::socket_operation_failed);
} else {
// read() returns 0 iff the connection was closed.
return fail(sec::socket_disconnected);
}
}
return true;
}
bool handle_write_event(endpoint_manager& manager) override {
CAF_LOG_TRACE(CAF_ARG2("handle", this->handle_.id)
<< CAF_ARG2("queue-size", write_queue_.size()));
auto drain_write_queue = [this]() -> error_code<sec> {
// Helper function to sort empty buffers back into the right caches.
auto recycle = [this]() {
auto& front = this->write_queue_.front();
auto& is_header = front.first;
auto& buf = front.second;
written_ = 0;
buf.clear();
if (is_header) {
if (this->header_bufs_.size() < this->header_bufs_.capacity())
this->header_bufs_.emplace_back(std::move(buf));
} else if (this->payload_bufs_.size()
< this->payload_bufs_.capacity()) {
this->payload_bufs_.emplace_back(std::move(buf));
}
write_queue_.pop_front();
};
auto fail = [this](sec err) {
CAF_LOG_DEBUG("write failed" << CAF_ARG(err));
this->next_layer_.handle_error(err);
return err;
};
// Write buffers from the write_queue_ for as long as possible.
while (!write_queue_.empty()) {
auto& buf = write_queue_.front().second;
CAF_ASSERT(!buf.empty());
auto data = buf.data() + written_;
auto len = buf.size() - written_;
auto num_bytes = write(this->handle(), make_span(data, len));
if (num_bytes > 0) {
CAF_LOG_DEBUG(CAF_ARG(this->handle_.id) << CAF_ARG(num_bytes));
written_ += num_bytes;
if (written_ >= static_cast<ptrdiff_t>(buf.size())) {
recycle();
written_ = 0;
}
} else if (num_bytes < 0) {
return last_socket_error_is_temporary()
? sec::unavailable_or_would_block
: fail(sec::socket_operation_failed);
} else {
// write() returns 0 iff the connection was closed.
return fail(sec::socket_disconnected);
}
}
return none;
};
auto fetch_next_message = [&] {
if (auto msg = manager.next_message()) {
this->next_layer_.write_message(*this, std::move(msg));
return true;
}
return false;
};
do {
if (auto err = drain_write_queue())
return err == sec::unavailable_or_would_block;
} while (fetch_next_message());
CAF_ASSERT(write_queue_.empty());
return false;
}
void write_packet(id_type, span<byte_buffer*> buffers) override {
CAF_LOG_TRACE("");
CAF_ASSERT(!buffers.empty());
if (this->write_queue_.empty())
this->manager().register_writing();
// By convention, the first buffer is a header buffer. Every other buffer is
// a payload buffer.
auto i = buffers.begin();
this->write_queue_.emplace_back(true, std::move(*(*i++)));
while (i != buffers.end())
this->write_queue_.emplace_back(false, std::move(*(*i++)));
}
void configure_read(receive_policy::config cfg) override {
rd_flag_ = cfg.first;
max_ = cfg.second;
prepare_next_read();
}
private:
// -- utility functions ------------------------------------------------------
void prepare_next_read() {
collected_ = 0;
switch (rd_flag_) {
case net::receive_policy_flag::exactly:
if (this->read_buf_.size() != max_)
this->read_buf_.resize(max_);
read_threshold_ = max_;
break;
case net::receive_policy_flag::at_most:
if (this->read_buf_.size() != max_)
this->read_buf_.resize(max_);
read_threshold_ = 1;
break;
case net::receive_policy_flag::at_least: {
// read up to 10% more, but at least allow 100 bytes more
auto max_size = max_ + std::max<size_t>(100, max_ / 10);
if (this->read_buf_.size() != max_size)
this->read_buf_.resize(max_size);
read_threshold_ = max_;
break;
}
}
}
write_queue_type write_queue_;
ptrdiff_t written_;
ptrdiff_t read_threshold_;
ptrdiff_t collected_;
size_t max_;
receive_policy_flag rd_flag_;
};
} // namespace caf::net
<|endoftext|>
|
<commit_before>#include "vo_features.h"
#include <iomanip>
#include <fstream>
#include <ostream>
#include <string>
#include "readBNO.h"
using namespace cv;
using namespace std;
#define MAX_FRAME 1001
//#define MIN_NUM_FEAT 200
#define PLOT_COLOR CV_RGB(0, 0, 0)
#define PL std::setprecision(3)
double scale = 1.00;
char text[100];
int fontFace = FONT_HERSHEY_PLAIN;
double fontScale = 1;
int thickness = 1;
cv::Point textOrg(10, 50);
#define REAL_TIME 1
//#define SHOW_IMAGE_ONLY 1
//#define BNO
#ifdef REAL_TIME
// new camera
const double focal = 837.69737925956247;
const cv::Point2d pp (332.96486550136854, 220.37986827273829);
#else
const double focal = 718.8560;
const cv::Point2d pp(607.1928, 185.2157);
#endif
int LEFT = 0;
int RIGHT = 1;
int main(int argc, char** argv) {
int fd = initBNO();
float q[4];
#ifdef __linux__
//linux code goes here
// string localDataDir = "/home/cwu/Downloads";
std::string localDataDir = "/home/cwu/project/dataset/images/2/";
std::string resultFile = "/home/cwu/project/stereo-vo/src/vo_result.txt";
//cout << "localDataDir is " << localDataDir << endl;
std::string imgDir="/home/cwu/project/dataset/images/4/";
std::string quaternionFile = imgDir + "q.txt";
std::ofstream myfile;
myfile.open(quaternionFile.c_str());
#else
// windows code goes here
// string localDataDir = "d:/vision";
string resultFile = "d:/vision/stereo-vo/src/vo_result.txt";
string imgDir = "d:/vision/dataset/images/1/";
string localDataDir = "d:/vision/dataset//images/1/";
//cout << "localDataDir is " << localDataDir << endl;
#endif
Mat current_img_left, current_img_right;
Mat previous_img_left, previous_img_right;
Mat leftEdge, rightEdge;
// for plotting purpose
Mat currImage_lc, currImage_rc;
Mat R_f, t_f; //the final rotation and translation vectors
Mat img_1, img_2; // two consecutive images from the same camera
#ifdef REAL_TIME
cout << "Running at real-time" <<endl;
VideoCapture left_capture(LEFT);
left_capture.set(CV_CAP_PROP_FPS,100);
left_capture.set(CV_CAP_PROP_BUFFERSIZE,3);
VideoCapture right_capture(RIGHT);
right_capture.set(CV_CAP_PROP_FPS,100);
right_capture.set(CV_CAP_PROP_BUFFERSIZE,3);
left_capture.read(img_1);
#ifdef SHOW_IMAGE_ONLY
namedWindow("LEFT image", 0);
namedWindow("RIGHT image", 1);
int numFrame = 1;
while (1) {
left_capture.read(current_img_left);
right_capture.read(current_img_right);
imshow("LEFT image", current_img_left);
imshow("RIGHT image", current_img_right);
stringstream ss;
ss << numFrame;
string idx = ss.str();
string leftImg = imgDir + "img_left/" + idx + ".png";
string rightImg = imgDir + "img_right/" + idx + ".png";
//cout << "leftImg = " << leftImg << endl;
Mat imgOut;
cvtColor(current_img_left, imgOut, COLOR_BGR2GRAY);
imwrite(leftImg, current_img_left);
cvtColor(current_img_right, imgOut, COLOR_BGR2GRAY);
imwrite(rightImg, imgOut);
#ifdef BNO
readQuaternion(fd, q);
myfile << q[0] << q[1] << q[2] << q[3] << endl;
#endif
numFrame++;
cout << "numFrame = " << numFrame << endl;
if (numFrame > MAX_FRAME) {
myfile.close();
return 0;
}
waitKey(100); //micro second
}
#endif
#else
cout << "Running at simulation mode!" << endl;
#endif
//obtain truth for plot comparison
string posePath = localDataDir + "/dataset/poses/00.txt";
std::ifstream infile(posePath.c_str());
std::string line;
float truthPosition[3] ;
Mat truthOrientation;
//getline(infile, line);
//getPosition(line, truthPosition);
// Open a txt file to store the results
ofstream fout(resultFile.c_str());
if (!fout) {
cout << "File not opened!" << endl;
return 1;
}
// features
vector < Point2f > keyFeatures;
#ifdef REAL_TIME
//left camera, second frame
left_capture.read(img_2);
// right camera
right_capture.read(previous_img_right);
#else
// use the first two images from left camera to compute the init values.
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000000.png", img_1, currImage_lc);
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000001.png", img_2, currImage_lc);
loadImage(localDataDir + "/img_left/1.png", img_1, currImage_lc);
loadImage(localDataDir + "/img_right/1.png", img_2, currImage_lc);
#endif
computeInitialPose(img_1, R_f, t_f, img_2, keyFeatures);
readQuaternion(fd, q);
//fout << 1 << "\t";
//fout << t_f.at<double>(0) << "\t" << t_f.at<double>(1) << "\t" << t_f.at<double>(2) << "\t";
//fout << 0 << "\t" << 0 << "\n";
// assign them to be previous
Mat prevImage = img_2;
vector < Point2f > prevFeatures = keyFeatures;
Mat currImage;
vector < Point2f > currFeatures;
string filename;
Mat E, R, t, mask;
clock_t begin = clock();
//namedWindow("Road facing camera", WINDOW_AUTOSIZE); // Create a window for display.
namedWindow("Trajectory", WINDOW_AUTOSIZE); // Create a window for display.
Mat traj = Mat::zeros(600, 600, CV_8UC3);
Mat trajTruth = Mat::zeros(600, 600, CV_8UC3);
string fileFolder = localDataDir + "/dataset/sequences/00/";
Mat R_f_left, t_f_left;
previous_img_left = img_2;
vector<Point2f> previous_feature_left = keyFeatures;;
vector<Point2f> current_feature_left;
Mat R_f_right, t_f_right;
vector<Point2f> previous_feature_right, current_feature_right;
#ifdef REAL_TIME
// new frame from left camera
previous_img_left = img_2;
left_capture.read(current_img_left);
// new frame from right camera
right_capture.read(current_img_right);
#else
// read the first two iamges from left camera
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000000.png", previous_img_left, currImage_lc );
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000001.png", current_img_left, currImage_lc);
loadImage(localDataDir + "/img_left/1.png", previous_img_left, currImage_lc );
loadImage(localDataDir + "/img_left/2.png", current_img_left, currImage_lc);
// read the first two iamges from right camera
loadImage(localDataDir + "/img_right/1.png", previous_img_right, currImage_rc);
loadImage(localDataDir + "/img_right/2.png", current_img_right, currImage_rc);
rectifyImage(previous_img_left, previous_img_right, previous_img_left, previous_img_right);
rectifyImage(current_img_left, current_img_right, current_img_left, current_img_right);
#endif
computeInitialStereoPose(previous_img_left,
current_img_left,
R_f_left,
t_f_left,
previous_feature_left,
previous_img_right,
current_img_right,
R_f_right,
t_f_right,
previous_feature_right);
for (int numFrame = 2; numFrame < MAX_FRAME; numFrame++) {
//filename = combineName(localDataDir + "/dataset/sequences/00/image_0/", numFrame);
//cout << "numFrame is " << numFrame << endl;
//getline(infile, line);
//getPosition(line, truthPosition);
#if 0
//scale = getAbsoluteScale(numFrame, 0, t_f.at<double>(2));
//cout << "scale is " << scale << endl;
updatePose(filename,
prevImage,
prevFeatures,
currFeatures,
R_f, t_f);
#else
#ifdef REAL_TIME
// Mat leftFrame;
bool readSuccess1 = left_capture.read(current_img_left);
if (readSuccess1){ currImage_lc = current_img_left;}
// Mat rightFrame;
bool readSuccess2 = right_capture.read(current_img_right);
if (readSuccess2) {currImage_rc = current_img_right; }
#else
//string filename1 = combineName(localDataDir + "/dataset/sequences/00/image_0/", numFrame);
//string filename2 = combineName(localDataDir + "/dataset/sequences/00/image_1/", numFrame);
stringstream ss;
ss << numFrame;
string idx = ss.str();
string filename1 = localDataDir + "/img_left/" + idx + ".png";
string filename2 = localDataDir + "/img_right/" + idx + ".png";
loadImage(filename1, current_img_left, currImage_lc);
loadImage(filename2, current_img_right, currImage_rc);
rectifyImage(current_img_left, current_img_right, current_img_left, current_img_right);
readQuaternion(fd, q); // read IMU
#endif
stereoVision(current_img_left,
current_img_right,
currImage_lc,
currImage_rc,
previous_img_left, previous_feature_left, current_feature_left,
previous_img_right, previous_feature_right, current_feature_right,
R_f, t_f);
#endif
// for plotting purpose
double x1 = t_f.at<double>(0);
double y1 = t_f.at<double>(1);
double z1 = t_f.at<double>(2);
int x = int(x1) + 300;
int y = int(z1) + 100;
int xTruth = int(truthPosition[0])+ 300;
int yTruth = int(truthPosition[2])+ 100;
// output to the screen
cout << "numFrame:" << numFrame <<" vo: x = " << PL<< x1 << "\t y = " << PL<< y1 << "\t z = " << PL<< z1 << endl;
#ifndef REAL_TIME
//cout << "tr: x = " << PL<< truthPosition[0] << "\t y = " << PL<< truthPosition[1] << "\t z = " << PL<< truthPosition[2] << endl;
#endif
// current point
circle(traj, Point(x, y), 0.2, CV_RGB(255, 0, 0), 2);
rectangle(traj, Point(10,30), Point(550, 50), PLOT_COLOR, CV_FILLED);
sprintf(text, "Coordinates: x = %04fm y = %04fm z = %04fm", x1, y1, z1);
putText(traj, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8);
// plot them
#ifndef REAL_TIME
imshow("Road facing camera", currImage_lc);
#endif
imshow("Trajectory", traj);
//imshow("Trajectory", trajTruth);
// Save the result
fout << numFrame << "\t";
fout << x1 << "\t" << y1 << "\t" << z1 << "\t" << x << "\t" << y << "\n";
waitKey(2); //microsecond
}
imwrite(localDataDir + "/final_map.png", traj);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "Total time taken: " << elapsed_secs << "s" << endl;
return 0;
}
<commit_msg>fixed logging issue<commit_after>#include "vo_features.h"
#include <iomanip>
#include <fstream>
#include <ostream>
#include <string>
#include "readBNO.h"
using namespace cv;
using namespace std;
#define MAX_FRAME 1001
//#define MIN_NUM_FEAT 200
#define PLOT_COLOR CV_RGB(0, 0, 0)
#define PL std::setprecision(3)
double scale = 1.00;
char text[100];
int fontFace = FONT_HERSHEY_PLAIN;
double fontScale = 1;
int thickness = 1;
cv::Point textOrg(10, 50);
#define REAL_TIME 1
#define SHOW_IMAGE_ONLY 1
#define BNO
#ifdef REAL_TIME
// new camera
const double focal = 837.69737925956247;
const cv::Point2d pp (332.96486550136854, 220.37986827273829);
#else
const double focal = 718.8560;
const cv::Point2d pp(607.1928, 185.2157);
#endif
int LEFT = 0;
int RIGHT = 1;
int main(int argc, char** argv) {
int fd = initBNO();
float q[4];
readQuaternion(fd, q); //the first sample is bad. So clean the buffer
#ifdef __linux__
//linux code goes here
// string localDataDir = "/home/cwu/Downloads";
std::string localDataDir = "/home/cwu/project/dataset/images/2/";
std::string resultFile = "/home/cwu/project/stereo-vo/src/vo_result.txt";
//cout << "localDataDir is " << localDataDir << endl;
std::string imgDir="/home/cwu/project/dataset/images/3/";
std::string quaternionFile = imgDir + "q.txt";
std::ofstream myfile;
myfile.open(quaternionFile.c_str());
#else
// windows code goes here
// string localDataDir = "d:/vision";
string resultFile = "d:/vision/stereo-vo/src/vo_result.txt";
string imgDir = "d:/vision/dataset/images/1/";
string localDataDir = "d:/vision/dataset//images/1/";
//cout << "localDataDir is " << localDataDir << endl;
#endif
Mat current_img_left, current_img_right;
Mat previous_img_left, previous_img_right;
Mat leftEdge, rightEdge;
// for plotting purpose
Mat currImage_lc, currImage_rc;
Mat R_f, t_f; //the final rotation and translation vectors
Mat img_1, img_2; // two consecutive images from the same camera
#ifdef REAL_TIME
cout << "Running at real-time" <<endl;
VideoCapture left_capture(LEFT);
left_capture.set(CV_CAP_PROP_FPS,100);
left_capture.set(CV_CAP_PROP_BUFFERSIZE,3);
VideoCapture right_capture(RIGHT);
right_capture.set(CV_CAP_PROP_FPS,100);
right_capture.set(CV_CAP_PROP_BUFFERSIZE,3);
left_capture.read(img_1);
#ifdef SHOW_IMAGE_ONLY
namedWindow("LEFT image", 0);
namedWindow("RIGHT image", 1);
int numFrame = 1;
while (1) {
left_capture.read(current_img_left);
right_capture.read(current_img_right);
imshow("LEFT image", current_img_left);
imshow("RIGHT image", current_img_right);
stringstream ss;
ss << numFrame;
string idx = ss.str();
string leftImg = imgDir + "img_left/" + idx + ".png";
string rightImg = imgDir + "img_right/" + idx + ".png";
//cout << "leftImg = " << leftImg << endl;
Mat imgOut;
cvtColor(current_img_left, imgOut, COLOR_BGR2GRAY);
imwrite(leftImg, current_img_left);
cvtColor(current_img_right, imgOut, COLOR_BGR2GRAY);
imwrite(rightImg, imgOut);
#ifdef BNO
readQuaternion(fd, q);
myfile << q[0] <<" " << q[1] <<" "<< q[2] <<" "<< q[3] << endl;
#endif
numFrame++;
cout << "numFrame = " << numFrame << endl;
if (numFrame > MAX_FRAME) {
myfile.close();
return 0;
}
waitKey(100); //micro second
}
#endif
#else
cout << "Running at simulation mode!" << endl;
#endif
//obtain truth for plot comparison
string posePath = localDataDir + "/dataset/poses/00.txt";
std::ifstream infile(posePath.c_str());
std::string line;
float truthPosition[3] ;
Mat truthOrientation;
//getline(infile, line);
//getPosition(line, truthPosition);
// Open a txt file to store the results
ofstream fout(resultFile.c_str());
if (!fout) {
cout << "File not opened!" << endl;
return 1;
}
// features
vector < Point2f > keyFeatures;
#ifdef REAL_TIME
//left camera, second frame
left_capture.read(img_2);
// right camera
right_capture.read(previous_img_right);
#else
// use the first two images from left camera to compute the init values.
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000000.png", img_1, currImage_lc);
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000001.png", img_2, currImage_lc);
loadImage(localDataDir + "/img_left/1.png", img_1, currImage_lc);
loadImage(localDataDir + "/img_right/1.png", img_2, currImage_lc);
#endif
computeInitialPose(img_1, R_f, t_f, img_2, keyFeatures);
readQuaternion(fd, q);
//fout << 1 << "\t";
//fout << t_f.at<double>(0) << "\t" << t_f.at<double>(1) << "\t" << t_f.at<double>(2) << "\t";
//fout << 0 << "\t" << 0 << "\n";
// assign them to be previous
Mat prevImage = img_2;
vector < Point2f > prevFeatures = keyFeatures;
Mat currImage;
vector < Point2f > currFeatures;
string filename;
Mat E, R, t, mask;
clock_t begin = clock();
//namedWindow("Road facing camera", WINDOW_AUTOSIZE); // Create a window for display.
namedWindow("Trajectory", WINDOW_AUTOSIZE); // Create a window for display.
Mat traj = Mat::zeros(600, 600, CV_8UC3);
Mat trajTruth = Mat::zeros(600, 600, CV_8UC3);
string fileFolder = localDataDir + "/dataset/sequences/00/";
Mat R_f_left, t_f_left;
previous_img_left = img_2;
vector<Point2f> previous_feature_left = keyFeatures;;
vector<Point2f> current_feature_left;
Mat R_f_right, t_f_right;
vector<Point2f> previous_feature_right, current_feature_right;
#ifdef REAL_TIME
// new frame from left camera
previous_img_left = img_2;
left_capture.read(current_img_left);
// new frame from right camera
right_capture.read(current_img_right);
#else
// read the first two iamges from left camera
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000000.png", previous_img_left, currImage_lc );
//loadImage(localDataDir + "/dataset/sequences/00/image_0/000001.png", current_img_left, currImage_lc);
loadImage(localDataDir + "/img_left/1.png", previous_img_left, currImage_lc );
loadImage(localDataDir + "/img_left/2.png", current_img_left, currImage_lc);
// read the first two iamges from right camera
loadImage(localDataDir + "/img_right/1.png", previous_img_right, currImage_rc);
loadImage(localDataDir + "/img_right/2.png", current_img_right, currImage_rc);
rectifyImage(previous_img_left, previous_img_right, previous_img_left, previous_img_right);
rectifyImage(current_img_left, current_img_right, current_img_left, current_img_right);
#endif
computeInitialStereoPose(previous_img_left,
current_img_left,
R_f_left,
t_f_left,
previous_feature_left,
previous_img_right,
current_img_right,
R_f_right,
t_f_right,
previous_feature_right);
for (int numFrame = 2; numFrame < MAX_FRAME; numFrame++) {
//filename = combineName(localDataDir + "/dataset/sequences/00/image_0/", numFrame);
//cout << "numFrame is " << numFrame << endl;
//getline(infile, line);
//getPosition(line, truthPosition);
#if 0
//scale = getAbsoluteScale(numFrame, 0, t_f.at<double>(2));
//cout << "scale is " << scale << endl;
updatePose(filename,
prevImage,
prevFeatures,
currFeatures,
R_f, t_f);
#else
#ifdef REAL_TIME
// Mat leftFrame;
bool readSuccess1 = left_capture.read(current_img_left);
if (readSuccess1){ currImage_lc = current_img_left;}
// Mat rightFrame;
bool readSuccess2 = right_capture.read(current_img_right);
if (readSuccess2) {currImage_rc = current_img_right; }
#else
//string filename1 = combineName(localDataDir + "/dataset/sequences/00/image_0/", numFrame);
//string filename2 = combineName(localDataDir + "/dataset/sequences/00/image_1/", numFrame);
stringstream ss;
ss << numFrame;
string idx = ss.str();
string filename1 = localDataDir + "/img_left/" + idx + ".png";
string filename2 = localDataDir + "/img_right/" + idx + ".png";
loadImage(filename1, current_img_left, currImage_lc);
loadImage(filename2, current_img_right, currImage_rc);
rectifyImage(current_img_left, current_img_right, current_img_left, current_img_right);
readQuaternion(fd, q); // read IMU
#endif
stereoVision(current_img_left,
current_img_right,
currImage_lc,
currImage_rc,
previous_img_left, previous_feature_left, current_feature_left,
previous_img_right, previous_feature_right, current_feature_right,
R_f, t_f);
#endif
// for plotting purpose
double x1 = t_f.at<double>(0);
double y1 = t_f.at<double>(1);
double z1 = t_f.at<double>(2);
int x = int(x1) + 300;
int y = int(z1) + 100;
int xTruth = int(truthPosition[0])+ 300;
int yTruth = int(truthPosition[2])+ 100;
// output to the screen
cout << "numFrame:" << numFrame <<" vo: x = " << PL<< x1 << "\t y = " << PL<< y1 << "\t z = " << PL<< z1 << endl;
#ifndef REAL_TIME
//cout << "tr: x = " << PL<< truthPosition[0] << "\t y = " << PL<< truthPosition[1] << "\t z = " << PL<< truthPosition[2] << endl;
#endif
// current point
circle(traj, Point(x, y), 0.2, CV_RGB(255, 0, 0), 2);
rectangle(traj, Point(10,30), Point(550, 50), PLOT_COLOR, CV_FILLED);
sprintf(text, "Coordinates: x = %04fm y = %04fm z = %04fm", x1, y1, z1);
putText(traj, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8);
// plot them
#ifndef REAL_TIME
imshow("Road facing camera", currImage_lc);
#endif
imshow("Trajectory", traj);
//imshow("Trajectory", trajTruth);
// Save the result
fout << numFrame << "\t";
fout << x1 << "\t" << y1 << "\t" << z1 << "\t" << x << "\t" << y << "\n";
waitKey(2); //microsecond
}
imwrite(localDataDir + "/final_map.png", traj);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "Total time taken: " << elapsed_secs << "s" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions 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 "libcef/browser/browser_host_impl.h"
#include <dwmapi.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <wininet.h>
#include <winspool.h>
#include "libcef/browser/thread_util.h"
#include "base/win/windows_version.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/base/win/hwnd_util.h"
#pragma comment(lib, "dwmapi.lib")
namespace {
bool IsAeroGlassEnabled() {
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return false;
BOOL enabled = FALSE;
return SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled;
}
void SetAeroGlass(HWND hWnd) {
if (!IsAeroGlassEnabled())
return;
// Make the whole window transparent.
MARGINS mgMarInset = { -1, -1, -1, -1 };
DwmExtendFrameIntoClientArea(hWnd, &mgMarInset);
}
void WriteTextToFile(const std::string& data, const std::wstring& file_path) {
FILE* fp;
errno_t err = _wfopen_s(&fp, file_path.c_str(), L"wt");
if (err)
return;
fwrite(data.c_str(), 1, data.size(), fp);
fclose(fp);
}
} // namespace
// static
void CefBrowserHostImpl::RegisterWindowClass() {
// Register the window class
WNDCLASSEX wcex = {
/* cbSize = */ sizeof(WNDCLASSEX),
/* style = */ CS_HREDRAW | CS_VREDRAW,
/* lpfnWndProc = */ CefBrowserHostImpl::WndProc,
/* cbClsExtra = */ 0,
/* cbWndExtra = */ 0,
/* hInstance = */ ::GetModuleHandle(NULL),
/* hIcon = */ NULL,
/* hCursor = */ LoadCursor(NULL, IDC_ARROW),
/* hbrBackground = */ 0,
/* lpszMenuName = */ NULL,
/* lpszClassName = */ CefBrowserHostImpl::GetWndClass(),
/* hIconSm = */ NULL,
};
RegisterClassEx(&wcex);
}
// static
LPCTSTR CefBrowserHostImpl::GetWndClass() {
return L"CefBrowserWindow";
}
// static
LRESULT CALLBACK CefBrowserHostImpl::WndProc(HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam) {
CefBrowserHostImpl* browser =
static_cast<CefBrowserHostImpl*>(ui::GetWindowUserData(hwnd));
switch (message) {
case WM_CLOSE:
if (browser) {
bool handled(false);
if (browser->client_.get()) {
CefRefPtr<CefLifeSpanHandler> handler =
browser->client_->GetLifeSpanHandler();
if (handler.get()) {
// Give the client a chance to handle this one.
handled = handler->DoClose(browser);
}
}
if (handled)
return 0;
// We are our own parent in this case.
browser->ParentWindowWillClose();
}
break;
case WM_DESTROY:
if (browser) {
// Clear the user data pointer.
ui::SetWindowUserData(hwnd, NULL);
// Destroy the browser.
browser->DestroyBrowser();
// Release the reference added in PlatformCreateWindow().
browser->Release();
}
return 0;
case WM_SIZE:
// Minimizing resizes the window to 0x0 which causes our layout to go all
// screwy, so we just ignore it.
if (wParam != SIZE_MINIMIZED && browser) {
// resize the web view window to the full size of the browser window
RECT rc;
GetClientRect(hwnd, &rc);
MoveWindow(browser->GetContentView(), 0, 0, rc.right, rc.bottom,
TRUE);
}
return 0;
case WM_SETFOCUS:
if (browser)
browser->OnSetFocus(FOCUS_SOURCE_SYSTEM);
return 0;
case WM_ERASEBKGND:
return 0;
case WM_DWMCOMPOSITIONCHANGED:
// Message sent to top-level windows when composition has been enabled or
// disabled.
if (browser && browser->window_info_.transparent_painting)
SetAeroGlass(hwnd);
break;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
bool CefBrowserHostImpl::PlatformCreateWindow() {
std::wstring windowName(CefString(&window_info_.window_name));
// Create the new browser window.
window_info_.window = CreateWindowEx(window_info_.ex_style,
GetWndClass(), windowName.c_str(), window_info_.style,
window_info_.x, window_info_.y, window_info_.width,
window_info_.height, window_info_.parent_window, window_info_.menu,
::GetModuleHandle(NULL), NULL);
// It's possible for CreateWindowEx to fail if the parent window was
// destroyed between the call to CreateBrowser and the above one.
DCHECK(window_info_.window != NULL);
if (!window_info_.window)
return false;
if (window_info_.transparent_painting &&
!(window_info_.style & WS_CHILD)) {
// Transparent top-level windows will be given "sheet of glass" effect.
SetAeroGlass(window_info_.window);
}
// Set window user data to this object for future reference from the window
// procedure.
ui::SetWindowUserData(window_info_.window, this);
// Add a reference that will be released in the WM_DESTROY handler.
AddRef();
// Parent the TabContents to the browser window.
SetParent(web_contents_->GetView()->GetNativeView(), window_info_.window);
// Size the web view window to the browser window.
RECT cr;
GetClientRect(window_info_.window, &cr);
// Respect the WS_VISIBLE window style when setting the window's position.
UINT flags = SWP_NOZORDER | SWP_SHOWWINDOW;
if (!(window_info_.style & WS_VISIBLE))
flags |= SWP_NOACTIVATE;
SetWindowPos(GetContentView(), NULL, cr.left, cr.top, cr.right,
cr.bottom, flags);
return true;
}
void CefBrowserHostImpl::PlatformCloseWindow() {
if (window_info_.window != NULL)
PostMessage(window_info_.window, WM_CLOSE, 0, 0);
}
void CefBrowserHostImpl::PlatformSizeTo(int width, int height) {
RECT rect = {0, 0, width, height};
DWORD style = GetWindowLong(window_info_.window, GWL_STYLE);
DWORD ex_style = GetWindowLong(window_info_.window, GWL_EXSTYLE);
bool has_menu = !(style & WS_CHILD) && (GetMenu(window_info_.window) != NULL);
// The size value is for the client area. Calculate the whole window size
// based on the current style.
AdjustWindowRectEx(&rect, style, has_menu, ex_style);
// Size the window.
SetWindowPos(window_info_.window, NULL, 0, 0, rect.right,
rect.bottom, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}
CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() {
return window_info_.window;
}
bool CefBrowserHostImpl::PlatformViewText(const std::string& text) {
CEF_REQUIRE_UIT();
DWORD dwRetVal;
DWORD dwBufSize = 512;
TCHAR lpPathBuffer[512];
UINT uRetVal;
TCHAR szTempName[512];
dwRetVal = GetTempPath(dwBufSize, // length of the buffer
lpPathBuffer); // buffer for path
if (dwRetVal > dwBufSize || (dwRetVal == 0))
return false;
// Create a temporary file.
uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
TEXT("src"), // temp file name prefix
0, // create unique name
szTempName); // buffer for name
if (uRetVal == 0)
return false;
size_t len = wcslen(szTempName);
wcscpy(szTempName + len - 3, L"txt");
WriteTextToFile(text, szTempName);
HWND frameWnd = GetAncestor(PlatformGetWindowHandle(), GA_ROOT);
int errorCode = reinterpret_cast<int>(ShellExecute(frameWnd, L"open",
szTempName, NULL, NULL, SW_SHOWNORMAL));
if (errorCode <= 32)
return false;
return true;
}
void CefBrowserHostImpl::PlatformHandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
// Any unhandled keyboard/character messages are sent to DefWindowProc so that
// shortcut keys work correctly.
DefWindowProc(event.os_event.hwnd, event.os_event.message,
event.os_event.wParam, event.os_event.lParam);
}
void CefBrowserHostImpl::PlatformRunFileChooser(
content::WebContents* contents,
const content::FileChooserParams& params,
std::vector<FilePath>& files) {
NOTIMPLEMENTED();
}
<commit_msg>Windows: Add dialog for input type="file" (issue #632).<commit_after>// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions 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 "libcef/browser/browser_host_impl.h"
#include <commdlg.h>
#include <dwmapi.h>
#include <shellapi.h>
#include <wininet.h>
#include <winspool.h>
#include "libcef/browser/thread_util.h"
#include "base/string_util.h"
#include "base/win/windows_version.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/file_chooser_params.h"
#include "ui/base/win/hwnd_util.h"
#pragma comment(lib, "dwmapi.lib")
namespace {
bool IsAeroGlassEnabled() {
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return false;
BOOL enabled = FALSE;
return SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled;
}
void SetAeroGlass(HWND hWnd) {
if (!IsAeroGlassEnabled())
return;
// Make the whole window transparent.
MARGINS mgMarInset = { -1, -1, -1, -1 };
DwmExtendFrameIntoClientArea(hWnd, &mgMarInset);
}
void WriteTextToFile(const std::string& data, const std::wstring& file_path) {
FILE* fp;
errno_t err = _wfopen_s(&fp, file_path.c_str(), L"wt");
if (err)
return;
fwrite(data.c_str(), 1, data.size(), fp);
fclose(fp);
}
// from chrome/browser/views/shell_dialogs_win.cc
bool RunOpenFileDialog(const std::wstring& filter, HWND owner, FilePath* path) {
OPENFILENAME ofn;
// We must do this otherwise the ofn's FlagsEx may be initialized to random
// junk in release builds which can cause the Places Bar not to show up!
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = owner;
wchar_t filename[MAX_PATH];
base::wcslcpy(filename, path->value().c_str(), arraysize(filename));
ofn.lpstrFile = filename;
ofn.nMaxFile = MAX_PATH;
// We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
// without having to close Chrome first.
ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
if (!filter.empty()) {
ofn.lpstrFilter = filter.c_str();
}
bool success = !!GetOpenFileName(&ofn);
if (success)
*path = FilePath(filename);
return success;
}
bool RunOpenMultiFileDialog(const std::wstring& filter, HWND owner,
std::vector<FilePath>* paths) {
OPENFILENAME ofn;
// We must do this otherwise the ofn's FlagsEx may be initialized to random
// junk in release builds which can cause the Places Bar not to show up!
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = owner;
scoped_array<wchar_t> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
filename[0] = 0;
ofn.lpstrFile = filename.get();
ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;
// We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
// without having to close Chrome first.
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER
| OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT;
if (!filter.empty()) {
ofn.lpstrFilter = filter.c_str();
}
bool success = !!GetOpenFileName(&ofn);
if (success) {
std::vector<FilePath> files;
const wchar_t* selection = ofn.lpstrFile;
while (*selection) { // Empty string indicates end of list.
files.push_back(FilePath(selection));
// Skip over filename and null-terminator.
selection += files.back().value().length() + 1;
}
if (files.empty()) {
success = false;
} else if (files.size() == 1) {
// When there is one file, it contains the path and filename.
paths->swap(files);
} else {
// Otherwise, the first string is the path, and the remainder are
// filenames.
std::vector<FilePath>::iterator path = files.begin();
for (std::vector<FilePath>::iterator file = path + 1;
file != files.end(); ++file) {
paths->push_back(path->Append(*file));
}
}
}
return success;
}
} // namespace
// static
void CefBrowserHostImpl::RegisterWindowClass() {
// Register the window class
WNDCLASSEX wcex = {
/* cbSize = */ sizeof(WNDCLASSEX),
/* style = */ CS_HREDRAW | CS_VREDRAW,
/* lpfnWndProc = */ CefBrowserHostImpl::WndProc,
/* cbClsExtra = */ 0,
/* cbWndExtra = */ 0,
/* hInstance = */ ::GetModuleHandle(NULL),
/* hIcon = */ NULL,
/* hCursor = */ LoadCursor(NULL, IDC_ARROW),
/* hbrBackground = */ 0,
/* lpszMenuName = */ NULL,
/* lpszClassName = */ CefBrowserHostImpl::GetWndClass(),
/* hIconSm = */ NULL,
};
RegisterClassEx(&wcex);
}
// static
LPCTSTR CefBrowserHostImpl::GetWndClass() {
return L"CefBrowserWindow";
}
// static
LRESULT CALLBACK CefBrowserHostImpl::WndProc(HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam) {
CefBrowserHostImpl* browser =
static_cast<CefBrowserHostImpl*>(ui::GetWindowUserData(hwnd));
switch (message) {
case WM_CLOSE:
if (browser) {
bool handled(false);
if (browser->client_.get()) {
CefRefPtr<CefLifeSpanHandler> handler =
browser->client_->GetLifeSpanHandler();
if (handler.get()) {
// Give the client a chance to handle this one.
handled = handler->DoClose(browser);
}
}
if (handled)
return 0;
// We are our own parent in this case.
browser->ParentWindowWillClose();
}
break;
case WM_DESTROY:
if (browser) {
// Clear the user data pointer.
ui::SetWindowUserData(hwnd, NULL);
// Destroy the browser.
browser->DestroyBrowser();
// Release the reference added in PlatformCreateWindow().
browser->Release();
}
return 0;
case WM_SIZE:
// Minimizing resizes the window to 0x0 which causes our layout to go all
// screwy, so we just ignore it.
if (wParam != SIZE_MINIMIZED && browser) {
// resize the web view window to the full size of the browser window
RECT rc;
GetClientRect(hwnd, &rc);
MoveWindow(browser->GetContentView(), 0, 0, rc.right, rc.bottom,
TRUE);
}
return 0;
case WM_SETFOCUS:
if (browser)
browser->OnSetFocus(FOCUS_SOURCE_SYSTEM);
return 0;
case WM_ERASEBKGND:
return 0;
case WM_DWMCOMPOSITIONCHANGED:
// Message sent to top-level windows when composition has been enabled or
// disabled.
if (browser && browser->window_info_.transparent_painting)
SetAeroGlass(hwnd);
break;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
bool CefBrowserHostImpl::PlatformCreateWindow() {
std::wstring windowName(CefString(&window_info_.window_name));
// Create the new browser window.
window_info_.window = CreateWindowEx(window_info_.ex_style,
GetWndClass(), windowName.c_str(), window_info_.style,
window_info_.x, window_info_.y, window_info_.width,
window_info_.height, window_info_.parent_window, window_info_.menu,
::GetModuleHandle(NULL), NULL);
// It's possible for CreateWindowEx to fail if the parent window was
// destroyed between the call to CreateBrowser and the above one.
DCHECK(window_info_.window != NULL);
if (!window_info_.window)
return false;
if (window_info_.transparent_painting &&
!(window_info_.style & WS_CHILD)) {
// Transparent top-level windows will be given "sheet of glass" effect.
SetAeroGlass(window_info_.window);
}
// Set window user data to this object for future reference from the window
// procedure.
ui::SetWindowUserData(window_info_.window, this);
// Add a reference that will be released in the WM_DESTROY handler.
AddRef();
// Parent the TabContents to the browser window.
SetParent(web_contents_->GetView()->GetNativeView(), window_info_.window);
// Size the web view window to the browser window.
RECT cr;
GetClientRect(window_info_.window, &cr);
// Respect the WS_VISIBLE window style when setting the window's position.
UINT flags = SWP_NOZORDER | SWP_SHOWWINDOW;
if (!(window_info_.style & WS_VISIBLE))
flags |= SWP_NOACTIVATE;
SetWindowPos(GetContentView(), NULL, cr.left, cr.top, cr.right,
cr.bottom, flags);
return true;
}
void CefBrowserHostImpl::PlatformCloseWindow() {
if (window_info_.window != NULL)
PostMessage(window_info_.window, WM_CLOSE, 0, 0);
}
void CefBrowserHostImpl::PlatformSizeTo(int width, int height) {
RECT rect = {0, 0, width, height};
DWORD style = GetWindowLong(window_info_.window, GWL_STYLE);
DWORD ex_style = GetWindowLong(window_info_.window, GWL_EXSTYLE);
bool has_menu = !(style & WS_CHILD) && (GetMenu(window_info_.window) != NULL);
// The size value is for the client area. Calculate the whole window size
// based on the current style.
AdjustWindowRectEx(&rect, style, has_menu, ex_style);
// Size the window.
SetWindowPos(window_info_.window, NULL, 0, 0, rect.right,
rect.bottom, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}
CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() {
return window_info_.window;
}
bool CefBrowserHostImpl::PlatformViewText(const std::string& text) {
CEF_REQUIRE_UIT();
DWORD dwRetVal;
DWORD dwBufSize = 512;
TCHAR lpPathBuffer[512];
UINT uRetVal;
TCHAR szTempName[512];
dwRetVal = GetTempPath(dwBufSize, // length of the buffer
lpPathBuffer); // buffer for path
if (dwRetVal > dwBufSize || (dwRetVal == 0))
return false;
// Create a temporary file.
uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
TEXT("src"), // temp file name prefix
0, // create unique name
szTempName); // buffer for name
if (uRetVal == 0)
return false;
size_t len = wcslen(szTempName);
wcscpy(szTempName + len - 3, L"txt");
WriteTextToFile(text, szTempName);
HWND frameWnd = GetAncestor(PlatformGetWindowHandle(), GA_ROOT);
int errorCode = reinterpret_cast<int>(ShellExecute(frameWnd, L"open",
szTempName, NULL, NULL, SW_SHOWNORMAL));
if (errorCode <= 32)
return false;
return true;
}
void CefBrowserHostImpl::PlatformHandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
// Any unhandled keyboard/character messages are sent to DefWindowProc so that
// shortcut keys work correctly.
DefWindowProc(event.os_event.hwnd, event.os_event.message,
event.os_event.wParam, event.os_event.lParam);
}
void CefBrowserHostImpl::PlatformRunFileChooser(
content::WebContents* contents,
const content::FileChooserParams& params,
std::vector<FilePath>& files) {
if (params.mode == content::FileChooserParams::OpenMultiple) {
RunOpenMultiFileDialog(L"", PlatformGetWindowHandle(), &files);
} else {
FilePath file_name;
if (RunOpenFileDialog(L"", PlatformGetWindowHandle(), &file_name))
files.push_back(file_name);
}
}
<|endoftext|>
|
<commit_before>/*
Copyright libCellML Contributors
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 "xmldoc.h"
#include <cstring>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <sstream>
#include <string>
#include <vector>
#include "xmlnode.h"
#include "debug.h"
namespace libcellml {
/**
* @brief Callback for errors from the libxml2 context parser.
*
* Structured callback @c xmlStructuredErrorFunc for errors
* from the libxml2 context parser used to parse this document.
*
* @param userData Private data type used to store the libxml context.
*
* @param error The @c xmlErrorPtr to the error raised by libxml.
*/
void structuredErrorCallback(void *userData, xmlErrorPtr error)
{
std::string errorString = std::string(error->message);
// Swap libxml2 carriage return for a period.
if (errorString.substr(errorString.length() - 1) == "\n") {
errorString.replace(errorString.end() - 1, errorString.end(), ".");
}
auto context = reinterpret_cast<xmlParserCtxtPtr>(userData);
auto doc = reinterpret_cast<XmlDoc *>(context->_private);
doc->addXmlError(errorString);
}
/**
* @brief The XmlDoc::XmlDocImpl struct.
*
* This struct is the private implementation struct for the XmlDoc class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct XmlDoc::XmlDocImpl
{
xmlDocPtr mXmlDocPtr = nullptr;
std::vector<std::string> mXmlErrors;
};
XmlDoc::XmlDoc()
: mPimpl(new XmlDocImpl())
{
}
XmlDoc::~XmlDoc()
{
if (mPimpl->mXmlDocPtr != nullptr) {
xmlFreeDoc(mPimpl->mXmlDocPtr);
}
delete mPimpl;
}
void XmlDoc::parse(const std::string &input)
{
xmlInitParser();
xmlParserCtxtPtr context = xmlNewParserCtxt();
context->_private = reinterpret_cast<void *>(this);
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0);
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();
xmlCleanupGlobals();
}
void XmlDoc::parseMathML(const std::string &input)
{
const std::string mathmlDtd =
#include "fullmathmldtd.h"
;
Debug() << "============";
Debug() << "here 1";
xmlInitParser();
Debug() << "here 2";
xmlParserCtxtPtr context = xmlNewParserCtxt();
Debug() << "here 3";
context->_private = reinterpret_cast<void *>(this);
Debug() << "here 4";
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
Debug() << "here 5";
mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0);
Debug() << "here 6";
xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(reinterpret_cast<const char *>(mathmlDtd.c_str()), mathmlDtd.size(), XML_CHAR_ENCODING_ASCII);
Debug() << "here 7" << buf;
xmlDtdPtr dtd = xmlIOParseDTD(NULL, buf, XML_CHAR_ENCODING_UTF8);
Debug() << "here 8";
xmlValidateDtd(&(context->vctxt), mPimpl->mXmlDocPtr, dtd);
Debug() << "here 9";
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();
xmlCleanupGlobals();
}
std::string XmlDoc::prettyPrint() const
{
xmlChar *buffer;
int size = 0;
xmlDocDumpFormatMemoryEnc(mPimpl->mXmlDocPtr, &buffer, &size, "UTF-8", 1);
std::stringstream res;
res << buffer;
xmlFree(buffer);
return res.str();
}
XmlNodePtr XmlDoc::rootNode() const
{
xmlNodePtr root = xmlDocGetRootElement(mPimpl->mXmlDocPtr);
XmlNodePtr rootHandle = nullptr;
if (root != nullptr) {
rootHandle = std::make_shared<XmlNode>();
rootHandle->setXmlNode(root);
}
return rootHandle;
}
void XmlDoc::addXmlError(const std::string &error)
{
mPimpl->mXmlErrors.push_back(error);
}
size_t XmlDoc::xmlErrorCount() const
{
return mPimpl->mXmlErrors.size();
}
std::string XmlDoc::xmlError(size_t index) const
{
return mPimpl->mXmlErrors.at(index);
}
} // namespace libcellml
<commit_msg>Change to using an in memory buffer for the MathML DTD.<commit_after>/*
Copyright libCellML Contributors
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 "xmldoc.h"
#include <cstring>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <sstream>
#include <string>
#include <vector>
#include "xmlnode.h"
namespace libcellml {
static const char *mathmlDtd =
#include "fullmathmldtd.h"
;
/**
* @brief Callback for errors from the libxml2 context parser.
*
* Structured callback @c xmlStructuredErrorFunc for errors
* from the libxml2 context parser used to parse this document.
*
* @param userData Private data type used to store the libxml context.
*
* @param error The @c xmlErrorPtr to the error raised by libxml.
*/
void structuredErrorCallback(void *userData, xmlErrorPtr error)
{
std::string errorString = std::string(error->message);
// Swap libxml2 carriage return for a period.
if (errorString.substr(errorString.length() - 1) == "\n") {
errorString.replace(errorString.end() - 1, errorString.end(), ".");
}
auto context = reinterpret_cast<xmlParserCtxtPtr>(userData);
auto doc = reinterpret_cast<XmlDoc *>(context->_private);
doc->addXmlError(errorString);
}
/**
* @brief The XmlDoc::XmlDocImpl struct.
*
* This struct is the private implementation struct for the XmlDoc class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct XmlDoc::XmlDocImpl
{
xmlDocPtr mXmlDocPtr = nullptr;
std::vector<std::string> mXmlErrors;
size_t bufferPointer = 0;
};
XmlDoc::XmlDoc()
: mPimpl(new XmlDocImpl())
{
}
XmlDoc::~XmlDoc()
{
if (mPimpl->mXmlDocPtr != nullptr) {
xmlFreeDoc(mPimpl->mXmlDocPtr);
}
delete mPimpl;
}
void XmlDoc::parse(const std::string &input)
{
xmlInitParser();
xmlParserCtxtPtr context = xmlNewParserCtxt();
context->_private = reinterpret_cast<void *>(this);
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0);
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();
xmlCleanupGlobals();
}
void XmlDoc::parseMathML(const std::string &input)
{
xmlInitParser();
xmlParserCtxtPtr context = xmlNewParserCtxt();
context->_private = reinterpret_cast<void *>(this);
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0);
xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(reinterpret_cast<const char *>(mathmlDtd), strlen(mathmlDtd), XML_CHAR_ENCODING_ASCII);
xmlDtdPtr dtd = xmlIOParseDTD(nullptr, buf, XML_CHAR_ENCODING_ASCII);
xmlValidateDtd(&(context->vctxt), mPimpl->mXmlDocPtr, dtd);
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlCleanupParser();
xmlCleanupGlobals();
}
std::string XmlDoc::prettyPrint() const
{
xmlChar *buffer;
int size = 0;
xmlDocDumpFormatMemoryEnc(mPimpl->mXmlDocPtr, &buffer, &size, "UTF-8", 1);
std::stringstream res;
res << buffer;
xmlFree(buffer);
return res.str();
}
XmlNodePtr XmlDoc::rootNode() const
{
xmlNodePtr root = xmlDocGetRootElement(mPimpl->mXmlDocPtr);
XmlNodePtr rootHandle = nullptr;
if (root != nullptr) {
rootHandle = std::make_shared<XmlNode>();
rootHandle->setXmlNode(root);
}
return rootHandle;
}
void XmlDoc::addXmlError(const std::string &error)
{
mPimpl->mXmlErrors.push_back(error);
}
size_t XmlDoc::xmlErrorCount() const
{
return mPimpl->mXmlErrors.size();
}
std::string XmlDoc::xmlError(size_t index) const
{
return mPimpl->mXmlErrors.at(index);
}
} // namespace libcellml
<|endoftext|>
|
<commit_before>#include "zipper.hpp"
// stl
#include <sstream>
#include <vector>
#include <cstring>
#include <algorithm>
//#include <iostream>
#include <node_buffer.h>
#include <node_version.h>
#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))
Persistent<FunctionTemplate> Zipper::constructor;
void Zipper::Initialize(Handle<Object> target) {
HandleScope scope;
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Zipper::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::NewSymbol("Zipper"));
// functions
NODE_SET_PROTOTYPE_METHOD(constructor, "addFile", addFile);
target->Set(String::NewSymbol("Zipper"),constructor->GetFunction());
}
Zipper::Zipper(std::string const& file_name) :
ObjectWrap(),
file_name_(file_name),
archive_() {}
Zipper::~Zipper() {
zip_close(archive_);
}
Handle<Value> Zipper::New(const Arguments& args)
{
HandleScope scope;
if (!args.IsConstructCall())
return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
if (args.Length() != 1 || !args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be a path to a zipfile")));
std::string input_file = TOSTR(args[0]);
struct zip *za;
int err;
char errstr[1024];
if ((za=zip_open(input_file.c_str(), ZIP_CREATE, &err)) == NULL) {
zip_error_to_str(errstr, sizeof(errstr), err, errno);
std::stringstream s;
s << "cannot open file: " << input_file << " error: " << errstr << "\n";
return ThrowException(Exception::Error(
String::New(s.str().c_str())));
}
Zipper* zf = new Zipper(input_file);
zf->archive_ = za;
zf->Wrap(args.This());
return args.This();
}
typedef struct {
Zipper* zf;
struct zip *za;
std::string name;
std::string path;
bool error;
std::string error_name;
std::vector<unsigned char> data;
Persistent<Function> cb;
} closure_t;
Handle<Value> Zipper::addFile(const Arguments& args)
{
HandleScope scope;
if (args.Length() < 3)
return ThrowException(Exception::TypeError(
String::New("requires two arguments, the path of a file and a callback")));
// first arg must be path
if(!args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be a file path to add to the zip")));
// second arg must be name
if(!args[1]->IsString())
return ThrowException(Exception::TypeError(
String::New("second argument must be a file name to add to the zip")));
// last arg must be function callback
if (!args[args.Length()-1]->IsFunction())
return ThrowException(Exception::TypeError(
String::New("last argument must be a callback function")));
std::string path = TOSTR(args[0]);
std::string name = TOSTR(args[1]);
Zipper* zf = ObjectWrap::Unwrap<Zipper>(args.This());
closure_t *closure = new closure_t();
// libzip is not threadsafe so we cannot use the zf->archive_
// instead we open a new zip archive for each thread
struct zip *za;
int err;
char errstr[1024];
if ((za=zip_open(zf->file_name_.c_str() , ZIP_CREATE, &err)) == NULL) {
zip_error_to_str(errstr, sizeof(errstr), err, errno);
std::stringstream s;
s << "cannot open file: " << zf->file_name_ << " error: " << errstr << "\n";
zip_close(za);
return ThrowException(Exception::Error(String::New(s.str().c_str())));
}
closure->zf = zf;
closure->za = za;
closure->error = false;
closure->path = path;
closure->name = name;
closure->cb = Persistent<Function>::New(Handle<Function>::Cast(args[args.Length()-1]));
eio_custom(EIO_AddFile, EIO_PRI_DEFAULT, EIO_AfterAddFile, closure);
ev_ref(EV_DEFAULT_UC);
zf->Ref();
return Undefined();
}
int Zipper::EIO_AddFile(eio_req *req)
{
closure_t *closure = static_cast<closure_t *>(req->data);
struct zip_source *source = zip_source_file(closure->za, closure->path.c_str(), 0, 0);
if (zip_add(closure->za, closure->name.c_str(), source) < 0) {
std::stringstream s;
s << "Cannot prepare file for add to zip: '" << closure->path << "'\n";
closure->error = true;
closure->error_name = s.str();
zip_source_free(source);
}
if (zip_close(closure->za) < 0) {
std::stringstream s;
s << "Cannot add file to zip: '" << closure->path << "' (" << zip_strerror(closure->za) << ")\n";
closure->error = true;
closure->error_name = s.str();
}
return 0;
}
int Zipper::EIO_AfterAddFile(eio_req *req)
{
HandleScope scope;
closure_t *closure = static_cast<closure_t *>(req->data);
ev_unref(EV_DEFAULT_UC);
TryCatch try_catch;
if (closure->error) {
Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
} else {
Local<Value> argv[1] = { Local<Value>::New(Null()) };
closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
}
if (try_catch.HasCaught()) {
FatalException(try_catch);
//try_catch.ReThrow();
}
closure->zf->Unref();
closure->cb.Dispose();
delete closure;
return 0;
}
<commit_msg>Fix error message.<commit_after>#include "zipper.hpp"
// stl
#include <sstream>
#include <vector>
#include <cstring>
#include <algorithm>
//#include <iostream>
#include <node_buffer.h>
#include <node_version.h>
#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))
Persistent<FunctionTemplate> Zipper::constructor;
void Zipper::Initialize(Handle<Object> target) {
HandleScope scope;
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Zipper::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::NewSymbol("Zipper"));
// functions
NODE_SET_PROTOTYPE_METHOD(constructor, "addFile", addFile);
target->Set(String::NewSymbol("Zipper"),constructor->GetFunction());
}
Zipper::Zipper(std::string const& file_name) :
ObjectWrap(),
file_name_(file_name),
archive_() {}
Zipper::~Zipper() {
zip_close(archive_);
}
Handle<Value> Zipper::New(const Arguments& args)
{
HandleScope scope;
if (!args.IsConstructCall())
return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
if (args.Length() != 1 || !args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be a path to a zipfile")));
std::string input_file = TOSTR(args[0]);
struct zip *za;
int err;
char errstr[1024];
if ((za=zip_open(input_file.c_str(), ZIP_CREATE, &err)) == NULL) {
zip_error_to_str(errstr, sizeof(errstr), err, errno);
std::stringstream s;
s << "cannot open file: " << input_file << " error: " << errstr << "\n";
return ThrowException(Exception::Error(
String::New(s.str().c_str())));
}
Zipper* zf = new Zipper(input_file);
zf->archive_ = za;
zf->Wrap(args.This());
return args.This();
}
typedef struct {
Zipper* zf;
struct zip *za;
std::string name;
std::string path;
bool error;
std::string error_name;
std::vector<unsigned char> data;
Persistent<Function> cb;
} closure_t;
Handle<Value> Zipper::addFile(const Arguments& args)
{
HandleScope scope;
if (args.Length() < 3)
return ThrowException(Exception::TypeError(
String::New("requires three arguments, the path of a file, a filename and a callback")));
// first arg must be path
if(!args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first argument must be a file path to add to the zip")));
// second arg must be name
if(!args[1]->IsString())
return ThrowException(Exception::TypeError(
String::New("second argument must be a file name to add to the zip")));
// last arg must be function callback
if (!args[args.Length()-1]->IsFunction())
return ThrowException(Exception::TypeError(
String::New("last argument must be a callback function")));
std::string path = TOSTR(args[0]);
std::string name = TOSTR(args[1]);
Zipper* zf = ObjectWrap::Unwrap<Zipper>(args.This());
closure_t *closure = new closure_t();
// libzip is not threadsafe so we cannot use the zf->archive_
// instead we open a new zip archive for each thread
struct zip *za;
int err;
char errstr[1024];
if ((za=zip_open(zf->file_name_.c_str() , ZIP_CREATE, &err)) == NULL) {
zip_error_to_str(errstr, sizeof(errstr), err, errno);
std::stringstream s;
s << "cannot open file: " << zf->file_name_ << " error: " << errstr << "\n";
zip_close(za);
return ThrowException(Exception::Error(String::New(s.str().c_str())));
}
closure->zf = zf;
closure->za = za;
closure->error = false;
closure->path = path;
closure->name = name;
closure->cb = Persistent<Function>::New(Handle<Function>::Cast(args[args.Length()-1]));
eio_custom(EIO_AddFile, EIO_PRI_DEFAULT, EIO_AfterAddFile, closure);
ev_ref(EV_DEFAULT_UC);
zf->Ref();
return Undefined();
}
int Zipper::EIO_AddFile(eio_req *req)
{
closure_t *closure = static_cast<closure_t *>(req->data);
struct zip_source *source = zip_source_file(closure->za, closure->path.c_str(), 0, 0);
if (zip_add(closure->za, closure->name.c_str(), source) < 0) {
std::stringstream s;
s << "Cannot prepare file for add to zip: '" << closure->path << "'\n";
closure->error = true;
closure->error_name = s.str();
zip_source_free(source);
}
if (zip_close(closure->za) < 0) {
std::stringstream s;
s << "Cannot add file to zip: '" << closure->path << "' (" << zip_strerror(closure->za) << ")\n";
closure->error = true;
closure->error_name = s.str();
}
return 0;
}
int Zipper::EIO_AfterAddFile(eio_req *req)
{
HandleScope scope;
closure_t *closure = static_cast<closure_t *>(req->data);
ev_unref(EV_DEFAULT_UC);
TryCatch try_catch;
if (closure->error) {
Local<Value> argv[1] = { Exception::Error(String::New(closure->error_name.c_str())) };
closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
} else {
Local<Value> argv[1] = { Local<Value>::New(Null()) };
closure->cb->Call(Context::GetCurrent()->Global(), 1, argv);
}
if (try_catch.HasCaught()) {
FatalException(try_catch);
//try_catch.ReThrow();
}
closure->zf->Unref();
closure->cb.Dispose();
delete closure;
return 0;
}
<|endoftext|>
|
<commit_before>// (C) 2013 Cybozu.
#include "util.hpp"
#include <cxxabi.h>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <execinfo.h>
#include <sstream>
#include <string.h>
#include <stdexcept>
#include <unistd.h>
namespace cybozu {
demangler::demangler(const char* name) {
int status;
char* demangled = abi::__cxa_demangle(name, 0, 0, &status);
if( status == 0 ) {
m_name = demangled;
std::free(demangled);
} else {
m_name = name;
}
}
#pragma GCC diagnostic ignored "-Wunused-result"
void dump_stack() noexcept {
char buf[32];
std::time_t t = std::time(nullptr);
std::size_t len = std::strlen(ctime_r(&t, buf));
::write(STDERR_FILENO, buf, len);
void* bt[100];
int n = backtrace(bt, 100);
backtrace_symbols_fd(bt, n, STDERR_FILENO);
}
#pragma GCC diagnostic pop
void clear_memory_(void* s, std::size_t n) {
volatile unsigned char *p = (unsigned char*)s;
while( n-- ) *p++ = 0;
}
void (* const volatile clear_memory)(void* s, std::size_t n) = clear_memory_;
} // namespace cybozu
<commit_msg>Make clear_memory_ anonymous.<commit_after>// (C) 2013 Cybozu.
#include "util.hpp"
#include <cxxabi.h>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <execinfo.h>
#include <sstream>
#include <string.h>
#include <stdexcept>
#include <unistd.h>
namespace {
void clear_memory_(void* s, std::size_t n) {
volatile unsigned char *p = (unsigned char*)s;
while( n-- ) *p++ = 0;
}
} // anonymous namespace
namespace cybozu {
demangler::demangler(const char* name) {
int status;
char* demangled = abi::__cxa_demangle(name, 0, 0, &status);
if( status == 0 ) {
m_name = demangled;
std::free(demangled);
} else {
m_name = name;
}
}
#pragma GCC diagnostic ignored "-Wunused-result"
void dump_stack() noexcept {
char buf[32];
std::time_t t = std::time(nullptr);
std::size_t len = std::strlen(ctime_r(&t, buf));
::write(STDERR_FILENO, buf, len);
void* bt[100];
int n = backtrace(bt, 100);
backtrace_symbols_fd(bt, n, STDERR_FILENO);
}
#pragma GCC diagnostic pop
void (* const volatile clear_memory)(void* s, std::size_t n) = clear_memory_;
} // namespace cybozu
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPP_STOP_WATCH_HPP
#define CPP_STOP_WATCH_HPP
#include <chrono>
#include <iostream>
namespace cpp {
typedef std::chrono::high_resolution_clock clock_type;
template<typename precision = std::chrono::milliseconds>
class stop_watch {
public:
stop_watch(){
start_point = clock_type::now();
}
double elapsed(){
auto end_point = clock_type::now();
auto time = std::chrono::duration_cast<precision>(end_point - start_point);
return time.count();
}
private:
clock_type::time_point start_point;
};
template<typename precision = std::chrono::milliseconds>
class auto_stop_watch {
public:
auto_stop_watch(std::string title) : title(title) {
//Empty
}
~auto_stop_watch(){
std::cout << title << " took " << watch.elapsed() << std::endl;
}
private:
std::string title;
stop_watch<precision> watch;
};
} //end of cpp namespace
#endif//CPP_STOP_WATCH_HPP
<commit_msg>Clean<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPP_STOP_WATCH_HPP
#define CPP_STOP_WATCH_HPP
#include <chrono>
#include <iostream>
namespace cpp {
typedef std::chrono::high_resolution_clock clock_type;
template<typename precision = std::chrono::milliseconds>
class stop_watch {
public:
stop_watch(){
start_point = clock_type::now();
}
double elapsed(){
auto end_point = clock_type::now();
auto time = std::chrono::duration_cast<precision>(end_point - start_point);
return time.count();
}
private:
clock_type::time_point start_point;
};
template<typename precision = std::chrono::milliseconds>
class auto_stop_watch {
public:
auto_stop_watch(std::string title) : title(title) {
//Empty
}
~auto_stop_watch(){
std::cout << title << " took " << watch.elapsed() << std::endl;
}
private:
std::string title;
stop_watch<precision> watch;
};
} //end of cpp namespace
#endif //CPP_STOP_WATCH_HPP
<|endoftext|>
|
<commit_before>#include "data-course.hpp"
using namespace std;
void Course::init(string identifier) {
// cout << identifier << endl;
copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
id = c.id;
number = c.number;
title = c.title;
description = c.description;
section = c.section;
majors = c.majors;
department = c.department;
concentrations = c.concentrations;
conversations = c.conversations;
professor = c.professor;
half_semester = c.half_semester;
pass_fail = c.pass_fail;
credits = c.credits;
location = c.location;
lab = c.lab;
geneds = c.geneds;
for (int i = 0; i < 7; ++i){
days[i] = c.days[i];
time[i] = c.time[i];
}
}
Course::Course() {
}
Course::Course(string str) {
init(str);
}
Course::Course(const Course& c) {
copy(c);
}
Course& Course::operator = (const Course &c) {
if (this == &c) return *this;
copy(c);
return *this;
}
Course::Course(istream &is) {
// cout << "Now indise Course()" << endl;
if (!is) return;
// cout << "Now inside Course(after return)" << endl;
string tmpLine;
getline(is, tmpLine); // read in so we can do things with it.
vector<string> record = split(tmpLine, ',');
for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
*i = removeAllQuotes(*i);
*i = removeTrailingSlashes(*i);
}
// printEntireRecord(record);
// 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);
// 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);
// 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);
}
updateID();
title = cleanTitle(title);
record.clear();
}
bool operator== (Course &c1, Course &c2) {
return (c1.id == c2.id);
}
bool operator!= (Course &c1, Course &c2) {
return !(c1 == c2);
}
string Course::cleanTitle(string title) {
vector<string> badEndings, badBeginnings;
badEndings.push_back(" Closed");
badEndings.push_back(" During course submission process");
badEndings.push_back(" Especially for ");
badEndings.push_back(" Film screenings");
badEndings.push_back(" First-Year Students may register only");
badEndings.push_back(" New course");
badEndings.push_back(" Not open to first-year students.");
badEndings.push_back(" Open only to ");
badEndings.push_back(" Open to ");
badEndings.push_back(" Permission of ");
badEndings.push_back(" Prereq");
badEndings.push_back(" Registration");
badEndings.push_back(" Taught in English.");
badEndings.push_back(" This course");
badEndings.push_back(" This lab has been canceled.");
badEndings.push_back(" Students in ");
badBeginnings.push_back("Top: ");
badBeginnings.push_back("Sem: ");
badBeginnings.push_back("Res: ");
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);
return title;
}
string Course::getProfessor() {
return professor;
}
void Course::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".
string dept = str.substr(0,str.size()-3);
if (str.find('/') != string::npos) {
department.push_back(Department(dept.substr(0,2)));
department.push_back(Department(dept.substr(3,2)));
}
else {
department.push_back(Department(dept));
}
}
void Course::updateID() {
string dept;
for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
dept += i->getName();
if (i != department.end()-1)
dept += "/";
}
id = dept + " " + tostring(number) + section;
}
string Course::getID() {
return id;
}
ostream& Course::getData(ostream &os) {
os << id;
if (lab) os << " L";
os << " - ";
os << title << " | ";
if (professor.length() > 0 && professor != " ")
os << professor;
return os;
}
void Course::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() {
cout << *this << endl;
}
void Course::displayMany() {
cout << id;
if (lab) cout << " L";
cout << "\t- ";
cout << title << " | ";
if (professor.length() > 0 && professor != " ")
cout << professor;
cout << endl;
}
Course getCourse(string identifier) {
// TODO: Merge the two ways of parsing IDs
// TODO: Add lab support.
// cout << "Before cleanup: " << identifier << endl;
// Make sure everything is uppercase
std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::toupper);
// Remove a possible space at the front
if (identifier[0] == ' ')
identifier.erase(0, 1);
// add a space into the course id, if there isn't one already
// find the first digit in the string
int firstDigit = identifier.find_first_of("0123456789");
if (identifier.find(" ") == string::npos)
identifier.insert(firstDigit, 1, ' ');
// cout << "After cleanup: " << identifier << endl;
for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
if (i->getID() == identifier)
return *i;
// If no match, return a blank course.
Course c;
return c;
}
<commit_msg>Switch to a long for firstDigit<commit_after>#include "data-course.hpp"
using namespace std;
void Course::init(string identifier) {
// cout << identifier << endl;
copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
id = c.id;
number = c.number;
title = c.title;
description = c.description;
section = c.section;
majors = c.majors;
department = c.department;
concentrations = c.concentrations;
conversations = c.conversations;
professor = c.professor;
half_semester = c.half_semester;
pass_fail = c.pass_fail;
credits = c.credits;
location = c.location;
lab = c.lab;
geneds = c.geneds;
for (int i = 0; i < 7; ++i){
days[i] = c.days[i];
time[i] = c.time[i];
}
}
Course::Course() {
}
Course::Course(string str) {
init(str);
}
Course::Course(const Course& c) {
copy(c);
}
Course& Course::operator = (const Course &c) {
if (this == &c) return *this;
copy(c);
return *this;
}
Course::Course(istream &is) {
// cout << "Now indise Course()" << endl;
if (!is) return;
// cout << "Now inside Course(after return)" << endl;
string tmpLine;
getline(is, tmpLine); // read in so we can do things with it.
vector<string> record = split(tmpLine, ',');
for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
*i = removeAllQuotes(*i);
*i = removeTrailingSlashes(*i);
}
// printEntireRecord(record);
// 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);
// 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);
// 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);
}
updateID();
title = cleanTitle(title);
record.clear();
}
bool operator== (Course &c1, Course &c2) {
return (c1.id == c2.id);
}
bool operator!= (Course &c1, Course &c2) {
return !(c1 == c2);
}
string Course::cleanTitle(string title) {
vector<string> badEndings, badBeginnings;
badEndings.push_back(" Closed");
badEndings.push_back(" During course submission process");
badEndings.push_back(" Especially for ");
badEndings.push_back(" Film screenings");
badEndings.push_back(" First-Year Students may register only");
badEndings.push_back(" New course");
badEndings.push_back(" Not open to first-year students.");
badEndings.push_back(" Open only to ");
badEndings.push_back(" Open to ");
badEndings.push_back(" Permission of ");
badEndings.push_back(" Prereq");
badEndings.push_back(" Registration");
badEndings.push_back(" Taught in English.");
badEndings.push_back(" This course");
badEndings.push_back(" This lab has been canceled.");
badEndings.push_back(" Students in ");
badBeginnings.push_back("Top: ");
badBeginnings.push_back("Sem: ");
badBeginnings.push_back("Res: ");
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);
return title;
}
string Course::getProfessor() {
return professor;
}
void Course::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".
string dept = str.substr(0,str.size()-3);
if (str.find('/') != string::npos) {
department.push_back(Department(dept.substr(0,2)));
department.push_back(Department(dept.substr(3,2)));
}
else {
department.push_back(Department(dept));
}
}
void Course::updateID() {
string dept;
for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
dept += i->getName();
if (i != department.end()-1)
dept += "/";
}
id = dept + " " + tostring(number) + section;
}
string Course::getID() {
return id;
}
ostream& Course::getData(ostream &os) {
os << id;
if (lab) os << " L";
os << " - ";
os << title << " | ";
if (professor.length() > 0 && professor != " ")
os << professor;
return os;
}
void Course::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() {
cout << *this << endl;
}
void Course::displayMany() {
cout << id;
if (lab) cout << " L";
cout << "\t- ";
cout << title << " | ";
if (professor.length() > 0 && professor != " ")
cout << professor;
cout << endl;
}
Course getCourse(string identifier) {
// TODO: Merge the two ways of parsing IDs
// TODO: Add lab support.
// cout << "Before cleanup: " << identifier << endl;
// Make sure everything is uppercase
std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::toupper);
// Remove a possible space at the front
if (identifier[0] == ' ')
identifier.erase(0, 1);
// add a space into the course id, if there isn't one already
// find the first digit in the string
long firstDigit = identifier.find_first_of("0123456789");
if (identifier.find(" ") == string::npos)
identifier.insert(firstDigit, 1, ' ');
// cout << "After cleanup: " << identifier << endl;
for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
if (i->getID() == identifier)
return *i;
// If no match, return a blank course.
Course c;
return c;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2015 Cornell University
*
* 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 <stdio.h>
#include <assert.h>
#include "SonicUserRequest.h"
#include "SonicUserIndication.h"
#define NUMBER_OF_TESTS 1
static SonicUserRequestProxy *device = 0;
//static sem_t wait_log;
class SonicUser : public SonicUserIndicationWrapper
{
public:
virtual void dtp_read_version_resp(uint32_t a) {
fprintf(stderr, "read version %d\n", a);
}
virtual void dtp_read_delay_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read delay(%d) %d\n", p, a);
}
virtual void dtp_read_state_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read state(%d) %d\n", p, a);
}
virtual void dtp_read_error_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read error(%d) %ld\n", p, a);
}
virtual void dtp_read_cnt_resp(uint64_t a) {
fprintf(stderr, "readCycleCount(%lx)\n", a);
}
virtual void dtp_logger_read_cnt_resp(uint8_t a, uint64_t b, uint64_t c, uint64_t d) {
fprintf(stderr, "read from port(%d) local_cnt(%lx) msg1(%lx) msg2(%lx)\n", a, b, c, d);
}
virtual void dtp_read_local_cnt_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%lx)\n", p, a);
}
virtual void dtp_read_global_cnt_resp(uint64_t a) {
fprintf(stderr, "read global_cnt(%lx)\n", a);
}
virtual void dtp_read_beacon_interval_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%x)\n", p, a);
}
virtual void dtp_debug_rcvd_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq1(%x) enq2(%x) deq(%x)\n", p, a, b, c);
}
virtual void dtp_debug_sent_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq(%x) deq1(%x) deq2(%x)\n", p, a, b, c);
}
virtual void dtp_debug_rcvd_err_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) err(%x)\n", p, a);
}
virtual void dtp_get_mode_resp(uint8_t a) {
fprintf(stderr, "read from mode(%x)\n", a);
}
SonicUser(unsigned int id) : SonicUserIndicationWrapper(id) {}
};
int main(int argc, const char **argv)
{
uint32_t count = 100;
SonicUser indication(IfcNames_SonicUserIndicationH2S);
device = new SonicUserRequestProxy(IfcNames_SonicUserRequestS2H);
device->pint.busyType = BUSY_SPIN; /* spin until request portal 'notFull' */
device->dtp_reset(32);
device->dtp_read_version();
fprintf(stderr, "Main::about to go to sleep\n");
while(true){
for (int i=0; i<1; i++) {
device->dtp_read_delay(i);
device->dtp_read_state(i);
device->dtp_read_error(i);
device->dtp_read_cnt(i);
}
for (int i=0; i<4; i++) {
device->dtp_logger_write_cnt(i, count);
}
for (int i=0; i<4; i++) {
device->dtp_logger_read_cnt(i);
}
count ++;
sleep(2);
}
}
<commit_msg>added a delay before sending log<commit_after>/* Copyright (c) 2015 Cornell University
*
* 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 <stdio.h>
#include <assert.h>
#include "SonicUserRequest.h"
#include "SonicUserIndication.h"
#define NUMBER_OF_TESTS 1
static SonicUserRequestProxy *device = 0;
//static sem_t wait_log;
class SonicUser : public SonicUserIndicationWrapper
{
public:
virtual void dtp_read_version_resp(uint32_t a) {
fprintf(stderr, "read version %d\n", a);
}
virtual void dtp_read_delay_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read delay(%d) %d\n", p, a);
}
virtual void dtp_read_state_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read state(%d) %d\n", p, a);
}
virtual void dtp_read_error_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read error(%d) %ld\n", p, a);
}
virtual void dtp_read_cnt_resp(uint64_t a) {
fprintf(stderr, "readCycleCount(%lx)\n", a);
}
virtual void dtp_logger_read_cnt_resp(uint8_t a, uint64_t b, uint64_t c, uint64_t d) {
fprintf(stderr, "read from port(%d) local_cnt(%lx) msg1(%lx) msg2(%lx)\n", a, b, c, d);
}
virtual void dtp_read_local_cnt_resp(uint8_t p, uint64_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%lx)\n", p, a);
}
virtual void dtp_read_global_cnt_resp(uint64_t a) {
fprintf(stderr, "read global_cnt(%lx)\n", a);
}
virtual void dtp_read_beacon_interval_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) local_cnt(%x)\n", p, a);
}
virtual void dtp_debug_rcvd_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq1(%x) enq2(%x) deq(%x)\n", p, a, b, c);
}
virtual void dtp_debug_sent_msg_resp(uint8_t p, uint32_t a, uint32_t b, uint32_t c) {
fprintf(stderr, "read from port(%d) enq(%x) deq1(%x) deq2(%x)\n", p, a, b, c);
}
virtual void dtp_debug_rcvd_err_resp(uint8_t p, uint32_t a) {
fprintf(stderr, "read from port(%d) err(%x)\n", p, a);
}
virtual void dtp_get_mode_resp(uint8_t a) {
fprintf(stderr, "read from mode(%x)\n", a);
}
SonicUser(unsigned int id) : SonicUserIndicationWrapper(id) {}
};
int main(int argc, const char **argv)
{
uint32_t count = 100;
SonicUser indication(IfcNames_SonicUserIndicationH2S);
device = new SonicUserRequestProxy(IfcNames_SonicUserRequestS2H);
device->pint.busyType = BUSY_SPIN; /* spin until request portal 'notFull' */
device->dtp_reset(32);
device->dtp_get_mode();
device->dtp_read_version();
fprintf(stderr, "Main::about to go to sleep\n");
while(true){
for (int i=0; i<1; i++) {
device->dtp_read_delay(i);
device->dtp_read_state(i);
device->dtp_read_error(i);
device->dtp_read_cnt(i);
}
sleep(1);
for (int i=0; i<4; i++) {
device->dtp_logger_write_cnt(i, count);
}
for (int i=0; i<4; i++) {
device->dtp_logger_read_cnt(i);
}
count ++;
sleep(1);
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
typedef int DataType;
struct tree_node
{
DataType data;
tree_node* left=NULL;
tree_node* right=NULL;
};
class binary_search_tree{
private:
tree_node* root;
int num;
public:
binary_search_tree() :num(0)
{
root = new tree_node;
root->left = NULL;
root->right = NULL;
}
bool find(DataType it,tree_node* root)
{
if (NULL == root)return false;
if (it == root->data) {
return true;
}
else if (it > root->data)
{
return find(it, root->right);
}
else
{
return find(it, root->left);
}
}
bool find_data(DataType it)
{
return find(it, root);
/*
tree_node* p = root;
while (p != NULL)
{
if (it < p->data)p = p->left;
else if (it>p->data)p = p->right;
else return true;
}
return false;
*/
}
void insert_data(DataType it)
{
if (0==num)
{
root->data = it;
num++;
return;
}
tree_node* p = root;
while (p != NULL)
{
if (it < p->data)
{
if (NULL == p->left)
{
p->left = new tree_node;
p->left->data = it;
num++;
return;
}
p = p->left;
}
else
{
if (NULL == p->right)
{
p->right = new tree_node;
p->right->data = it;
num++;
return;
}
p = p->right;
}
}
}
void delet(DataType it)
{
if (NULL == root)return;
tree_node* p = root;
tree_node* pp = NULL;//pp¼pĸڵ
while (p != NULL&&p->data != it)
{
pp = p;
if (it > p->data)p = p->right;
else
p = p->left;
}
if (p == NULL)return;//ûҵ
//ɾĽڵӽڵ
if (p->left != NULL&&p->right != NULL)
{
tree_node* minP = p->right;
tree_node* minPP = p;//¼Pĸڵ
while (minP->left != NULL)//ѰСڵ
{
minPP = minP;
minP = minP->left;
}
p->data = minP->data;//minP滻p
//pҶڵϣʹҶڵ㷽ɾ
p = minP;
pp = minPP;
}
//ɾڵҶڵǽһڵ
tree_node* child;
if (p->left != NULL) child = p->left;
else if (p->right != NULL) child = p->right;
else child = NULL;
if (NULL == pp) root = child;//ɾǸڵ
else if (p == pp->left)pp->left = child;
else pp->right = child;
}
DataType get_max()
{
if (NULL == root)return NULL;
tree_node* tmp=root;
while (tmp->right != NULL)
{
tmp = tmp->right;
}
return tmp->data;
}
DataType get_min()
{
if (NULL == root)return NULL;
tree_node* tmp=root;
while (tmp->left != NULL)
{
tmp = tmp->left;
}
return tmp->data;
}
DataType get_prenode(DataType it)
{
if (NULL == root)return NULL;
if (it == root->data) return NULL;
tree_node* p=root;
tree_node* pp=NULL;
while ((p->data != it)&&(p!=NULL))
{
pp = p;
if (p->data < it)
{
p=p->right;
}
else
{
p = p->left;
}
}
return ((NULL==p)?NULL:pp->data);
}
DataType get_postnode(DataType it)
{
if (NULL == root)return -1;
tree_node* p = root;
while ((p->data != it) && (p != NULL))
{
if (p->data < it)
{
p = p->left;
}
else
{
p = p->right;
}
}
if (NULL == p)
{
return -1;
}
else if (p->left!=NULL)
{
return p->left->data;
}
else if (p->right!=-NULL)
{
return p->right->data;
}
else
{
return NULL;
}
}
void mid_order(tree_node* rt)
{
if (NULL == rt)return;
mid_order(rt->left);
cout << rt->data;
mid_order(rt->right);
}
void order()
{
if (NULL == root)return;
return mid_order(root);
}
int get_high(tree_node* rt)
{
int lhigh = 0;
int rhigh = 0;
if (NULL == rt)return 0;
lhigh = get_high(rt->left);
rhigh = get_high(rt->right);
return ((lhigh > rhigh) ? (lhigh + 1) : (rhigh + 1));
}
int high()
{
if (NULL == root) return 1;
return get_high(root);
}
};
int main()
{
binary_search_tree my_tree;
my_tree.insert_data(5);
my_tree.insert_data(4);
my_tree.insert_data(6);
my_tree.insert_data(10);
my_tree.insert_data(3);
my_tree.insert_data(8);
my_tree.insert_data(1);
if (my_tree.find_data(3))
{
cout << "ҵ3" << endl;
}
else
{
cout << "ûҵ3" << endl;
}
my_tree.delet(4);
cout << "Max" << my_tree.get_max() << endl;
cout << "Min" << my_tree.get_min() << endl;
cout << "pre node of 5 is " <<my_tree.get_prenode(5) <<endl;
cout << "post node of 5 is " << my_tree.get_postnode(5) << endl;
my_tree.order();
cout << "high of tree is " << my_tree.high() << endl;
return 0;
} <commit_msg>fix bug<commit_after>/*
* Filename: /home/zwk/code/data_structrue/c++/tree/binary_search_tree/main.cpp
* Path: /home/zwk/code/data_structrue/c++/tree/binary_search_tree
* Created Date: Wednesday, May 8th 2019, 11:04:48 pm
* Author: zwk
*
* refer to https://time.geekbang.org/column/article/68334
*/
#include <iostream>
using namespace std;
typedef int DataType;
struct treeNode
{
DataType data;
treeNode *left = nullptr;
treeNode *right = nullptr;
};
class binarySearchTree
{
private:
treeNode *root;
int num; // tree node numbers
public:
binarySearchTree() : num(0)
{
root = new treeNode;
root->left = nullptr;
root->right = nullptr;
}
bool find(DataType it, treeNode *root)
{
if (nullptr == root)
return false;
if (it == root->data) {
return true;
} else if (it > root->data) {
return find(it, root->right);
} else {
return find(it, root->left);
}
}
bool find_data(DataType it)
{
return find(it, root);
/*
treeNode* p = root;
while (p != nullptr)
{
if (it < p->data)p = p->left;
else if (it>p->data)p = p->right;
else return true;
}
return false;
*/
}
DataType get_max()
{
if (nullptr == root)
return NULL;
treeNode *tmp = root;
while (tmp->right != nullptr) {
tmp = tmp->right;
}
return tmp->data;
}
DataType get_min()
{
if (nullptr == root)
return NULL;
treeNode *tmp = root;
while (tmp->left != nullptr) {
tmp = tmp->left;
}
return tmp->data;
}
void insert_data(DataType it)
// 利用二分查找的思想,借助树的结构使用递归
{
if (0 == num) {
root->data = it;
num++;
return;
}
treeNode *p = root;
while (p != nullptr) {
if (it < p->data) {
if (nullptr == p->left) {
p->left = new treeNode;
p->left->data = it;
num++;
return;
}
p = p->left;
} else {
if (nullptr == p->right) {
p->right = new treeNode;
p->right->data = it;
num++;
return;
}
p = p->right;
}
}
}
DataType get_prenode(DataType it)
{
if (nullptr == root)
return NULL;
if (it == root->data)
return NULL;
treeNode *p = root;
treeNode *pp = nullptr;
while (p != nullptr) {
if (p->data < it) {
pp = p; // label parent root
p = p->right;
} else if (p->data > it) {
pp = p; // label parent root
p = p->left;
} else {
break;
}
}
return ((nullptr == p) ? NULL : pp->data);
}
DataType get_postnode(DataType it)
{
if (nullptr == root)
return -1;
treeNode *p = root;
while (p != nullptr) {
if (p->data < it) {
p = p->right;
} else if (p->data > it) {
p = p->left;
} else {
break;
}
}
if (nullptr == p) {
return -1;
} else if (p->left != nullptr) {
return p->left->data;
} else if (p->right != nullptr) {
return p->right->data;
} else {
return NULL;
}
}
void mid_order(treeNode *rt)
{
if (nullptr == rt)
return;
mid_order(rt->left);
cout << rt->data << '\t';
mid_order(rt->right);
}
void order()
{
if (nullptr == root)
return;
return mid_order(root);
}
int get_high(treeNode *rt)
{
int lhigh = 0;
int rhigh = 0;
if (nullptr == rt)
return 0;
lhigh = get_high(rt->left);
rhigh = get_high(rt->right);
return ((lhigh > rhigh) ? (lhigh + 1) : (rhigh + 1));
}
int high()
{
if (nullptr == root)
return 1;
return get_high(root);
}
void delet(DataType it)
{
if (NULL == root)
return;
treeNode *p = root;
treeNode *pp = NULL; //pp记录的是p的父节点
while (p != NULL && p->data != it) {
pp = p;
if (it > p->data)
p = p->right;
else
p = p->left;
}
if (p == NULL)
return; //没有找到
//删除的节点有两个子节点
if (p->left != NULL && p->right != NULL) {
treeNode *minP = p->right;
treeNode *minPP = p; //记录P的父节点
while (minP->left != NULL) //寻找右子树最小节点
{
minPP = minP;
minP = minP->left;
}
// 注意这里,非常巧妙的办法。只是换值。“换汤不换药”
// 用后继节点替换到要删除节点的位置。 然后就变成删除后继节点的问题了。为了逻辑统一 代码书写简洁。我们把后继节点赋给了p
p->data = minP->data; //将minP的值替换到p中
//将p换到叶节点上,使用叶节点方法进行删除, 而且最小节点肯定没有左节点,叶节点删除方法参见后面的代码。
p = minP;
pp = minPP;
}
//删除节点是叶节点或者是仅有一个节点
treeNode *child;
if (p->left != NULL)
child = p->left;
else if (p->right != NULL)
child = p->right;
else
child = NULL;
if (NULL == pp)
root = child; //删除的是根节点
else if (p == pp->left)
pp->left = child;
else
pp->right = child;
}
};
int main()
{
binarySearchTree my_tree;
// must input in the order of layers
my_tree.insert_data(33);
my_tree.insert_data(16);
my_tree.insert_data(50);
my_tree.insert_data(13);
my_tree.insert_data(18);
my_tree.insert_data(34);
my_tree.insert_data(58);
my_tree.insert_data(15);
my_tree.insert_data(17);
my_tree.insert_data(25);
my_tree.insert_data(51);
my_tree.insert_data(66);
my_tree.insert_data(19);
my_tree.insert_data(27);
my_tree.insert_data(55);
if (my_tree.find_data(25)) {
cout << "找到了数字25" << endl;
} else {
cout << "没有找到数字25" << endl;
}
my_tree.delet(13);
my_tree.delet(18);
my_tree.delet(55);
cout << "Max: " << my_tree.get_max() << endl;
cout << "Min: " << my_tree.get_min() << endl;
cout << "pre node of 17 is " << my_tree.get_prenode(17) << endl;
cout << "pre node of 51 is " << my_tree.get_prenode(51) << endl;
cout << "pre node of 33 is " << my_tree.get_prenode(33) << endl;
cout << "post node of 19 is " << my_tree.get_postnode(19) << endl;
cout << "post node of 25 is " << my_tree.get_postnode(25) << endl;
cout << "post node of 58 is " << my_tree.get_postnode(58) << endl;
cout << "post node of 58 is " << my_tree.get_postnode(51) << endl;
my_tree.order();
cout << "high of tree is " << my_tree.high() << endl;
return 0;
}
<|endoftext|>
|
<commit_before>// crbarker@google.com
//
// Implements JoystickNavigator.
#include "joystick_navigator.h"
#include <time.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <algorithm>
#include <cmath>
#include "camera_buffer.h"
#include "slinky_nav/SlinkyPose.h"
static const double kPi = 3.141592653589793;
static const double kPoleLat = 90.0 - 0.000001;
static const double kEarthRadius = 6371000;
static const timespec kExpectedInterval = {0, 33333333}; // 30 Hz
JoystickNavigator::JoystickNavigator()
: under_joy_control_(false),
camera_buffer_(NULL) {
// The sensitivities and gutter are hard-coded here.
// In this case, linear_sensitivity_ refers to linear scaling
// (vs. quadratic scaling) not linear motion (vs. angular).
linear_sensitivity_.linear.x = 0.0; // longitude
linear_sensitivity_.linear.y = 0.0; // latitude
linear_sensitivity_.linear.z = 0.0; // altitude
linear_sensitivity_.angular.x = 0.0; // pitch
linear_sensitivity_.angular.y = 0.0; // roll
linear_sensitivity_.angular.z = 0.0; // heading
quadratic_sensitivity_.linear.x = 0.000001; // longitude
quadratic_sensitivity_.linear.y = 0.000001; // latitude
quadratic_sensitivity_.linear.z = 0.2; // altitude
quadratic_sensitivity_.angular.x = 5.0; // pitch
quadratic_sensitivity_.angular.y = 0.0; // roll
quadratic_sensitivity_.angular.z = 4.0; // heading
// If all joystick inputs are all less than the gutter, the input
// is ignored, and it's assumed that we're under touch/mouse control.
gutter_.linear.x = 0.001;
gutter_.linear.y = 0.001;
gutter_.linear.z = 0.001;
gutter_.angular.x = 0.001;
gutter_.angular.y = 0.001;
gutter_.angular.z = 0.001;
}
void JoystickNavigator::Init(CameraBuffer* camera_buffer) {
camera_buffer_ = camera_buffer;
clock_gettime(CLOCK_REALTIME, &last_joy_time_);
}
void JoystickNavigator::ProcessCameraMoved(
const slinky_nav::SlinkyPose& slinky_pose) {
last_camera_pose_ = slinky_pose.current_pose;
pose_minimums_ = slinky_pose.pose_minimums;
pose_maximums_ = slinky_pose.pose_maximums;
}
void JoystickNavigator::ProcessJoy(const geometry_msgs::Twist& normalized_joy) {
// The joystick sensitivities are tuned for a nominal input frequency.
// However, inputs can come faster/slower than that, so we apply further
// scaling.
timespec current_time;
clock_gettime(CLOCK_REALTIME, ¤t_time);
timespec diff_time = DiffTimespec(last_joy_time_, current_time);
last_joy_time_ = current_time;
double interval_scale = DivTimespec(diff_time, kExpectedInterval);
// If the entire normalized_joy is at steady state then we exit early.
if (IsWithinGutter(normalized_joy)) {
// This breadcrumb tells us to base future navigation on the last received
// camera pose, not our requested pose.
under_joy_control_ = false;
return;
}
// Otherwise, we don't gutter any inputs. If we're moving the camera at all,
// we'll move it based on all inputs, no matter how tiny.
// If we've been under control of the joystick since the last call, we start
// from the last pose the joystick requested (preventing stutter in case
// the camera response gets delayed). However, if this is the first time
// we're moving since the joystick was in the gutter, we'll start from
// the last reported camera position.
geometry_msgs::Pose& starting_pose = last_requested_pose_;
if (!under_joy_control_) {
starting_pose = last_camera_pose_;
under_joy_control_ = true;
}
geometry_msgs::Pose ending_pose = starting_pose;
geometry_msgs::Twist scaled_joy;
Scale(normalized_joy, interval_scale, &scaled_joy);
// Altitude: Adjusts camera altitude per joystick linear Z axis.
// Altitude is computed first, since it affects scaling of other inputs.
ending_pose.position.z =
Clamp(starting_pose.position.z +
(starting_pose.position.z * scaled_joy.linear.z),
pose_minimums_.position.z, pose_maximums_.position.z);
// Heading: Adjusts compass heading per joystick angular Z axis.
// This is computed early because it affects the direction of translations.
// [0, 360), with wrapping.
ending_pose.orientation.z =
fmod(starting_pose.orientation.z + 360 - scaled_joy.angular.z, 360);
ending_pose.orientation.z =
Clamp(ending_pose.orientation.z,
pose_minimums_.orientation.z,
pose_maximums_.orientation.z);
// Tilt: Adjusts tilt per joystick angular X axis.
// TODO(crbarker): clamp the tilt intelligently so we never omit earth.
ending_pose.orientation.x =
Clamp(starting_pose.orientation.x + scaled_joy.angular.x,
pose_minimums_.orientation.x,
pose_maximums_.orientation.x);
// Translate: Translates the camera per joystick linear X/Y axes.
// Translation speed is dependent on altitude and direction is dependent
// on heading.
// Latitude (-90, 90)
// Longitude [-180, 180), with wrapping as we pass the meridian.
double heading_radians = ending_pose.orientation.z * kPi / 180;
double cos_heading = cos(heading_radians);
double sin_heading = sin(heading_radians);
double delta_lat =
(cos_heading * scaled_joy.linear.y) -
(sin_heading * scaled_joy.linear.x);
double delta_lon =
(cos_heading * scaled_joy.linear.x) +
(sin_heading * scaled_joy.linear.y);
// The further we are from the ground, the more we should translate x and y.
double alt_scale = ending_pose.position.z;
ending_pose.position.y =
Clamp(starting_pose.position.y + (delta_lat * alt_scale),
kPoleLat * -1.0,
kPoleLat);
ending_pose.position.y =
Clamp(ending_pose.position.y,
pose_minimums_.position.y,
pose_maximums_.position.y);
ending_pose.position.x =
fmod((starting_pose.position.x + (delta_lon * alt_scale)) + 180, 360) -
180;
ending_pose.position.x =
Clamp(ending_pose.position.x,
pose_minimums_.position.x,
pose_maximums_.position.x);
last_requested_pose_ = ending_pose;
camera_buffer_->RequestPose(ending_pose);
}
double JoystickNavigator::Quadratic(double v) {
return std::abs(v) * v;
}
double JoystickNavigator::Clamp(double v, double min, double max) {
return std::max(std::min(v, max), min);
}
timespec JoystickNavigator::DiffTimespec(timespec start, timespec end) {
timespec diff;
if ((end.tv_nsec - start.tv_nsec) < 0) {
diff.tv_sec = end.tv_sec - start.tv_sec - 1;
diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
} else {
diff.tv_sec = end.tv_sec - start.tv_sec;
diff.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return diff;
}
double JoystickNavigator::DivTimespec(timespec num, timespec denom) {
double lnum = num.tv_sec * 1000000000 + num.tv_nsec;
double ldenom = denom.tv_sec * 1000000000 + denom.tv_nsec;
return lnum / ldenom;
}
// Compares the 'normal' and returns true if anything is outside the gutter.
bool JoystickNavigator::IsWithinGutter(const geometry_msgs::Twist& normal) {
return (std::abs(normal.linear.x) < gutter_.linear.x) &&
(std::abs(normal.linear.y) < gutter_.linear.y) &&
(std::abs(normal.linear.z) < gutter_.linear.z) &&
(std::abs(normal.angular.x) < gutter_.angular.x) &&
(std::abs(normal.angular.y) < gutter_.angular.y) &&
(std::abs(normal.angular.z) < gutter_.angular.z);
}
// Multiplies the 'normal' by linear_sensitivity_, and multiplies the quadratic
// scaled 'normal' by quadratic_sensitivity_. Then scales the whole thing by
// 'interval_scale.'
void JoystickNavigator::Scale(
const geometry_msgs::Twist& normal,
double interval_scale,
geometry_msgs::Twist* result) {
result->linear.x = (normal.linear.x * linear_sensitivity_.linear.x +
Quadratic(normal.linear.x) * quadratic_sensitivity_.linear.x) *
interval_scale;
result->linear.y = (normal.linear.y * linear_sensitivity_.linear.y +
Quadratic(normal.linear.y) * quadratic_sensitivity_.linear.y) *
interval_scale;
result->linear.z = (normal.linear.z * linear_sensitivity_.linear.z +
Quadratic(normal.linear.z) * quadratic_sensitivity_.linear.z) *
interval_scale;
result->angular.x = (normal.angular.x * linear_sensitivity_.angular.x +
Quadratic(normal.angular.x) * quadratic_sensitivity_.angular.x) *
interval_scale;
result->angular.y = (normal.angular.y * linear_sensitivity_.angular.y +
Quadratic(normal.angular.y) * quadratic_sensitivity_.angular.y) *
interval_scale;
result->angular.z = (normal.angular.z * linear_sensitivity_.angular.z +
Quadratic(normal.angular.z) * quadratic_sensitivity_.angular.z) *
interval_scale;
}
<commit_msg>Fixes navigation across the anti-meridian.<commit_after>// crbarker@google.com
//
// Implements JoystickNavigator.
#include "joystick_navigator.h"
#include <time.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <algorithm>
#include <cmath>
#include "camera_buffer.h"
#include "slinky_nav/SlinkyPose.h"
static const double kPi = 3.141592653589793;
static const double kPoleLat = 90.0 - 0.000001;
static const double kEarthRadius = 6371000;
static const timespec kExpectedInterval = {0, 33333333}; // 30 Hz
JoystickNavigator::JoystickNavigator()
: under_joy_control_(false),
camera_buffer_(NULL) {
// The sensitivities and gutter are hard-coded here.
// In this case, linear_sensitivity_ refers to linear scaling
// (vs. quadratic scaling) not linear motion (vs. angular).
linear_sensitivity_.linear.x = 0.0; // longitude
linear_sensitivity_.linear.y = 0.0; // latitude
linear_sensitivity_.linear.z = 0.0; // altitude
linear_sensitivity_.angular.x = 0.0; // pitch
linear_sensitivity_.angular.y = 0.0; // roll
linear_sensitivity_.angular.z = 0.0; // heading
quadratic_sensitivity_.linear.x = 0.000001; // longitude
quadratic_sensitivity_.linear.y = 0.000001; // latitude
quadratic_sensitivity_.linear.z = 0.2; // altitude
quadratic_sensitivity_.angular.x = 5.0; // pitch
quadratic_sensitivity_.angular.y = 0.0; // roll
quadratic_sensitivity_.angular.z = 4.0; // heading
// If all joystick inputs are all less than the gutter, the input
// is ignored, and it's assumed that we're under touch/mouse control.
gutter_.linear.x = 0.001;
gutter_.linear.y = 0.001;
gutter_.linear.z = 0.001;
gutter_.angular.x = 0.001;
gutter_.angular.y = 0.001;
gutter_.angular.z = 0.001;
}
void JoystickNavigator::Init(CameraBuffer* camera_buffer) {
camera_buffer_ = camera_buffer;
clock_gettime(CLOCK_REALTIME, &last_joy_time_);
}
void JoystickNavigator::ProcessCameraMoved(
const slinky_nav::SlinkyPose& slinky_pose) {
last_camera_pose_ = slinky_pose.current_pose;
pose_minimums_ = slinky_pose.pose_minimums;
pose_maximums_ = slinky_pose.pose_maximums;
}
void JoystickNavigator::ProcessJoy(const geometry_msgs::Twist& normalized_joy) {
// The joystick sensitivities are tuned for a nominal input frequency.
// However, inputs can come faster/slower than that, so we apply further
// scaling.
timespec current_time;
clock_gettime(CLOCK_REALTIME, ¤t_time);
timespec diff_time = DiffTimespec(last_joy_time_, current_time);
last_joy_time_ = current_time;
double interval_scale = DivTimespec(diff_time, kExpectedInterval);
// If the entire normalized_joy is at steady state then we exit early.
if (IsWithinGutter(normalized_joy)) {
// This breadcrumb tells us to base future navigation on the last received
// camera pose, not our requested pose.
under_joy_control_ = false;
return;
}
// Otherwise, we don't gutter any inputs. If we're moving the camera at all,
// we'll move it based on all inputs, no matter how tiny.
// If we've been under control of the joystick since the last call, we start
// from the last pose the joystick requested (preventing stutter in case
// the camera response gets delayed). However, if this is the first time
// we're moving since the joystick was in the gutter, we'll start from
// the last reported camera position.
geometry_msgs::Pose& starting_pose = last_requested_pose_;
if (!under_joy_control_) {
starting_pose = last_camera_pose_;
under_joy_control_ = true;
}
geometry_msgs::Pose ending_pose = starting_pose;
geometry_msgs::Twist scaled_joy;
Scale(normalized_joy, interval_scale, &scaled_joy);
// Altitude: Adjusts camera altitude per joystick linear Z axis.
// Altitude is computed first, since it affects scaling of other inputs.
ending_pose.position.z =
Clamp(starting_pose.position.z +
(starting_pose.position.z * scaled_joy.linear.z),
pose_minimums_.position.z, pose_maximums_.position.z);
// Heading: Adjusts compass heading per joystick angular Z axis.
// This is computed early because it affects the direction of translations.
// [0, 360), with wrapping.
ending_pose.orientation.z =
fmod(starting_pose.orientation.z + 360 - scaled_joy.angular.z, 360);
ending_pose.orientation.z =
Clamp(ending_pose.orientation.z,
pose_minimums_.orientation.z,
pose_maximums_.orientation.z);
// Tilt: Adjusts tilt per joystick angular X axis.
// TODO(crbarker): clamp the tilt intelligently so we never omit earth.
ending_pose.orientation.x =
Clamp(starting_pose.orientation.x + scaled_joy.angular.x,
pose_minimums_.orientation.x,
pose_maximums_.orientation.x);
// Translate: Translates the camera per joystick linear X/Y axes.
// Translation speed is dependent on altitude and direction is dependent
// on heading.
// Latitude (-90, 90)
// Longitude [-180, 180), with wrapping as we pass the meridian.
double heading_radians = ending_pose.orientation.z * kPi / 180;
double cos_heading = cos(heading_radians);
double sin_heading = sin(heading_radians);
double delta_lat =
(cos_heading * scaled_joy.linear.y) -
(sin_heading * scaled_joy.linear.x);
double delta_lon =
(cos_heading * scaled_joy.linear.x) +
(sin_heading * scaled_joy.linear.y);
// The further we are from the ground, the more we should translate x and y.
double alt_scale = ending_pose.position.z;
ending_pose.position.y =
Clamp(starting_pose.position.y + (delta_lat * alt_scale),
kPoleLat * -1.0,
kPoleLat);
ending_pose.position.y =
Clamp(ending_pose.position.y,
pose_minimums_.position.y,
pose_maximums_.position.y);
ending_pose.position.x =
fmod((starting_pose.position.x + (delta_lon * alt_scale)) + 540, 360) -
180;
ending_pose.position.x =
Clamp(ending_pose.position.x,
pose_minimums_.position.x,
pose_maximums_.position.x);
last_requested_pose_ = ending_pose;
camera_buffer_->RequestPose(ending_pose);
}
double JoystickNavigator::Quadratic(double v) {
return std::abs(v) * v;
}
double JoystickNavigator::Clamp(double v, double min, double max) {
return std::max(std::min(v, max), min);
}
timespec JoystickNavigator::DiffTimespec(timespec start, timespec end) {
timespec diff;
if ((end.tv_nsec - start.tv_nsec) < 0) {
diff.tv_sec = end.tv_sec - start.tv_sec - 1;
diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
} else {
diff.tv_sec = end.tv_sec - start.tv_sec;
diff.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return diff;
}
double JoystickNavigator::DivTimespec(timespec num, timespec denom) {
double lnum = num.tv_sec * 1000000000 + num.tv_nsec;
double ldenom = denom.tv_sec * 1000000000 + denom.tv_nsec;
return lnum / ldenom;
}
// Compares the 'normal' and returns true if anything is outside the gutter.
bool JoystickNavigator::IsWithinGutter(const geometry_msgs::Twist& normal) {
return (std::abs(normal.linear.x) < gutter_.linear.x) &&
(std::abs(normal.linear.y) < gutter_.linear.y) &&
(std::abs(normal.linear.z) < gutter_.linear.z) &&
(std::abs(normal.angular.x) < gutter_.angular.x) &&
(std::abs(normal.angular.y) < gutter_.angular.y) &&
(std::abs(normal.angular.z) < gutter_.angular.z);
}
// Multiplies the 'normal' by linear_sensitivity_, and multiplies the quadratic
// scaled 'normal' by quadratic_sensitivity_. Then scales the whole thing by
// 'interval_scale.'
void JoystickNavigator::Scale(
const geometry_msgs::Twist& normal,
double interval_scale,
geometry_msgs::Twist* result) {
result->linear.x = (normal.linear.x * linear_sensitivity_.linear.x +
Quadratic(normal.linear.x) * quadratic_sensitivity_.linear.x) *
interval_scale;
result->linear.y = (normal.linear.y * linear_sensitivity_.linear.y +
Quadratic(normal.linear.y) * quadratic_sensitivity_.linear.y) *
interval_scale;
result->linear.z = (normal.linear.z * linear_sensitivity_.linear.z +
Quadratic(normal.linear.z) * quadratic_sensitivity_.linear.z) *
interval_scale;
result->angular.x = (normal.angular.x * linear_sensitivity_.angular.x +
Quadratic(normal.angular.x) * quadratic_sensitivity_.angular.x) *
interval_scale;
result->angular.y = (normal.angular.y * linear_sensitivity_.angular.y +
Quadratic(normal.angular.y) * quadratic_sensitivity_.angular.y) *
interval_scale;
result->angular.z = (normal.angular.z * linear_sensitivity_.angular.z +
Quadratic(normal.angular.z) * quadratic_sensitivity_.angular.z) *
interval_scale;
}
<|endoftext|>
|
<commit_before>// @(#)root/test:$Name: $:$Id: Event.cxx,v 1.14 2001/11/22 15:12:25 brun Exp $
// Author: Rene Brun 19/08/96
////////////////////////////////////////////////////////////////////////
//
// Event and Track classes
// =======================
//
// The Event class is a naive/simple example of an event structure.
// public:
// char fType[20];
// Int_t fNtrack;
// Int_t fNseg;
// Int_t fNvertex;
// UInt_t fFlag;
// Float_t fTemperature;
// Int_t fMeasures[10];
// Float_t fMatrix[4][4];
// Float_t *fClosestDistance; //[fNvertex] indexed array!
// EventHeader fEvtHdr;
// TClonesArray *fTracks;
// TRefArray *fHighPt; //array of High Pt tracks only
// TRefArray *fMuons; //array of Muon tracks only
// TRef fLastTrack; //pointer to last track
// TRef fHistoWeb; //EXEC:GetHistoWeb reference to an histogram in a TWebFile
// TH1F *fH;
//
// The EventHeader class has 3 data members (integers):
// public:
// Int_t fEvtNum;
// Int_t fRun;
// Int_t fDate;
//
//
// The Event data member fTracks is a pointer to a TClonesArray.
// It is an array of a variable number of tracks per event.
// Each element of the array is an object of class Track with the members:
// private:
// Float_t fPx; //X component of the momentum
// Float_t fPy; //Y component of the momentum
// Float_t fPz; //Z component of the momentum
// Float_t fRandom; //A random track quantity
// Float_t fMass2; //The mass square of this particle
// Float_t fBx; //X intercept at the vertex
// Float_t fBy; //Y intercept at the vertex
// Float_t fMeanCharge; //Mean charge deposition of all hits of this track
// Float_t fXfirst; //X coordinate of the first point
// Float_t fXlast; //X coordinate of the last point
// Float_t fYfirst; //Y coordinate of the first point
// Float_t fYlast; //Y coordinate of the last point
// Float_t fZfirst; //Z coordinate of the first point
// Float_t fZlast; //Z coordinate of the last point
// Float_t fCharge; //Charge of this track
// Float_t fVertex[3]; //Track vertex position
// Int_t fNpoint; //Number of points for this track
// Short_t fValid; //Validity criterion
//
// An example of a batch program to use the Event/Track classes is given
// in this directory: MainEvent.
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
// During the processing of the event (optionally) also a large number
// of histograms can be filled. The creation and handling of the
// histograms is taken care of by the HistogramManager class.
//
////////////////////////////////////////////////////////////////////////
#include "TRandom.h"
#include "TDirectory.h"
#include "Event.h"
ClassImp(EventHeader)
ClassImp(Event)
ClassImp(Track)
ClassImp(HistogramManager)
TClonesArray *Event::fgTracks = 0;
TH1F *Event::fgHist = 0;
//______________________________________________________________________________
Event::Event()
{
// Create an Event object.
// When the constructor is invoked for the first time, the class static
// variable fgTracks is 0 and the TClonesArray fgTracks is created.
if (!fgTracks) fgTracks = new TClonesArray("Track", 1000);
fTracks = fgTracks;
fHighPt = new TRefArray;
fMuons = new TRefArray;
fNtrack = 0;
fH = 0;
Int_t i0,i1;
for (i0 = 0; i0 < 4; i0++) {
for (i1 = 0; i1 < 4; i1++) {
fMatrix[i0][i1] = 0.0;
}
}
for (i0 = 0; i0 <10; i0++) fMeasures[i0] = 0;
fClosestDistance = 0;
fEventName = 0;
fWebHistogram.SetAction(this);
}
//______________________________________________________________________________
Event::~Event()
{
Clear();
if (fH == fgHist) fgHist = 0;
delete fH; fH = 0;
delete fHighPt; fHighPt = 0;
delete fMuons; fMuons = 0;
delete [] fClosestDistance;
if (fEventName) delete [] fEventName;
}
//______________________________________________________________________________
void Event::Build(Int_t ev, Int_t arg5, Float_t ptmin) {
char etype[20];
Float_t sigmat, sigmas;
gRandom->Rannor(sigmat,sigmas);
Int_t ntrack = Int_t(arg5 +arg5*sigmat/120.);
Float_t random = gRandom->Rndm(1);
//Save current Object count
Int_t ObjectNumber = TRef::GetObjectCount();
Clear();
fHighPt->Delete();
fMuons->Delete();
Int_t nch = 15;
if (ev > 100) nch += 3;
if (ev > 10000) nch += 3;
if (fEventName) delete [] fEventName;
fEventName = new char[nch];
sprintf(fEventName,"Event%d_Run%d",ev,200);
sprintf(etype,"type%d",ev%5);
SetType(etype);
SetHeader(ev, 200, 960312, random);
SetNseg(Int_t(10*ntrack+20*sigmas));
SetNvertex(Int_t(1+20*gRandom->Rndm()));
SetFlag(UInt_t(random+0.5));
SetTemperature(random+20.);
for(UChar_t m = 0; m < 10; m++) {
SetMeasure(m, Int_t(gRandom->Gaus(m,m+1)));
}
for(UChar_t i0 = 0; i0 < 4; i0++) {
for(UChar_t i1 = 0; i1 < 4; i1++) {
SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1));
}
}
// Create and Fill the Track objects
for (Int_t t = 0; t < ntrack; t++) AddTrack(random,ptmin);
//Restore Object count
//To save space in the table keeping track of all referenced objects
//we assume that our events do not address each other. We reset the
//object count to what it was at the beginning of the event.
TRef::SetObjectCount(ObjectNumber);
}
//______________________________________________________________________________
Track *Event::AddTrack(Float_t random, Float_t ptmin)
{
// Add a new track to the list of tracks for this event.
// To avoid calling the very time consuming operator new for each track,
// the standard but not well know C++ operator "new with placement"
// is called. If tracks[i] is 0, a new Track object will be created
// otherwise the previous Track[i] will be overwritten.
TClonesArray &tracks = *fTracks;
Track *track = new(tracks[fNtrack++]) Track(random);
//Save reference to last Track in the collection of Tracks
fLastTrack = track;
//Save reference in fHighPt if track is a high Pt track
if (track->GetPt() > ptmin) fHighPt->Add(track);
//Save reference in fMuons if track is a muon candidate
if (track->GetMass2() < 0.11) fMuons->Add(track);
return track;
}
//______________________________________________________________________________
void Event::Clear(Option_t *option)
{
fTracks->Clear(option);
fHighPt->Delete();
fMuons->Delete();
}
//______________________________________________________________________________
void Event::Reset(Option_t *option)
{
// Static function to reset all static objects for this event
// fgTracks->Delete(option);
delete fgTracks; fgTracks = 0;
fgHist = 0;
}
//______________________________________________________________________________
void Event::SetHeader(Int_t i, Int_t run, Int_t date, Float_t random)
{
fNtrack = 0;
fEvtHdr.Set(i, run, date);
if (!fgHist) fgHist = new TH1F("hstat","Event Histogram",100,0,1);
fH = fgHist;
fH->Fill(random);
}
//______________________________________________________________________________
void Event::SetMeasure(UChar_t which, Int_t what) {
if (which<10) fMeasures[which] = what;
}
//______________________________________________________________________________
void Event::SetRandomVertex() {
// This delete is to test the relocation of variable length array
if (fClosestDistance) delete [] fClosestDistance;
if (!fNvertex) {
fClosestDistance = 0;
return;
}
fClosestDistance = new Float_t[fNvertex];
for (Int_t k = 0; k < fNvertex; k++ ) {
fClosestDistance[k] = gRandom->Gaus(1,1);
}
}
//______________________________________________________________________________
Track::Track(Float_t random) : TObject()
{
// Create a track object.
// Note that in this example, data members do not have any physical meaning.
Float_t a,b,px,py;
gRandom->Rannor(px,py);
fPx = px;
fPy = py;
fPz = TMath::Sqrt(px*px+py*py);
fRandom = 1000*random;
if (fRandom < 10) fMass2 = 0.106;
else if (fRandom < 100) fMass2 = 0.8;
else if (fRandom < 500) fMass2 = 4.5;
else if (fRandom < 900) fMass2 = 8.9;
else fMass2 = 9.8;
gRandom->Rannor(a,b);
fBx = 0.1*a;
fBy = 0.1*b;
fMeanCharge = 0.01*gRandom->Rndm(1);
gRandom->Rannor(a,b);
fXfirst = a*10;
fXlast = b*10;
gRandom->Rannor(a,b);
fYfirst = a*12;
fYlast = b*16;
gRandom->Rannor(a,b);
fZfirst = 50 + 5*a;
fZlast = 200 + 10*b;
fCharge = Float_t(Int_t(3*gRandom->Rndm(1)) - 1);
fVertex[0] = gRandom->Gaus(0,0.1);
fVertex[1] = gRandom->Gaus(0,0.2);
fVertex[2] = gRandom->Gaus(0,10);
fNpoint = Int_t(60+10*gRandom->Rndm(1));
fValid = Int_t(0.6+gRandom->Rndm(1));
}
//______________________________________________________________________________
HistogramManager::HistogramManager(TDirectory *dir)
{
// Create histogram manager object. Histograms will be created
// in the "dir" directory.
// Save current directory and cd to "dir".
TDirectory *saved = gDirectory;
dir->cd();
fNtrack = new TH1F("hNtrack", "Ntrack",100,575,625);
fNseg = new TH1F("hNseg", "Nseg",100,5800,6200);
fTemperature = new TH1F("hTemperature","Temperature",100,19.5,20.5);
fPx = new TH1F("hPx", "Px",100,-4,4);
fPy = new TH1F("hPy", "Py",100,-4,4);
fPz = new TH1F("hPz", "Pz",100,0,5);
fRandom = new TH1F("hRandom", "Random",100,0,1000);
fMass2 = new TH1F("hMass2", "Mass2",100,0,12);
fBx = new TH1F("hBx", "Bx",100,-0.5,0.5);
fBy = new TH1F("hBy", "By",100,-0.5,0.5);
fMeanCharge = new TH1F("hMeanCharge","MeanCharge",100,0,0.01);
fXfirst = new TH1F("hXfirst", "Xfirst",100,-40,40);
fXlast = new TH1F("hXlast", "Xlast",100,-40,40);
fYfirst = new TH1F("hYfirst", "Yfirst",100,-40,40);
fYlast = new TH1F("hYlast", "Ylast",100,-40,40);
fZfirst = new TH1F("hZfirst", "Zfirst",100,0,80);
fZlast = new TH1F("hZlast", "Zlast",100,0,250);
fCharge = new TH1F("hCharge", "Charge",100,-1.5,1.5);
fNpoint = new TH1F("hNpoint", "Npoint",100,50,80);
fValid = new TH1F("hValid", "Valid",100,0,1.2);
// cd back to original directory
saved->cd();
}
//______________________________________________________________________________
HistogramManager::~HistogramManager()
{
// Clean up all histograms.
// Nothing to do. Histograms will be deleted when the directory
// in which tey are stored is closed.
}
//______________________________________________________________________________
void HistogramManager::Hfill(Event *event)
{
// Fill histograms.
fNtrack->Fill(event->GetNtrack());
fNseg->Fill(event->GetNseg());
fTemperature->Fill(event->GetTemperature());
for (Int_t itrack = 0; itrack < event->GetNtrack(); itrack++) {
Track *track = (Track*)event->GetTracks()->UncheckedAt(itrack);
fPx->Fill(track->GetPx());
fPy->Fill(track->GetPy());
fPz->Fill(track->GetPz());
fRandom->Fill(track->GetRandom());
fMass2->Fill(track->GetMass2());
fBx->Fill(track->GetBx());
fBy->Fill(track->GetBy());
fMeanCharge->Fill(track->GetMeanCharge());
fXfirst->Fill(track->GetXfirst());
fXlast->Fill(track->GetXlast());
fYfirst->Fill(track->GetYfirst());
fYlast->Fill(track->GetYlast());
fZfirst->Fill(track->GetZfirst());
fZlast->Fill(track->GetZlast());
fCharge->Fill(track->GetCharge());
fNpoint->Fill(track->GetNpoint());
fValid->Fill(track->GetValid());
}
}
<commit_msg>Modify Event::Build to call TProcessID::GetObjectCount instead of TRef::GetObjectCount<commit_after>// @(#)root/test:$Name: $:$Id: Event.cxx,v 1.15 2001/11/28 15:00:08 brun Exp $
// Author: Rene Brun 19/08/96
////////////////////////////////////////////////////////////////////////
//
// Event and Track classes
// =======================
//
// The Event class is a naive/simple example of an event structure.
// public:
// char fType[20];
// Int_t fNtrack;
// Int_t fNseg;
// Int_t fNvertex;
// UInt_t fFlag;
// Float_t fTemperature;
// Int_t fMeasures[10];
// Float_t fMatrix[4][4];
// Float_t *fClosestDistance; //[fNvertex] indexed array!
// EventHeader fEvtHdr;
// TClonesArray *fTracks;
// TRefArray *fHighPt; //array of High Pt tracks only
// TRefArray *fMuons; //array of Muon tracks only
// TRef fLastTrack; //pointer to last track
// TRef fHistoWeb; //EXEC:GetHistoWeb reference to an histogram in a TWebFile
// TH1F *fH;
//
// The EventHeader class has 3 data members (integers):
// public:
// Int_t fEvtNum;
// Int_t fRun;
// Int_t fDate;
//
//
// The Event data member fTracks is a pointer to a TClonesArray.
// It is an array of a variable number of tracks per event.
// Each element of the array is an object of class Track with the members:
// private:
// Float_t fPx; //X component of the momentum
// Float_t fPy; //Y component of the momentum
// Float_t fPz; //Z component of the momentum
// Float_t fRandom; //A random track quantity
// Float_t fMass2; //The mass square of this particle
// Float_t fBx; //X intercept at the vertex
// Float_t fBy; //Y intercept at the vertex
// Float_t fMeanCharge; //Mean charge deposition of all hits of this track
// Float_t fXfirst; //X coordinate of the first point
// Float_t fXlast; //X coordinate of the last point
// Float_t fYfirst; //Y coordinate of the first point
// Float_t fYlast; //Y coordinate of the last point
// Float_t fZfirst; //Z coordinate of the first point
// Float_t fZlast; //Z coordinate of the last point
// Float_t fCharge; //Charge of this track
// Float_t fVertex[3]; //Track vertex position
// Int_t fNpoint; //Number of points for this track
// Short_t fValid; //Validity criterion
//
// An example of a batch program to use the Event/Track classes is given
// in this directory: MainEvent.
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
// During the processing of the event (optionally) also a large number
// of histograms can be filled. The creation and handling of the
// histograms is taken care of by the HistogramManager class.
//
////////////////////////////////////////////////////////////////////////
#include "TRandom.h"
#include "TDirectory.h"
#include "TProcessID.h"
#include "Event.h"
ClassImp(EventHeader)
ClassImp(Event)
ClassImp(Track)
ClassImp(HistogramManager)
TClonesArray *Event::fgTracks = 0;
TH1F *Event::fgHist = 0;
//______________________________________________________________________________
Event::Event()
{
// Create an Event object.
// When the constructor is invoked for the first time, the class static
// variable fgTracks is 0 and the TClonesArray fgTracks is created.
if (!fgTracks) fgTracks = new TClonesArray("Track", 1000);
fTracks = fgTracks;
fHighPt = new TRefArray;
fMuons = new TRefArray;
fNtrack = 0;
fH = 0;
Int_t i0,i1;
for (i0 = 0; i0 < 4; i0++) {
for (i1 = 0; i1 < 4; i1++) {
fMatrix[i0][i1] = 0.0;
}
}
for (i0 = 0; i0 <10; i0++) fMeasures[i0] = 0;
fClosestDistance = 0;
fEventName = 0;
fWebHistogram.SetAction(this);
}
//______________________________________________________________________________
Event::~Event()
{
Clear();
if (fH == fgHist) fgHist = 0;
delete fH; fH = 0;
delete fHighPt; fHighPt = 0;
delete fMuons; fMuons = 0;
delete [] fClosestDistance;
if (fEventName) delete [] fEventName;
}
//______________________________________________________________________________
void Event::Build(Int_t ev, Int_t arg5, Float_t ptmin) {
char etype[20];
Float_t sigmat, sigmas;
gRandom->Rannor(sigmat,sigmas);
Int_t ntrack = Int_t(arg5 +arg5*sigmat/120.);
Float_t random = gRandom->Rndm(1);
//Save current Object count
Int_t ObjectNumber = TProcessID::GetObjectCount();
Clear();
fHighPt->Delete();
fMuons->Delete();
Int_t nch = 15;
if (ev > 100) nch += 3;
if (ev > 10000) nch += 3;
if (fEventName) delete [] fEventName;
fEventName = new char[nch];
sprintf(fEventName,"Event%d_Run%d",ev,200);
sprintf(etype,"type%d",ev%5);
SetType(etype);
SetHeader(ev, 200, 960312, random);
SetNseg(Int_t(10*ntrack+20*sigmas));
SetNvertex(Int_t(1+20*gRandom->Rndm()));
SetFlag(UInt_t(random+0.5));
SetTemperature(random+20.);
for(UChar_t m = 0; m < 10; m++) {
SetMeasure(m, Int_t(gRandom->Gaus(m,m+1)));
}
for(UChar_t i0 = 0; i0 < 4; i0++) {
for(UChar_t i1 = 0; i1 < 4; i1++) {
SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1));
}
}
// Create and Fill the Track objects
for (Int_t t = 0; t < ntrack; t++) AddTrack(random,ptmin);
//Restore Object count
//To save space in the table keeping track of all referenced objects
//we assume that our events do not address each other. We reset the
//object count to what it was at the beginning of the event.
TProcessID::SetObjectCount(ObjectNumber);
}
//______________________________________________________________________________
Track *Event::AddTrack(Float_t random, Float_t ptmin)
{
// Add a new track to the list of tracks for this event.
// To avoid calling the very time consuming operator new for each track,
// the standard but not well know C++ operator "new with placement"
// is called. If tracks[i] is 0, a new Track object will be created
// otherwise the previous Track[i] will be overwritten.
TClonesArray &tracks = *fTracks;
Track *track = new(tracks[fNtrack++]) Track(random);
//Save reference to last Track in the collection of Tracks
fLastTrack = track;
//Save reference in fHighPt if track is a high Pt track
if (track->GetPt() > ptmin) fHighPt->Add(track);
//Save reference in fMuons if track is a muon candidate
if (track->GetMass2() < 0.11) fMuons->Add(track);
return track;
}
//______________________________________________________________________________
void Event::Clear(Option_t *option)
{
fTracks->Clear(option);
fHighPt->Delete();
fMuons->Delete();
}
//______________________________________________________________________________
void Event::Reset(Option_t *option)
{
// Static function to reset all static objects for this event
// fgTracks->Delete(option);
delete fgTracks; fgTracks = 0;
fgHist = 0;
}
//______________________________________________________________________________
void Event::SetHeader(Int_t i, Int_t run, Int_t date, Float_t random)
{
fNtrack = 0;
fEvtHdr.Set(i, run, date);
if (!fgHist) fgHist = new TH1F("hstat","Event Histogram",100,0,1);
fH = fgHist;
fH->Fill(random);
}
//______________________________________________________________________________
void Event::SetMeasure(UChar_t which, Int_t what) {
if (which<10) fMeasures[which] = what;
}
//______________________________________________________________________________
void Event::SetRandomVertex() {
// This delete is to test the relocation of variable length array
if (fClosestDistance) delete [] fClosestDistance;
if (!fNvertex) {
fClosestDistance = 0;
return;
}
fClosestDistance = new Float_t[fNvertex];
for (Int_t k = 0; k < fNvertex; k++ ) {
fClosestDistance[k] = gRandom->Gaus(1,1);
}
}
//______________________________________________________________________________
Track::Track(Float_t random) : TObject()
{
// Create a track object.
// Note that in this example, data members do not have any physical meaning.
Float_t a,b,px,py;
gRandom->Rannor(px,py);
fPx = px;
fPy = py;
fPz = TMath::Sqrt(px*px+py*py);
fRandom = 1000*random;
if (fRandom < 10) fMass2 = 0.106;
else if (fRandom < 100) fMass2 = 0.8;
else if (fRandom < 500) fMass2 = 4.5;
else if (fRandom < 900) fMass2 = 8.9;
else fMass2 = 9.8;
gRandom->Rannor(a,b);
fBx = 0.1*a;
fBy = 0.1*b;
fMeanCharge = 0.01*gRandom->Rndm(1);
gRandom->Rannor(a,b);
fXfirst = a*10;
fXlast = b*10;
gRandom->Rannor(a,b);
fYfirst = a*12;
fYlast = b*16;
gRandom->Rannor(a,b);
fZfirst = 50 + 5*a;
fZlast = 200 + 10*b;
fCharge = Float_t(Int_t(3*gRandom->Rndm(1)) - 1);
fVertex[0] = gRandom->Gaus(0,0.1);
fVertex[1] = gRandom->Gaus(0,0.2);
fVertex[2] = gRandom->Gaus(0,10);
fNpoint = Int_t(60+10*gRandom->Rndm(1));
fValid = Int_t(0.6+gRandom->Rndm(1));
}
//______________________________________________________________________________
HistogramManager::HistogramManager(TDirectory *dir)
{
// Create histogram manager object. Histograms will be created
// in the "dir" directory.
// Save current directory and cd to "dir".
TDirectory *saved = gDirectory;
dir->cd();
fNtrack = new TH1F("hNtrack", "Ntrack",100,575,625);
fNseg = new TH1F("hNseg", "Nseg",100,5800,6200);
fTemperature = new TH1F("hTemperature","Temperature",100,19.5,20.5);
fPx = new TH1F("hPx", "Px",100,-4,4);
fPy = new TH1F("hPy", "Py",100,-4,4);
fPz = new TH1F("hPz", "Pz",100,0,5);
fRandom = new TH1F("hRandom", "Random",100,0,1000);
fMass2 = new TH1F("hMass2", "Mass2",100,0,12);
fBx = new TH1F("hBx", "Bx",100,-0.5,0.5);
fBy = new TH1F("hBy", "By",100,-0.5,0.5);
fMeanCharge = new TH1F("hMeanCharge","MeanCharge",100,0,0.01);
fXfirst = new TH1F("hXfirst", "Xfirst",100,-40,40);
fXlast = new TH1F("hXlast", "Xlast",100,-40,40);
fYfirst = new TH1F("hYfirst", "Yfirst",100,-40,40);
fYlast = new TH1F("hYlast", "Ylast",100,-40,40);
fZfirst = new TH1F("hZfirst", "Zfirst",100,0,80);
fZlast = new TH1F("hZlast", "Zlast",100,0,250);
fCharge = new TH1F("hCharge", "Charge",100,-1.5,1.5);
fNpoint = new TH1F("hNpoint", "Npoint",100,50,80);
fValid = new TH1F("hValid", "Valid",100,0,1.2);
// cd back to original directory
saved->cd();
}
//______________________________________________________________________________
HistogramManager::~HistogramManager()
{
// Clean up all histograms.
// Nothing to do. Histograms will be deleted when the directory
// in which tey are stored is closed.
}
//______________________________________________________________________________
void HistogramManager::Hfill(Event *event)
{
// Fill histograms.
fNtrack->Fill(event->GetNtrack());
fNseg->Fill(event->GetNseg());
fTemperature->Fill(event->GetTemperature());
for (Int_t itrack = 0; itrack < event->GetNtrack(); itrack++) {
Track *track = (Track*)event->GetTracks()->UncheckedAt(itrack);
fPx->Fill(track->GetPx());
fPy->Fill(track->GetPy());
fPz->Fill(track->GetPz());
fRandom->Fill(track->GetRandom());
fMass2->Fill(track->GetMass2());
fBx->Fill(track->GetBx());
fBy->Fill(track->GetBy());
fMeanCharge->Fill(track->GetMeanCharge());
fXfirst->Fill(track->GetXfirst());
fXlast->Fill(track->GetXlast());
fYfirst->Fill(track->GetYfirst());
fYlast->Fill(track->GetYlast());
fZfirst->Fill(track->GetZfirst());
fZlast->Fill(track->GetZlast());
fCharge->Fill(track->GetCharge());
fNpoint->Fill(track->GetNpoint());
fValid->Fill(track->GetValid());
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: app.cpp
* Purpose: Implementation of classes for syncodbcquery
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
IMPLEMENT_APP(App)
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
, m_Running(false)
, m_Stopped(false)
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxExMenu* menuView = new wxExMenu();
menuView->AppendBars();
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Query = new wxExSTCWithFrame(this, this);
m_Query->SetLexer("sql");
m_Results = new wxExGrid(this);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
m_Shell->SetFocus();
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
SetupStatusBar(panes);
#endif
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
}
void Frame::OnCommandConfigDialog(
wxWindowID dialogid,
int commandid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
}
else
{
wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
}
}
wxExGrid* Frame::GetGrid()
{
if (m_Results->IsShown())
{
return m_Results;
}
else
{
const wxExGrid* grid = m_Statistics.GetGrid();
if (grid != NULL && grid->IsShown())
{
return (wxExGrid*)grid;
}
else
{
return NULL;
}
}
}
wxExSTCFile* Frame::GetSTC()
{
if (m_Query->IsShown())
{
return m_Query;
}
return NULL;
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, m_Query);
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion("v1.0.1");
info.SetCopyright("(c) 2008-2010, Anton van Wezenbeek");
info.AddDeveloper(wxVERSION_STRING);
info.AddDeveloper(wxEX_VERSION_STRING);
info.AddDeveloper(wxExOTL::Version());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->FileNew(wxEmptyString);
m_Query->SetLexer("sql");
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql) | *.sql",
true);
break;
case wxID_PREFERENCES:
event.Skip();
break;
case wxID_SAVE:
m_Query->FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this, m_Query,
_("File Save As"),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
m_otl.Logoff();
m_Shell->SetPrompt(">");
break;
case ID_DATABASE_OPEN:
m_otl.Logon(this);
m_Shell->SetPrompt(
(m_otl.IsConnected() ? wxConfigBase::Get()->Read(_("Datasource")): "") + ">");
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString query = event.GetString().substr(
0,
event.GetString().length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
long flags)
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
return m_Query->Open(filename, line_number, match, flags);
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw, rpc);
}
else
{
const auto rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw, rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
rpc,
(float)sw.Time() / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), sw.Time());
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), sw.Time());
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>preferences already handled by base class<commit_after>/******************************************************************************\
* File: app.cpp
* Purpose: Implementation of classes for syncodbcquery
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
IMPLEMENT_APP(App)
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
, m_Running(false)
, m_Stopped(false)
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxExMenu* menuView = new wxExMenu();
menuView->AppendBars();
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Query = new wxExSTCWithFrame(this, this);
m_Query->SetLexer("sql");
m_Results = new wxExGrid(this);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
m_Shell->SetFocus();
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
SetupStatusBar(panes);
#endif
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
}
void Frame::OnCommandConfigDialog(
wxWindowID dialogid,
int commandid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
}
else
{
wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
}
}
wxExGrid* Frame::GetGrid()
{
if (m_Results->IsShown())
{
return m_Results;
}
else
{
const wxExGrid* grid = m_Statistics.GetGrid();
if (grid != NULL && grid->IsShown())
{
return (wxExGrid*)grid;
}
else
{
return NULL;
}
}
}
wxExSTCFile* Frame::GetSTC()
{
if (m_Query->IsShown())
{
return m_Query;
}
return NULL;
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, m_Query);
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion("v1.0.1");
info.SetCopyright("(c) 2008-2010, Anton van Wezenbeek");
info.AddDeveloper(wxVERSION_STRING);
info.AddDeveloper(wxEX_VERSION_STRING);
info.AddDeveloper(wxExOTL::Version());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->FileNew(wxEmptyString);
m_Query->SetLexer("sql");
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql) | *.sql",
true);
break;
case wxID_SAVE:
m_Query->FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this, m_Query,
_("File Save As"),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
m_otl.Logoff();
m_Shell->SetPrompt(">");
break;
case ID_DATABASE_OPEN:
m_otl.Logon(this);
m_Shell->SetPrompt(
(m_otl.IsConnected() ? wxConfigBase::Get()->Read(_("Datasource")): "") + ">");
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString query = event.GetString().substr(
0,
event.GetString().length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
long flags)
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
return m_Query->Open(filename, line_number, match, flags);
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw, rpc);
}
else
{
const auto rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw, rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
rpc,
(float)sw.Time() / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), sw.Time());
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), sw.Time());
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|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/chromeos/login/background_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/feedback_menu_button.h"
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"
// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
using views::WidgetGtk;
namespace chromeos {
BackgroundView::BackgroundView() : status_area_(NULL),
os_version_label_(NULL),
boot_times_label_(NULL),
did_paint_(false) {
views::Painter* painter = chromeos::CreateWizardPainter(
&chromeos::BorderDefinition::kWizardBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
InitStatusArea();
InitInfoLabels();
}
static void ResetXCursor() {
// TODO(sky): nuke this once new window manager is in place.
// This gets rid of the ugly X default cursor.
Display* display = x11_util::GetXDisplay();
Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
XID root_window = x11_util::GetX11RootWindow();
XSetWindowAttributes attr;
attr.cursor = cursor;
XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}
// static
views::Widget* BackgroundView::CreateWindowContainingView(
const gfx::Rect& bounds,
BackgroundView** view) {
ResetXCursor();
WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
window->Init(NULL, bounds);
*view = new BackgroundView();
window->SetContentsView(*view);
(*view)->UpdateWindowType();
// This keeps the window from flashing at startup.
GdkWindow* gdk_window = window->GetNativeView()->window;
gdk_window_set_back_pixmap(gdk_window, NULL, false);
return window;
}
void BackgroundView::SetStatusAreaVisible(bool visible) {
status_area_->SetVisible(visible);
}
void BackgroundView::Paint(gfx::Canvas* canvas) {
views::View::Paint(canvas);
if (!did_paint_) {
did_paint_ = true;
UpdateWindowType();
}
}
void BackgroundView::Layout() {
int corner_padding =
chromeos::BorderDefinition::kWizardBorder.padding +
chromeos::BorderDefinition::kWizardBorder.corner_radius / 2;
int kInfoLeftPadding = 60;
int kInfoBottomPadding = 40;
int kInfoBetweenLinesPadding = 4;
gfx::Size status_area_size = status_area_->GetPreferredSize();
status_area_->SetBounds(
width() - status_area_size.width() - corner_padding,
corner_padding,
status_area_size.width(),
status_area_size.height());
gfx::Size version_size = os_version_label_->GetPreferredSize();
os_version_label_->SetBounds(
kInfoLeftPadding,
height() -
((2 * version_size.height()) +
kInfoBottomPadding +
kInfoBetweenLinesPadding),
width() - 2 * kInfoLeftPadding,
version_size.height());
boot_times_label_->SetBounds(
kInfoLeftPadding,
height() - (version_size.height() + kInfoBottomPadding),
width() - 2 * corner_padding,
version_size.height());
}
void BackgroundView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
gfx::NativeWindow BackgroundView::GetNativeWindow() const {
return
GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}
bool BackgroundView::ShouldOpenButtonOptions(
const views::View* button_view) const {
if (button_view == status_area_->clock_view() ||
button_view == status_area_->feedback_view() ||
button_view == status_area_->language_view() ||
button_view == status_area_->network_view()) {
return false;
}
return true;
}
void BackgroundView::OpenButtonOptions(const views::View* button_view) const {
// TODO(avayvod): Add some dialog for options or remove them completely.
}
bool BackgroundView::IsButtonVisible(const views::View* button_view) const {
return true;
}
bool BackgroundView::IsBrowserMode() const {
return false;
}
void BackgroundView::LocaleChanged() {
Layout();
SchedulePaint();
}
void BackgroundView::InitStatusArea() {
DCHECK(status_area_ == NULL);
status_area_ = new StatusAreaView(this);
status_area_->Init();
AddChildView(status_area_);
}
void BackgroundView::InitInfoLabels() {
const SkColor kVersionColor = 0xff8eb1f4;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
os_version_label_ = new views::Label();
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(os_version_label_);
boot_times_label_ = new views::Label();
boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
boot_times_label_->SetColor(kVersionColor);
boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(boot_times_label_);
if (CrosLibrary::Get()->EnsureLoaded()) {
version_loader_.GetVersion(
&version_consumer_, NewCallback(this, &BackgroundView::OnVersion));
boot_times_loader_.GetBootTimes(
&boot_times_consumer_, NewCallback(this, &BackgroundView::OnBootTimes));
} else {
os_version_label_->SetText(
ASCIIToWide(CrosLibrary::Get()->load_error_string()));
}
}
void BackgroundView::UpdateWindowType() {
std::vector<int> params;
params.push_back(did_paint_ ? 1 : 0);
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_BACKGROUND,
¶ms);
}
void BackgroundView::OnVersion(
VersionLoader::Handle handle, std::string version) {
std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
version_text += ' ';
version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
version_text += ' ';
version_text += version;
os_version_label_->SetText(ASCIIToWide(version_text));
}
void BackgroundView::OnBootTimes(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
// TODO(davemoore) if we decide to keep these times visible we will need
// to localize the strings.
const char* kBootTimesNoChromeExec =
"Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Boot took %.2f seconds "
"(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome_exec > 0) {
boot_times_text =
StringPrintf(
kBootTimesChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.chrome_exec - boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.chrome_exec);
} else {
boot_times_text =
StringPrintf(
kBootTimesNoChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.pre_startup);
}
boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}
} // namespace chromeos
<commit_msg>Made feedback icon hidden on login screen.<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/chromeos/login/background_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/feedback_menu_button.h"
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"
// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
using views::WidgetGtk;
namespace chromeos {
BackgroundView::BackgroundView() : status_area_(NULL),
os_version_label_(NULL),
boot_times_label_(NULL),
did_paint_(false) {
views::Painter* painter = chromeos::CreateWizardPainter(
&chromeos::BorderDefinition::kWizardBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
InitStatusArea();
InitInfoLabels();
}
static void ResetXCursor() {
// TODO(sky): nuke this once new window manager is in place.
// This gets rid of the ugly X default cursor.
Display* display = x11_util::GetXDisplay();
Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
XID root_window = x11_util::GetX11RootWindow();
XSetWindowAttributes attr;
attr.cursor = cursor;
XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}
// static
views::Widget* BackgroundView::CreateWindowContainingView(
const gfx::Rect& bounds,
BackgroundView** view) {
ResetXCursor();
WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
window->Init(NULL, bounds);
*view = new BackgroundView();
window->SetContentsView(*view);
(*view)->UpdateWindowType();
// This keeps the window from flashing at startup.
GdkWindow* gdk_window = window->GetNativeView()->window;
gdk_window_set_back_pixmap(gdk_window, NULL, false);
return window;
}
void BackgroundView::SetStatusAreaVisible(bool visible) {
status_area_->SetVisible(visible);
}
void BackgroundView::Paint(gfx::Canvas* canvas) {
views::View::Paint(canvas);
if (!did_paint_) {
did_paint_ = true;
UpdateWindowType();
}
}
void BackgroundView::Layout() {
int corner_padding =
chromeos::BorderDefinition::kWizardBorder.padding +
chromeos::BorderDefinition::kWizardBorder.corner_radius / 2;
int kInfoLeftPadding = 60;
int kInfoBottomPadding = 40;
int kInfoBetweenLinesPadding = 4;
gfx::Size status_area_size = status_area_->GetPreferredSize();
status_area_->SetBounds(
width() - status_area_size.width() - corner_padding,
corner_padding,
status_area_size.width(),
status_area_size.height());
gfx::Size version_size = os_version_label_->GetPreferredSize();
os_version_label_->SetBounds(
kInfoLeftPadding,
height() -
((2 * version_size.height()) +
kInfoBottomPadding +
kInfoBetweenLinesPadding),
width() - 2 * kInfoLeftPadding,
version_size.height());
boot_times_label_->SetBounds(
kInfoLeftPadding,
height() - (version_size.height() + kInfoBottomPadding),
width() - 2 * corner_padding,
version_size.height());
}
void BackgroundView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
gfx::NativeWindow BackgroundView::GetNativeWindow() const {
return
GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}
bool BackgroundView::ShouldOpenButtonOptions(
const views::View* button_view) const {
if (button_view == status_area_->clock_view() ||
button_view == status_area_->feedback_view() ||
button_view == status_area_->language_view() ||
button_view == status_area_->network_view()) {
return false;
}
return true;
}
void BackgroundView::OpenButtonOptions(const views::View* button_view) const {
// TODO(avayvod): Add some dialog for options or remove them completely.
}
bool BackgroundView::IsButtonVisible(const views::View* button_view) const {
if (button_view == status_area_->feedback_view())
return false;
return true;
}
bool BackgroundView::IsBrowserMode() const {
return false;
}
void BackgroundView::LocaleChanged() {
Layout();
SchedulePaint();
}
void BackgroundView::InitStatusArea() {
DCHECK(status_area_ == NULL);
status_area_ = new StatusAreaView(this);
status_area_->Init();
status_area_->Update();
AddChildView(status_area_);
}
void BackgroundView::InitInfoLabels() {
const SkColor kVersionColor = 0xff8eb1f4;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
os_version_label_ = new views::Label();
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(os_version_label_);
boot_times_label_ = new views::Label();
boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
boot_times_label_->SetColor(kVersionColor);
boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
AddChildView(boot_times_label_);
if (CrosLibrary::Get()->EnsureLoaded()) {
version_loader_.GetVersion(
&version_consumer_, NewCallback(this, &BackgroundView::OnVersion));
boot_times_loader_.GetBootTimes(
&boot_times_consumer_, NewCallback(this, &BackgroundView::OnBootTimes));
} else {
os_version_label_->SetText(
ASCIIToWide(CrosLibrary::Get()->load_error_string()));
}
}
void BackgroundView::UpdateWindowType() {
std::vector<int> params;
params.push_back(did_paint_ ? 1 : 0);
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_BACKGROUND,
¶ms);
}
void BackgroundView::OnVersion(
VersionLoader::Handle handle, std::string version) {
std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
version_text += ' ';
version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
version_text += ' ';
version_text += version;
os_version_label_->SetText(ASCIIToWide(version_text));
}
void BackgroundView::OnBootTimes(
BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
// TODO(davemoore) if we decide to keep these times visible we will need
// to localize the strings.
const char* kBootTimesNoChromeExec =
"Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Boot took %.2f seconds "
"(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome_exec > 0) {
boot_times_text =
StringPrintf(
kBootTimesChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.chrome_exec - boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.chrome_exec);
} else {
boot_times_text =
StringPrintf(
kBootTimesNoChromeExec,
boot_times.firmware + boot_times.login_prompt_ready,
boot_times.firmware,
boot_times.pre_startup,
boot_times.login_prompt_ready - boot_times.pre_startup);
}
boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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/debugger/inspectable_tab_proxy.h"
#include "base/json_reader.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/debugger/debugger_remote_service.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/sessions/session_id.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/devtools_messages.h"
// The debugged tab has closed.
void DevToolsClientHostImpl::InspectedTabClosing() {
TabClosed();
delete this;
}
// The remote debugger has detached.
void DevToolsClientHostImpl::Close() {
NotifyCloseListener();
delete this;
}
void DevToolsClientHostImpl::SendMessageToClient(
const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void DevToolsClientHostImpl::OnRpcMessage(const std::string& class_name,
const std::string& message_name,
const std::string& msg) {
static const std::string kDebuggerAgentDelegate = "DebuggerAgentDelegate";
static const std::string kToolsAgentDelegate = "ToolsAgentDelegate";
static const std::string kDebuggerOutput = "DebuggerOutput";
static const std::string kFrameNavigate = "FrameNavigate";
scoped_ptr<Value> message(JSONReader::Read(msg, false));
if (!message->IsType(Value::TYPE_LIST)) {
NOTREACHED(); // The RPC protocol has changed :(
return;
}
ListValue* list_msg = static_cast<ListValue*>(message.get());
if (class_name == kDebuggerAgentDelegate && message_name == kDebuggerOutput) {
std::string str;
list_msg->GetString(0, &str);
DebuggerOutput(str);
} else if (class_name == kToolsAgentDelegate &&
message_name == kFrameNavigate) {
std::string url;
list_msg->GetString(0, &url);
FrameNavigate(url);
}
}
void DevToolsClientHostImpl::DebuggerOutput(const std::string& msg) {
service_->DebuggerOutput(id_, msg);
}
void DevToolsClientHostImpl::FrameNavigate(const std::string& url) {
service_->FrameNavigate(id_, url);
}
void DevToolsClientHostImpl::TabClosed() {
service_->TabClosed(id_);
}
const InspectableTabProxy::ControllersMap&
InspectableTabProxy::controllers_map() {
controllers_map_.clear();
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
NavigationController& controller =
model->GetTabContentsAt(i)->controller();
controllers_map_[controller.session_id().id()] = &controller;
}
}
return controllers_map_;
}
DevToolsClientHostImpl* InspectableTabProxy::ClientHostForTabId(
int32 id) {
InspectableTabProxy::IdToClientHostMap::const_iterator it =
id_to_client_host_map_.find(id);
if (it == id_to_client_host_map_.end()) {
return NULL;
}
return it->second;
}
DevToolsClientHost* InspectableTabProxy::NewClientHost(
int32 id,
DebuggerRemoteService* service) {
DevToolsClientHostImpl* client_host =
new DevToolsClientHostImpl(id, service, &id_to_client_host_map_);
id_to_client_host_map_[id] = client_host;
return client_host;
}
void InspectableTabProxy::OnRemoteDebuggerDetached() {
while (id_to_client_host_map_.size() > 0) {
IdToClientHostMap::iterator it = id_to_client_host_map_.begin();
it->second->debugger_remote_service()->DetachFromTab(IntToString(it->first),
NULL);
}
}
<commit_msg>Coverity underground warfare: check return code - Check return code consistently - NOTREACHED() added in one case - CID 4169<commit_after>// Copyright (c) 2009 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/debugger/inspectable_tab_proxy.h"
#include "base/json_reader.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/debugger/debugger_remote_service.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/sessions/session_id.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/devtools_messages.h"
// The debugged tab has closed.
void DevToolsClientHostImpl::InspectedTabClosing() {
TabClosed();
delete this;
}
// The remote debugger has detached.
void DevToolsClientHostImpl::Close() {
NotifyCloseListener();
delete this;
}
void DevToolsClientHostImpl::SendMessageToClient(
const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void DevToolsClientHostImpl::OnRpcMessage(const std::string& class_name,
const std::string& message_name,
const std::string& msg) {
static const std::string kDebuggerAgentDelegate = "DebuggerAgentDelegate";
static const std::string kToolsAgentDelegate = "ToolsAgentDelegate";
static const std::string kDebuggerOutput = "DebuggerOutput";
static const std::string kFrameNavigate = "FrameNavigate";
scoped_ptr<Value> message(JSONReader::Read(msg, false));
if (!message->IsType(Value::TYPE_LIST)) {
NOTREACHED(); // The RPC protocol has changed :(
return;
}
ListValue* list_msg = static_cast<ListValue*>(message.get());
if (class_name == kDebuggerAgentDelegate && message_name == kDebuggerOutput) {
std::string str;
if (!list_msg->GetString(0, &str))
return;
DebuggerOutput(str);
} else if (class_name == kToolsAgentDelegate &&
message_name == kFrameNavigate) {
std::string url;
if (!list_msg->GetString(0, &url)) {
NOTREACHED();
return;
}
FrameNavigate(url);
}
}
void DevToolsClientHostImpl::DebuggerOutput(const std::string& msg) {
service_->DebuggerOutput(id_, msg);
}
void DevToolsClientHostImpl::FrameNavigate(const std::string& url) {
service_->FrameNavigate(id_, url);
}
void DevToolsClientHostImpl::TabClosed() {
service_->TabClosed(id_);
}
const InspectableTabProxy::ControllersMap&
InspectableTabProxy::controllers_map() {
controllers_map_.clear();
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
NavigationController& controller =
model->GetTabContentsAt(i)->controller();
controllers_map_[controller.session_id().id()] = &controller;
}
}
return controllers_map_;
}
DevToolsClientHostImpl* InspectableTabProxy::ClientHostForTabId(
int32 id) {
InspectableTabProxy::IdToClientHostMap::const_iterator it =
id_to_client_host_map_.find(id);
if (it == id_to_client_host_map_.end()) {
return NULL;
}
return it->second;
}
DevToolsClientHost* InspectableTabProxy::NewClientHost(
int32 id,
DebuggerRemoteService* service) {
DevToolsClientHostImpl* client_host =
new DevToolsClientHostImpl(id, service, &id_to_client_host_map_);
id_to_client_host_map_[id] = client_host;
return client_host;
}
void InspectableTabProxy::OnRemoteDebuggerDetached() {
while (id_to_client_host_map_.size() > 0) {
IdToClientHostMap::iterator it = id_to_client_host_map_.begin();
it->second->debugger_remote_service()->DetachFromTab(IntToString(it->first),
NULL);
}
}
<|endoftext|>
|
<commit_before>#include <silicium/config.hpp>
#include <silicium/bounded_int.hpp>
#include <silicium/variant.hpp>
#include <silicium/arithmetic/add.hpp>
#include <boost/test/unit_test.hpp>
#if SILICIUM_COMPILER_HAS_USING
namespace Si
{
namespace m2
{
using std::size_t;
using std::move;
struct empty_t
{
};
static BOOST_CONSTEXPR_OR_CONST empty_t empty;
struct out_of_memory
{
};
struct piece_of_memory
{
void *begin;
piece_of_memory()
: begin(nullptr)
{
}
explicit piece_of_memory(void *begin)
: begin(begin)
{
}
};
struct standard_allocator
{
variant<piece_of_memory, out_of_memory> allocate(size_t size)
{
void *memory = std::malloc(size);
if (memory)
{
return piece_of_memory{memory};
}
return out_of_memory();
}
variant<piece_of_memory, out_of_memory>
reallocate(piece_of_memory existing_allocation, size_t new_size)
{
void *new_allocation =
std::realloc(existing_allocation.begin, new_size);
if (new_allocation)
{
return piece_of_memory{new_allocation};
}
return out_of_memory();
}
void deallocate(piece_of_memory existing_allocation)
{
std::free(existing_allocation.begin);
}
};
enum class resize_result
{
success,
out_of_memory
};
template <class T, class Length, class Allocator>
struct dynamic_storage : private Allocator
{
typedef T element_type;
typedef Length length_type;
dynamic_storage(empty_t, Allocator allocator = Allocator())
: Allocator(move(allocator))
, m_begin()
, m_length(length_type::template literal<0>())
{
}
~dynamic_storage()
{
Allocator::deallocate(m_begin);
}
length_type length() const
{
return m_length;
}
resize_result resize(length_type new_length)
{
// TODO: handle overflow
size_t const size_in_bytes =
new_length.value() * sizeof(element_type);
return visit<resize_result>(
Allocator::reallocate(m_begin, size_in_bytes),
[this, new_length](piece_of_memory const reallocated)
{
m_begin = reallocated;
m_length = new_length;
return resize_result::success;
},
[](out_of_memory)
{
return resize_result::out_of_memory;
});
}
T &data() const
{
return *begin();
}
dynamic_storage(dynamic_storage &&other) BOOST_NOEXCEPT
: Allocator(move(other)),
m_begin(other.m_begin),
m_length(other.m_length)
{
other.m_begin = piece_of_memory();
other.m_length = length_type::template literal<0>();
}
dynamic_storage &operator=(dynamic_storage &&other) BOOST_NOEXCEPT
{
using std::swap;
swap(static_cast<Allocator &>(*this),
static_cast<Allocator &>(other));
swap(m_begin, other.m_begin);
swap(m_length, other.m_length);
return *this;
}
SILICIUM_DISABLE_COPY(dynamic_storage)
private:
piece_of_memory m_begin;
length_type m_length;
T *begin() const
{
return static_cast<T *>(m_begin.begin);
}
};
enum class emplace_back_result
{
success,
out_of_memory,
full
};
template <class DynamicStorage>
struct basic_vector
{
typedef typename DynamicStorage::element_type element_type;
typedef typename DynamicStorage::length_type length_type;
basic_vector(empty_t, DynamicStorage storage)
: m_storage(move(storage))
, m_used(length_type::template literal<0>())
{
}
~basic_vector() BOOST_NOEXCEPT
{
for (typename length_type::value_type i = 0;
i < length().value(); ++i)
{
(&m_storage.data())[length().value() - 1 - i]
.~element_type();
}
}
length_type capacity() const BOOST_NOEXCEPT
{
return m_storage.length();
}
length_type length() const BOOST_NOEXCEPT
{
return m_used;
}
template <class... Args>
emplace_back_result emplace_back(Args &&... args)
{
overflow_or<typename length_type::value_type> const
maybe_new_size =
checked_add<typename length_type::value_type>(
capacity().value(), 1);
if (maybe_new_size.is_overflow())
{
return emplace_back_result::full;
}
length_type const new_size =
*length_type::create(*maybe_new_size.value());
if (m_storage.length() < new_size)
{
// TODO: exponential growth
switch (m_storage.resize(new_size))
{
case resize_result::success:
break;
case resize_result::out_of_memory:
return emplace_back_result::out_of_memory;
}
}
new (&m_storage.data())
element_type{std::forward<Args>(args)...};
m_used = new_size;
return emplace_back_result::success;
}
basic_vector(basic_vector &&other) BOOST_NOEXCEPT
: m_storage(move(other.m_storage)),
m_used(other.m_used)
{
// TODO: solve more generically
other.m_used = length_type::template literal<0>();
}
basic_vector &operator=(basic_vector &&other) BOOST_NOEXCEPT
{
m_storage = move(other.m_storage);
m_used = other.m_used;
// TODO: solve more generically
other.m_used = length_type::template literal<0>();
return *this;
}
SILICIUM_DISABLE_COPY(basic_vector)
private:
DynamicStorage m_storage;
length_type m_used;
};
template <class T, class Length>
using vector =
basic_vector<dynamic_storage<T, Length, standard_allocator>>;
}
}
BOOST_AUTO_TEST_CASE(move2_vector_emplace_back)
{
Si::m2::vector<std::uint64_t, Si::bounded_int<std::size_t, 0, 10>> v{
Si::m2::empty,
Si::m2::dynamic_storage<std::uint64_t,
Si::bounded_int<std::size_t, 0, 10>,
Si::m2::standard_allocator>{Si::m2::empty}};
BOOST_REQUIRE_EQUAL(0u, v.length().value());
BOOST_REQUIRE_EQUAL(0u, v.capacity().value());
BOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));
BOOST_REQUIRE_EQUAL(1u, v.length().value());
BOOST_REQUIRE_EQUAL(1u, v.capacity().value());
BOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(13u));
BOOST_REQUIRE_EQUAL(2u, v.length().value());
BOOST_REQUIRE_EQUAL(2u, v.capacity().value());
}
BOOST_AUTO_TEST_CASE(move2_vector_move_construct)
{
Si::m2::vector<std::uint64_t, Si::bounded_int<std::size_t, 0, 10>> v{
Si::m2::empty,
Si::m2::dynamic_storage<std::uint64_t,
Si::bounded_int<std::size_t, 0, 10>,
Si::m2::standard_allocator>{Si::m2::empty}};
BOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));
Si::m2::vector<std::uint64_t, Si::bounded_int<std::size_t, 0, 10>> w{
std::move(v)};
BOOST_REQUIRE_EQUAL(0u, v.length().value());
BOOST_REQUIRE_EQUAL(1u, w.length().value());
}
BOOST_AUTO_TEST_CASE(move2_vector_move_assign)
{
Si::m2::vector<std::uint64_t, Si::bounded_int<std::size_t, 0, 10>> v{
Si::m2::empty,
Si::m2::dynamic_storage<std::uint64_t,
Si::bounded_int<std::size_t, 0, 10>,
Si::m2::standard_allocator>{Si::m2::empty}};
BOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));
Si::m2::vector<std::uint64_t, Si::bounded_int<std::size_t, 0, 10>> w{
Si::m2::empty,
Si::m2::dynamic_storage<std::uint64_t,
Si::bounded_int<std::size_t, 0, 10>,
Si::m2::standard_allocator>{Si::m2::empty}};
w = std::move(v);
BOOST_REQUIRE_EQUAL(0u, v.length().value());
BOOST_REQUIRE_EQUAL(1u, w.length().value());
}
#endif
<commit_msg>remove an obsolete experiment<commit_after><|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <cpuinfo.h>
#include <cpuinfo-mock.h>
TEST(PROCESSORS, count) {
ASSERT_EQ(2, cpuinfo_processors_count);
}
TEST(PROCESSORS, non_null) {
ASSERT_TRUE(cpuinfo_processors);
}
TEST(PROCESSORS, vendor) {
for (uint32_t i = 0; i < cpuinfo_processors_count; i++) {
ASSERT_EQ(cpuinfo_vendor_nvidia, cpuinfo_processors[i].vendor);
}
}
TEST(PROCESSORS, uarch) {
for (uint32_t i = 0; i < cpuinfo_processors_count; i++) {
ASSERT_EQ(cpuinfo_uarch_denver, cpuinfo_processors[i].uarch);
}
}
#if CPUINFO_ARCH_ARM
TEST(ISA, thumb) {
ASSERT_TRUE(cpuinfo_isa.thumb);
}
TEST(ISA, thumb2) {
ASSERT_TRUE(cpuinfo_isa.thumb2);
}
TEST(ISA, thumbee) {
ASSERT_FALSE(cpuinfo_isa.thumbee);
}
TEST(ISA, jazelle) {
ASSERT_FALSE(cpuinfo_isa.jazelle);
}
TEST(ISA, armv5e) {
ASSERT_TRUE(cpuinfo_isa.armv5e);
}
TEST(ISA, armv6) {
ASSERT_TRUE(cpuinfo_isa.armv6);
}
TEST(ISA, armv6k) {
ASSERT_TRUE(cpuinfo_isa.armv6k);
}
TEST(ISA, armv7) {
ASSERT_TRUE(cpuinfo_isa.armv7);
}
TEST(ISA, armv7mp) {
ASSERT_TRUE(cpuinfo_isa.armv7mp);
}
TEST(ISA, idiv) {
ASSERT_TRUE(cpuinfo_isa.idiv);
}
TEST(ISA, vfpv2) {
ASSERT_FALSE(cpuinfo_isa.vfpv2);
}
TEST(ISA, vfpv3) {
ASSERT_TRUE(cpuinfo_isa.vfpv3);
}
TEST(ISA, d32) {
ASSERT_TRUE(cpuinfo_isa.d32);
}
TEST(ISA, fp16) {
ASSERT_TRUE(cpuinfo_isa.fp16);
}
TEST(ISA, fma) {
ASSERT_TRUE(cpuinfo_isa.fma);
}
TEST(ISA, wmmx) {
ASSERT_FALSE(cpuinfo_isa.wmmx);
}
TEST(ISA, wmmx2) {
ASSERT_FALSE(cpuinfo_isa.wmmx2);
}
TEST(ISA, neon) {
ASSERT_TRUE(cpuinfo_isa.neon);
}
#endif /* CPUINFO_ARCH_ARM */
TEST(ISA, aes) {
ASSERT_TRUE(cpuinfo_isa.aes);
}
TEST(ISA, sha1) {
ASSERT_TRUE(cpuinfo_isa.sha1);
}
TEST(ISA, sha2) {
ASSERT_TRUE(cpuinfo_isa.sha2);
}
TEST(ISA, pmull) {
ASSERT_TRUE(cpuinfo_isa.pmull);
}
TEST(ISA, crc32) {
ASSERT_TRUE(cpuinfo_isa.crc32);
}
#if CPUINFO_ARCH_ARM64
TEST(ISA, atomics) {
ASSERT_FALSE(cpuinfo_isa.atomics);
}
TEST(ISA, rdm) {
ASSERT_FALSE(cpuinfo_isa.rdm);
}
TEST(ISA, fp16arith) {
ASSERT_FALSE(cpuinfo_isa.fp16arith);
}
TEST(ISA, jscvt) {
ASSERT_FALSE(cpuinfo_isa.jscvt);
}
TEST(ISA, fcma) {
ASSERT_FALSE(cpuinfo_isa.fcma);
}
#endif /* CPUINFO_ARCH_ARM64 */
TEST(L1I, count) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
ASSERT_EQ(2, l1i.count);
}
TEST(L1I, non_null) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
ASSERT_TRUE(l1i.instances);
}
TEST(L1I, size) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(128 * 1024, l1i.instances[k].size);
}
}
TEST(L1I, associativity) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(4, l1i.instances[k].associativity);
}
}
TEST(L1I, sets) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(l1i.instances[k].size,
l1i.instances[k].sets * l1i.instances[k].line_size * l1i.instances[k].partitions * l1i.instances[k].associativity);
}
}
TEST(L1I, partitions) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(1, l1i.instances[k].partitions);
}
}
TEST(L1I, line_size) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(64, l1i.instances[k].line_size);
}
}
TEST(L1I, flags) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(0, l1i.instances[k].flags);
}
}
TEST(L1I, processors) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(k, l1i.instances[k].processor_start);
ASSERT_EQ(1, l1i.instances[k].processor_count);
}
}
TEST(L1D, count) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
ASSERT_EQ(2, l1d.count);
}
TEST(L1D, non_null) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
ASSERT_TRUE(l1d.instances);
}
TEST(L1D, size) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(64 * 1024, l1d.instances[k].size);
}
}
TEST(L1D, associativity) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(4, l1d.instances[k].associativity);
}
}
TEST(L1D, sets) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(l1d.instances[k].size,
l1d.instances[k].sets * l1d.instances[k].line_size * l1d.instances[k].partitions * l1d.instances[k].associativity);
}
}
TEST(L1D, partitions) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(1, l1d.instances[k].partitions);
}
}
TEST(L1D, line_size) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(64, l1d.instances[k].line_size);
}
}
TEST(L1D, flags) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(0, l1d.instances[k].flags);
}
}
TEST(L1D, processors) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(k, l1d.instances[k].processor_start);
ASSERT_EQ(1, l1d.instances[k].processor_count);
}
}
TEST(L2, DISABLED_count) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
ASSERT_EQ(1, l2.count);
}
TEST(L2, non_null) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
ASSERT_TRUE(l2.instances);
}
TEST(L2, size) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(2 * 1024 * 1024, l2.instances[k].size);
}
}
TEST(L2, associativity) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(16, l2.instances[k].associativity);
}
}
TEST(L2, sets) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(l2.instances[k].size,
l2.instances[k].sets * l2.instances[k].line_size * l2.instances[k].partitions * l2.instances[k].associativity);
}
}
TEST(L2, partitions) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(1, l2.instances[k].partitions);
}
}
TEST(L2, line_size) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(64, l2.instances[k].line_size);
}
}
TEST(L2, flags) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(0, l2.instances[k].flags);
}
}
TEST(L2, DISABLED_processors) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(0, l2.instances[k].processor_start);
ASSERT_EQ(2, l2.instances[k].processor_count);
}
}
TEST(L3, none) {
cpuinfo_caches l3 = cpuinfo_get_l3_cache();
ASSERT_EQ(0, l3.count);
ASSERT_FALSE(l3.instances);
}
TEST(L4, none) {
cpuinfo_caches l4 = cpuinfo_get_l4_cache();
ASSERT_EQ(0, l4.count);
ASSERT_FALSE(l4.instances);
}
#include <nexus9.h>
int main(int argc, char* argv[]) {
cpuinfo_mock_filesystem(filesystem);
cpuinfo_initialize();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Re-enable cluster-related cases in Nexus 9 mock test<commit_after>#include <gtest/gtest.h>
#include <cpuinfo.h>
#include <cpuinfo-mock.h>
TEST(PROCESSORS, count) {
ASSERT_EQ(2, cpuinfo_processors_count);
}
TEST(PROCESSORS, non_null) {
ASSERT_TRUE(cpuinfo_processors);
}
TEST(PROCESSORS, vendor) {
for (uint32_t i = 0; i < cpuinfo_processors_count; i++) {
ASSERT_EQ(cpuinfo_vendor_nvidia, cpuinfo_processors[i].vendor);
}
}
TEST(PROCESSORS, uarch) {
for (uint32_t i = 0; i < cpuinfo_processors_count; i++) {
ASSERT_EQ(cpuinfo_uarch_denver, cpuinfo_processors[i].uarch);
}
}
#if CPUINFO_ARCH_ARM
TEST(ISA, thumb) {
ASSERT_TRUE(cpuinfo_isa.thumb);
}
TEST(ISA, thumb2) {
ASSERT_TRUE(cpuinfo_isa.thumb2);
}
TEST(ISA, thumbee) {
ASSERT_FALSE(cpuinfo_isa.thumbee);
}
TEST(ISA, jazelle) {
ASSERT_FALSE(cpuinfo_isa.jazelle);
}
TEST(ISA, armv5e) {
ASSERT_TRUE(cpuinfo_isa.armv5e);
}
TEST(ISA, armv6) {
ASSERT_TRUE(cpuinfo_isa.armv6);
}
TEST(ISA, armv6k) {
ASSERT_TRUE(cpuinfo_isa.armv6k);
}
TEST(ISA, armv7) {
ASSERT_TRUE(cpuinfo_isa.armv7);
}
TEST(ISA, armv7mp) {
ASSERT_TRUE(cpuinfo_isa.armv7mp);
}
TEST(ISA, idiv) {
ASSERT_TRUE(cpuinfo_isa.idiv);
}
TEST(ISA, vfpv2) {
ASSERT_FALSE(cpuinfo_isa.vfpv2);
}
TEST(ISA, vfpv3) {
ASSERT_TRUE(cpuinfo_isa.vfpv3);
}
TEST(ISA, d32) {
ASSERT_TRUE(cpuinfo_isa.d32);
}
TEST(ISA, fp16) {
ASSERT_TRUE(cpuinfo_isa.fp16);
}
TEST(ISA, fma) {
ASSERT_TRUE(cpuinfo_isa.fma);
}
TEST(ISA, wmmx) {
ASSERT_FALSE(cpuinfo_isa.wmmx);
}
TEST(ISA, wmmx2) {
ASSERT_FALSE(cpuinfo_isa.wmmx2);
}
TEST(ISA, neon) {
ASSERT_TRUE(cpuinfo_isa.neon);
}
#endif /* CPUINFO_ARCH_ARM */
TEST(ISA, aes) {
ASSERT_TRUE(cpuinfo_isa.aes);
}
TEST(ISA, sha1) {
ASSERT_TRUE(cpuinfo_isa.sha1);
}
TEST(ISA, sha2) {
ASSERT_TRUE(cpuinfo_isa.sha2);
}
TEST(ISA, pmull) {
ASSERT_TRUE(cpuinfo_isa.pmull);
}
TEST(ISA, crc32) {
ASSERT_TRUE(cpuinfo_isa.crc32);
}
#if CPUINFO_ARCH_ARM64
TEST(ISA, atomics) {
ASSERT_FALSE(cpuinfo_isa.atomics);
}
TEST(ISA, rdm) {
ASSERT_FALSE(cpuinfo_isa.rdm);
}
TEST(ISA, fp16arith) {
ASSERT_FALSE(cpuinfo_isa.fp16arith);
}
TEST(ISA, jscvt) {
ASSERT_FALSE(cpuinfo_isa.jscvt);
}
TEST(ISA, fcma) {
ASSERT_FALSE(cpuinfo_isa.fcma);
}
#endif /* CPUINFO_ARCH_ARM64 */
TEST(L1I, count) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
ASSERT_EQ(2, l1i.count);
}
TEST(L1I, non_null) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
ASSERT_TRUE(l1i.instances);
}
TEST(L1I, size) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(128 * 1024, l1i.instances[k].size);
}
}
TEST(L1I, associativity) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(4, l1i.instances[k].associativity);
}
}
TEST(L1I, sets) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(l1i.instances[k].size,
l1i.instances[k].sets * l1i.instances[k].line_size * l1i.instances[k].partitions * l1i.instances[k].associativity);
}
}
TEST(L1I, partitions) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(1, l1i.instances[k].partitions);
}
}
TEST(L1I, line_size) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(64, l1i.instances[k].line_size);
}
}
TEST(L1I, flags) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(0, l1i.instances[k].flags);
}
}
TEST(L1I, processors) {
cpuinfo_caches l1i = cpuinfo_get_l1i_cache();
for (uint32_t k = 0; k < l1i.count; k++) {
ASSERT_EQ(k, l1i.instances[k].processor_start);
ASSERT_EQ(1, l1i.instances[k].processor_count);
}
}
TEST(L1D, count) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
ASSERT_EQ(2, l1d.count);
}
TEST(L1D, non_null) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
ASSERT_TRUE(l1d.instances);
}
TEST(L1D, size) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(64 * 1024, l1d.instances[k].size);
}
}
TEST(L1D, associativity) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(4, l1d.instances[k].associativity);
}
}
TEST(L1D, sets) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(l1d.instances[k].size,
l1d.instances[k].sets * l1d.instances[k].line_size * l1d.instances[k].partitions * l1d.instances[k].associativity);
}
}
TEST(L1D, partitions) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(1, l1d.instances[k].partitions);
}
}
TEST(L1D, line_size) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(64, l1d.instances[k].line_size);
}
}
TEST(L1D, flags) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(0, l1d.instances[k].flags);
}
}
TEST(L1D, processors) {
cpuinfo_caches l1d = cpuinfo_get_l1d_cache();
for (uint32_t k = 0; k < l1d.count; k++) {
ASSERT_EQ(k, l1d.instances[k].processor_start);
ASSERT_EQ(1, l1d.instances[k].processor_count);
}
}
TEST(L2, count) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
ASSERT_EQ(1, l2.count);
}
TEST(L2, non_null) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
ASSERT_TRUE(l2.instances);
}
TEST(L2, size) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(2 * 1024 * 1024, l2.instances[k].size);
}
}
TEST(L2, associativity) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(16, l2.instances[k].associativity);
}
}
TEST(L2, sets) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(l2.instances[k].size,
l2.instances[k].sets * l2.instances[k].line_size * l2.instances[k].partitions * l2.instances[k].associativity);
}
}
TEST(L2, partitions) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(1, l2.instances[k].partitions);
}
}
TEST(L2, line_size) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(64, l2.instances[k].line_size);
}
}
TEST(L2, flags) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(0, l2.instances[k].flags);
}
}
TEST(L2, processors) {
cpuinfo_caches l2 = cpuinfo_get_l2_cache();
for (uint32_t k = 0; k < l2.count; k++) {
ASSERT_EQ(0, l2.instances[k].processor_start);
ASSERT_EQ(2, l2.instances[k].processor_count);
}
}
TEST(L3, none) {
cpuinfo_caches l3 = cpuinfo_get_l3_cache();
ASSERT_EQ(0, l3.count);
ASSERT_FALSE(l3.instances);
}
TEST(L4, none) {
cpuinfo_caches l4 = cpuinfo_get_l4_cache();
ASSERT_EQ(0, l4.count);
ASSERT_FALSE(l4.instances);
}
#include <nexus9.h>
int main(int argc, char* argv[]) {
cpuinfo_mock_filesystem(filesystem);
cpuinfo_initialize();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
* @author Christoph Jentzsch <cj@ethdev.com>
* @date 2014
* State test functions.
*/
#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/ExtVM.h>
#include <libethereum/Defaults.h>
#include <libevm/VM.h>
#include "TestHelper.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;
namespace dev { namespace test {
void doStateTests(json_spirit::mValue& v, bool _fillin)
{
processCommandLineOptions();
for (auto& i: v.get_obj())
{
cerr << i.first << endl;
mObject& o = i.second.get_obj();
BOOST_REQUIRE(o.count("env") > 0);
BOOST_REQUIRE(o.count("pre") > 0);
BOOST_REQUIRE(o.count("transaction") > 0);
ImportTest importer(o, _fillin);
State theState = importer.m_statePre;
bytes tx = importer.m_transaction.rlp();
bytes output;
try
{
theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);
}
catch (Exception const& _e)
{
cnote << "state execution did throw an exception: " << diagnostic_information(_e);
theState.commit();
}
catch (std::exception const& _e)
{
cnote << "state execution did throw an exception: " << _e.what();
}
if (_fillin)
{
#if ETH_FATDB
importer.exportTest(output, theState);
#else
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("You can not fill tests when FATDB is switched off"));
#endif
}
else
{
BOOST_REQUIRE(o.count("post") > 0);
BOOST_REQUIRE(o.count("out") > 0);
// check output
checkOutput(output, o);
// check logs
checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);
// check addresses
#if ETH_FATDB
auto expectedAddrs = importer.m_statePost.addresses();
auto resultAddrs = theState.addresses();
for (auto& expectedPair : expectedAddrs)
{
auto& expectedAddr = expectedPair.first;
auto resultAddrIt = resultAddrs.find(expectedAddr);
if (resultAddrIt == resultAddrs.end())
BOOST_ERROR("Missing expected address " << expectedAddr);
else
{
BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code");
checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);
}
}
checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);
#endif
BOOST_CHECK_MESSAGE(theState.rootHash() == h256(o["postStateRoot"].get_str()), "wrong post state root");
}
}
}
} }// Namespace Close
BOOST_AUTO_TEST_SUITE(StateTests)
BOOST_AUTO_TEST_CASE(stExample)
{
dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSystemOperationsTest)
{
dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stPreCompiledContracts)
{
dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stLogTests)
{
dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRecursiveCreate)
{
dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stInitCodeTest)
{
dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stTransactionTest)
{
dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSpecialTest)
{
dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRefundTest)
{
dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stBlockHashTest)
{
dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests);
}
//BOOST_AUTO_TEST_CASE(stQuadraticComplexityTest)
//{
// for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
// {
// string arg = boost::unit_test::framework::master_test_suite().argv[i];
// if (arg == "--quadratic" || arg == "--all")
// {
// auto start = chrono::steady_clock::now();
// dev::test::executeTests("stQuadraticComplexityTest", "/StateTests", dev::test::doStateTests);
// auto end = chrono::steady_clock::now();
// auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
// cnote << "test duration: " << duration.count() << " milliseconds.\n";
// }
// }
//}
BOOST_AUTO_TEST_CASE(stMemoryStressTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--memory" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stMemoryStressTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stSolidityTest)
{
dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stMemoryTest)
{
dev::test::executeTests("stMemoryTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stCreateTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--createtest")
{
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
{
cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
return;
}
try
{
cnote << "Populating tests...";
json_spirit::mValue v;
string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
json_spirit::read_string(s, v);
dev::test::doStateTests(v, true);
writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
}
catch (Exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e));
}
catch (std::exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << _e.what());
}
}
}
}
BOOST_AUTO_TEST_CASE(userDefinedFileState)
{
dev::test::userDefinedTest("--singletest", dev::test::doStateTests);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add quadratic complexity tests<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
* @author Christoph Jentzsch <cj@ethdev.com>
* @date 2014
* State test functions.
*/
#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/ExtVM.h>
#include <libethereum/Defaults.h>
#include <libevm/VM.h>
#include "TestHelper.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;
namespace dev { namespace test {
void doStateTests(json_spirit::mValue& v, bool _fillin)
{
processCommandLineOptions();
for (auto& i: v.get_obj())
{
cerr << i.first << endl;
mObject& o = i.second.get_obj();
BOOST_REQUIRE(o.count("env") > 0);
BOOST_REQUIRE(o.count("pre") > 0);
BOOST_REQUIRE(o.count("transaction") > 0);
ImportTest importer(o, _fillin);
State theState = importer.m_statePre;
bytes tx = importer.m_transaction.rlp();
bytes output;
try
{
theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);
}
catch (Exception const& _e)
{
cnote << "state execution did throw an exception: " << diagnostic_information(_e);
theState.commit();
}
catch (std::exception const& _e)
{
cnote << "state execution did throw an exception: " << _e.what();
}
if (_fillin)
{
#if ETH_FATDB
importer.exportTest(output, theState);
#else
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("You can not fill tests when FATDB is switched off"));
#endif
}
else
{
BOOST_REQUIRE(o.count("post") > 0);
BOOST_REQUIRE(o.count("out") > 0);
// check output
checkOutput(output, o);
// check logs
checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);
// check addresses
#if ETH_FATDB
auto expectedAddrs = importer.m_statePost.addresses();
auto resultAddrs = theState.addresses();
for (auto& expectedPair : expectedAddrs)
{
auto& expectedAddr = expectedPair.first;
auto resultAddrIt = resultAddrs.find(expectedAddr);
if (resultAddrIt == resultAddrs.end())
BOOST_ERROR("Missing expected address " << expectedAddr);
else
{
BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code");
checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);
}
}
checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);
#endif
BOOST_CHECK_MESSAGE(theState.rootHash() == h256(o["postStateRoot"].get_str()), "wrong post state root");
}
}
}
} }// Namespace Close
BOOST_AUTO_TEST_SUITE(StateTests)
BOOST_AUTO_TEST_CASE(stExample)
{
dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSystemOperationsTest)
{
dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stPreCompiledContracts)
{
dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stLogTests)
{
dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRecursiveCreate)
{
dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stInitCodeTest)
{
dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stTransactionTest)
{
dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSpecialTest)
{
dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRefundTest)
{
dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stBlockHashTest)
{
dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stQuadraticComplexityTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--quadratic" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stQuadraticComplexityTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stMemoryStressTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--memory" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stMemoryStressTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stSolidityTest)
{
dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stMemoryTest)
{
dev::test::executeTests("stMemoryTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stCreateTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--createtest")
{
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
{
cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
return;
}
try
{
cnote << "Populating tests...";
json_spirit::mValue v;
string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
json_spirit::read_string(s, v);
dev::test::doStateTests(v, true);
writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
}
catch (Exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e));
}
catch (std::exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << _e.what());
}
}
}
}
BOOST_AUTO_TEST_CASE(userDefinedFileState)
{
dev::test::userDefinedTest("--singletest", dev::test::doStateTests);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#include "../googletest/include/gtest/gtest.h"
#include "../include/easylogging++.h"
#include "../include/llg.hpp"
INITIALIZE_EASYLOGGINGPP
TEST(llg, drift)
{
double deriv[3];
double state[3] = {2, 3, 4};
double field[3] = {1, 2, 3};
double time=0, damping=3;
llg::drift( deriv, state, time, damping, field );
EXPECT_EQ( -34, deriv[0] );
EXPECT_EQ( -4, deriv[1] );
EXPECT_EQ( 20, deriv[2] );
}
<commit_msg>diffusion test<commit_after>#include "../googletest/include/gtest/gtest.h"
#include "../include/easylogging++.h"
#include "../include/llg.hpp"
INITIALIZE_EASYLOGGINGPP
TEST(llg, drift)
{
double deriv[3];
double state[3] = {2, 3, 4};
double field[3] = {1, 2, 3};
double time=0, damping=3;
llg::drift( deriv, state, time, damping, field );
EXPECT_EQ( -34, deriv[0] );
EXPECT_EQ( -4, deriv[1] );
EXPECT_EQ( 20, deriv[2] );
}
TEST(llg, diffusion)
{
double deriv[3*3];
double state[3] = { 2, 3, 4 };
double time=0; double sr=2; double alpha=3;
llg::diffusion( deriv, state, time, sr, alpha );
EXPECT_EQ( 150, deriv[0] );
EXPECT_EQ( -28, deriv[1] );
EXPECT_EQ ( -54, deriv[2] );
EXPECT_EQ ( -44, deriv[3] );
EXPECT_EQ ( 120, deriv[4] );
EXPECT_EQ ( -68, deriv[5] );
EXPECT_EQ ( -42, deriv[6] );
EXPECT_EQ ( -76, deriv[7] );
EXPECT_EQ ( 78, deriv[8] );
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.