text
stringlengths 54
60.6k
|
---|
<commit_before>#ifndef NK_ASIO_NETLINK_HPP_
#define NK_ASIO_NETLINK_HPP_
#include <asm/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
template <typename Proto>
class nl_endpoint
{
public:
typedef Proto protocol_type;
typedef asio::detail::socket_addr_type data_type;
nl_endpoint(int group, int pid = getpid()) {
sockaddr_.nl_family = PF_NETLINK;
sockaddr_.nl_groups = group;
sockaddr_.nl_pid = pid;
}
nl_endpoint() : nl_endpoint(0) {}
nl_endpoint(const nl_endpoint &other) {
sockaddr_ = other.sockaddr_;
}
nl_endpoint &operator=(const nl_endpoint &other) {
sockaddr_ = other.sockaddr_;
return *this;
}
protocol_type protocol() const { return protocol_type(); }
data_type *data() {
return reinterpret_cast<struct sockaddr *>(&sockaddr_);
}
const data_type *data() const {
return reinterpret_cast<const struct sockaddr *>(&sockaddr_);
}
void resize(std::size_t size) {}
std::size_t size() const { return sizeof sockaddr_; }
std::size_t capacity() const { return sizeof sockaddr_; }
friend bool operator==(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_ == other.sockaddr_;
}
friend bool operator!=(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_ != other.sockaddr_;
}
friend bool operator<(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_ < other.sockaddr_;
}
friend bool operator>(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_ > other.sockaddr_;
}
friend bool operator>=(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return !(self < other);
}
friend bool operator<=(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return !(other < self);
}
private:
sockaddr_nl sockaddr_;
};
class nl_protocol
{
public:
nl_protocol() : proto_(0) {}
nl_protocol(int proto) : proto_(proto) {}
int type() const { return SOCK_RAW; }
int protocol() const { return proto_; }
int family() const { return PF_NETLINK; }
typedef nl_endpoint<nl_protocol> endpoint;
typedef asio::basic_raw_socket<nl_protocol> socket;
private:
int proto_;
};
#endif
<commit_msg>asio_netlink: sockaddr_nl comparisons should use nl_pid field.<commit_after>#ifndef NK_ASIO_NETLINK_HPP_
#define NK_ASIO_NETLINK_HPP_
#include <asm/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
template <typename Proto>
class nl_endpoint
{
public:
typedef Proto protocol_type;
typedef asio::detail::socket_addr_type data_type;
nl_endpoint(int group, int pid = getpid()) {
sockaddr_.nl_family = PF_NETLINK;
sockaddr_.nl_groups = group;
sockaddr_.nl_pid = pid;
}
nl_endpoint() : nl_endpoint(0) {}
nl_endpoint(const nl_endpoint &other) {
sockaddr_ = other.sockaddr_;
}
nl_endpoint &operator=(const nl_endpoint &other) {
sockaddr_ = other.sockaddr_;
return *this;
}
protocol_type protocol() const { return protocol_type(); }
data_type *data() {
return reinterpret_cast<struct sockaddr *>(&sockaddr_);
}
const data_type *data() const {
return reinterpret_cast<const struct sockaddr *>(&sockaddr_);
}
void resize(std::size_t size) {}
std::size_t size() const { return sizeof sockaddr_; }
std::size_t capacity() const { return sizeof sockaddr_; }
friend bool operator==(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_.nl_pid == other.sockaddr_.nl_pid;
}
friend bool operator!=(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_.nl_pid != other.sockaddr_.nl_pid;
}
friend bool operator<(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_.nl_pid < other.sockaddr_.nl_pid;
}
friend bool operator>(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return self.sockaddr_.nl_pid > other.sockaddr_.nl_pid;
}
friend bool operator>=(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return !(self < other);
}
friend bool operator<=(const nl_endpoint<Proto> &self,
const nl_endpoint<Proto> &other) {
return !(other < self);
}
private:
sockaddr_nl sockaddr_;
};
class nl_protocol
{
public:
nl_protocol() : proto_(0) {}
nl_protocol(int proto) : proto_(proto) {}
int type() const { return SOCK_RAW; }
int protocol() const { return proto_; }
int family() const { return PF_NETLINK; }
typedef nl_endpoint<nl_protocol> endpoint;
typedef asio::basic_raw_socket<nl_protocol> socket;
private:
int proto_;
};
#endif
<|endoftext|> |
<commit_before>/*
* Reference: http://plms.oxfordjournals.org/content/s2-42/1/230.full.pdf+html
*
* Instruction set
* ===============
* m-config symbol operations final m-config
* string char op1,op2,... string
*
* op:
* L - move left one step
* R - move right one step
* P<symbol> - print symbol on tap
* E - erase symbol from tap
* symbol:
* ~ - matches blank cell
* * - matches any symbol
* other char matches themselves
*
* Lines starting with # are ignored by the interpreter
*/
#include <iostream>
#include <string>
#include <regex>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
#include <unistd.h>
using namespace std;
struct Configuration {
string state;
char symbol;
bool operator<(const Configuration &o) const {
return state < o.state || (state == o.state && symbol < o.symbol);
}
};
struct Action {
string ops;
string state;
};
struct Machine {
int tp = 0;
string curr;
map< Configuration, Action > program;
map< int, char > tape;
void load_program() {
cin.sync_with_stdio(false);
string line;
string input;
while (getline(cin, line)) {
// skip empty lines
if (line.length() == 0) {
continue;
}
// lines begining with # are comments
if (line.at(0) == '#') {
continue;
}
size_t n = std::count(line.begin(), line.end(), ' ');
// part of the machine table
if (n == 3) {
istringstream iss(line);
string state, symbol, ops, fstate;
iss >> state >> symbol >> ops >> fstate;
if (curr.length() == 0) {
curr = state;
}
Configuration c = {state, symbol.at(0)};
Action a = {ops, fstate};
program[c] = a;
// part of the input
} else {
input += line;
}
}
for (int i = 0; i < input.length(); i++) {
tape[i] = input.at(i);
}
}
void print_program() {
for (auto it = program.begin(); it != program.end(); it++) {
cout << it->first.state << " ";
cout << it->first.symbol << " ";
cout << it->second.ops << " ";
cout << it->second.state << endl;
}
}
void print_tape() {
cout << "tape: ";
const int first = min(tp, tape.begin()->first);
const int last = max(tp, tape.rbegin()->first);
for (int i = first; i <= last; i++) {
cout << read_tape(i);
}
cout << endl;
}
void print_head() {
cout << "head: ";
const int first = min(tp, tape.begin()->first);
const int last = tp;
for (int i = first; i <= last; i++) {
if (i == tp) {
cout << 'v';
cout << " (" << curr << ")";
} else {
cout << ' ';
}
}
cout << endl;
}
char read_tape(int p) {
if (tape.count(p)) {
return tape[p];
} else {
return '~';
}
}
int perform_ops(string ops) {
for (int i = 0; i < ops.length(); i++) {
char op = ops.at(i);
switch (op) {
case 'R':
tp++;
break;
case 'L':
tp--;
break;
case 'E':
tape[tp] = '~';
break;
case 'P':
i++;
tape[tp] = ops.at(i);
break;
case ',':
break;
default:
cout << "unknown op: " << op << endl;
exit(1);
}
}
return tp;
}
void run(int max, int fps) {
int cnt = 0;
while (cnt < max) {
Configuration c = {curr, read_tape(tp)};
if (program.count(c) == 0) {
c = {curr, '*'};
}
if (program.count(c) == 0) {
break;
}
Action a = program[c];
tp = perform_ops(a.ops);
curr = a.state;
cnt++;
if (cnt > 1 && fps > 0) {
clear_previous(fps);
}
print_action(a);
print_head();
print_tape();
}
}
void clear_previous(int fps) {
usleep(1000000 / fps);
for (int i = 0; i < 3; i++) {
cout << "\x1B[1A"; // Move the cursor up one line
cout << "\x1B[2K"; // Erase the entire current line
}
}
void print_config(Configuration c) {
cout << "conf: " << c.state << " " << c.symbol << endl;
}
void print_action(Action a) {
cout << "ops : " << a.ops << endl;
}
};
int main(int argc, char *argv[]) {
Machine m;
m.load_program();
m.print_program();
cout << endl;
if (argc == 1) {
m.run(1000, 10);
} else if (argc == 2) {
m.run(atoi(argv[1]), 10);
} else if (argc == 3) {
m.run(atoi(argv[1]), atoi(argv[2]));
}
return 0;
}
<commit_msg>defaults to no animation<commit_after>/*
* Reference: http://plms.oxfordjournals.org/content/s2-42/1/230.full.pdf+html
*
* Instruction set
* ===============
* m-config symbol operations final m-config
* string char op1,op2,... string
*
* op:
* L - move left one step
* R - move right one step
* P<symbol> - print symbol on tap
* E - erase symbol from tap
* symbol:
* ~ - matches blank cell
* * - matches any symbol
* other char matches themselves
*
* Lines starting with # are ignored by the interpreter
*/
#include <iostream>
#include <string>
#include <regex>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
#include <unistd.h>
using namespace std;
struct Configuration {
string state;
char symbol;
bool operator<(const Configuration &o) const {
return state < o.state || (state == o.state && symbol < o.symbol);
}
};
struct Action {
string ops;
string state;
};
struct Machine {
int tp = 0;
string curr;
map< Configuration, Action > program;
map< int, char > tape;
void load_program() {
cin.sync_with_stdio(false);
string line;
string input;
while (getline(cin, line)) {
// skip empty lines
if (line.length() == 0) {
continue;
}
// lines begining with # are comments
if (line.at(0) == '#') {
continue;
}
size_t n = std::count(line.begin(), line.end(), ' ');
// part of the machine table
if (n == 3) {
istringstream iss(line);
string state, symbol, ops, fstate;
iss >> state >> symbol >> ops >> fstate;
if (curr.length() == 0) {
curr = state;
}
Configuration c = {state, symbol.at(0)};
Action a = {ops, fstate};
program[c] = a;
// part of the input
} else {
input += line;
}
}
for (int i = 0; i < input.length(); i++) {
tape[i] = input.at(i);
}
}
void print_program() {
for (auto it = program.begin(); it != program.end(); it++) {
cout << it->first.state << " ";
cout << it->first.symbol << " ";
cout << it->second.ops << " ";
cout << it->second.state << endl;
}
}
void print_tape() {
cout << "tape: ";
const int first = min(tp, tape.begin()->first);
const int last = max(tp, tape.rbegin()->first);
for (int i = first; i <= last; i++) {
cout << read_tape(i);
}
cout << endl;
}
void print_head() {
cout << "head: ";
const int first = min(tp, tape.begin()->first);
const int last = tp;
for (int i = first; i <= last; i++) {
if (i == tp) {
cout << 'v';
cout << " (" << curr << ")";
} else {
cout << ' ';
}
}
cout << endl;
}
char read_tape(int p) {
if (tape.count(p)) {
return tape[p];
} else {
return '~';
}
}
int perform_ops(string ops) {
for (int i = 0; i < ops.length(); i++) {
char op = ops.at(i);
switch (op) {
case 'R':
tp++;
break;
case 'L':
tp--;
break;
case 'E':
tape[tp] = '~';
break;
case 'P':
i++;
tape[tp] = ops.at(i);
break;
case ',':
break;
default:
cout << "unknown op: " << op << endl;
exit(1);
}
}
return tp;
}
void run(int max, int fps) {
int cnt = 0;
while (cnt < max) {
Configuration c = {curr, read_tape(tp)};
if (program.count(c) == 0) {
c = {curr, '*'};
}
if (program.count(c) == 0) {
break;
}
Action a = program[c];
tp = perform_ops(a.ops);
curr = a.state;
cnt++;
if (cnt > 1 && fps > 0) {
clear_previous(fps);
}
print_action(a);
print_head();
print_tape();
}
}
void clear_previous(int fps) {
usleep(1000000 / fps);
for (int i = 0; i < 3; i++) {
cout << "\x1B[1A"; // Move the cursor up one line
cout << "\x1B[2K"; // Erase the entire current line
}
}
void print_config(Configuration c) {
cout << "conf: " << c.state << " " << c.symbol << endl;
}
void print_action(Action a) {
cout << "ops : " << a.ops << endl;
}
};
int main(int argc, char *argv[]) {
Machine m;
m.load_program();
m.print_program();
cout << endl;
if (argc == 1) {
m.run(1000, 0);
} else if (argc == 2) {
m.run(atoi(argv[1]), 0);
} else if (argc == 3) {
m.run(atoi(argv[1]), atoi(argv[2]));
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>print number of internal vertices before improvement<commit_after><|endoftext|> |
<commit_before>#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/utilities/String.hh>
#include <fstream>
#include <istream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using DataType = double;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
std::vector<SimplicialComplex> readData( std::istream& in )
{
std::string line;
while( std::getline( in, line ) )
{
auto tokens
= aleph::utilities::split(
line,
std::string( "[:;,[:space:]]+" )
);
std::vector<DataType> values;
values.reserve( tokens.size() );
for( auto&& token : tokens )
{
bool success = false;
auto value = aleph::utilities::convert<DataType>( token, success );
if( !success )
throw std::runtime_error( "Unable to convert token to expected data type" );
values.emplace_back( value );
}
}
}
void usage()
{
}
int main( int argc, char** argv )
{
if( argc < 1 )
{
usage();
return -1;
}
}
<commit_msg>Basic simplicial complex loading for functions<commit_after>#include <aleph/topology/io/Function.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/utilities/String.hh>
#include <fstream>
#include <istream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using DataType = double;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
std::vector<SimplicialComplex> readData( std::istream& in )
{
std::vector<SimplicialComplex> complexes;
std::string line;
while( std::getline( in, line ) )
{
auto tokens
= aleph::utilities::split(
line,
std::string( "[:;,[:space:]]+" )
);
std::vector<DataType> values;
values.reserve( tokens.size() );
for( auto&& token : tokens )
{
bool success = false;
auto value = aleph::utilities::convert<DataType>( token, success );
if( !success )
throw std::runtime_error( "Unable to convert token to expected data type" );
values.emplace_back( value );
}
complexes.push_back(
aleph::topology::io::loadFunction<SimplicialComplex>(
values.begin(), values.end(),
[] ( DataType x, DataType y )
{
return std::max(x,y);
}
)
);
}
return complexes;
}
void usage()
{
}
int main( int argc, char** argv )
{
if( argc < 1 )
{
usage();
return -1;
}
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QSet>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QMetaObject>
#include <QMetaProperty>
#include <QPushButton>
#include <QDebug>
#include <iostream>
#include <QtDeclarative>
#include <QtDeclarative/private/qdeclarativemetatype_p.h>
#include <QtDeclarative/QDeclarativeView>
static QHash<QByteArray, const QDeclarativeType *> qmlTypeByCppName;
static QHash<QByteArray, QByteArray> cppToQml;
QByteArray convertToQmlType(const QByteArray &cppName)
{
QByteArray qmlName = cppToQml.value(cppName, cppName);
qmlName.replace("::", ".");
qmlName.replace("/", ".");
return qmlName;
}
void erasure(QByteArray *typeName, bool *isList, bool *isPointer)
{
static QByteArray declListPrefix = "QDeclarativeListProperty<";
if (typeName->endsWith('*')) {
*isPointer = true;
typeName->truncate(typeName->length() - 1);
erasure(typeName, isList, isPointer);
} else if (typeName->startsWith(declListPrefix)) {
*isList = true;
typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
*typeName = typeName->mid(declListPrefix.size());
erasure(typeName, isList, isPointer);
}
*typeName = convertToQmlType(*typeName);
}
void processMetaObject(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
{
if (! meta || metas->contains(meta))
return;
metas->insert(meta);
processMetaObject(meta->superClass(), metas);
}
void processObject(QObject *object, QSet<const QMetaObject *> *metas)
{
if (! object)
return;
const QMetaObject *meta = object->metaObject();
processMetaObject(meta, metas);
for (int index = 0; index < meta->propertyCount(); ++index) {
QMetaProperty prop = meta->property(index);
if (QDeclarativeMetaType::isQObject(prop.userType())) {
QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
if (oo && !metas->contains(oo->metaObject()))
processObject(oo, metas);
}
}
}
void processDeclarativeType(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
{
processMetaObject(ty->metaObject(), metas);
}
void writeType(QXmlStreamAttributes *attrs, QByteArray typeName)
{
bool isList = false, isPointer = false;
erasure(&typeName, &isList, &isPointer);
attrs->append(QXmlStreamAttribute("type", typeName));
if (isList)
attrs->append(QXmlStreamAttribute("isList", "true"));
}
void dump(const QMetaProperty &prop, QXmlStreamWriter *xml)
{
xml->writeStartElement("property");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(prop.name())));
writeType(&attributes, prop.typeName());
xml->writeAttributes(attributes);
xml->writeEndElement();
}
void dump(const QMetaMethod &meth, QXmlStreamWriter *xml)
{
if (meth.methodType() == QMetaMethod::Signal) {
if (meth.access() != QMetaMethod::Protected)
return; // nothing to do.
} else if (meth.access() != QMetaMethod::Public) {
return; // nothing to do.
}
QByteArray name = meth.signature();
int lparenIndex = name.indexOf('(');
if (lparenIndex == -1) {
return; // invalid signature
}
name = name.left(lparenIndex);
QString elementName = QLatin1String("method");
QXmlStreamAttributes attributes;
if (meth.methodType() == QMetaMethod::Signal)
elementName = QLatin1String("signal");
xml->writeStartElement(elementName);
attributes.append(QXmlStreamAttribute("name", name));
const QString typeName = convertToQmlType(meth.typeName());
if (! typeName.isEmpty())
attributes.append(QXmlStreamAttribute("type", typeName));
xml->writeAttributes(attributes);
for (int i = 0; i < meth.parameterTypes().size(); ++i) {
QByteArray argName = meth.parameterNames().at(i);
xml->writeStartElement("param");
QXmlStreamAttributes attrs;
if (! argName.isEmpty())
attrs.append(QXmlStreamAttribute("name", argName));
writeType(&attrs, meth.parameterTypes().at(i));
xml->writeAttributes(attrs);
xml->writeEndElement();
}
xml->writeEndElement();
}
void dump(const QMetaEnum &e, QXmlStreamWriter *xml)
{
xml->writeStartElement("enum");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.name()))); // ### FIXME
xml->writeAttributes(attributes);
for (int index = 0; index < e.keyCount(); ++index) {
xml->writeStartElement("enumerator");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.key(index))));
attributes.append(QXmlStreamAttribute("value", QString::number(e.value(index))));
xml->writeAttributes(attributes);
xml->writeEndElement();
}
xml->writeEndElement();
}
class FriendlyQObject: public QObject
{
public:
static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
};
void dump(const QMetaObject *meta, QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", convertToQmlType(meta->className())));
if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {
attributes.append(QXmlStreamAttribute("version", QString("%1.%2").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));
}
for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
QMetaClassInfo classInfo = meta->classInfo(index);
if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
attributes.append(QXmlStreamAttribute("defaultProperty", QLatin1String(classInfo.value())));
break;
}
}
QString version;
if (meta->superClass())
attributes.append(QXmlStreamAttribute("extends", convertToQmlType(meta->superClass()->className())));
if (! version.isEmpty())
attributes.append(QXmlStreamAttribute("version", version));
xml->writeAttributes(attributes);
for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
dump(meta->enumerator(index), xml);
for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
dump(meta->property(index), xml);
for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
dump(meta->method(index), xml);
xml->writeEndElement();
}
void writeEasingCurve(QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "QEasingCurve"));
attributes.append(QXmlStreamAttribute("extends", "Qt.Easing"));
xml->writeAttributes(attributes);
}
xml->writeEndElement();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDeclarativeView view;
QDeclarativeEngine *engine = view.engine();
{
QByteArray code;
code += "import Qt 4.7;\n";
code += "import Qt.labs.particles 4.7;\n";
code += "import Qt.labs.gestures 4.7;\n";
code += "import Qt.labs.folderlistmodel 4.7;\n";
code += "import org.webkit 1.0;\n";
code += "Item {}";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
c.create();
}
cppToQml.insert("QString", "string");
cppToQml.insert("QDeclarativeEasingValueType::Type", "Type");
QSet<const QMetaObject *> metas;
metas.insert(FriendlyQObject::qtMeta());
QMultiHash<QByteArray, QByteArray> extensions;
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
qmlTypeByCppName.insert(ty->metaObject()->className(), ty);
if (ty->isExtendedType()) {
extensions.insert(ty->typeName(), ty->metaObject()->className());
} else {
cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());
}
processDeclarativeType(ty, &metas);
}
// Adjust qml names of extended objects.
// The chain ends up being:
// __extended__.originalname - the base object
// __extension_0_.originalname - first extension
// ..
// __extension_n-2_.originalname - second to last extension
// originalname - last extension
foreach (const QByteArray &extendedCpp, extensions.keys()) {
const QByteArray extendedQml = cppToQml.value(extendedCpp);
cppToQml.insert(extendedCpp, "__extended__." + extendedQml);
QList<QByteArray> extensionCppNames = extensions.values(extendedCpp);
for (int i = 0; i < extensionCppNames.size() - 1; ++i) {
QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(i), QString(extendedQml)).toAscii();
cppToQml.insert(extensionCppNames.value(i), adjustedName);
}
cppToQml.insert(extensionCppNames.last(), extendedQml);
}
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
if (ty->isExtendedType())
continue;
QByteArray tyName = ty->qmlTypeName();
tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
QByteArray code;
code += "import Qt 4.7;\n";
code += "import Qt.labs.particles 4.7;\n";
code += "import Qt.labs.gestures 4.7;\n";
code += "import Qt.labs.folderlistmodel 4.7;\n";
code += "import org.webkit 1.0;\n";
code += tyName;
code += " {}\n";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
processObject(c.create(), &metas);
}
QByteArray bytes;
QXmlStreamWriter xml(&bytes);
xml.setAutoFormatting(true);
xml.writeStartDocument("1.0");
xml.writeStartElement("module");
QMap<QString, const QMetaObject *> nameToMeta;
foreach (const QMetaObject *meta, metas) {
nameToMeta.insert(convertToQmlType(meta->className()), meta);
}
foreach (const QMetaObject *meta, nameToMeta) {
dump(meta, &xml);
}
// define QEasingCurve as an extension of Qt.Easing
writeEasingCurve(&xml);
xml.writeEndElement();
xml.writeEndDocument();
std::cout << bytes.constData();
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
timer.start();
return app.exec();
}
<commit_msg>QmlJS: Adjust qmldump to allow selectively dumping types from plugins.<commit_after>#include <QApplication>
#include <QSet>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QMetaObject>
#include <QMetaProperty>
#include <QPushButton>
#include <QDebug>
#include <iostream>
#include <QtDeclarative>
#include <QtDeclarative/private/qdeclarativemetatype_p.h>
#include <QtDeclarative/QDeclarativeView>
static QHash<QByteArray, const QDeclarativeType *> qmlTypeByCppName;
static QHash<QByteArray, QByteArray> cppToQml;
static QByteArray pluginPackage;
QByteArray convertToQmlType(const QByteArray &cppName)
{
QByteArray qmlName = cppToQml.value(cppName, cppName);
qmlName.replace("::", ".");
qmlName.replace("/", ".");
return qmlName;
}
void erasure(QByteArray *typeName, bool *isList, bool *isPointer)
{
static QByteArray declListPrefix = "QDeclarativeListProperty<";
if (typeName->endsWith('*')) {
*isPointer = true;
typeName->truncate(typeName->length() - 1);
erasure(typeName, isList, isPointer);
} else if (typeName->startsWith(declListPrefix)) {
*isList = true;
typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
*typeName = typeName->mid(declListPrefix.size());
erasure(typeName, isList, isPointer);
}
*typeName = convertToQmlType(*typeName);
}
void processMetaObject(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
{
if (! meta || metas->contains(meta))
return;
metas->insert(meta);
processMetaObject(meta->superClass(), metas);
}
void processObject(QObject *object, QSet<const QMetaObject *> *metas)
{
if (! object)
return;
const QMetaObject *meta = object->metaObject();
processMetaObject(meta, metas);
for (int index = 0; index < meta->propertyCount(); ++index) {
QMetaProperty prop = meta->property(index);
if (QDeclarativeMetaType::isQObject(prop.userType())) {
QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
if (oo && !metas->contains(oo->metaObject()))
processObject(oo, metas);
}
}
}
void processDeclarativeType(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
{
processMetaObject(ty->metaObject(), metas);
}
void writeType(QXmlStreamAttributes *attrs, QByteArray typeName)
{
bool isList = false, isPointer = false;
erasure(&typeName, &isList, &isPointer);
attrs->append(QXmlStreamAttribute("type", typeName));
if (isList)
attrs->append(QXmlStreamAttribute("isList", "true"));
}
void dump(const QMetaProperty &prop, QXmlStreamWriter *xml)
{
xml->writeStartElement("property");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(prop.name())));
writeType(&attributes, prop.typeName());
xml->writeAttributes(attributes);
xml->writeEndElement();
}
void dump(const QMetaMethod &meth, QXmlStreamWriter *xml)
{
if (meth.methodType() == QMetaMethod::Signal) {
if (meth.access() != QMetaMethod::Protected)
return; // nothing to do.
} else if (meth.access() != QMetaMethod::Public) {
return; // nothing to do.
}
QByteArray name = meth.signature();
int lparenIndex = name.indexOf('(');
if (lparenIndex == -1) {
return; // invalid signature
}
name = name.left(lparenIndex);
QString elementName = QLatin1String("method");
QXmlStreamAttributes attributes;
if (meth.methodType() == QMetaMethod::Signal)
elementName = QLatin1String("signal");
xml->writeStartElement(elementName);
attributes.append(QXmlStreamAttribute("name", name));
const QString typeName = convertToQmlType(meth.typeName());
if (! typeName.isEmpty())
attributes.append(QXmlStreamAttribute("type", typeName));
xml->writeAttributes(attributes);
for (int i = 0; i < meth.parameterTypes().size(); ++i) {
QByteArray argName = meth.parameterNames().at(i);
xml->writeStartElement("param");
QXmlStreamAttributes attrs;
if (! argName.isEmpty())
attrs.append(QXmlStreamAttribute("name", argName));
writeType(&attrs, meth.parameterTypes().at(i));
xml->writeAttributes(attrs);
xml->writeEndElement();
}
xml->writeEndElement();
}
void dump(const QMetaEnum &e, QXmlStreamWriter *xml)
{
xml->writeStartElement("enum");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.name()))); // ### FIXME
xml->writeAttributes(attributes);
for (int index = 0; index < e.keyCount(); ++index) {
xml->writeStartElement("enumerator");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.key(index))));
attributes.append(QXmlStreamAttribute("value", QString::number(e.value(index))));
xml->writeAttributes(attributes);
xml->writeEndElement();
}
xml->writeEndElement();
}
class FriendlyQObject: public QObject
{
public:
static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
};
void dump(const QMetaObject *meta, QXmlStreamWriter *xml)
{
QByteArray qmlTypeName = convertToQmlType(meta->className());
if (!pluginPackage.isEmpty() && !qmlTypeName.startsWith(pluginPackage))
return;
xml->writeStartElement("type");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", qmlTypeName));
if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {
attributes.append(QXmlStreamAttribute("version", QString("%1.%2").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));
}
for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
QMetaClassInfo classInfo = meta->classInfo(index);
if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
attributes.append(QXmlStreamAttribute("defaultProperty", QLatin1String(classInfo.value())));
break;
}
}
QString version;
if (meta->superClass())
attributes.append(QXmlStreamAttribute("extends", convertToQmlType(meta->superClass()->className())));
if (! version.isEmpty())
attributes.append(QXmlStreamAttribute("version", version));
xml->writeAttributes(attributes);
for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
dump(meta->enumerator(index), xml);
for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
dump(meta->property(index), xml);
for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
dump(meta->method(index), xml);
xml->writeEndElement();
}
void writeEasingCurve(QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "QEasingCurve"));
attributes.append(QXmlStreamAttribute("extends", "Qt.Easing"));
xml->writeAttributes(attributes);
}
xml->writeEndElement();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
if (argc != 1 && argc != 2) {
qWarning() << "Usage: qmldump [path/to/plugin/directory]";
return 1;
}
QString pluginImportName;
QString pluginImportPath;
if (argc == 2) {
QFileInfo pluginPath(argv[1]);
if (pluginPath.exists() && pluginPath.isDir()) {
pluginImportPath = pluginPath.absolutePath();
pluginImportName = pluginPath.fileName();
pluginPackage = (pluginImportName + ".").toLatin1();
}
}
QDeclarativeView view;
QDeclarativeEngine *engine = view.engine();
if (!pluginImportPath.isEmpty())
engine->addImportPath(pluginImportPath);
QByteArray importCode;
importCode += "import Qt 4.7;\n";
importCode += "import Qt.labs.particles 4.7;\n";
importCode += "import Qt.labs.gestures 4.7;\n";
importCode += "import Qt.labs.folderlistmodel 4.7;\n";
importCode += "import org.webkit 1.0;\n";
if (!pluginImportName.isEmpty())
importCode += QString("import %0 1.0;\n").arg(pluginImportName);
{
QByteArray code = importCode;
code += "Item {}";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
c.create();
if (!c.errors().isEmpty())
qDebug() << c.errorString();
}
cppToQml.insert("QString", "string");
cppToQml.insert("QDeclarativeEasingValueType::Type", "Type");
QSet<const QMetaObject *> metas;
metas.insert(FriendlyQObject::qtMeta());
QMultiHash<QByteArray, QByteArray> extensions;
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
qmlTypeByCppName.insert(ty->metaObject()->className(), ty);
if (ty->isExtendedType()) {
extensions.insert(ty->typeName(), ty->metaObject()->className());
} else {
cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());
}
processDeclarativeType(ty, &metas);
}
// Adjust qml names of extended objects.
// The chain ends up being:
// __extended__.originalname - the base object
// __extension_0_.originalname - first extension
// ..
// __extension_n-2_.originalname - second to last extension
// originalname - last extension
foreach (const QByteArray &extendedCpp, extensions.keys()) {
const QByteArray extendedQml = cppToQml.value(extendedCpp);
cppToQml.insert(extendedCpp, "__extended__." + extendedQml);
QList<QByteArray> extensionCppNames = extensions.values(extendedCpp);
for (int i = 0; i < extensionCppNames.size() - 1; ++i) {
QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(i), QString(extendedQml)).toAscii();
cppToQml.insert(extensionCppNames.value(i), adjustedName);
}
cppToQml.insert(extensionCppNames.last(), extendedQml);
}
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
if (ty->isExtendedType())
continue;
QByteArray tyName = ty->qmlTypeName();
tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
QByteArray code = importCode;
code += tyName;
code += " {}\n";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
processObject(c.create(), &metas);
}
QByteArray bytes;
QXmlStreamWriter xml(&bytes);
xml.setAutoFormatting(true);
xml.writeStartDocument("1.0");
xml.writeStartElement("module");
QMap<QString, const QMetaObject *> nameToMeta;
foreach (const QMetaObject *meta, metas) {
nameToMeta.insert(convertToQmlType(meta->className()), meta);
}
foreach (const QMetaObject *meta, nameToMeta) {
dump(meta, &xml);
}
// define QEasingCurve as an extension of Qt.Easing
writeEasingCurve(&xml);
xml.writeEndElement();
xml.writeEndDocument();
std::cout << bytes.constData();
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
timer.start();
return app.exec();
}
<|endoftext|> |
<commit_before>/*
** Copyright 2009-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QtSql>
#include <map>
#include "com/centreon/broker/bam/configuration/db.hh"
#include "com/centreon/broker/bam/configuration/state.hh"
#include "com/centreon/broker/bam/configuration/reader.hh"
#include "com/centreon/broker/bam/configuration/reader_exception.hh"
using namespace com::centreon::broker::bam::configuration;
/**
* @class create_map
* @brief A clever piece of code found on the net to
* automate the loading of a map from a literal expression
* .... why write it yourself? ... This sort of code needs a seperate namespace..
*/
template <typename T, typename U>
class create_map
{
public:
create_map(const T& key, const U& val)
{
m_map[key] = val;
}
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return (*this);
}
operator std::map<T, U>()
{
return (m_map);
}
private:
std::map<T,U> m_map;
};
/**
* @function map_2_QT
*
* @brief maps the logical name for a RDBMS to the Qlib name
* @param[in] The logical name for the database
* @return The QT lib name for the database system
*/
QString map_2_QT(const std::string& dbtype){
using namespace std;
// lower case the string
QString qt_db_type(dbtype.c_str());
qt_db_type = qt_db_type.toLower();
// load map only ONCE.. at first execution
// avantage : logN, typesafe, thread-safe ( AFTER init)
// disavantage : race on initialisation...
typedef map<QString, QString> string_2_string;
static string_2_string name_2_qname=
create_map<QString,QString>
("db2", "QDB2")
("ibase", "QIBASE")
("interbase", "QIBASE")
("mysql", "QMYSQL")
("oci", "QOCI")
("oracle", "QOCI")
("odbc", "QODBC")
("psql", "QPSQL")
("postgres", "QPSQL")
("postgresql", "QPSQL")
("sqlite", "QSQLITE")
("tds", "QTDS")
("sybase", "QTDS");
// find the database in table
string_2_string::iterator found = name_2_qname.find(qt_db_type);
return (found != name_2_qname.end() ? found->first : qt_db_type);
}
/**
* Constructor.
*
* @param[in] mydb Information for accessing database.
*/
reader::reader(configuration::db const& mydb)
: _db(),
_dbinfo(mydb){
QString id;
id.setNum((qulonglong)this, 16);
_db = QSqlDatabase::addDatabase(map_2_QT(mydb.get_type()), id);
_ensure_open();
}
/**
* Destructor.
*/
reader::~reader() {
_db.close();
}
/**
* Reader
*
* @param[out] st All the configuration state for the BA subsystem
* recuperated from the specified database
*/
void reader::read(state& st) {
try {
_ensure_open();
_db.transaction(); // A single explicit transaction is more efficient
_load( st.get_bas());
_load( st.get_kpis());
_load( st.get_boolexps());
_db.commit();
}
catch (std::exception& e) {
//apparently, no need to rollback transaction.. achieved in the db destructor
st.clear();
throw;
}
}
/**
* Copy constructor
*
* @Brief Hidden implementation
*/
reader::reader(reader const& other) :
_dbinfo(other._dbinfo){
}
/**
* assignment operator
*
* @Brief Hidden implementation
*
*/
reader& reader::operator=(reader const& other){
(void)other;
return (*this);
}
/**
* open
*
* @brief Enforce that the database be open as a postcondition
*/
void reader::_ensure_open(){
if(!_db.isOpen()){
_db.setHostName(_dbinfo.get_host().c_str() );
_db.setDatabaseName(_dbinfo.get_name().c_str() );
_db.setUserName(_dbinfo.get_user().c_str() );
_db.setPassword(_dbinfo.get_password().c_str() );
// we must have a valid database connexion at this point
if( !_db.open() ){
throw (reader_exception()
<< "BAM: Database access failure"
<< ", Reason: "<< _db.lastError().text()
<< ", Type: " << _dbinfo.get_type()
<< ", Host: " << _dbinfo.get_host()
<< ", Name: " << _dbinfo.get_name());
}
}
}
/**
* Load
*
* @param[out] list of kpis in database
*/
void reader::_load(state::kpis& kpis){
kpis.clear();
QSqlQuery query =
_db.exec("SELECT k.kpi_id, "
" k.state_type, "
" k.host_id, "
" k.service_id, "
" k.id_ba, "
" k.current_status, "
" k.last_level, "
" k.downtime, "
" k.acknowledged, "
" k.ignore_downtime, "
" k.ignore_acknowledged, "
" coalesce(k.drop_warning,ww.impact), "
" coalesce(k.drop_critical,cc.impact), "
" coalesce(k.drop_unknown,uu.impact) "
"FROM mod_bam_kpi AS k "
"LEFT JOIN mod_bam_impacts AS ww ON k.drop_warning_impact_id = ww.id_impact "
"LEFT JOIN mod_bam_impacts AS cc ON k.drop_critical_impact_id = cc.id_impact "
"LEFT JOIN mod_bam_impacts AS uu ON k.drop_unknown_impact_id = uu.id_impact;");
_assert_query(query);
while (query.next()) {
kpis.push_back(
kpi(
query.value(0).toInt(), //unsigned int id = 0,
query.value(1).toInt(), //short state_type = 0,
query.value(2).toInt(), //unsigned int hostid = 0,
query.value(3).toInt(),//unsigned int serviceid = 0
query.value(4).toInt(),//unsigned int ba = 0,
query.value(5).toInt(),//short status = 0,
query.value(6).toInt(),//short lasthardstate = 0,
query.value(7).toFloat(),//bool downtimed = false,
query.value(8).toFloat(),//bool acknowledged = false,
query.value(9).toBool(),//bool ignoredowntime = false,
query.value(10).toBool(),//bool ignoreacknowledgement = false,
query.value(11).toDouble(),//double warning = 0,
query.value(12).toDouble(),//double critical = 0,
query.value(13).toDouble()//double unknown = 0);
));
}
}
/**
* Load
*
* @param[out] list of bas in database
*/
void reader::_load(state::bas& bas){
QSqlQuery query = _db.exec("SELECT ba_id, "
" name, "
" current_level, "
" level_w, "
" level_c, "
"FROM mod_bam");
_assert_query(query);
while (query.next()) {
bas.push_back(
ba(query.value(0).toInt(), //unsigned int id = 0,
query.value(1).toString().toStdString() ,//std::string const& name = "",
query.value(2).toFloat(), //double level = 0.0,
query.value(3).toFloat(), //double warning_level = 0.0
query.value(4).toFloat() //double critical_level = 0.0);
));
}
}
/**
* Load
*
* @param[out] list of bool expression in database
*/
void reader::_load(state::bool_exps& bool_exps){
QSqlQuery query = _db.exec("SELECT be.boolean_id, "
" COALESCE(be.impact,imp.impact)"
" be.expression,"
" be.bool_state,"
" be.current_state"
"FROM mod_bam_boolean as be"
"LEFT JOIN mod_bam_impacts as imp ON be.impact_id = imp.id_impact "
);
_assert_query(query);
while (query.next()) {
bool_exps.push_back(
bool_expression(
query.value(0).toInt(), //unsigned int id = 0,
query.value(1).toFloat(),//double impact = 0.0,
query.value(2).toString().toStdString(),//std::string const& expression = "",
query.value(3).toBool(),//bool impact_if = false,
query.value(4).toBool()//bool state = false
));
}
}
/**
* Assert query
*
* @param[in] assert that the query succeeded
*/
void reader::_assert_query(QSqlQuery& query){
if(!query.isActive()){
throw reader_exception() << "Database Select Error: " << query.lastError().text()
<< ", Type: " << _dbinfo.get_type()
<< ", Host:" << _db.hostName()
<< ", Name:" << _db.databaseName() ;
}
}
<commit_msg>BAM:conformance<commit_after>/*
** Copyright 2009-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QtSql>
#include <map>
#include "com/centreon/broker/bam/configuration/db.hh"
#include "com/centreon/broker/bam/configuration/state.hh"
#include "com/centreon/broker/bam/configuration/reader.hh"
#include "com/centreon/broker/bam/configuration/reader_exception.hh"
using namespace com::centreon::broker::bam::configuration;
/**
* @class create_map
* @brief A clever piece of code found on the net to
* automate the loading of a map from a literal expression
* .... why write it yourself? ... This sort of code needs a seperate namespace..
*/
template <typename T, typename U>
class create_map
{
public:
/**
* Constructor
*
*/
create_map(const T& key, const U& val)
{
m_map[key] = val;
}
/**
* Operator ( key, value )
*
* @brief This operator takes the same parameters as constructor
* so that the row for the constructor and all preceding rows are identical.
* This allows for a clean layout of table rows.
*/
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return (*this);
}
/**
* Operator map
*
* @return Returns the internal map loaded with all the values of the literal table.
*/
operator std::map<T, U>()
{
return (m_map);
}
private:
std::map<T,U> m_map;
};
/**
* @function map_2_QT
*
* @brief maps the logical name for a RDBMS to the Qlib name
* @param[in] The logical name for the database
* @return The QT lib name for the database system
*/
QString map_2_QT(const std::string& dbtype){
using namespace std;
// lower case the string
QString qt_db_type(dbtype.c_str());
qt_db_type = qt_db_type.toLower();
// load map only ONCE.. at first execution
// avantage : logN, typesafe, thread-safe ( AFTER init)
// disavantage : race on initialisation...
typedef map<QString, QString> string_2_string;
static string_2_string name_2_qname=
create_map<QString,QString>
("db2", "QDB2")
("ibase", "QIBASE")
("interbase", "QIBASE")
("mysql", "QMYSQL")
("oci", "QOCI")
("oracle", "QOCI")
("odbc", "QODBC")
("psql", "QPSQL")
("postgres", "QPSQL")
("postgresql", "QPSQL")
("sqlite", "QSQLITE")
("tds", "QTDS")
("sybase", "QTDS");
// find the database in table
string_2_string::iterator found = name_2_qname.find(qt_db_type);
return (found != name_2_qname.end() ? found->first : qt_db_type);
}
/**
* Constructor.
*
* @param[in] mydb Information for accessing database.
*/
reader::reader(configuration::db const& mydb)
: _db(),
_dbinfo(mydb){
QString id;
id.setNum((qulonglong)this, 16);
_db = QSqlDatabase::addDatabase(map_2_QT(mydb.get_type()), id);
_ensure_open();
}
/**
* Destructor.
*/
reader::~reader() {
_db.close();
}
/**
* Reader
*
* @param[out] st All the configuration state for the BA subsystem
* recuperated from the specified database
*/
void reader::read(state& st) {
try {
_ensure_open();
_db.transaction(); // A single explicit transaction is more efficient
_load( st.get_bas());
_load( st.get_kpis());
_load( st.get_boolexps());
_db.commit();
}
catch (std::exception& e) {
//apparently, no need to rollback transaction.. achieved in the db destructor
st.clear();
throw;
}
}
/**
* Copy constructor
*
* @Brief Hidden implementation
*/
reader::reader(reader const& other) :
_dbinfo(other._dbinfo){
}
/**
* assignment operator
*
* @Brief Hidden implementation
*
*/
reader& reader::operator=(reader const& other){
(void)other;
return (*this);
}
/**
* open
*
* @brief Enforce that the database be open as a postcondition
*/
void reader::_ensure_open(){
if(!_db.isOpen()){
_db.setHostName(_dbinfo.get_host().c_str() );
_db.setDatabaseName(_dbinfo.get_name().c_str() );
_db.setUserName(_dbinfo.get_user().c_str() );
_db.setPassword(_dbinfo.get_password().c_str() );
// we must have a valid database connexion at this point
if( !_db.open() ){
throw (reader_exception()
<< "BAM: Database access failure"
<< ", Reason: "<< _db.lastError().text()
<< ", Type: " << _dbinfo.get_type()
<< ", Host: " << _dbinfo.get_host()
<< ", Name: " << _dbinfo.get_name());
}
}
}
/**
* Load
*
* @param[out] list of kpis in database
*/
void reader::_load(state::kpis& kpis){
kpis.clear();
QSqlQuery query =
_db.exec("SELECT k.kpi_id, "
" k.state_type, "
" k.host_id, "
" k.service_id, "
" k.id_ba, "
" k.current_status, "
" k.last_level, "
" k.downtime, "
" k.acknowledged, "
" k.ignore_downtime, "
" k.ignore_acknowledged, "
" coalesce(k.drop_warning,ww.impact), "
" coalesce(k.drop_critical,cc.impact), "
" coalesce(k.drop_unknown,uu.impact) "
"FROM mod_bam_kpi AS k "
"LEFT JOIN mod_bam_impacts AS ww ON k.drop_warning_impact_id = ww.id_impact "
"LEFT JOIN mod_bam_impacts AS cc ON k.drop_critical_impact_id = cc.id_impact "
"LEFT JOIN mod_bam_impacts AS uu ON k.drop_unknown_impact_id = uu.id_impact;");
_assert_query(query);
while (query.next()) {
kpis.push_back(
kpi(
query.value(0).toInt(), //unsigned int id = 0,
query.value(1).toInt(), //short state_type = 0,
query.value(2).toInt(), //unsigned int hostid = 0,
query.value(3).toInt(),//unsigned int serviceid = 0
query.value(4).toInt(),//unsigned int ba = 0,
query.value(5).toInt(),//short status = 0,
query.value(6).toInt(),//short lasthardstate = 0,
query.value(7).toFloat(),//bool downtimed = false,
query.value(8).toFloat(),//bool acknowledged = false,
query.value(9).toBool(),//bool ignoredowntime = false,
query.value(10).toBool(),//bool ignoreacknowledgement = false,
query.value(11).toDouble(),//double warning = 0,
query.value(12).toDouble(),//double critical = 0,
query.value(13).toDouble()//double unknown = 0);
));
}
}
/**
* Load
*
* @param[out] list of bas in database
*/
void reader::_load(state::bas& bas){
QSqlQuery query = _db.exec("SELECT ba_id, "
" name, "
" current_level, "
" level_w, "
" level_c, "
"FROM mod_bam");
_assert_query(query);
while (query.next()) {
bas.push_back(
ba(query.value(0).toInt(), //unsigned int id = 0,
query.value(1).toString().toStdString() ,//std::string const& name = "",
query.value(2).toFloat(), //double level = 0.0,
query.value(3).toFloat(), //double warning_level = 0.0
query.value(4).toFloat() //double critical_level = 0.0);
));
}
}
/**
* Load
*
* @param[out] list of bool expression in database
*/
void reader::_load(state::bool_exps& bool_exps){
QSqlQuery query = _db.exec("SELECT be.boolean_id, "
" COALESCE(be.impact,imp.impact)"
" be.expression,"
" be.bool_state,"
" be.current_state"
"FROM mod_bam_boolean as be"
"LEFT JOIN mod_bam_impacts as imp ON be.impact_id = imp.id_impact "
);
_assert_query(query);
while (query.next()) {
bool_exps.push_back(
bool_expression(
query.value(0).toInt(), //unsigned int id = 0,
query.value(1).toFloat(),//double impact = 0.0,
query.value(2).toString().toStdString(),//std::string const& expression = "",
query.value(3).toBool(),//bool impact_if = false,
query.value(4).toBool()//bool state = false
));
}
}
/**
* Assert query
*
* @param[in] assert that the query succeeded
*/
void reader::_assert_query(QSqlQuery& query){
if(!query.isActive()){
throw reader_exception() << "Database Select Error: " << query.lastError().text()
<< ", Type: " << _dbinfo.get_type()
<< ", Host:" << _db.hostName()
<< ", Name:" << _db.databaseName() ;
}
}
<|endoftext|> |
<commit_before><commit_msg>Disable SystemMonitor.* in base_unittests.<commit_after><|endoftext|> |
<commit_before><commit_msg>basebmp: B2IRange::isEmpty is surprisingly, unhelpfully lame - workaround<commit_after><|endoftext|> |
<commit_before>// vim:filetype=cpp:textwidth=120:shiftwidth=2:softtabstop=2:expandtab
// Copyright 2014--2016 Christoph Schwering
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <lela/solver.h>
#include <lela/internal/maybe.h>
#include <lela/format/output.h>
#include <lela/format/syntax.h>
using namespace lela;
using namespace lela::format;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
typedef std::string SortDecl;
//struct SortDecl { std::string id; };
struct VarDecl { std::string id; std::string sort; };
struct NameDecl { std::string id; std::string sort; };
struct FunDecl { std::string id; std::string sort; int arity; };
//BOOST_FUSION_ADAPT_STRUCT(
// SortDecl,
// (std::string, id)
//)
BOOST_FUSION_ADAPT_STRUCT(
VarDecl,
(std::string, id)
(std::string, sort)
)
BOOST_FUSION_ADAPT_STRUCT(
NameDecl,
(std::string, id)
(std::string, sort)
)
BOOST_FUSION_ADAPT_STRUCT(
FunDecl,
(std::string, id)
(std::string, sort)
(int, arity)
)
typedef boost::variant<//boost::recursive_wrapper<SortDecl>,
boost::recursive_wrapper<VarDecl>,
boost::recursive_wrapper<NameDecl>,
boost::recursive_wrapper<FunDecl>> Decl;
struct Entailment {
Entailment() : context_(solver_.sf(), solver_.tf()) {}
~Entailment() {
for (auto p : funs_) {
if (p.second)
delete p.second;
}
}
void RegisterSort(const std::string& id) { std::cout << "RegisterSort " << id << std::endl; sorts_[id] = context_.NewSort(); }
void RegisterVar(const std::string& id, const std::string& sort) { std::cout << "RegisterVar " << id << " / " << sort << std::endl; vars_[id] = context_.NewVar(sorts_[sort]); }
void RegisterName(const std::string& id, const std::string& sort) { std::cout << "RegisterName " << id << " / " << sort << std::endl; names_[id] = context_.NewName(sorts_[sort]); }
void RegisterFun(const std::string& id, const std::string& sort, int arity) { std::cout << "RegisterFun " << id << " / " << sort << " / " << arity << std::endl; funs_[id] = new Symbol(context_.NewFun(sorts_[sort], arity)); }
std::map<std::string, Symbol::Sort> sorts_;
std::map<std::string, Term> vars_;
std::map<std::string, Term> names_;
std::map<std::string, Symbol*> funs_;
Solver solver_;
Context context_;
};
template<typename Iter>
class Syntax : public qi::grammar<Iter, std::vector<std::string>(), ascii::space_type> {
public:
Syntax() : Syntax::base_type(decls_) {
using qi::char_;
using qi::int_;
using qi::lit;
using qi::alpha;
using qi::alnum;
using qi::lexeme;
using namespace qi::labels;
identifier_ %= alpha >> *alnum;
sort_decl_ = (identifier_ >> lit(':') >> lit("sort") >> lit(';')) [boost::bind(&Entailment::RegisterSort, &e, ::_1)];
var_decl_ = (identifier_ >> lit(':') >> lit("BOOL") >> lit("variable") >> lit(';')) [boost::bind(&Entailment::RegisterVar, &e, "", "")];
name_decl_ = (identifier_ >> lit(':') >> identifier_ >> lit("name") >> lit(';')) [boost::bind(&Entailment::RegisterName, &e, "", "")];
fun_decl_ = (identifier_ >> lit(':') >> identifier_ >> lit("function") >> lit("of") >> lit("arity") >> int_ >> lit(';')) [boost::bind(&Entailment::RegisterFun, &e, "", "", 0)];
decls_ = *(sort_decl_ | var_decl_ | name_decl_ | fun_decl_);
}
private:
Entailment e;
qi::rule<Iter, std::string(), ascii::space_type> identifier_;
qi::rule<Iter, std::string(), ascii::space_type> sort_decl_;
qi::rule<Iter, std::string(), ascii::space_type> var_decl_;
qi::rule<Iter, std::string(), ascii::space_type> name_decl_;
qi::rule<Iter, std::string(), ascii::space_type> fun_decl_;
qi::rule<Iter, std::vector<std::string>(), ascii::space_type> decls_;
};
#if 0
class Parser {
public:
Parser() = default;
virtual ~Parser() = default;
virtual internal::Maybe<std::string> ReadLine() = 0;
private:
};
class StreamParser : public Parser {
explicit StreamParser(std::istream& stream) : stream_(stream) {}
virtual internal::Maybe<std::string> ReadLine() override {
internal::Maybe<std::string> str;
std::getline(stream_, str.val);
return internal::Just(str);
}
private:
std::istream& stream_;
};
#endif
int main() {
const std::string s = "BOOL : sort;"\
"x : BOOL variable;"\
"HUMAN : sort;"\
"T : BOOL name;"\
"F : BOOL name;"\
"fatherOf : HUMAN function of arity 3";
Syntax<std::string::const_iterator> syntax;
std::vector<std::string> d;
qi::phrase_parse(s.begin(), s.end(), syntax, ascii::space, d);
}
<commit_msg>Abandoning Boost Spirit.<commit_after>// vim:filetype=cpp:textwidth=120:shiftwidth=2:softtabstop=2:expandtab
// Copyright 2014--2016 Christoph Schwering
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <lela/solver.h>
#include <lela/internal/maybe.h>
#include <lela/format/output.h>
#include <lela/format/syntax.h>
using namespace lela;
using namespace lela::format;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
struct syntax_error : public std::exception {
syntax_error(const std::string& id) : id_(id) {}
virtual const char* what() const noexcept override { return id_.c_str(); }
private:
std::string id_;
};
struct redeclared_error : public syntax_error { using syntax_error::syntax_error; };
struct undeclared_error : public syntax_error { using syntax_error::syntax_error; };
struct Entailment {
Entailment() : context_(solver_.sf(), solver_.tf()) {}
~Entailment() {
for (auto p : funs_) {
if (p.second) {
delete p.second;
}
}
}
void RegisterSort(const std::string& id) {
const Symbol::Sort sort = context_.NewSort();
lela::format::RegisterSort(sort, id);
sorts_[id] = sort;
std::cout << "RegisterSort " << id << std::endl;
}
Symbol::Sort LookupSort(const std::string& id) const {
const auto it = sorts_.find(id);
if (it == sorts_.end())
throw undeclared_error(id);
return it->second;
}
void RegisterVar(const boost::fusion::vector<std::string, std::string>& d) {
const std::string id = boost::fusion::at_c<0>(d);
const std::string sort_id = boost::fusion::at_c<1>(d);
if (vars_.find(id) != vars_.end() || names_.find(id) != names_.end() || funs_.find(id) != funs_.end())
throw redeclared_error(id);
const Symbol::Sort sort = LookupSort(sort_id);
const Term var = context_.NewVar(sort);
vars_[id] = var;
lela::format::RegisterSymbol(var.symbol(), id);
std::cout << "RegisterVar " << id << " / " << sort_id << std::endl;
}
Term LookupVar(const std::string& id) const {
const auto it = vars_.find(id);
if (it == vars_.end())
throw undeclared_error(id);
return it->second;
}
void RegisterName(const boost::fusion::vector<std::string, std::string>& d) {
const std::string id = boost::fusion::at_c<0>(d);
const std::string sort_id = boost::fusion::at_c<1>(d);
if (vars_.find(id) != vars_.end() || names_.find(id) != names_.end() || funs_.find(id) != funs_.end())
throw redeclared_error(id);
const Symbol::Sort sort = LookupSort(sort_id);
const Term name = context_.NewName(sort);
names_[id] = name;
lela::format::RegisterSymbol(name.symbol(), id);
std::cout << "RegisterName " << id << " / " << sort_id << std::endl;
}
Term LookupName(const std::string& id) const {
const auto it = names_.find(id);
if (it == names_.end())
throw undeclared_error(id);
return it->second;
}
const Symbol& LookupFun(const std::string& id) const {
const auto it = funs_.find(id);
if (it == funs_.end())
throw undeclared_error(id);
return *it->second;
}
void RegisterFun(const boost::fusion::vector<std::string, int, std::string>& d) {
const std::string id = boost::fusion::at_c<0>(d);
const std::string sort_id = boost::fusion::at_c<2>(d);
const int arity = boost::fusion::at_c<1>(d);
if (vars_.find(id) != vars_.end() || names_.find(id) != names_.end() || funs_.find(id) != funs_.end())
throw redeclared_error(id);
const Symbol::Sort sort = sorts_[sort_id];
const Symbol* symbol = new Symbol(context_.NewFun(sort, arity));
funs_[id] = symbol;
lela::format::RegisterSymbol(*symbol, id);
std::cout << "RegisterFun " << id << " / " << arity << " / " << sort_id << std::endl;
}
private:
std::map<std::string, Symbol::Sort> sorts_;
std::map<std::string, Term> vars_;
std::map<std::string, Term> names_;
std::map<std::string, const Symbol*> funs_;
Solver solver_;
Context context_;
};
template<typename Iter>
class Syntax : public qi::grammar<Iter, void(), ascii::space_type> {
public:
Syntax() : Syntax::base_type(decls_) {
identifier_ %= qi::alpha >> *qi::alnum;
sort_keyword_ = "sort";
var_keyword_ = "variable";
name_keyword_ = "name";
fun_keyword_ = "function";
sort_decl_ = (identifier_ >> ':' >> sort_keyword_ >> ';') [boost::bind(&Entailment::RegisterSort, &e, ::_1)];
var_decl_ = (identifier_ >> ':' >> var_keyword_ >> identifier_ >> ';') [boost::bind(&Entailment::RegisterVar, &e, ::_1)];
name_decl_ = (identifier_ >> ':' >> name_keyword_ >> identifier_ >> ';') [boost::bind(&Entailment::RegisterName, &e, ::_1)];
fun_decl_ = (identifier_ >> ':' >> fun_keyword_ >> '/' >> qi::uint_ >> identifier_ >> ';') [boost::bind(&Entailment::RegisterFun, &e, ::_1)];
decls_ = *(sort_decl_ | var_decl_ | name_decl_ | fun_decl_);
term_ = identifier_ >> -('(' >> (term_ % ',') >> ')');
literal_ = term_ >> ("==" || "!=") >> term_;
clause_ = literal_ >> *("||" >> literal_);
}
private:
Entailment e;
qi::rule<Iter, void(), ascii::space_type> sort_keyword_;
qi::rule<Iter, void(), ascii::space_type> var_keyword_;
qi::rule<Iter, void(), ascii::space_type> name_keyword_;
qi::rule<Iter, void(), ascii::space_type> fun_keyword_;
qi::rule<Iter, void(), ascii::space_type> eol_;
qi::rule<Iter, std::string(), ascii::space_type> identifier_;
qi::rule<Iter, std::string(), ascii::space_type> sort_decl_;
qi::rule<Iter, boost::tuple<std::string, std::string>(), ascii::space_type> var_decl_;
qi::rule<Iter, boost::tuple<std::string, std::string>(), ascii::space_type> name_decl_;
qi::rule<Iter, boost::tuple<std::string, int, std::string>(), ascii::space_type> fun_decl_;
qi::rule<Iter, void(), ascii::space_type> decls_;
qi::rule<Iter, Term(), ascii::space_type> term_;
qi::rule<Iter, Literal(), ascii::space_type> literal_;
qi::rule<Iter, Clause(), ascii::space_type> clause_;
};
#if 0
class Parser {
public:
Parser() = default;
virtual ~Parser() = default;
virtual internal::Maybe<std::string> ReadLine() = 0;
private:
};
class StreamParser : public Parser {
explicit StreamParser(std::istream& stream) : stream_(stream) {}
virtual internal::Maybe<std::string> ReadLine() override {
internal::Maybe<std::string> str;
std::getline(stream_, str.val);
return internal::Just(str);
}
private:
std::istream& stream_;
};
#endif
int main() {
const std::string s = "BOOL : sort;"\
"x : variable BOOL;"\
"y : variable BOOL;"\
"HUMAN:sort;"\
"T : name BOOL;"\
"F : name BOOL;"\
"fatherOf : function / 3 HUMAN;"\
"fatherOf2 : function/3 HUMAN;";
Syntax<std::string::const_iterator> syntax;
std::vector<std::string> d;
qi::phrase_parse(s.begin(), s.end(), syntax, qi::ascii::space, d);
}
<|endoftext|> |
<commit_before>#include "OI.h"
#include "Commands/DefaultDrive.h"
#include "Subsystems/Chassis.h"
#include "Misc/ToggleClass.h"
/// Default constructor of the class.
DefaultDrive::DefaultDrive()
{
Requires(Chassis::GetInstance());
shifterToggle = new Toggle<bool>(false, true);
}
/// Called just before this Command runs the first time.
void DefaultDrive::Initialize()
{
Chassis::GetInstance()->ReleaseAngle();
}
//Pass values from joysticks to the Drive subsystem
void DefaultDrive::Execute()
{
OI* oi = OI::GetInstance();
double moveSpeed = -oi->stickL->GetY();
double turnSpeed = -oi->stickR->GetX();
// double moveThrottle = (-0.5 * OI::GetInstance()->stickL->GetRawAxis(3)) + 0.5; //Get Slider Value
// double turnThrottle = (-0.5 * OI::GetInstance()->stickR->GetRawAxis(3)) + 0.5; //Get Slider Value
// Only driving manual should require Quadratic inputs. By default it should be turned off
// Therefore here we turn it on explicitly.
Chassis::GetInstance()->DriveArcade(moveSpeed, turnSpeed, true);
}
/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool DefaultDrive::IsFinished()
{
return false;
}
/// Called once after isFinished returns true
void DefaultDrive::End()
{
}
/// Called when another command which requires one or more of the same
/// subsystems is scheduled to run
void DefaultDrive::Interrupted()
{
}
<commit_msg>Re-enabled turn throttle.<commit_after>#include "OI.h"
#include "Commands/DefaultDrive.h"
#include "Subsystems/Chassis.h"
#include "Misc/ToggleClass.h"
/// Default constructor of the class.
DefaultDrive::DefaultDrive()
{
Requires(Chassis::GetInstance());
shifterToggle = new Toggle<bool>(false, true);
}
/// Called just before this Command runs the first time.
void DefaultDrive::Initialize()
{
Chassis::GetInstance()->ReleaseAngle();
}
//Pass values from joysticks to the Drive subsystem
void DefaultDrive::Execute()
{
OI* oi = OI::GetInstance();
double moveSpeed = -oi->stickL->GetY();
double turnSpeed = -oi->stickR->GetX();
// double moveThrottle = (-0.5 * OI::GetInstance()->stickL->GetRawAxis(3)) + 0.5; //Get Slider Value
double turnThrottle = (-0.5 * OI::GetInstance()->stickR->GetRawAxis(3)) + 0.5; //Get Slider Value
// Only driving manual should require Quadratic inputs. By default it should be turned off
// Therefore here we turn it on explicitly.
Chassis::GetInstance()->DriveArcade(moveSpeed, turnSpeed * turnThrottle, true);
}
/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool DefaultDrive::IsFinished()
{
return false;
}
/// Called once after isFinished returns true
void DefaultDrive::End()
{
}
/// Called when another command which requires one or more of the same
/// subsystems is scheduled to run
void DefaultDrive::Interrupted()
{
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <TSqlORMapper>
#include <TCriteria>
#include "tsessionsqlobjectstore.h"
#include "tsessionobject.h"
/*!
\class TSessionSqlObjectStore
\brief The TSessionSqlObjectStore class stores HTTP sessions into database
system using object-relational mapping tool.
\sa TSessionObject
*/
/* create table session ( id varchar(50) primary key, data blob, updated_at datetime ); */
bool TSessionSqlObjectStore::store(TSession &session)
{
TSqlORMapper<TSessionObject> mapper;
TCriteria cri(TSessionObject::Id, TSql::Equal, session.id());
TSessionObject so = mapper.findFirst(cri);
QDataStream ds(&so.data, QIODevice::WriteOnly);
ds << *static_cast<const QVariantMap *>(&session);
if (so.isEmpty()) {
so.id = session.id();
return so.create();
}
return so.update();
}
TSession TSessionSqlObjectStore::find(const QByteArray &id)
{
QDateTime modified = QDateTime::currentDateTime().addSecs(-lifeTimeSecs());
TSqlORMapper<TSessionObject> mapper;
TCriteria cri;
cri.add(TSessionObject::Id, TSql::Equal, id);
cri.add(TSessionObject::UpdatedAt, TSql::GreaterEqual, modified);
TSessionObject sess = mapper.findFirst(cri);
if (sess.isEmpty())
return TSession();
TSession result(id);
QDataStream ds(&sess.data, QIODevice::ReadOnly);
ds >> *static_cast<QVariantMap *>(&result);
return result;
}
bool TSessionSqlObjectStore::remove(const QByteArray &id)
{
TSqlORMapper<TSessionObject> mapper;
int cnt = mapper.removeAll(TCriteria(TSessionObject::Id, id));
return (cnt > 0);
}
int TSessionSqlObjectStore::gc(const QDateTime &expire)
{
TSqlORMapper<TSessionObject> mapper;
TCriteria cri(TSessionObject::UpdatedAt, TSql::LessThan, expire);
int cnt = mapper.removeAll(cri);
return cnt;
}
<commit_msg>fix a bug of session sqlobject store in PostgreSQL.<commit_after>/* Copyright (c) 2010-2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <TSqlORMapper>
#include <TCriteria>
#include "tsessionsqlobjectstore.h"
#include "tsessionobject.h"
/*!
\class TSessionSqlObjectStore
\brief The TSessionSqlObjectStore class stores HTTP sessions into database
system using object-relational mapping tool.
\sa TSessionObject
*/
/* create table session ( id varchar(50) primary key, data blob, updated_at datetime ); */
bool TSessionSqlObjectStore::store(TSession &session)
{
TSqlORMapper<TSessionObject> mapper;
QString id = QString::fromLatin1(session.id().data(), session.id().length());
TCriteria cri(TSessionObject::Id, TSql::Equal, id);
TSessionObject so = mapper.findFirst(cri);
QDataStream ds(&so.data, QIODevice::WriteOnly);
ds << *static_cast<const QVariantMap *>(&session);
if (so.isEmpty()) {
so.id = session.id();
return so.create();
}
return so.update();
}
TSession TSessionSqlObjectStore::find(const QByteArray &id)
{
QDateTime modified = QDateTime::currentDateTime().addSecs(-lifeTimeSecs());
TSqlORMapper<TSessionObject> mapper;
TCriteria cri;
cri.add(TSessionObject::Id, TSql::Equal, QString::fromLatin1(id.data(), id.length()));
cri.add(TSessionObject::UpdatedAt, TSql::GreaterEqual, modified);
TSessionObject sess = mapper.findFirst(cri);
if (sess.isEmpty())
return TSession();
TSession result(id);
QDataStream ds(&sess.data, QIODevice::ReadOnly);
ds >> *static_cast<QVariantMap *>(&result);
return result;
}
bool TSessionSqlObjectStore::remove(const QByteArray &id)
{
TSqlORMapper<TSessionObject> mapper;
int cnt = mapper.removeAll(TCriteria(TSessionObject::Id, id));
return (cnt > 0);
}
int TSessionSqlObjectStore::gc(const QDateTime &expire)
{
TSqlORMapper<TSessionObject> mapper;
TCriteria cri(TSessionObject::UpdatedAt, TSql::LessThan, expire);
int cnt = mapper.removeAll(cri);
return cnt;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* UNIX string conversion functions.
*/
#if defined(__linux__) || defined(__FreeBSD__)
#include "generic.h"
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
char* java_to_char(JNIEnv *env, jstring string, jobject result) {
size_t stringLen = env->GetStringLength(string);
wchar_t* wideString = (wchar_t*)malloc(sizeof(wchar_t) * (stringLen+1));
const jchar* javaString = env->GetStringChars(string, NULL);
for (size_t i = 0; i < stringLen; i++) {
wideString[i] = javaString[i];
}
wideString[stringLen] = L'\0';
env->ReleaseStringChars(string, javaString);
size_t bytes = wcstombs(NULL, wideString, 0);
if (bytes == (size_t)-1) {
mark_failed_with_message(env, "could not convert string to current locale", result);
free(wideString);
return NULL;
}
char* chars = (char*)malloc(bytes + 1);
wcstombs(chars, wideString, bytes+1);
free(wideString);
return chars;
}
jstring char_to_java(JNIEnv* env, const char* chars, jobject result) {
size_t bytes = strlen(chars);
wchar_t* wideString = (wchar_t*)malloc(sizeof(wchar_t) * (bytes+1));
if (mbstowcs(wideString, chars, bytes+1) == (size_t)-1) {
mark_failed_with_message(env, "could not convert string from current locale", result);
free(wideString);
return NULL;
}
size_t stringLen = wcslen(wideString);
jchar* javaString = (jchar*)malloc(sizeof(jchar) * stringLen);
for (int i =0; i < stringLen; i++) {
javaString[i] = (jchar)wideString[i];
}
jstring string = env->NewString(javaString, stringLen);
free(wideString);
free(javaString);
return string;
}
#endif
<commit_msg>Format unix_strings.cpp<commit_after>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* UNIX string conversion functions.
*/
#if defined(__linux__) || defined(__FreeBSD__)
#include "generic.h"
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
char* java_to_char(JNIEnv* env, jstring string, jobject result) {
size_t stringLen = env->GetStringLength(string);
wchar_t* wideString = (wchar_t*) malloc(sizeof(wchar_t) * (stringLen + 1));
const jchar* javaString = env->GetStringChars(string, NULL);
for (size_t i = 0; i < stringLen; i++) {
wideString[i] = javaString[i];
}
wideString[stringLen] = L'\0';
env->ReleaseStringChars(string, javaString);
size_t bytes = wcstombs(NULL, wideString, 0);
if (bytes == (size_t) -1) {
mark_failed_with_message(env, "could not convert string to current locale", result);
free(wideString);
return NULL;
}
char* chars = (char*) malloc(bytes + 1);
wcstombs(chars, wideString, bytes + 1);
free(wideString);
return chars;
}
jstring char_to_java(JNIEnv* env, const char* chars, jobject result) {
size_t bytes = strlen(chars);
wchar_t* wideString = (wchar_t*) malloc(sizeof(wchar_t) * (bytes + 1));
if (mbstowcs(wideString, chars, bytes + 1) == (size_t) -1) {
mark_failed_with_message(env, "could not convert string from current locale", result);
free(wideString);
return NULL;
}
size_t stringLen = wcslen(wideString);
jchar* javaString = (jchar*) malloc(sizeof(jchar) * stringLen);
for (int i = 0; i < stringLen; i++) {
javaString[i] = (jchar) wideString[i];
}
jstring string = env->NewString(javaString, stringLen);
free(wideString);
free(javaString);
return string;
}
#endif
<|endoftext|> |
<commit_before>#ifndef MINIASCAPE_CONWAYS_LIFE_GAME_TRAITS
#define MINIASCAPE_CONWAYS_LIFE_GAME_TRAITS
#include "core/Cell.hpp"
#include "core/Rule.hpp"
#include "core/Observer.hpp"
#include "core/NeighborhoodIndex.hpp"
#include "core/PeriodicBoundary.hpp"
#include "core/RandomStateGenerator.hpp"
#include "GraphicalObserver.hpp"
namespace miniascape
{
struct boolean
{
boolean() : val(false){}
boolean(const bool b) : val(b){}
bool val;
operator bool &() {return val;}
operator bool const&() const {return val;}
};
struct ConwaysLifeGameTraits
{
using size_type = std::size_t;
using time_type = std::size_t;
using state_type = boolean;
using cell_type = Cell<8, state_type>;
using neighbor_type = MooreNeighborhood;
using boundary_type = PeriodicBoundary<neighbor_type>;
};
class ConwaysLifeGameRule : public RuleBase<ConwaysLifeGameTraits>
{
public:
using base_type = RuleBase<ConwaysLifeGameTraits>;
using time_type = typename base_type::time_type;
using state_type = typename base_type::state_type;
using cell_type = typename base_type::cell_type;
public:
ConwaysLifeGameRule() = default;
~ConwaysLifeGameRule() override = default;
state_type step(const cell_type& cell) const override;
time_type delta_t() const override {return 1;}
};
inline typename ConwaysLifeGameRule::state_type
ConwaysLifeGameRule::step(const cell_type& cell) const
{
std::size_t lives = 0;
for(auto iter = cell.neighbors.cbegin();
iter != cell.neighbors.cend(); ++iter)
if((*iter)->state.val) ++lives;
return (cell.state) ? (lives == 2 or lives == 3) : (lives == 3);
}
template<>
class RandomStateGenerator<boolean>
{
public:
explicit RandomStateGenerator(const unsigned int s) : mt_(s), bn_(0.5){}
~RandomStateGenerator() = default;
boolean operator()(){return bn_(mt_);}
std::mt19937 mt_;
std::bernoulli_distribution bn_;
};
using ConwaysLifeGameObserver = ConwaysLifeGameVisualizer<ConwaysLifeGameTraits>;
}
#endif /* MINIASCAPE_CONWAYS_LIFE_GAME_TRAITS */
<commit_msg>fix include filename<commit_after>#ifndef MINIASCAPE_CONWAYS_LIFE_GAME_TRAITS
#define MINIASCAPE_CONWAYS_LIFE_GAME_TRAITS
#include "core/Cell.hpp"
#include "core/Rule.hpp"
#include "core/Observer.hpp"
#include "core/NeighborhoodIndex.hpp"
#include "core/PeriodicBoundary.hpp"
#include "core/RandomStateGenerator.hpp"
#include "ConwaysLifeGameVisualizer.hpp"
namespace miniascape
{
struct boolean
{
boolean() : val(false){}
boolean(const bool b) : val(b){}
bool val;
operator bool &() {return val;}
operator bool const&() const {return val;}
};
struct ConwaysLifeGameTraits
{
using size_type = std::size_t;
using time_type = std::size_t;
using state_type = boolean;
using cell_type = Cell<8, state_type>;
using neighbor_type = MooreNeighborhood;
using boundary_type = PeriodicBoundary<neighbor_type>;
};
class ConwaysLifeGameRule : public RuleBase<ConwaysLifeGameTraits>
{
public:
using base_type = RuleBase<ConwaysLifeGameTraits>;
using time_type = typename base_type::time_type;
using state_type = typename base_type::state_type;
using cell_type = typename base_type::cell_type;
public:
ConwaysLifeGameRule() = default;
~ConwaysLifeGameRule() override = default;
state_type step(const cell_type& cell) const override;
time_type delta_t() const override {return 1;}
};
inline typename ConwaysLifeGameRule::state_type
ConwaysLifeGameRule::step(const cell_type& cell) const
{
std::size_t lives = 0;
for(auto iter = cell.neighbors.cbegin();
iter != cell.neighbors.cend(); ++iter)
if((*iter)->state.val) ++lives;
return (cell.state) ? (lives == 2 or lives == 3) : (lives == 3);
}
template<>
class RandomStateGenerator<boolean>
{
public:
explicit RandomStateGenerator(const unsigned int s) : mt_(s), bn_(0.5){}
~RandomStateGenerator() = default;
boolean operator()(){return bn_(mt_);}
std::mt19937 mt_;
std::bernoulli_distribution bn_;
};
using ConwaysLifeGameObserver = ConwaysLifeGameVisualizer<ConwaysLifeGameTraits>;
}
#endif /* MINIASCAPE_CONWAYS_LIFE_GAME_TRAITS */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/SimpleString.h"
#include "CppUTest/PlatformSpecificFunctions.h"
#include "CppUTest/TestMemoryAllocator.h"
TestMemoryAllocator* SimpleString::stringAllocator_ = NULL;
TestMemoryAllocator* SimpleString::getStringAllocator()
{
if (stringAllocator_ == NULL)
return defaultNewArrayAllocator();
return stringAllocator_;
}
void SimpleString::setStringAllocator(TestMemoryAllocator* allocator)
{
stringAllocator_ = allocator;
}
/* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */
char* SimpleString::allocStringBuffer(size_t _size)
{
return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__);
}
void SimpleString::deallocStringBuffer(char* str)
{
getStringAllocator()->free_memory(str, __FILE__, __LINE__);
}
char* SimpleString::getEmptyString() const
{
char* empty = allocStringBuffer(1);
empty[0] = '\0';
return empty;
}
SimpleString::SimpleString(const char *otherBuffer)
{
if (otherBuffer == 0) {
buffer_ = getEmptyString();
}
else {
size_t len = PlatformSpecificStrLen(otherBuffer) + 1;
buffer_ = allocStringBuffer(len);
PlatformSpecificStrCpy(buffer_, otherBuffer);
}
}
SimpleString::SimpleString(const char *other, size_t repeatCount)
{
size_t len = PlatformSpecificStrLen(other) * repeatCount + 1;
buffer_ = allocStringBuffer(len);
char* next = buffer_;
for (size_t i = 0; i < repeatCount; i++) {
PlatformSpecificStrCpy(next, other);
next += PlatformSpecificStrLen(other);
}
*next = 0;
}
SimpleString::SimpleString(const SimpleString& other)
{
size_t len = other.size() + 1;
buffer_ = allocStringBuffer(len);
PlatformSpecificStrCpy(buffer_, other.buffer_);
}
SimpleString& SimpleString::operator=(const SimpleString& other)
{
if (this != &other) {
deallocStringBuffer(buffer_);
size_t len = other.size() + 1;
buffer_ = allocStringBuffer(len);
PlatformSpecificStrCpy(buffer_, other.buffer_);
}
return *this;
}
bool SimpleString::contains(const SimpleString& other) const
{
//strstr on some machines does not handle ""
//the right way. "" should be found in any string
if (PlatformSpecificStrLen(other.buffer_) == 0) return true;
else if (PlatformSpecificStrLen(buffer_) == 0) return false;
else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0;
}
bool SimpleString::containsNoCase(const SimpleString& other) const
{
return toLower().contains(other.toLower());
}
bool SimpleString::startsWith(const SimpleString& other) const
{
if (PlatformSpecificStrLen(other.buffer_) == 0) return true;
else if (PlatformSpecificStrLen(buffer_) == 0) return false;
else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_;
}
bool SimpleString::endsWith(const SimpleString& other) const
{
size_t buffer_length = PlatformSpecificStrLen(buffer_);
size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_);
if (other_buffer_length == 0) return true;
if (buffer_length == 0) return false;
if (buffer_length < other_buffer_length) return false;
return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0;
}
size_t SimpleString::count(const SimpleString& substr) const
{
size_t num = 0;
char* str = buffer_;
while ((str = PlatformSpecificStrStr(str, substr.buffer_))) {
num++;
str++;
}
return num;
}
void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const
{
size_t num = count(delimiter);
size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1;
col.allocate(num + extraEndToken);
char* str = buffer_;
char* prev;
for (size_t i = 0; i < num; ++i) {
prev = str;
str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1;
size_t len = (size_t) (str - prev);
char* sub = allocStringBuffer(len + 1);
PlatformSpecificStrNCpy(sub, prev, len);
sub[len] = '\0';
col[i] = sub;
deallocStringBuffer(sub);
}
if (extraEndToken) {
col[num] = str;
}
}
void SimpleString::replace(char to, char with)
{
size_t s = size();
for (size_t i = 0; i < s; i++) {
if (buffer_[i] == to) buffer_[i] = with;
}
}
void SimpleString::replace(const char* to, const char* with)
{
size_t c = count(to);
size_t len = size();
size_t tolen = PlatformSpecificStrLen(to);
size_t withlen = PlatformSpecificStrLen(with);
size_t newsize = len + (withlen * c) - (tolen * c) + 1;
if (newsize) {
char* newbuf = allocStringBuffer(newsize);
for (size_t i = 0, j = 0; i < len;) {
if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) {
PlatformSpecificStrNCpy(&newbuf[j], with, withlen);
j += withlen;
i += tolen;
}
else {
newbuf[j] = buffer_[i];
j++;
i++;
}
}
deallocStringBuffer(buffer_);
buffer_ = newbuf;
buffer_[newsize - 1] = '\0';
}
else {
buffer_ = getEmptyString();
buffer_[0] = '\0';
}
}
SimpleString SimpleString::toLower() const
{
SimpleString str(*this);
size_t str_size = str.size();
for (size_t i = 0; i < str_size; i++)
str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]);
return str;
}
const char *SimpleString::asCharString() const
{
return buffer_;
}
size_t SimpleString::size() const
{
return PlatformSpecificStrLen(buffer_);
}
bool SimpleString::isEmpty() const
{
return size() == 0;
}
SimpleString::~SimpleString()
{
deallocStringBuffer(buffer_);
}
bool operator==(const SimpleString& left, const SimpleString& right)
{
return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString());
}
bool SimpleString::equalsNoCase(const SimpleString& str) const
{
return toLower() == str.toLower();
}
bool operator!=(const SimpleString& left, const SimpleString& right)
{
return !(left == right);
}
SimpleString SimpleString::operator+(const SimpleString& rhs)
{
SimpleString t(buffer_);
t += rhs.buffer_;
return t;
}
SimpleString& SimpleString::operator+=(const SimpleString& rhs)
{
return operator+=(rhs.buffer_);
}
SimpleString& SimpleString::operator+=(const char* rhs)
{
size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1;
char* tbuffer = allocStringBuffer(len);
PlatformSpecificStrCpy(tbuffer, this->buffer_);
PlatformSpecificStrCat(tbuffer, rhs);
deallocStringBuffer(buffer_);
buffer_ = tbuffer;
return *this;
}
void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter)
{
if (str1.size() > str2.size()) {
padStringsToSameLength(str2, str1, padCharacter);
return;
}
char pad[2];
pad[0] = padCharacter;
pad[1] = 0;
str1 = SimpleString(pad, str2.size() - str1.size()) + str1;
}
SimpleString SimpleString::subString(size_t beginPos, size_t amount) const
{
if (beginPos > size()-1) return "";
SimpleString newString = buffer_ + beginPos;
if (newString.size() > amount)
newString.buffer_[amount] = '\0';
return newString;
}
char SimpleString::at(int pos) const
{
return buffer_[pos];
}
int SimpleString::find(char ch) const
{
return findFrom(0, ch);
}
int SimpleString::findFrom(size_t starting_position, char ch) const
{
size_t length = size();
for (size_t i = starting_position; i < length; i++)
if (buffer_[i] == ch) return (int) i;
return -1;
}
SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const
{
int beginPos = find(startChar);
if (beginPos < 0) return "";
int endPos = findFrom((size_t)beginPos, lastExcludedChar);
if (endPos == -1) return subString((size_t)beginPos, size());
return subString((size_t)beginPos, (size_t) (endPos - beginPos));
}
void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const
{
if (bufferToCopy == NULL || bufferSize == 0) return;
size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size();
PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy);
bufferToCopy[sizeToCopy] = '\0';
}
SimpleString StringFrom(bool value)
{
return SimpleString(StringFromFormat("%s", value ? "true" : "false"));
}
SimpleString StringFrom(const char *value)
{
return SimpleString(value);
}
SimpleString StringFromOrNull(const char * expected)
{
return (expected) ? StringFrom(expected) : "(null)";
}
SimpleString StringFrom(int value)
{
return StringFromFormat("%d", value);
}
SimpleString StringFrom(long value)
{
return StringFromFormat("%ld", value);
}
SimpleString StringFrom(const void* value)
{
return SimpleString("0x") + HexStringFrom((long) value);
}
SimpleString HexStringFrom(long value)
{
return StringFromFormat("%lx", value);
}
SimpleString StringFrom(double value, int precision)
{
SimpleString format = StringFromFormat("%%.%dg", precision);
return StringFromFormat(format.asCharString(), value);
}
SimpleString StringFrom(char value)
{
return StringFromFormat("%c", value);
}
SimpleString StringFrom(const SimpleString& value)
{
return SimpleString(value);
}
SimpleString StringFromFormat(const char* format, ...)
{
SimpleString resultString;
va_list arguments;
va_start(arguments, format);
resultString = VStringFromFormat(format, arguments);
va_end(arguments);
return resultString;
}
#if CPPUTEST_USE_STD_CPP_LIB
#include <string>
SimpleString StringFrom(const std::string& value)
{
return SimpleString(value.c_str());
}
SimpleString StringFrom(uint32_t i)
{
return StringFromFormat("%10u (0x%08x)", i, i);
}
SimpleString StringFrom(uint16_t i)
{
return StringFromFormat("%5u (0x%04x)", i, i);
}
SimpleString StringFrom(uint8_t i)
{
return StringFromFormat("%3u (0x%02x)", i, i);
}
#endif
//Kludge to get a va_copy in VC++ V6
#ifndef va_copy
#define va_copy(copy, original) copy = original;
#endif
SimpleString VStringFromFormat(const char* format, va_list args)
{
va_list argsCopy;
va_copy(argsCopy, args);
enum
{
sizeOfdefaultBuffer = 100
};
char defaultBuffer[sizeOfdefaultBuffer];
SimpleString resultString;
int size = PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args);
if (size < sizeOfdefaultBuffer) {
resultString = SimpleString(defaultBuffer);
}
else {
size_t newBufferSize = (size_t) size + 1;
char* newBuffer = SimpleString::allocStringBuffer(newBufferSize);
PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy);
resultString = SimpleString(newBuffer);
SimpleString::deallocStringBuffer(newBuffer);
}
va_end(argsCopy);
return resultString;
}
SimpleStringCollection::SimpleStringCollection()
{
collection_ = 0;
size_ = 0;
}
void SimpleStringCollection::allocate(size_t _size)
{
if (collection_) delete[] collection_;
size_ = _size;
collection_ = new SimpleString[size_];
}
SimpleStringCollection::~SimpleStringCollection()
{
delete[] (collection_);
}
size_t SimpleStringCollection::size() const
{
return size_;
}
SimpleString& SimpleStringCollection::operator[](size_t index)
{
if (index >= size_) {
empty_ = "";
return empty_;
}
return collection_[index];
}
<commit_msg>Fix size_t error<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/SimpleString.h"
#include "CppUTest/PlatformSpecificFunctions.h"
#include "CppUTest/TestMemoryAllocator.h"
TestMemoryAllocator* SimpleString::stringAllocator_ = NULL;
TestMemoryAllocator* SimpleString::getStringAllocator()
{
if (stringAllocator_ == NULL)
return defaultNewArrayAllocator();
return stringAllocator_;
}
void SimpleString::setStringAllocator(TestMemoryAllocator* allocator)
{
stringAllocator_ = allocator;
}
/* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */
char* SimpleString::allocStringBuffer(size_t _size)
{
return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__);
}
void SimpleString::deallocStringBuffer(char* str)
{
getStringAllocator()->free_memory(str, __FILE__, __LINE__);
}
char* SimpleString::getEmptyString() const
{
char* empty = allocStringBuffer(1);
empty[0] = '\0';
return empty;
}
SimpleString::SimpleString(const char *otherBuffer)
{
if (otherBuffer == 0) {
buffer_ = getEmptyString();
}
else {
size_t len = PlatformSpecificStrLen(otherBuffer) + 1;
buffer_ = allocStringBuffer(len);
PlatformSpecificStrCpy(buffer_, otherBuffer);
}
}
SimpleString::SimpleString(const char *other, size_t repeatCount)
{
size_t len = PlatformSpecificStrLen(other) * repeatCount + 1;
buffer_ = allocStringBuffer(len);
char* next = buffer_;
for (size_t i = 0; i < repeatCount; i++) {
PlatformSpecificStrCpy(next, other);
next += PlatformSpecificStrLen(other);
}
*next = 0;
}
SimpleString::SimpleString(const SimpleString& other)
{
size_t len = other.size() + 1;
buffer_ = allocStringBuffer(len);
PlatformSpecificStrCpy(buffer_, other.buffer_);
}
SimpleString& SimpleString::operator=(const SimpleString& other)
{
if (this != &other) {
deallocStringBuffer(buffer_);
size_t len = other.size() + 1;
buffer_ = allocStringBuffer(len);
PlatformSpecificStrCpy(buffer_, other.buffer_);
}
return *this;
}
bool SimpleString::contains(const SimpleString& other) const
{
//strstr on some machines does not handle ""
//the right way. "" should be found in any string
if (PlatformSpecificStrLen(other.buffer_) == 0) return true;
else if (PlatformSpecificStrLen(buffer_) == 0) return false;
else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0;
}
bool SimpleString::containsNoCase(const SimpleString& other) const
{
return toLower().contains(other.toLower());
}
bool SimpleString::startsWith(const SimpleString& other) const
{
if (PlatformSpecificStrLen(other.buffer_) == 0) return true;
else if (PlatformSpecificStrLen(buffer_) == 0) return false;
else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_;
}
bool SimpleString::endsWith(const SimpleString& other) const
{
size_t buffer_length = PlatformSpecificStrLen(buffer_);
size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_);
if (other_buffer_length == 0) return true;
if (buffer_length == 0) return false;
if (buffer_length < other_buffer_length) return false;
return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0;
}
size_t SimpleString::count(const SimpleString& substr) const
{
size_t num = 0;
char* str = buffer_;
while ((str = PlatformSpecificStrStr(str, substr.buffer_))) {
num++;
str++;
}
return num;
}
void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const
{
size_t num = count(delimiter);
size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U;
col.allocate(num + extraEndToken);
char* str = buffer_;
char* prev;
for (size_t i = 0; i < num; ++i) {
prev = str;
str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1;
size_t len = (size_t) (str - prev);
char* sub = allocStringBuffer(len + 1);
PlatformSpecificStrNCpy(sub, prev, len);
sub[len] = '\0';
col[i] = sub;
deallocStringBuffer(sub);
}
if (extraEndToken) {
col[num] = str;
}
}
void SimpleString::replace(char to, char with)
{
size_t s = size();
for (size_t i = 0; i < s; i++) {
if (buffer_[i] == to) buffer_[i] = with;
}
}
void SimpleString::replace(const char* to, const char* with)
{
size_t c = count(to);
size_t len = size();
size_t tolen = PlatformSpecificStrLen(to);
size_t withlen = PlatformSpecificStrLen(with);
size_t newsize = len + (withlen * c) - (tolen * c) + 1;
if (newsize) {
char* newbuf = allocStringBuffer(newsize);
for (size_t i = 0, j = 0; i < len;) {
if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) {
PlatformSpecificStrNCpy(&newbuf[j], with, withlen);
j += withlen;
i += tolen;
}
else {
newbuf[j] = buffer_[i];
j++;
i++;
}
}
deallocStringBuffer(buffer_);
buffer_ = newbuf;
buffer_[newsize - 1] = '\0';
}
else {
buffer_ = getEmptyString();
buffer_[0] = '\0';
}
}
SimpleString SimpleString::toLower() const
{
SimpleString str(*this);
size_t str_size = str.size();
for (size_t i = 0; i < str_size; i++)
str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]);
return str;
}
const char *SimpleString::asCharString() const
{
return buffer_;
}
size_t SimpleString::size() const
{
return PlatformSpecificStrLen(buffer_);
}
bool SimpleString::isEmpty() const
{
return size() == 0;
}
SimpleString::~SimpleString()
{
deallocStringBuffer(buffer_);
}
bool operator==(const SimpleString& left, const SimpleString& right)
{
return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString());
}
bool SimpleString::equalsNoCase(const SimpleString& str) const
{
return toLower() == str.toLower();
}
bool operator!=(const SimpleString& left, const SimpleString& right)
{
return !(left == right);
}
SimpleString SimpleString::operator+(const SimpleString& rhs)
{
SimpleString t(buffer_);
t += rhs.buffer_;
return t;
}
SimpleString& SimpleString::operator+=(const SimpleString& rhs)
{
return operator+=(rhs.buffer_);
}
SimpleString& SimpleString::operator+=(const char* rhs)
{
size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1;
char* tbuffer = allocStringBuffer(len);
PlatformSpecificStrCpy(tbuffer, this->buffer_);
PlatformSpecificStrCat(tbuffer, rhs);
deallocStringBuffer(buffer_);
buffer_ = tbuffer;
return *this;
}
void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter)
{
if (str1.size() > str2.size()) {
padStringsToSameLength(str2, str1, padCharacter);
return;
}
char pad[2];
pad[0] = padCharacter;
pad[1] = 0;
str1 = SimpleString(pad, str2.size() - str1.size()) + str1;
}
SimpleString SimpleString::subString(size_t beginPos, size_t amount) const
{
if (beginPos > size()-1) return "";
SimpleString newString = buffer_ + beginPos;
if (newString.size() > amount)
newString.buffer_[amount] = '\0';
return newString;
}
char SimpleString::at(int pos) const
{
return buffer_[pos];
}
int SimpleString::find(char ch) const
{
return findFrom(0, ch);
}
int SimpleString::findFrom(size_t starting_position, char ch) const
{
size_t length = size();
for (size_t i = starting_position; i < length; i++)
if (buffer_[i] == ch) return (int) i;
return -1;
}
SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const
{
int beginPos = find(startChar);
if (beginPos < 0) return "";
int endPos = findFrom((size_t)beginPos, lastExcludedChar);
if (endPos == -1) return subString((size_t)beginPos, size());
return subString((size_t)beginPos, (size_t) (endPos - beginPos));
}
void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const
{
if (bufferToCopy == NULL || bufferSize == 0) return;
size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size();
PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy);
bufferToCopy[sizeToCopy] = '\0';
}
SimpleString StringFrom(bool value)
{
return SimpleString(StringFromFormat("%s", value ? "true" : "false"));
}
SimpleString StringFrom(const char *value)
{
return SimpleString(value);
}
SimpleString StringFromOrNull(const char * expected)
{
return (expected) ? StringFrom(expected) : "(null)";
}
SimpleString StringFrom(int value)
{
return StringFromFormat("%d", value);
}
SimpleString StringFrom(long value)
{
return StringFromFormat("%ld", value);
}
SimpleString StringFrom(const void* value)
{
return SimpleString("0x") + HexStringFrom((long) value);
}
SimpleString HexStringFrom(long value)
{
return StringFromFormat("%lx", value);
}
SimpleString StringFrom(double value, int precision)
{
SimpleString format = StringFromFormat("%%.%dg", precision);
return StringFromFormat(format.asCharString(), value);
}
SimpleString StringFrom(char value)
{
return StringFromFormat("%c", value);
}
SimpleString StringFrom(const SimpleString& value)
{
return SimpleString(value);
}
SimpleString StringFromFormat(const char* format, ...)
{
SimpleString resultString;
va_list arguments;
va_start(arguments, format);
resultString = VStringFromFormat(format, arguments);
va_end(arguments);
return resultString;
}
#if CPPUTEST_USE_STD_CPP_LIB
#include <string>
SimpleString StringFrom(const std::string& value)
{
return SimpleString(value.c_str());
}
SimpleString StringFrom(uint32_t i)
{
return StringFromFormat("%10u (0x%08x)", i, i);
}
SimpleString StringFrom(uint16_t i)
{
return StringFromFormat("%5u (0x%04x)", i, i);
}
SimpleString StringFrom(uint8_t i)
{
return StringFromFormat("%3u (0x%02x)", i, i);
}
#endif
//Kludge to get a va_copy in VC++ V6
#ifndef va_copy
#define va_copy(copy, original) copy = original;
#endif
SimpleString VStringFromFormat(const char* format, va_list args)
{
va_list argsCopy;
va_copy(argsCopy, args);
enum
{
sizeOfdefaultBuffer = 100
};
char defaultBuffer[sizeOfdefaultBuffer];
SimpleString resultString;
int size = PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args);
if (size < sizeOfdefaultBuffer) {
resultString = SimpleString(defaultBuffer);
}
else {
size_t newBufferSize = (size_t) size + 1;
char* newBuffer = SimpleString::allocStringBuffer(newBufferSize);
PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy);
resultString = SimpleString(newBuffer);
SimpleString::deallocStringBuffer(newBuffer);
}
va_end(argsCopy);
return resultString;
}
SimpleStringCollection::SimpleStringCollection()
{
collection_ = 0;
size_ = 0;
}
void SimpleStringCollection::allocate(size_t _size)
{
if (collection_) delete[] collection_;
size_ = _size;
collection_ = new SimpleString[size_];
}
SimpleStringCollection::~SimpleStringCollection()
{
delete[] (collection_);
}
size_t SimpleStringCollection::size() const
{
return size_;
}
SimpleString& SimpleStringCollection::operator[](size_t index)
{
if (index >= size_) {
empty_ = "";
return empty_;
}
return collection_[index];
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2012 Kim Walisch, <[email protected]>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of 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.
#include "SieveOfEratosthenes.h"
#include "PreSieve.h"
#include "EratSmall.h"
#include "EratMedium.h"
#include "EratBig.h"
#include "imath.h"
#include <stdint.h>
#include <stdexcept>
#include <cstdlib>
namespace soe {
const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 };
/// De Bruijn sequence for first set bitValues_
const uint_t SieveOfEratosthenes::bruijnBitValues_[32] =
{
7, 11, 109, 13, 113, 59, 97, 17,
119, 89, 79, 61, 101, 71, 19, 37,
121, 107, 53, 91, 83, 77, 67, 31,
103, 49, 73, 29, 47, 23, 43, 41
};
/// @param start Sieve the primes within the interval [start, stop].
/// @param stop Sieve the primes within the interval [start, stop].
/// @param preSieveLimit Multiples of small primes <= preSieveLimit are
/// pre-sieved to speed up the sieve of Eratosthenes,
/// preSieveLimit >= 13 && <= 23.
/// @param sieveSize A sieve size in kilobytes, sieveSize >= 1 && <= 4096.
///
SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start,
uint64_t stop,
uint_t preSieveLimit,
uint_t sieveSize) :
start_(start),
stop_(stop),
sqrtStop_(static_cast<uint_t>(isqrt(stop))),
preSieve_(preSieveLimit),
sieve_(NULL),
sieveSize_(sieveSize * 1024),
eratSmall_(NULL),
eratMedium_(NULL),
eratBig_(NULL)
{
if (start_ < 7 || start_ > stop_)
throw std::invalid_argument("SieveOfEratosthenes: start must be >= 7 && <= stop.");
if (sieveSize_ < 1024)
throw std::invalid_argument("SieveOfEratosthenes: sieveSize must be >= 1 kilobyte.");
segmentLow_ = start_ - getByteRemainder(start_);
// '+1' is a correction for primes of type i * 30 + 31
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
initEratAlgorithms();
// allocate the sieve of Eratosthenes array
sieve_ = new uint8_t[sieveSize_ + 8];
}
SieveOfEratosthenes::~SieveOfEratosthenes() {
delete eratSmall_;
delete eratMedium_;
delete eratBig_;
delete[] sieve_;
}
void SieveOfEratosthenes::initEratAlgorithms() {
try {
if (sqrtStop_ > preSieve_.getLimit()) {
eratSmall_ = new EratSmall(*this);
if (sqrtStop_ > eratSmall_->getLimit()) {
eratMedium_ = new EratMedium(*this);
if (sqrtStop_ > eratMedium_->getLimit())
eratBig_ = new EratBig(*this);
}
}
} catch (...) {
delete eratSmall_;
delete eratMedium_;
delete eratBig_;
throw;
}
}
uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n) {
uint64_t remainder = n % NUMBERS_PER_BYTE;
if (remainder <= 1)
remainder += NUMBERS_PER_BYTE;
return remainder;
}
/// Pre-sieve multiples of small primes <= preSieve_.getLimit()
/// to speed up the sieve of Eratosthenes.
/// @see PreSieve.cpp
///
void SieveOfEratosthenes::preSieve() {
preSieve_.doIt(sieve_, sieveSize_, segmentLow_);
// unset bits (numbers) < start_
if (segmentLow_ <= start_) {
if (start_ <= preSieve_.getLimit())
sieve_[0] = 0xff;
uint64_t remainder = getByteRemainder(start_);
for (int i = 0; i < 8; i++)
if (bitValues_[i] < remainder)
sieve_[0] &= ~(1 << i);
}
}
void SieveOfEratosthenes::crossOffMultiples() {
if (eratSmall_ != NULL) {
// process the sieving primes with many multiples per segment
eratSmall_->crossOff(sieve_, &sieve_[sieveSize_]);
if (eratMedium_ != NULL) {
// process the sieving primes with a few ...
eratMedium_->crossOff(sieve_, sieveSize_);
if (eratBig_ != NULL)
// process the sieving primes with very few ...
eratBig_->crossOff(sieve_);
}
}
}
/// Sieve the primes within the current segment i.e.
/// [segmentLow_, segmentHigh_].
///
void SieveOfEratosthenes::sieveSegment() {
preSieve();
crossOffMultiples();
segmentProcessed(sieve_, sieveSize_);
}
/// Sieve the last segments remaining after that sieve(prime) has
/// been called for all primes up to sqrt(stop_).
///
void SieveOfEratosthenes::finish() {
// sieve all segments left except the last one
while (segmentHigh_ < stop_) {
sieveSegment();
segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE;
segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE;
}
// sieve the last segment
uint64_t remainder = getByteRemainder(stop_);
sieveSize_ = static_cast<uint_t>((stop_ - remainder) - segmentLow_) / NUMBERS_PER_BYTE + 1;
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
preSieve();
crossOffMultiples();
// unset bits and bytes (numbers) > stop_
for (int i = 0; i < 8; i++) {
if (bitValues_[i] > remainder)
sieve_[sieveSize_ - 1] &= ~(1 << i);
sieve_[sieveSize_ + i] = 0;
}
segmentProcessed(sieve_, sieveSize_);
}
} // namespace soe
<commit_msg>improved code readability<commit_after>//
// Copyright (c) 2012 Kim Walisch, <[email protected]>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of 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.
#include "SieveOfEratosthenes.h"
#include "PreSieve.h"
#include "EratSmall.h"
#include "EratMedium.h"
#include "EratBig.h"
#include "imath.h"
#include <stdint.h>
#include <stdexcept>
#include <cstdlib>
#include <algorithm>
namespace soe {
const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 };
/// De Bruijn sequence for first set bitValues_
const uint_t SieveOfEratosthenes::bruijnBitValues_[32] =
{
7, 11, 109, 13, 113, 59, 97, 17,
119, 89, 79, 61, 101, 71, 19, 37,
121, 107, 53, 91, 83, 77, 67, 31,
103, 49, 73, 29, 47, 23, 43, 41
};
/// @param start Sieve the primes within the interval [start, stop].
/// @param stop Sieve the primes within the interval [start, stop].
/// @param preSieveLimit Multiples of small primes <= preSieveLimit are
/// pre-sieved to speed up the sieve of Eratosthenes,
/// preSieveLimit >= 13 && <= 23.
/// @param sieveSize A sieve size in kilobytes, sieveSize >= 1 && <= 4096.
///
SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start,
uint64_t stop,
uint_t preSieveLimit,
uint_t sieveSize) :
start_(start),
stop_(stop),
sqrtStop_(static_cast<uint_t>(isqrt(stop))),
preSieve_(preSieveLimit),
sieveSize_(std::max(1u, sieveSize) * 1024), // convert to bytes
eratSmall_(NULL),
eratMedium_(NULL),
eratBig_(NULL)
{
if (start_ < 7)
throw std::invalid_argument("SieveOfEratosthenes: start must be >= 7.");
if (start_ > stop_)
throw std::invalid_argument("SieveOfEratosthenes: start must be <= stop.");
segmentLow_ = start_ - getByteRemainder(start_);
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
initEratAlgorithms();
// allocate the sieve of Eratosthenes array
sieve_ = new uint8_t[sieveSize_ + 8];
}
SieveOfEratosthenes::~SieveOfEratosthenes() {
delete eratSmall_;
delete eratMedium_;
delete eratBig_;
delete[] sieve_;
}
void SieveOfEratosthenes::initEratAlgorithms() {
try {
if (sqrtStop_ > preSieve_.getLimit()) {
eratSmall_ = new EratSmall(*this);
if (sqrtStop_ > eratSmall_->getLimit()) {
eratMedium_ = new EratMedium(*this);
if (sqrtStop_ > eratMedium_->getLimit())
eratBig_ = new EratBig(*this);
}
}
} catch (...) {
delete eratSmall_;
delete eratMedium_;
delete eratBig_;
throw;
}
}
uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n) {
uint64_t remainder = n % NUMBERS_PER_BYTE;
if (remainder <= 1)
remainder += NUMBERS_PER_BYTE;
return remainder;
}
/// Pre-sieve multiples of small primes <= preSieve_.getLimit()
/// to speed up the sieve of Eratosthenes.
/// @see PreSieve.cpp
///
void SieveOfEratosthenes::preSieve() {
preSieve_.doIt(sieve_, sieveSize_, segmentLow_);
// unset bits (numbers) < start_
if (segmentLow_ <= start_) {
if (start_ <= preSieve_.getLimit())
sieve_[0] = 0xff;
uint64_t remainder = getByteRemainder(start_);
for (int i = 0; i < 8; i++)
if (bitValues_[i] < remainder)
sieve_[0] &= ~(1 << i);
}
}
void SieveOfEratosthenes::crossOffMultiples() {
if (eratSmall_ != NULL) {
// process the sieving primes with many multiples per segment
eratSmall_->crossOff(sieve_, &sieve_[sieveSize_]);
if (eratMedium_ != NULL) {
// process the sieving primes with a few multiples per segment
eratMedium_->crossOff(sieve_, sieveSize_);
if (eratBig_ != NULL)
// process the sieving primes with very few ...
eratBig_->crossOff(sieve_);
}
}
}
/// Sieve the primes within the current segment i.e.
/// [segmentLow_, segmentHigh_].
///
void SieveOfEratosthenes::sieveSegment() {
preSieve();
crossOffMultiples();
segmentProcessed(sieve_, sieveSize_);
}
/// Sieve the last segments remaining after that sieve(prime) has
/// been called for all primes up to sqrt(stop_).
///
void SieveOfEratosthenes::finish() {
// sieve all segments left except the last one
while (segmentHigh_ < stop_) {
sieveSegment();
segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE;
segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE;
}
// sieve the last segment
uint64_t remainder = getByteRemainder(stop_);
sieveSize_ = static_cast<uint_t>((stop_ - remainder) - segmentLow_) / NUMBERS_PER_BYTE + 1;
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
preSieve();
crossOffMultiples();
// unset bits and bytes (numbers) > stop_
for (int i = 0; i < 8; i++) {
if (bitValues_[i] > remainder)
sieve_[sieveSize_ - 1] &= ~(1 << i);
sieve_[sieveSize_ + i] = 0;
}
segmentProcessed(sieve_, sieveSize_);
}
} // namespace soe
<|endoftext|> |
<commit_before>/*
* Copyright Copyright 2012, System Insights, 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.
*/
#define __STDC_LIMIT_MACROS 1
#include "adapter.hpp"
#include "device.hpp"
#include "globals.hpp"
#include "dlib/logger.h"
using namespace std;
static dlib::logger sLogger("input.adapter");
/* Adapter public methods */
Adapter::Adapter(const string& device,
const string& server,
const unsigned int port,
int aLegacyTimeout)
: Connector(server, port, aLegacyTimeout), mDeviceName(device), mRunning(true),
mDupCheck(false), mAutoAvailable(false), mIgnoreTimestamps(false), mRelativeTime(false), mConversionRequired(true),
mBaseTime(0), mBaseOffset(0), mParseTime(false), mGatheringAsset(false), mReconnectInterval(10 * 1000)
{
}
Adapter::~Adapter()
{
if (mRunning) stop();
}
void Adapter::stop()
{
// Will stop threaded object gracefully Adapter::thread()
mRunning = false;
close();
wait();
}
void Adapter::setAgent(Agent &aAgent)
{
mAgent = &aAgent;
mDevice = mAgent->getDeviceByName(mDeviceName);
mDevice->addAdapter(this);
if (mDevice != NULL)
mAllDevices.push_back(mDevice);
}
void Adapter::addDevice(string &aName)
{
Device *dev = mAgent->getDeviceByName(aName);
if (dev != NULL) {
mAllDevices.push_back(dev);
dev->addAdapter(this);
}
}
inline static bool splitKey(string &key, string &dev)
{
size_t found = key.find_first_of(':');
if (found == string::npos) {
return false;
} else {
dev = key;
dev.erase(found);
key.erase(0, found + 1);
return true;
}
}
inline static void trim(std::string &str)
{
size_t index = str.find_first_not_of(" \r\t");
if (index != string::npos && index > 0)
str.erase(0, index);
index = str.find_last_not_of(" \r\t");
if (index != string::npos)
str.erase(index + 1);
}
/**
* Expected data to parse in SDHR format:
* Time|Alarm|Code|NativeCode|Severity|State|Description
* Time|Item|Value
* Time|Item1|Value1|Item2|Value2...
*
* Support for assets:
* Time|@ASSET@|id|type|<...>...</...>
*/
void Adapter::processData(const string& data)
{
if (mGatheringAsset)
{
if (data == mTerminator)
{
mAgent->addAsset(mAssetDevice, mAssetId, mBody.str(), mAssetType, mTime);
mGatheringAsset = false;
}
else
{
mBody << data << endl;
}
return;
}
istringstream toParse(data);
string key, value, dev;
Device *device;
getline(toParse, key, '|');
string time = key;
// Check how to handle time. If the time is relative, then we need to compute the first
// offsets, otherwise, if this function is being used as an API, add the current time.
if (mRelativeTime) {
uint64_t offset;
if (mBaseTime == 0) {
mBaseTime = getCurrentTimeInMicros();
if (time.find('T') != string::npos) {
mParseTime = true;
mBaseOffset = parseTimeMicro(time);
} else {
mBaseOffset = (uint64_t) (atof(time.c_str()) * 1000.0);
}
offset = 0;
} else if (mParseTime) {
offset = parseTimeMicro(time) - mBaseOffset;
} else {
offset = ((uint64_t) (atof(time.c_str()) * 1000.0)) - mBaseOffset;
}
time = getRelativeTimeString(mBaseTime + offset);
} else if (mIgnoreTimestamps || time.empty()) {
time = getCurrentTime(GMT_UV_SEC);
}
getline(toParse, key, '|');
getline(toParse, value, '|');
if (splitKey(key, dev)) {
device = mAgent->getDeviceByName(dev);
} else {
device = mDevice;
}
if (key == "@ASSET@") {
string type, rest;
getline(toParse, type, '|');
getline(toParse, rest);
// Chck for an update and parse key value pairs. If only a type
// is presented, then assume the remainder is a complete doc.
// if the rest of the line begins with --multiline--... then
// set multiline and accumulate until a completed document is found
if (rest.find("--multiline--") != rest.npos)
{
mAssetDevice = device;
mGatheringAsset = true;
mTerminator = rest;
mTime = time;
mAssetType = type;
mAssetId = value;
mBody.str("");
mBody.clear();
}
else
{
mAgent->addAsset(device, value, rest, type, time);
}
return;
}
else if (key == "@UPDATE_ASSET@")
{
string assetId = value;
AssetChangeList list;
getline(toParse, key, '|');
if (key[0] == '<')
{
do {
pair<string,string> kv("xml", key);
list.push_back(kv);
} while (getline(toParse, key, '|'));
}
else
{
while (getline(toParse, value, '|'))
{
pair<string,string> kv(key, value);
list.push_back(kv);
if (!getline(toParse, key, '|'))
break;
}
}
mAgent->updateAsset(device, assetId, list, time);
return;
}
else if (key == "@REMOVE_ASSET@")
{
string assetId = value;
mAgent->removeAsset(device, assetId, time);
return;
}
DataItem *dataItem;
if (device != NULL) {
dataItem = device->getDeviceDataItem(key);
if (dataItem == NULL)
{
sLogger << LWARN << "(" << device->getName() << ") Could not find data item: " << key <<
" from line '" << data << "'";
} else {
string rest;
if (dataItem->isCondition() || dataItem->isAlarm() || dataItem->isMessage() ||
dataItem->isTimeSeries())
{
getline(toParse, rest);
value = value + "|" + rest;
}
// Add key->value pairings
dataItem->setDataSource(this);
trim(value);
// Check for duplication
const string &uppered = toUpperCase(value);
if (!isDuplicate(dataItem, uppered))
{
mAgent->addToBuffer(dataItem, uppered, time);
}
else if (mDupCheck)
{
//sLogger << LDEBUG << "Dropping duplicate value for " << key << " of " << value;
}
}
} else {
sLogger << LDEBUG << "Could not find device: " << dev;
}
// Look for more key->value pairings in the rest of the data
while (getline(toParse, key, '|') && getline(toParse, value, '|'))
{
if (splitKey(key, dev)) {
device = mAgent->getDeviceByName(dev);
} else {
device = mDevice;
}
if (device == NULL) {
sLogger << LDEBUG << "Could not find device: " << dev;
continue;
}
dataItem = device->getDeviceDataItem(key);
if (dataItem == NULL)
{
sLogger << LWARN << "Could not find data item: " << key << " for device " << mDeviceName;
}
else
{
dataItem->setDataSource(this);
trim(value);
const string &uppered = toUpperCase(value);
if (!isDuplicate(dataItem, uppered))
{
mAgent->addToBuffer(dataItem, uppered, time);
}
else if (mDupCheck)
{
//sLogger << LDEBUG << "Dropping duplicate value for " << key << " of " << value;
}
}
}
}
void Adapter::protocolCommand(const std::string& data)
{
// Handle initial push of settings for uuid, serial number and manufacturer.
// This will override the settings in the device from the xml
if (data == "* PROBE") {
string response = mAgent->handleProbe(mDeviceName);
string probe = "* PROBE LENGTH=";
probe.append(intToString(response.length()));
probe.append("\n");
probe.append(response);
probe.append("\n");
mConnection->write(probe.c_str(), probe.length());
} else {
size_t index = data.find(':', 2);
if (index != string::npos)
{
// Slice from the second character to the :, without the colon
string key = data.substr(2, index - 2);
trim(key);
string value = data.substr(index + 1);
trim(value);
bool updateDom = true;
if (key == "uuid") {
if (!mDevice->mPreserveUuid) mDevice->setUuid(value);
} else if (key == "manufacturer")
mDevice->setManufacturer(value);
else if (key == "station")
mDevice->setStation(value);
else if (key == "serialNumber")
mDevice->setSerialNumber(value);
else if (key == "description")
mDevice->setDescription(value);
else if (key == "nativeName")
mDevice->setNativeName(value);
else if (key == "calibration")
parseCalibration(value);
else {
sLogger << LWARN << "Unknown command '" << data << "' for device '" << mDeviceName;
updateDom = false;
}
if (updateDom) {
mAgent->updateDom(mDevice);
}
}
}
}
void Adapter::parseCalibration(const std::string &aLine)
{
istringstream toParse(aLine);
// Look for name|factor|offset triples
string name, factor, offset;
while (getline(toParse, name, '|') &&
getline(toParse, factor, '|') &&
getline(toParse, offset, '|')) {
// Convert to a floating point number
DataItem *di = mDevice->getDeviceDataItem(name);
if (di == NULL) {
sLogger << LWARN << "Cannot find data item to calibrate for " << name;
} else {
double fact_value = strtod(factor.c_str(), NULL);
double off_value = strtod(offset.c_str(), NULL);
di->setConversionFactor(fact_value, off_value);
}
}
}
void Adapter::disconnected()
{
mBaseTime = 0;
mAgent->disconnected(this, mAllDevices);
}
void Adapter::connected()
{
mAgent->connected(this, mAllDevices);
}
/* Adapter private methods */
void Adapter::thread()
{
while (mRunning)
{
try
{
// Start the connection to the socket
connect();
// make sure we're closed...
close();
}
catch (...)
{
sLogger << LERROR << "Thread for adapter " << mDeviceName << "'s thread threw an unhandled exception";
}
if (!mRunning) break;
// Try to reconnect every 10 seconds
sLogger << LINFO << "Will try to reconnect in " << mReconnectInterval << " milliseconds";
dlib::sleep(mReconnectInterval);
}
sLogger << LINFO << "Adapter thread stopped";
}
<commit_msg>Added additional adapter protocol commands.<commit_after>/*
* Copyright Copyright 2012, System Insights, 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.
*/
#define __STDC_LIMIT_MACROS 1
#include "adapter.hpp"
#include "device.hpp"
#include "globals.hpp"
#include "dlib/logger.h"
using namespace std;
static dlib::logger sLogger("input.adapter");
/* Adapter public methods */
Adapter::Adapter(const string& device,
const string& server,
const unsigned int port,
int aLegacyTimeout)
: Connector(server, port, aLegacyTimeout), mDeviceName(device), mRunning(true),
mDupCheck(false), mAutoAvailable(false), mIgnoreTimestamps(false), mRelativeTime(false), mConversionRequired(true),
mBaseTime(0), mBaseOffset(0), mParseTime(false), mGatheringAsset(false), mReconnectInterval(10 * 1000)
{
}
Adapter::~Adapter()
{
if (mRunning) stop();
}
void Adapter::stop()
{
// Will stop threaded object gracefully Adapter::thread()
mRunning = false;
close();
wait();
}
void Adapter::setAgent(Agent &aAgent)
{
mAgent = &aAgent;
mDevice = mAgent->getDeviceByName(mDeviceName);
mDevice->addAdapter(this);
if (mDevice != NULL)
mAllDevices.push_back(mDevice);
}
void Adapter::addDevice(string &aName)
{
Device *dev = mAgent->getDeviceByName(aName);
if (dev != NULL) {
mAllDevices.push_back(dev);
dev->addAdapter(this);
}
}
inline static bool splitKey(string &key, string &dev)
{
size_t found = key.find_first_of(':');
if (found == string::npos) {
return false;
} else {
dev = key;
dev.erase(found);
key.erase(0, found + 1);
return true;
}
}
inline static void trim(std::string &str)
{
size_t index = str.find_first_not_of(" \r\t");
if (index != string::npos && index > 0)
str.erase(0, index);
index = str.find_last_not_of(" \r\t");
if (index != string::npos)
str.erase(index + 1);
}
/**
* Expected data to parse in SDHR format:
* Time|Alarm|Code|NativeCode|Severity|State|Description
* Time|Item|Value
* Time|Item1|Value1|Item2|Value2...
*
* Support for assets:
* Time|@ASSET@|id|type|<...>...</...>
*/
void Adapter::processData(const string& data)
{
if (mGatheringAsset)
{
if (data == mTerminator)
{
mAgent->addAsset(mAssetDevice, mAssetId, mBody.str(), mAssetType, mTime);
mGatheringAsset = false;
}
else
{
mBody << data << endl;
}
return;
}
istringstream toParse(data);
string key, value, dev;
Device *device;
getline(toParse, key, '|');
string time = key;
// Check how to handle time. If the time is relative, then we need to compute the first
// offsets, otherwise, if this function is being used as an API, add the current time.
if (mRelativeTime) {
uint64_t offset;
if (mBaseTime == 0) {
mBaseTime = getCurrentTimeInMicros();
if (time.find('T') != string::npos) {
mParseTime = true;
mBaseOffset = parseTimeMicro(time);
} else {
mBaseOffset = (uint64_t) (atof(time.c_str()) * 1000.0);
}
offset = 0;
} else if (mParseTime) {
offset = parseTimeMicro(time) - mBaseOffset;
} else {
offset = ((uint64_t) (atof(time.c_str()) * 1000.0)) - mBaseOffset;
}
time = getRelativeTimeString(mBaseTime + offset);
} else if (mIgnoreTimestamps || time.empty()) {
time = getCurrentTime(GMT_UV_SEC);
}
getline(toParse, key, '|');
getline(toParse, value, '|');
if (splitKey(key, dev)) {
device = mAgent->getDeviceByName(dev);
} else {
device = mDevice;
}
if (key == "@ASSET@") {
string type, rest;
getline(toParse, type, '|');
getline(toParse, rest);
// Chck for an update and parse key value pairs. If only a type
// is presented, then assume the remainder is a complete doc.
// if the rest of the line begins with --multiline--... then
// set multiline and accumulate until a completed document is found
if (rest.find("--multiline--") != rest.npos)
{
mAssetDevice = device;
mGatheringAsset = true;
mTerminator = rest;
mTime = time;
mAssetType = type;
mAssetId = value;
mBody.str("");
mBody.clear();
}
else
{
mAgent->addAsset(device, value, rest, type, time);
}
return;
}
else if (key == "@UPDATE_ASSET@")
{
string assetId = value;
AssetChangeList list;
getline(toParse, key, '|');
if (key[0] == '<')
{
do {
pair<string,string> kv("xml", key);
list.push_back(kv);
} while (getline(toParse, key, '|'));
}
else
{
while (getline(toParse, value, '|'))
{
pair<string,string> kv(key, value);
list.push_back(kv);
if (!getline(toParse, key, '|'))
break;
}
}
mAgent->updateAsset(device, assetId, list, time);
return;
}
else if (key == "@REMOVE_ASSET@")
{
string assetId = value;
mAgent->removeAsset(device, assetId, time);
return;
}
DataItem *dataItem;
if (device != NULL) {
dataItem = device->getDeviceDataItem(key);
if (dataItem == NULL)
{
sLogger << LWARN << "(" << device->getName() << ") Could not find data item: " << key <<
" from line '" << data << "'";
} else {
string rest;
if (dataItem->isCondition() || dataItem->isAlarm() || dataItem->isMessage() ||
dataItem->isTimeSeries())
{
getline(toParse, rest);
value = value + "|" + rest;
}
// Add key->value pairings
dataItem->setDataSource(this);
trim(value);
// Check for duplication
const string &uppered = toUpperCase(value);
if (!isDuplicate(dataItem, uppered))
{
mAgent->addToBuffer(dataItem, uppered, time);
}
else if (mDupCheck)
{
//sLogger << LDEBUG << "Dropping duplicate value for " << key << " of " << value;
}
}
} else {
sLogger << LDEBUG << "Could not find device: " << dev;
}
// Look for more key->value pairings in the rest of the data
while (getline(toParse, key, '|') && getline(toParse, value, '|'))
{
if (splitKey(key, dev)) {
device = mAgent->getDeviceByName(dev);
} else {
device = mDevice;
}
if (device == NULL) {
sLogger << LDEBUG << "Could not find device: " << dev;
continue;
}
dataItem = device->getDeviceDataItem(key);
if (dataItem == NULL)
{
sLogger << LWARN << "Could not find data item: " << key << " for device " << mDeviceName;
}
else
{
dataItem->setDataSource(this);
trim(value);
const string &uppered = toUpperCase(value);
if (!isDuplicate(dataItem, uppered))
{
mAgent->addToBuffer(dataItem, uppered, time);
}
else if (mDupCheck)
{
//sLogger << LDEBUG << "Dropping duplicate value for " << key << " of " << value;
}
}
}
}
static inline bool is_true(const string &aValue)
{
return(aValue == "yes" || aValue == "true" || aValue == "1");
}
void Adapter::protocolCommand(const std::string& data)
{
// Handle initial push of settings for uuid, serial number and manufacturer.
// This will override the settings in the device from the xml
if (data == "* PROBE") {
string response = mAgent->handleProbe(mDeviceName);
string probe = "* PROBE LENGTH=";
probe.append(intToString(response.length()));
probe.append("\n");
probe.append(response);
probe.append("\n");
mConnection->write(probe.c_str(), probe.length());
} else {
size_t index = data.find(':', 2);
if (index != string::npos)
{
// Slice from the second character to the :, without the colon
string key = data.substr(2, index - 2);
trim(key);
string value = data.substr(index + 1);
trim(value);
bool updateDom = true;
if (key == "uuid") {
if (!mDevice->mPreserveUuid) mDevice->setUuid(value);
} else if (key == "manufacturer")
mDevice->setManufacturer(value);
else if (key == "station")
mDevice->setStation(value);
else if (key == "serialNumber")
mDevice->setSerialNumber(value);
else if (key == "description")
mDevice->setDescription(value);
else if (key == "nativeName")
mDevice->setNativeName(value);
else if (key == "calibration")
parseCalibration(value);
else if (key == "conversionRequired")
mConversionRequired = is_true(value);
else if (key == "relativeTime")
mRelativeTime = is_true(value);
else if (key == "realTime")
mRealTime = is_true(value);
else
{
sLogger << LWARN << "Unknown command '" << data << "' for device '" << mDeviceName;
updateDom = false;
}
if (updateDom) {
mAgent->updateDom(mDevice);
}
}
}
}
void Adapter::parseCalibration(const std::string &aLine)
{
istringstream toParse(aLine);
// Look for name|factor|offset triples
string name, factor, offset;
while (getline(toParse, name, '|') &&
getline(toParse, factor, '|') &&
getline(toParse, offset, '|')) {
// Convert to a floating point number
DataItem *di = mDevice->getDeviceDataItem(name);
if (di == NULL) {
sLogger << LWARN << "Cannot find data item to calibrate for " << name;
} else {
double fact_value = strtod(factor.c_str(), NULL);
double off_value = strtod(offset.c_str(), NULL);
di->setConversionFactor(fact_value, off_value);
}
}
}
void Adapter::disconnected()
{
mBaseTime = 0;
mAgent->disconnected(this, mAllDevices);
}
void Adapter::connected()
{
mAgent->connected(this, mAllDevices);
}
/* Adapter private methods */
void Adapter::thread()
{
while (mRunning)
{
try
{
// Start the connection to the socket
connect();
// make sure we're closed...
close();
}
catch (...)
{
sLogger << LERROR << "Thread for adapter " << mDeviceName << "'s thread threw an unhandled exception";
}
if (!mRunning) break;
// Try to reconnect every 10 seconds
sLogger << LINFO << "Will try to reconnect in " << mReconnectInterval << " milliseconds";
dlib::sleep(mReconnectInterval);
}
sLogger << LINFO << "Adapter thread stopped";
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* 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 any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
/**
@brief Figure out what flags we have to pass to the compiler in order to build for a specific architecture.
An empty string indicates this is the default.
ALL supported triplets must be listed here; the absence of an entry is an error.
*/
GNUToolchain::GNUToolchain(string arch)
{
if(arch == "x86_64-linux-gnu")
{
m_archflags["x86_64-linux-gnu"] = "-m64";
m_archflags["x86_64-linux-gnux32"] = "-mx32";
m_archflags["i386-linux-gnu"] = "-m32";
}
else if(arch == "x86_64-w64-mingw32")
{
m_archflags[arch] = "";
}
else if(arch == "i386-linux-gnu")
{
m_archflags[arch] = "";
}
else if(arch == "mips-elf")
{
m_archflags["mips-elf"] = "-EB";
m_archflags["mipsel-elf"] = "-EL";
}
else if(arch == "arm-linux-gnueabihf")
{
m_archflags[arch] = "";
}
else
{
LogWarning("Don't know what flags to use for target %s\n", arch.c_str());
}
}
void GNUToolchain::FindDefaultIncludePaths(vector<string>& paths, string exe, bool cpp, string arch)
{
//LogDebug(" Finding default include paths\n");
//We must have valid flags for this arch
if(m_archflags.find(arch) == m_archflags.end())
{
LogError("Don't know how to target %s\n", arch.c_str());
return;
}
string aflags = m_archflags[arch];
//Ask the compiler what the paths are
vector<string> lines;
string cmd = exe + " " + aflags + " -E -Wp,-v ";
if(cpp)
cmd += "-x c++ ";
cmd += "- < /dev/null 2>&1";
ParseLines(ShellCommand(cmd), lines);
//Look for the beginning of the search path list
size_t i = 0;
for(; i<lines.size(); i++)
{
auto line = lines[i];
if(line.find("starts here") != string::npos)
break;
}
//Get the actual paths
for(; i<lines.size(); i++)
{
auto line = lines[i];
if(line == "End of search list.")
break;
if(line[0] == '#')
continue;
paths.push_back(line.substr(1));
}
//Debug dump
//for(auto p : paths)
// LogDebug(" %s\n", p.c_str());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Meta-flag processing
/**
@brief Convert a build flag to the actual executable flag representation
*/
string GNUToolchain::FlagToString(BuildFlag flag)
{
string s = flag;
//Optimization flags
if(s == "optimize/none")
return "-O0";
else if(s == "optimize/speed")
return "-O2";
//Debug info flags
else if(s == "debug/gdb")
return "-ggdb";
//Language dialect
else if(s == "dialect/c++11")
return "--std=c++11";
//Warning levels
else if(s == "warning/max")
return "-Wall -Wextra -Wcast-align -Winit-self -Wmissing-declarations -Wswitch -Wwrite-strings";
else
{
LogWarning("GNUToolchain does not implement flag %s yet\n", s.c_str());
return "";
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Actual operations
/**
@brief Scans a source file for dependencies (include files, etc)
*/
bool GNUToolchain::ScanDependencies(
string exe,
string triplet,
string path,
string root,
set<BuildFlag> flags,
const vector<string>& sysdirs,
set<string>& deps,
map<string, string>& dephashes)
{
//We must have valid flags for this arch
if(m_archflags.find(triplet) == m_archflags.end())
{
LogError("Don't know how to target %s\n", triplet.c_str());
return false;
}
//Look up some arch-specific stuff
string aflags = m_archflags[triplet];
auto apath = m_virtualSystemIncludePath[triplet];
//Make the full scan command line
string cmdline = exe + " " + aflags + " -M -MG ";
for(auto f : flags)
cmdline += FlagToString(f) + " ";
cmdline += path;
LogDebug("Command line: %s\n", cmdline.c_str());
LogDebug("Dependency scan for arch %s\n", triplet.c_str());
//Run it
string makerule = ShellCommand(cmdline);
//Parse it
size_t offset = makerule.find(':');
if(offset == string::npos)
{
LogError("GNUToolchain::ScanDependencies - Make rule was not well formed (scan error?)\n");
return false;
}
vector<string> files;
string tmp;
for(size_t i=offset + 1; i<makerule.length(); i++)
{
bool last_was_slash = (makerule[i-1] == '\\');
//Skip leading spaces
char c = makerule[i];
if( tmp.empty() && isspace(c) )
continue;
//If not a space, it's part of a file name
else if(!isspace(c))
tmp += c;
//Space after a slash is part of a file name
else if( (c == ' ') && last_was_slash)
tmp += c;
//Any other space is a delimiter
else
{
if(tmp != "\\")
files.push_back(tmp);
tmp = "";
}
}
if(!tmp.empty() && (tmp != "\\") )
files.push_back(tmp);
//First entry is always the source file itself, so we can skip that
//Loop over the other entries and convert them to system/project relative paths
//LogDebug("Absolute paths:\n");
for(size_t i=1; i<files.size(); i++)
{
//If the path begins with our working copy directory, trim it off and call the rest the relative path
string f = files[i];
if(f.find(root) == 0)
{
//LogDebug(" local dir\n");
f = f.substr(root.length() + 1);
}
//No go - loop over the system include paths
else
{
string longest_prefix = "";
for(auto dir : sysdirs)
{
if(f.find(dir) != 0)
continue;
if(dir.length() > longest_prefix.length())
longest_prefix = dir;
}
//If it's not in the project dir OR a system path, we have a problem.
//Including random headers by absolute path is not portable!
if(longest_prefix == "")
{
LogError("Path %s could not be resolved to a system or project include directory\n",
f.c_str());
return false;
}
//Trim off the prefix and go
//LogDebug(" system dir %s\n", longest_prefix.c_str());
f = apath + "/" + f.substr(longest_prefix.length() + 1);
}
//TODO: Don't even read the file if we already have it in the cache?
//Add file to cache
string data = GetFileContents(files[i]);
string hash = sha256(data);
if(!g_cache->IsCached(hash))
g_cache->AddFile(f, hash, hash, data.c_str(), data.size());
//Add virtual path to output dep list
deps.emplace(f);
dephashes[f] = hash;
}
/*
LogDebug(" Project-relative dependency paths:\n");
for(auto f : deps)
LogDebug(" %s\n", f.c_str());
*/
return true;
}
<commit_msg>splashcore: added support for more ARM targets in GNUToolchain<commit_after>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* 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 any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
/**
@brief Figure out what flags we have to pass to the compiler in order to build for a specific architecture.
An empty string indicates this is the default.
ALL supported triplets must be listed here; the absence of an entry is an error.
*/
GNUToolchain::GNUToolchain(string arch)
{
/////////////////////////////////////////////////////////////////////////////
// X86
if(arch == "x86_64-linux-gnu")
{
m_archflags["x86_64-linux-gnu"] = "-m64";
m_archflags["x86_64-linux-gnux32"] = "-mx32";
m_archflags["i386-linux-gnu"] = "-m32";
}
else if(arch == "x86_64-w64-mingw32")
{
m_archflags[arch] = "";
}
else if(arch == "i386-linux-gnu")
{
m_archflags[arch] = "";
}
/////////////////////////////////////////////////////////////////////////////
// MIPS
else if(arch == "mips-elf")
{
m_archflags["mips-elf"] = "-EB";
m_archflags["mipsel-elf"] = "-EL";
}
/////////////////////////////////////////////////////////////////////////////
// ARM
else if(arch == "arm-linux-gnueabihf")
{
m_archflags[arch] = "";
}
else if(arch == "arm-linux-gnueabi")
{
m_archflags[arch] = "";
}
else if(arch == "arm-none-eabi")
{
m_archflags[arch] = "";
}
/////////////////////////////////////////////////////////////////////////////
// INVALID
else
{
LogWarning("Don't know what flags to use for target %s\n", arch.c_str());
}
}
void GNUToolchain::FindDefaultIncludePaths(vector<string>& paths, string exe, bool cpp, string arch)
{
//LogDebug(" Finding default include paths\n");
//We must have valid flags for this arch
if(m_archflags.find(arch) == m_archflags.end())
{
LogError("Don't know how to target %s\n", arch.c_str());
return;
}
string aflags = m_archflags[arch];
//Ask the compiler what the paths are
vector<string> lines;
string cmd = exe + " " + aflags + " -E -Wp,-v ";
if(cpp)
cmd += "-x c++ ";
cmd += "- < /dev/null 2>&1";
ParseLines(ShellCommand(cmd), lines);
//Look for the beginning of the search path list
size_t i = 0;
for(; i<lines.size(); i++)
{
auto line = lines[i];
if(line.find("starts here") != string::npos)
break;
}
//Get the actual paths
for(; i<lines.size(); i++)
{
auto line = lines[i];
if(line == "End of search list.")
break;
if(line[0] == '#')
continue;
paths.push_back(line.substr(1));
}
//Debug dump
//for(auto p : paths)
// LogDebug(" %s\n", p.c_str());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Meta-flag processing
/**
@brief Convert a build flag to the actual executable flag representation
*/
string GNUToolchain::FlagToString(BuildFlag flag)
{
string s = flag;
//Optimization flags
if(s == "optimize/none")
return "-O0";
else if(s == "optimize/speed")
return "-O2";
//Debug info flags
else if(s == "debug/gdb")
return "-ggdb";
//Language dialect
else if(s == "dialect/c++11")
return "--std=c++11";
//Warning levels
else if(s == "warning/max")
return "-Wall -Wextra -Wcast-align -Winit-self -Wmissing-declarations -Wswitch -Wwrite-strings";
else
{
LogWarning("GNUToolchain does not implement flag %s yet\n", s.c_str());
return "";
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Actual operations
/**
@brief Scans a source file for dependencies (include files, etc)
*/
bool GNUToolchain::ScanDependencies(
string exe,
string triplet,
string path,
string root,
set<BuildFlag> flags,
const vector<string>& sysdirs,
set<string>& deps,
map<string, string>& dephashes)
{
//We must have valid flags for this arch
if(m_archflags.find(triplet) == m_archflags.end())
{
LogError("Don't know how to target %s\n", triplet.c_str());
return false;
}
//Look up some arch-specific stuff
string aflags = m_archflags[triplet];
auto apath = m_virtualSystemIncludePath[triplet];
//Make the full scan command line
string cmdline = exe + " " + aflags + " -M -MG ";
for(auto f : flags)
cmdline += FlagToString(f) + " ";
cmdline += path;
LogDebug("Command line: %s\n", cmdline.c_str());
LogDebug("Dependency scan for arch %s\n", triplet.c_str());
//Run it
string makerule = ShellCommand(cmdline);
//Parse it
size_t offset = makerule.find(':');
if(offset == string::npos)
{
LogError("GNUToolchain::ScanDependencies - Make rule was not well formed (scan error?)\n");
return false;
}
vector<string> files;
string tmp;
for(size_t i=offset + 1; i<makerule.length(); i++)
{
bool last_was_slash = (makerule[i-1] == '\\');
//Skip leading spaces
char c = makerule[i];
if( tmp.empty() && isspace(c) )
continue;
//If not a space, it's part of a file name
else if(!isspace(c))
tmp += c;
//Space after a slash is part of a file name
else if( (c == ' ') && last_was_slash)
tmp += c;
//Any other space is a delimiter
else
{
if(tmp != "\\")
files.push_back(tmp);
tmp = "";
}
}
if(!tmp.empty() && (tmp != "\\") )
files.push_back(tmp);
//First entry is always the source file itself, so we can skip that
//Loop over the other entries and convert them to system/project relative paths
//LogDebug("Absolute paths:\n");
for(size_t i=1; i<files.size(); i++)
{
//If the path begins with our working copy directory, trim it off and call the rest the relative path
string f = files[i];
if(f.find(root) == 0)
{
//LogDebug(" local dir\n");
f = f.substr(root.length() + 1);
}
//No go - loop over the system include paths
else
{
string longest_prefix = "";
for(auto dir : sysdirs)
{
if(f.find(dir) != 0)
continue;
if(dir.length() > longest_prefix.length())
longest_prefix = dir;
}
//If it's not in the project dir OR a system path, we have a problem.
//Including random headers by absolute path is not portable!
if(longest_prefix == "")
{
LogError("Path %s could not be resolved to a system or project include directory\n",
f.c_str());
return false;
}
//Trim off the prefix and go
//LogDebug(" system dir %s\n", longest_prefix.c_str());
f = apath + "/" + f.substr(longest_prefix.length() + 1);
}
//TODO: Don't even read the file if we already have it in the cache?
//Add file to cache
string data = GetFileContents(files[i]);
string hash = sha256(data);
if(!g_cache->IsCached(hash))
g_cache->AddFile(f, hash, hash, data.c_str(), data.size());
//Add virtual path to output dep list
deps.emplace(f);
dephashes[f] = hash;
}
/*
LogDebug(" Project-relative dependency paths:\n");
for(auto f : deps)
LogDebug(" %s\n", f.c_str());
*/
return true;
}
<|endoftext|> |
<commit_before>#include <QtGui>
#include "seafile-applet.h"
#include "configurator.h"
#include "init-seafile-dialog.h"
namespace {
#if defined(Q_WS_WIN)
#include <ShlObj.h>
#include <shlwapi.h>
static QString
get_largest_drive()
{
wchar_t drives[MAX_PATH];
wchar_t *p, *largest_drive;
ULARGE_INTEGER free_space;
ULARGE_INTEGER largest_free_space;
largest_free_space.QuadPart = 0;
largest_drive = NULL;
GetLogicalDriveStringsW (sizeof(drives), drives);
for (p = drives; *p != L'\0'; p += wcslen(p) + 1) {
/* Skip floppy disk, network drive, etc */
if (GetDriveTypeW(p) != DRIVE_FIXED)
continue;
if (GetDiskFreeSpaceExW (p, &free_space, NULL, NULL)) {
if (free_space.QuadPart > largest_free_space.QuadPart) {
largest_free_space.QuadPart = free_space.QuadPart;
if (largest_drive != NULL) {
free (largest_drive);
}
largest_drive = wcsdup(p);
}
} else {
qDebug ("failed to GetDiskFreeSpaceEx(), GLE=%lu\n",
GetLastError());
}
}
QString ret;
if (largest_drive) {
ret = QString::fromStdWString(largest_drive);
free(largest_drive);
}
return ret;
}
#endif
} // namespace
InitSeafileDialog::InitSeafileDialog(QWidget *parent)
: QDialog(parent)
{
setupUi(this);
setWindowTitle(tr("%1 Initialzation").arg(SEAFILE_CLIENT_BRAND));
setWindowIcon(QIcon(":/images/seafile.png"));
connect(mChooseDirBtn, SIGNAL(clicked()), this, SLOT(chooseDir()));
connect(mOkBtn, SIGNAL(clicked()), this, SLOT(onOkClicked()));
connect(mCancelBtn, SIGNAL(clicked()), this, SLOT(onCancelClicked()));
mLogo->setPixmap(QPixmap(":/images/seafile-32.png"));
mDirectory->setText(getInitialPath());
const QRect screen = QApplication::desktop()->screenGeometry();
move(screen.center() - this->rect().center());
}
QString InitSeafileDialog::getInitialPath()
{
#if defined(Q_WS_WIN)
return get_largest_drive();
#else
return QDir::home().path();
#endif
}
void InitSeafileDialog::chooseDir()
{
QString initial_path;
// On windows, set the initial path to the max volume, on linux/mac, set
// to the home direcotry.
QString dir = QFileDialog::getExistingDirectory(this, tr("Please choose a directory"),
getInitialPath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
if (dir.isEmpty())
return;
mDirectory->setText(dir);
}
void InitSeafileDialog::onOkClicked()
{
QString path = mDirectory->text();
if (path.isEmpty()) {
QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
tr("Please choose a directory"),
QMessageBox::Ok);
return;
}
QDir dir(path);
if (!dir.exists()) {
QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
tr("The folder %1 does not exist").arg(path),
QMessageBox::Ok);
return;
}
#if defined(Q_WS_WIN)
dir.mkpath("Seafile/seafile-data");
QString seafile_dir = dir.filePath("Seafile/seafile-data");
#else
dir.mkpath("Seafile/.seafile-data");
QString seafile_dir = dir.filePath("Seafile/.seafile-data");
#endif
emit seafileDirSet(seafile_dir);
accept();
}
void InitSeafileDialog::onCancelClicked()
{
QString question = tr("Initialzation is not finished. Really quit?");
if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND),
question,
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::Yes) {
reject();
}
}
void InitSeafileDialog::closeEvent(QCloseEvent *event)
{
QString question = tr("Initialzation is not finished. Really quit?");
if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND),
question,
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::Yes) {
QDialog::closeEvent(event);
return;
}
event->ignore();
}
<commit_msg>Update init-seafile-dialog.cpp<commit_after>#include <QtGui>
#include "seafile-applet.h"
#include "configurator.h"
#include "init-seafile-dialog.h"
namespace {
#if defined(Q_WS_WIN)
#include <ShlObj.h>
#include <shlwapi.h>
static QString
get_largest_drive()
{
wchar_t drives[MAX_PATH];
wchar_t *p, *largest_drive;
ULARGE_INTEGER free_space;
ULARGE_INTEGER largest_free_space;
largest_free_space.QuadPart = 0;
largest_drive = NULL;
GetLogicalDriveStringsW (sizeof(drives), drives);
for (p = drives; *p != L'\0'; p += wcslen(p) + 1) {
/* Skip floppy disk, network drive, etc */
if (GetDriveTypeW(p) != DRIVE_FIXED)
continue;
if (GetDiskFreeSpaceExW (p, &free_space, NULL, NULL)) {
if (free_space.QuadPart > largest_free_space.QuadPart) {
largest_free_space.QuadPart = free_space.QuadPart;
if (largest_drive != NULL) {
free (largest_drive);
}
largest_drive = wcsdup(p);
}
} else {
qDebug ("failed to GetDiskFreeSpaceEx(), GLE=%lu\n",
GetLastError());
}
}
QString ret;
if (largest_drive) {
ret = QString::fromStdWString(largest_drive);
free(largest_drive);
}
return ret;
}
#endif
} // namespace
InitSeafileDialog::InitSeafileDialog(QWidget *parent)
: QDialog(parent)
{
setupUi(this);
setWindowTitle(tr("%1 Initialization").arg(SEAFILE_CLIENT_BRAND));
setWindowIcon(QIcon(":/images/seafile.png"));
connect(mChooseDirBtn, SIGNAL(clicked()), this, SLOT(chooseDir()));
connect(mOkBtn, SIGNAL(clicked()), this, SLOT(onOkClicked()));
connect(mCancelBtn, SIGNAL(clicked()), this, SLOT(onCancelClicked()));
mLogo->setPixmap(QPixmap(":/images/seafile-32.png"));
mDirectory->setText(getInitialPath());
const QRect screen = QApplication::desktop()->screenGeometry();
move(screen.center() - this->rect().center());
}
QString InitSeafileDialog::getInitialPath()
{
#if defined(Q_WS_WIN)
return get_largest_drive();
#else
return QDir::home().path();
#endif
}
void InitSeafileDialog::chooseDir()
{
QString initial_path;
// On windows, set the initial path to the max volume, on linux/mac, set
// to the home direcotry.
QString dir = QFileDialog::getExistingDirectory(this, tr("Please choose a directory"),
getInitialPath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
if (dir.isEmpty())
return;
mDirectory->setText(dir);
}
void InitSeafileDialog::onOkClicked()
{
QString path = mDirectory->text();
if (path.isEmpty()) {
QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
tr("Please choose a directory"),
QMessageBox::Ok);
return;
}
QDir dir(path);
if (!dir.exists()) {
QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
tr("The folder %1 does not exist").arg(path),
QMessageBox::Ok);
return;
}
#if defined(Q_WS_WIN)
dir.mkpath("Seafile/seafile-data");
QString seafile_dir = dir.filePath("Seafile/seafile-data");
#else
dir.mkpath("Seafile/.seafile-data");
QString seafile_dir = dir.filePath("Seafile/.seafile-data");
#endif
emit seafileDirSet(seafile_dir);
accept();
}
void InitSeafileDialog::onCancelClicked()
{
QString question = tr("Initialization is not finished. Really quit?");
if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND),
question,
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::Yes) {
reject();
}
}
void InitSeafileDialog::closeEvent(QCloseEvent *event)
{
QString question = tr("Initialization is not finished. Really quit?");
if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND),
question,
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::Yes) {
QDialog::closeEvent(event);
return;
}
event->ignore();
}
<|endoftext|> |
<commit_before>
// HTTPServer.cpp
// Implements the cHTTPServer class representing a HTTP webserver that uses cListenThread and cSocketThreads for processing
#include "Globals.h"
#include "HTTPServer.h"
#include "HTTPMessage.h"
#include "HTTPConnection.h"
#include "HTTPFormParser.h"
#include "SslHTTPConnection.h"
// Disable MSVC warnings:
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4355) // 'this' : used in base member initializer list
#endif
class cDebugCallbacks :
public cHTTPServer::cCallbacks,
protected cHTTPFormParser::cCallbacks
{
virtual void OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override
{
UNUSED(a_Connection);
if (cHTTPFormParser::HasFormData(a_Request))
{
a_Request.SetUserData(new cHTTPFormParser(a_Request, *this));
}
}
virtual void OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) override
{
UNUSED(a_Connection);
cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData());
if (FormParser != NULL)
{
FormParser->Parse(a_Data, a_Size);
}
}
virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override
{
cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData());
if (FormParser != NULL)
{
if (FormParser->Finish())
{
cHTTPResponse Resp;
Resp.SetContentType("text/html");
a_Connection.Send(Resp);
a_Connection.Send("<html><body><table border=1 cellspacing=0><tr><th>Name</th><th>Value</th></tr>\r\n");
for (cHTTPFormParser::iterator itr = FormParser->begin(), end = FormParser->end(); itr != end; ++itr)
{
a_Connection.Send(Printf("<tr><td valign=\"top\"><pre>%s</pre></td><td valign=\"top\"><pre>%s</pre></td></tr>\r\n", itr->first.c_str(), itr->second.c_str()));
} // for itr - FormParser[]
a_Connection.Send("</table></body></html>");
return;
}
// Parsing failed:
cHTTPResponse Resp;
Resp.SetContentType("text/plain");
a_Connection.Send(Resp);
a_Connection.Send("Form parsing failed");
return;
}
// Test the auth failure and success:
if (a_Request.GetURL() == "/auth")
{
if (!a_Request.HasAuth() || (a_Request.GetAuthUsername() != "a") || (a_Request.GetAuthPassword() != "b"))
{
a_Connection.SendNeedAuth("MCServer WebAdmin");
return;
}
}
cHTTPResponse Resp;
Resp.SetContentType("text/plain");
a_Connection.Send(Resp);
a_Connection.Send("Hello, world");
}
virtual void OnFileStart(cHTTPFormParser & a_Parser, const AString & a_FileName) override
{
// TODO
}
virtual void OnFileData(cHTTPFormParser & a_Parser, const char * a_Data, size_t a_Size) override
{
// TODO
}
virtual void OnFileEnd(cHTTPFormParser & a_Parser) override
{
// TODO
}
} g_DebugCallbacks;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cHTTPServer:
cHTTPServer::cHTTPServer(void) :
m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer IPv4"),
m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer IPv6"),
m_Callbacks(NULL)
{
AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt");
AString KeyFile = cFile::ReadWholeFile("webadmin/httpskey.pem");
if (!CertFile.empty() && !KeyFile.empty())
{
m_Cert.reset(new cX509Cert);
int res = m_Cert->Parse(CertFile.data(), CertFile.size());
if (res == 0)
{
m_CertPrivKey.reset(new cCryptoKey);
int res2 = m_CertPrivKey->ParsePrivate(KeyFile.data(), KeyFile.size(), "");
if (res2 != 0)
{
// Reading the private key failed, reset the cert:
LOGWARNING("WebAdmin: Cannot read HTTPS certificate private key: -0x%x", -res2);
m_Cert.reset();
}
}
else
{
LOGWARNING("WebAdmin: Cannot read HTTPS certificate: -0x%x", -res);
}
}
}
cHTTPServer::~cHTTPServer()
{
Stop();
}
bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_PortsIPv6)
{
bool HasAnyPort;
HasAnyPort = m_ListenThreadIPv4.Initialize(a_PortsIPv4);
HasAnyPort = m_ListenThreadIPv6.Initialize(a_PortsIPv6) || HasAnyPort;
if (!HasAnyPort)
{
return false;
}
return true;
}
bool cHTTPServer::Start(cCallbacks & a_Callbacks)
{
m_Callbacks = &a_Callbacks;
if (!m_ListenThreadIPv4.Start())
{
return false;
}
if (!m_ListenThreadIPv6.Start())
{
m_ListenThreadIPv4.Stop();
return false;
}
return true;
}
void cHTTPServer::Stop(void)
{
m_ListenThreadIPv4.Stop();
m_ListenThreadIPv6.Stop();
// Drop all current connections:
cCSLock Lock(m_CSConnections);
while (!m_Connections.empty())
{
m_Connections.front()->Terminate();
} // for itr - m_Connections[]
}
void cHTTPServer::OnConnectionAccepted(cSocket & a_Socket)
{
cHTTPConnection * Connection;
if (m_Cert.get() != NULL)
{
Connection = new cSslHTTPConnection(*this, m_Cert, m_CertPrivKey);
}
else
{
Connection = new cHTTPConnection(*this);
}
m_SocketThreads.AddClient(a_Socket, Connection);
cCSLock Lock(m_CSConnections);
m_Connections.push_back(Connection);
}
void cHTTPServer::CloseConnection(cHTTPConnection & a_Connection)
{
m_SocketThreads.RemoveClient(&a_Connection);
cCSLock Lock(m_CSConnections);
for (cHTTPConnections::iterator itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (*itr == &a_Connection)
{
m_Connections.erase(itr);
break;
}
}
delete &a_Connection;
}
void cHTTPServer::NotifyConnectionWrite(cHTTPConnection & a_Connection)
{
m_SocketThreads.NotifyWrite(&a_Connection);
}
void cHTTPServer::NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request)
{
m_Callbacks->OnRequestBegun(a_Connection, a_Request);
}
void cHTTPServer::RequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size)
{
m_Callbacks->OnRequestBody(a_Connection, a_Request, a_Data, a_Size);
}
void cHTTPServer::RequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request)
{
m_Callbacks->OnRequestFinished(a_Connection, a_Request);
a_Connection.AwaitNextRequest();
}
<commit_msg>WebAdmin outputs a log message about HTTP / HTTPS status.<commit_after>
// HTTPServer.cpp
// Implements the cHTTPServer class representing a HTTP webserver that uses cListenThread and cSocketThreads for processing
#include "Globals.h"
#include "HTTPServer.h"
#include "HTTPMessage.h"
#include "HTTPConnection.h"
#include "HTTPFormParser.h"
#include "SslHTTPConnection.h"
// Disable MSVC warnings:
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4355) // 'this' : used in base member initializer list
#endif
class cDebugCallbacks :
public cHTTPServer::cCallbacks,
protected cHTTPFormParser::cCallbacks
{
virtual void OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override
{
UNUSED(a_Connection);
if (cHTTPFormParser::HasFormData(a_Request))
{
a_Request.SetUserData(new cHTTPFormParser(a_Request, *this));
}
}
virtual void OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) override
{
UNUSED(a_Connection);
cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData());
if (FormParser != NULL)
{
FormParser->Parse(a_Data, a_Size);
}
}
virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override
{
cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData());
if (FormParser != NULL)
{
if (FormParser->Finish())
{
cHTTPResponse Resp;
Resp.SetContentType("text/html");
a_Connection.Send(Resp);
a_Connection.Send("<html><body><table border=1 cellspacing=0><tr><th>Name</th><th>Value</th></tr>\r\n");
for (cHTTPFormParser::iterator itr = FormParser->begin(), end = FormParser->end(); itr != end; ++itr)
{
a_Connection.Send(Printf("<tr><td valign=\"top\"><pre>%s</pre></td><td valign=\"top\"><pre>%s</pre></td></tr>\r\n", itr->first.c_str(), itr->second.c_str()));
} // for itr - FormParser[]
a_Connection.Send("</table></body></html>");
return;
}
// Parsing failed:
cHTTPResponse Resp;
Resp.SetContentType("text/plain");
a_Connection.Send(Resp);
a_Connection.Send("Form parsing failed");
return;
}
// Test the auth failure and success:
if (a_Request.GetURL() == "/auth")
{
if (!a_Request.HasAuth() || (a_Request.GetAuthUsername() != "a") || (a_Request.GetAuthPassword() != "b"))
{
a_Connection.SendNeedAuth("MCServer WebAdmin");
return;
}
}
cHTTPResponse Resp;
Resp.SetContentType("text/plain");
a_Connection.Send(Resp);
a_Connection.Send("Hello, world");
}
virtual void OnFileStart(cHTTPFormParser & a_Parser, const AString & a_FileName) override
{
// TODO
}
virtual void OnFileData(cHTTPFormParser & a_Parser, const char * a_Data, size_t a_Size) override
{
// TODO
}
virtual void OnFileEnd(cHTTPFormParser & a_Parser) override
{
// TODO
}
} g_DebugCallbacks;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cHTTPServer:
cHTTPServer::cHTTPServer(void) :
m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer IPv4"),
m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer IPv6"),
m_Callbacks(NULL)
{
}
cHTTPServer::~cHTTPServer()
{
Stop();
}
bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_PortsIPv6)
{
// Read the HTTPS cert + key:
AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt");
AString KeyFile = cFile::ReadWholeFile("webadmin/httpskey.pem");
if (!CertFile.empty() && !KeyFile.empty())
{
m_Cert.reset(new cX509Cert);
int res = m_Cert->Parse(CertFile.data(), CertFile.size());
if (res == 0)
{
m_CertPrivKey.reset(new cCryptoKey);
int res2 = m_CertPrivKey->ParsePrivate(KeyFile.data(), KeyFile.size(), "");
if (res2 != 0)
{
// Reading the private key failed, reset the cert:
LOGWARNING("WebServer: Cannot read HTTPS certificate private key: -0x%x", -res2);
m_Cert.reset();
}
}
else
{
LOGWARNING("WebServer: Cannot read HTTPS certificate: -0x%x", -res);
}
}
// Notify the admin about the HTTPS / HTTP status
if (m_Cert.get() == NULL)
{
LOGWARNING("WebServer: The server is running in unsecure HTTP mode.");
}
else
{
LOGINFO("WebServer: The server is running in secure HTTPS mode.");
}
// Open up requested ports:
bool HasAnyPort;
HasAnyPort = m_ListenThreadIPv4.Initialize(a_PortsIPv4);
HasAnyPort = m_ListenThreadIPv6.Initialize(a_PortsIPv6) || HasAnyPort;
if (!HasAnyPort)
{
return false;
}
return true;
}
bool cHTTPServer::Start(cCallbacks & a_Callbacks)
{
m_Callbacks = &a_Callbacks;
if (!m_ListenThreadIPv4.Start())
{
return false;
}
if (!m_ListenThreadIPv6.Start())
{
m_ListenThreadIPv4.Stop();
return false;
}
return true;
}
void cHTTPServer::Stop(void)
{
m_ListenThreadIPv4.Stop();
m_ListenThreadIPv6.Stop();
// Drop all current connections:
cCSLock Lock(m_CSConnections);
while (!m_Connections.empty())
{
m_Connections.front()->Terminate();
} // for itr - m_Connections[]
}
void cHTTPServer::OnConnectionAccepted(cSocket & a_Socket)
{
cHTTPConnection * Connection;
if (m_Cert.get() != NULL)
{
Connection = new cSslHTTPConnection(*this, m_Cert, m_CertPrivKey);
}
else
{
Connection = new cHTTPConnection(*this);
}
m_SocketThreads.AddClient(a_Socket, Connection);
cCSLock Lock(m_CSConnections);
m_Connections.push_back(Connection);
}
void cHTTPServer::CloseConnection(cHTTPConnection & a_Connection)
{
m_SocketThreads.RemoveClient(&a_Connection);
cCSLock Lock(m_CSConnections);
for (cHTTPConnections::iterator itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (*itr == &a_Connection)
{
m_Connections.erase(itr);
break;
}
}
delete &a_Connection;
}
void cHTTPServer::NotifyConnectionWrite(cHTTPConnection & a_Connection)
{
m_SocketThreads.NotifyWrite(&a_Connection);
}
void cHTTPServer::NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request)
{
m_Callbacks->OnRequestBegun(a_Connection, a_Request);
}
void cHTTPServer::RequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size)
{
m_Callbacks->OnRequestBody(a_Connection, a_Request, a_Data, a_Size);
}
void cHTTPServer::RequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request)
{
m_Callbacks->OnRequestFinished(a_Connection, a_Request);
a_Connection.AwaitNextRequest();
}
<|endoftext|> |
<commit_before>// Copyright 2010-2011 Google
// 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.
//
// This model implements a simple jobshop problem.
//
// A jobshop is a standard scheduling problem where you must schedule a
// set of jobs on a set of machines. Each job is a sequence of tasks
// (a task can only start when the preceding task finished), each of
// which occupies a single specific machine during a specific
// duration. Therefore, a job is simply given by a sequence of pairs
// (machine id, duration).
// The objective is to minimize the 'makespan', which is the duration
// between the start of the first task (across all machines) and the
// completion of the last task (across all machines).
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
//
// Search will then be applied on the sequence constraints.
#include <cstdio>
#include <cstdlib>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/strtoint.h"
#include "base/file.h"
#include "base/split.h"
#include "constraint_solver/constraint_solver.h"
DEFINE_string(
data_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jssp format:\n"
" - the first line is \"instance <instance name>\"\n"
" - the second line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\"\n"
"note: jobs with one task are not supported");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
namespace operations_research {
// ----- JobShopData -----
// A JobShopData parses data files and stores all data internally for
// easy retrieval.
class JobShopData {
public:
// A task is the basic block of a jobshop.
struct Task {
Task(int j, int m, int d) : job_id(j), machine_id(m), duration(d) {}
int job_id;
int machine_id;
int duration;
};
JobShopData()
: name_(""),
machine_count_(0),
job_count_(0),
horizon_(0),
current_job_index_(0) {}
~JobShopData() {}
// Parses a file in jssp format and loads the model. See the flag
// --data_file for a description of the format. Note that the format
// is only partially checked: bad inputs might cause undefined
// behavior.
void Load(const string& filename) {
const int kMaxLineLength = 1024;
File* const data_file = File::Open(filename, "r");
scoped_array<char> line(new char[kMaxLineLength]);
while (data_file->ReadLine(line.get(), kMaxLineLength)) {
ProcessNewLine(line.get());
}
data_file->Close();
}
// The number of machines in the jobshop.
int machine_count() const { return machine_count_; }
// The number of jobs in the jobshop.
int job_count() const { return job_count_; }
// The name of the jobshop instance.
const string& name() const { return name_; }
// The horizon of the workshop (the sum of all durations), which is
// a trivial upper bound of the optimal make_span.
int horizon() const { return horizon_; }
// Returns the tasks of a job, ordered by precedence.
const std::vector<Task>& TasksOfJob(int job_id) const {
return all_tasks_[job_id];
}
private:
void ProcessNewLine(char* const line) {
// TODO(user): more robust logic to support single-task jobs.
static const char kWordDelimiters[] = " ";
std::vector<string> words;
SplitStringUsing(line, kWordDelimiters, &words);
if (words.size() == 2) {
if (words[0] == "instance") {
LOG(INFO) << "Name = " << words[1];
name_ = words[1];
} else {
job_count_ = atoi32(words[0]);
machine_count_ = atoi32(words[1]);
CHECK_GT(machine_count_, 0);
CHECK_GT(job_count_, 0);
LOG(INFO) << machine_count_ << " machines and "
<< job_count_ << " jobs";
all_tasks_.resize(job_count_);
}
}
if (words.size() > 2 && machine_count_ != 0) {
CHECK_EQ(words.size(), machine_count_ * 2);
for (int i = 0; i < machine_count_; ++i) {
const int machine_id = atoi32(words[2 * i]);
const int duration = atoi32(words[2 * i + 1]);
AddTask(current_job_index_, machine_id, duration);
}
current_job_index_++;
}
}
void AddTask(int job_id, int machine_id, int duration) {
all_tasks_[job_id].push_back(Task(job_id, machine_id, duration));
horizon_ += duration;
}
string name_;
int machine_count_;
int job_count_;
int horizon_;
std::vector<std::vector<Task> > all_tasks_;
int current_job_index_;
};
void Jobshop(const JobShopData& data) {
Solver solver("jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const std::vector<JobShopData::Task>& tasks = data.TasksOfJob(job_id);
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const JobShopData::Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Creates array of end_times of jobs.
std::vector<IntVar*> all_ends;
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
IntervalVar* const task = jobs_to_tasks[job_id][task_count - 1];
all_ends.push_back(task->EndExpr()->Var());
}
// Objective: minimize the makespan (maximum end times of all tasks)
// of the problem.
IntVar* const objective_var = solver.MakeMax(all_ends)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_data_file.empty()) {
LOG(FATAL) << "Please supply a data file with --data_file=";
}
operations_research::JobShopData data;
data.Load(FLAGS_data_file);
operations_research::Jobshop(data);
return 0;
}
<commit_msg>better behavior of jobshop<commit_after>// Copyright 2010-2011 Google
// 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.
//
// This model implements a simple jobshop problem.
//
// A jobshop is a standard scheduling problem where you must schedule a
// set of jobs on a set of machines. Each job is a sequence of tasks
// (a task can only start when the preceding task finished), each of
// which occupies a single specific machine during a specific
// duration. Therefore, a job is simply given by a sequence of pairs
// (machine id, duration).
// The objective is to minimize the 'makespan', which is the duration
// between the start of the first task (across all machines) and the
// completion of the last task (across all machines).
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
//
// Search will then be applied on the sequence constraints.
#include <cstdio>
#include <cstdlib>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/strtoint.h"
#include "base/file.h"
#include "base/split.h"
#include "constraint_solver/constraint_solver.h"
DEFINE_string(
data_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jssp format:\n"
" - the first line is \"instance <instance name>\"\n"
" - the second line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\"\n"
"note: jobs with one task are not supported");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
namespace operations_research {
// ----- JobShopData -----
// A JobShopData parses data files and stores all data internally for
// easy retrieval.
class JobShopData {
public:
// A task is the basic block of a jobshop.
struct Task {
Task(int j, int m, int d) : job_id(j), machine_id(m), duration(d) {}
int job_id;
int machine_id;
int duration;
};
JobShopData()
: name_(""),
machine_count_(0),
job_count_(0),
horizon_(0),
current_job_index_(0) {}
~JobShopData() {}
// Parses a file in jssp format and loads the model. See the flag
// --data_file for a description of the format. Note that the format
// is only partially checked: bad inputs might cause undefined
// behavior.
void Load(const string& filename) {
const int kMaxLineLength = 1024;
File* const data_file = File::Open(filename, "r");
scoped_array<char> line(new char[kMaxLineLength]);
while (data_file->ReadLine(line.get(), kMaxLineLength)) {
ProcessNewLine(line.get());
}
data_file->Close();
}
// The number of machines in the jobshop.
int machine_count() const { return machine_count_; }
// The number of jobs in the jobshop.
int job_count() const { return job_count_; }
// The name of the jobshop instance.
const string& name() const { return name_; }
// The horizon of the workshop (the sum of all durations), which is
// a trivial upper bound of the optimal make_span.
int horizon() const { return horizon_; }
// Returns the tasks of a job, ordered by precedence.
const std::vector<Task>& TasksOfJob(int job_id) const {
return all_tasks_[job_id];
}
private:
void ProcessNewLine(char* const line) {
// TODO(user): more robust logic to support single-task jobs.
static const char kWordDelimiters[] = " ";
std::vector<string> words;
SplitStringUsing(line, kWordDelimiters, &words);
if (words.size() == 2) {
if (words[0] == "instance") {
LOG(INFO) << "Name = " << words[1];
name_ = words[1];
} else {
job_count_ = atoi32(words[0]);
machine_count_ = atoi32(words[1]);
CHECK_GT(machine_count_, 0);
CHECK_GT(job_count_, 0);
LOG(INFO) << machine_count_ << " machines and "
<< job_count_ << " jobs";
all_tasks_.resize(job_count_);
}
}
if (words.size() > 2 && machine_count_ != 0) {
CHECK_EQ(words.size(), machine_count_ * 2);
for (int i = 0; i < machine_count_; ++i) {
const int machine_id = atoi32(words[2 * i]);
const int duration = atoi32(words[2 * i + 1]);
AddTask(current_job_index_, machine_id, duration);
}
current_job_index_++;
}
}
void AddTask(int job_id, int machine_id, int duration) {
all_tasks_[job_id].push_back(Task(job_id, machine_id, duration));
horizon_ += duration;
}
string name_;
int machine_count_;
int job_count_;
int horizon_;
std::vector<std::vector<Task> > all_tasks_;
int current_job_index_;
};
void Jobshop(const JobShopData& data) {
Solver solver("jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const std::vector<JobShopData::Task>& tasks = data.TasksOfJob(job_id);
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const JobShopData::Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Creates array of end_times of jobs.
std::vector<IntVar*> all_ends;
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
IntervalVar* const task = jobs_to_tasks[job_id][task_count - 1];
all_ends.push_back(task->EndExpr()->Var());
}
// Objective: minimize the makespan (maximum end times of all tasks)
// of the problem.
IntVar* const objective_var = solver.MakeMax(all_ends)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_data_file.empty()) {
LOG(INFO) << "Please supply a data file with --data_file=";
return 0;
}
operations_research::JobShopData data;
data.Load(FLAGS_data_file);
operations_research::Jobshop(data);
return 0;
}
<|endoftext|> |
<commit_before>/*
TCPConnector.h
TCPConnector class definition. TCPConnector provides methods to actively
establish TCP/IP connections with a server.
------------------------------------------
Copyright 2013 [Vic Hargrave - http://vichargrave.com]
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 "TCPConnector.h"
#include <errno.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#ifdef _WIN32
#include <WinSock2.h>
#include <WS2tcpip.h>
#else
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#include "TCPStream.h"
#include "llvm/SmallString.h"
#include "../Log.h"
#include "SocketError.h"
using namespace tcpsockets;
static int ResolveHostName(const char* hostname, struct in_addr* addr) {
struct addrinfo* res;
int result = getaddrinfo(hostname, nullptr, nullptr, &res);
if (result == 0) {
std::memcpy(addr, &((struct sockaddr_in*)res->ai_addr)->sin_addr,
sizeof(struct in_addr));
freeaddrinfo(res);
}
return result;
}
std::unique_ptr<NetworkStream> TCPConnector::connect(const char* server,
int port, int timeout) {
#ifdef _WIN32
struct WSAHelper {
WSAHelper() {
WSAData wsaData;
WORD wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
}
~WSAHelper() { WSACleanup(); }
};
static WSAHelper helper;
#endif
struct sockaddr_in address;
std::memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
if (ResolveHostName(server, &(address.sin_addr)) != 0) {
#ifdef _WIN32
llvm::SmallString<128> addr_copy(server);
addr_copy.push_back('\0');
int size = sizeof(address);
WSAStringToAddress(addr_copy.data(), PF_INET, nullptr, (struct sockaddr*)&address, &size);
#else
inet_pton(PF_INET, server, &(address.sin_addr));
#endif
}
address.sin_port = htons(port);
if (timeout == 0) {
int sd = socket(AF_INET, SOCK_STREAM, 0);
if (::connect(sd, (struct sockaddr*)&address, sizeof(address)) != 0) {
DEBUG("connect() failed: " << SocketStrerror());
return nullptr;
}
return std::unique_ptr<NetworkStream>(new TCPStream(sd, &address));
}
long arg;
fd_set sdset;
struct timeval tv;
socklen_t len;
int result = -1, valopt, sd = socket(AF_INET, SOCK_STREAM, 0);
// Set socket to non-blocking
#ifdef _WIN32
u_long mode = 1;
ioctlsocket(sd, FIONBIO, &mode);
#else
arg = fcntl(sd, F_GETFL, nullptr);
arg |= O_NONBLOCK;
fcntl(sd, F_SETFL, arg);
#endif
// Connect with time limit
if ((result = ::connect(sd, (struct sockaddr*)&address, sizeof(address))) <
0) {
int my_errno = SocketErrno();
#ifdef _WIN32
if (my_errno == WSAEWOULDBLOCK || my_errno == WSAEINPROGRESS) {
#else
if (my_errno == EWOULDBLOCK || my_errno == EINPROGRESS) {
#endif
tv.tv_sec = timeout;
tv.tv_usec = 0;
FD_ZERO(&sdset);
FD_SET(sd, &sdset);
if (select(sd + 1, nullptr, &sdset, nullptr, &tv) > 0) {
len = sizeof(int);
getsockopt(sd, SOL_SOCKET, SO_ERROR, (char*)(&valopt), &len);
if (valopt) {
DEBUG("select() error " << valopt << " - " << SocketStrerror(valopt));
}
// connection established
else
result = 0;
} else
DEBUG("connect() timed out");
} else
DEBUG("connect() error " << SocketErrno() << " - " << SocketStrerror());
}
// Return socket to blocking mode
#ifdef _WIN32
mode = 0;
ioctlsocket(sd, FIONBIO, &mode);
#else
arg = fcntl(sd, F_GETFL, nullptr);
arg &= (~O_NONBLOCK);
fcntl(sd, F_SETFL, arg);
#endif
// Create stream object if connected
if (result == -1) return nullptr;
return std::unique_ptr<NetworkStream>(new TCPStream(sd, &address));
}
<commit_msg>Silence unused variable warning.<commit_after>/*
TCPConnector.h
TCPConnector class definition. TCPConnector provides methods to actively
establish TCP/IP connections with a server.
------------------------------------------
Copyright 2013 [Vic Hargrave - http://vichargrave.com]
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 "TCPConnector.h"
#include <errno.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#ifdef _WIN32
#include <WinSock2.h>
#include <WS2tcpip.h>
#else
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#include "TCPStream.h"
#include "llvm/SmallString.h"
#include "../Log.h"
#include "SocketError.h"
using namespace tcpsockets;
static int ResolveHostName(const char* hostname, struct in_addr* addr) {
struct addrinfo* res;
int result = getaddrinfo(hostname, nullptr, nullptr, &res);
if (result == 0) {
std::memcpy(addr, &((struct sockaddr_in*)res->ai_addr)->sin_addr,
sizeof(struct in_addr));
freeaddrinfo(res);
}
return result;
}
std::unique_ptr<NetworkStream> TCPConnector::connect(const char* server,
int port, int timeout) {
#ifdef _WIN32
struct WSAHelper {
WSAHelper() {
WSAData wsaData;
WORD wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
}
~WSAHelper() { WSACleanup(); }
};
static WSAHelper helper;
#endif
struct sockaddr_in address;
std::memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
if (ResolveHostName(server, &(address.sin_addr)) != 0) {
#ifdef _WIN32
llvm::SmallString<128> addr_copy(server);
addr_copy.push_back('\0');
int size = sizeof(address);
WSAStringToAddress(addr_copy.data(), PF_INET, nullptr, (struct sockaddr*)&address, &size);
#else
inet_pton(PF_INET, server, &(address.sin_addr));
#endif
}
address.sin_port = htons(port);
if (timeout == 0) {
int sd = socket(AF_INET, SOCK_STREAM, 0);
if (::connect(sd, (struct sockaddr*)&address, sizeof(address)) != 0) {
DEBUG("connect() failed: " << SocketStrerror());
return nullptr;
}
return std::unique_ptr<NetworkStream>(new TCPStream(sd, &address));
}
fd_set sdset;
struct timeval tv;
socklen_t len;
int result = -1, valopt, sd = socket(AF_INET, SOCK_STREAM, 0);
// Set socket to non-blocking
#ifdef _WIN32
u_long mode = 1;
ioctlsocket(sd, FIONBIO, &mode);
#else
long arg;
arg = fcntl(sd, F_GETFL, nullptr);
arg |= O_NONBLOCK;
fcntl(sd, F_SETFL, arg);
#endif
// Connect with time limit
if ((result = ::connect(sd, (struct sockaddr*)&address, sizeof(address))) <
0) {
int my_errno = SocketErrno();
#ifdef _WIN32
if (my_errno == WSAEWOULDBLOCK || my_errno == WSAEINPROGRESS) {
#else
if (my_errno == EWOULDBLOCK || my_errno == EINPROGRESS) {
#endif
tv.tv_sec = timeout;
tv.tv_usec = 0;
FD_ZERO(&sdset);
FD_SET(sd, &sdset);
if (select(sd + 1, nullptr, &sdset, nullptr, &tv) > 0) {
len = sizeof(int);
getsockopt(sd, SOL_SOCKET, SO_ERROR, (char*)(&valopt), &len);
if (valopt) {
DEBUG("select() error " << valopt << " - " << SocketStrerror(valopt));
}
// connection established
else
result = 0;
} else
DEBUG("connect() timed out");
} else
DEBUG("connect() error " << SocketErrno() << " - " << SocketStrerror());
}
// Return socket to blocking mode
#ifdef _WIN32
mode = 0;
ioctlsocket(sd, FIONBIO, &mode);
#else
arg = fcntl(sd, F_GETFL, nullptr);
arg &= (~O_NONBLOCK);
fcntl(sd, F_SETFL, arg);
#endif
// Create stream object if connected
if (result == -1) return nullptr;
return std::unique_ptr<NetworkStream>(new TCPStream(sd, &address));
}
<|endoftext|> |
<commit_before>void Config()
{
new AliGeant3("C++ Interface to Geant3");
//=======================================================================
// Create the output file
TFile *rootfile = new TFile("galice.root","recreate");
rootfile->SetCompressionLevel(2);
TGeant3 *geant3 = (TGeant3*)gMC;
//=======================================================================
// ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
geant3->SetTRIG(1); //Number of events to be processed
geant3->SetSWIT(4,10);
geant3->SetDEBU(0,0,1);
//geant3->SetSWIT(2,2);
geant3->SetDCAY(1);
geant3->SetPAIR(1);
geant3->SetCOMP(1);
geant3->SetPHOT(1);
geant3->SetPFIS(0);
geant3->SetDRAY(0);
geant3->SetANNI(1);
geant3->SetBREM(1);
geant3->SetMUNU(1);
geant3->SetCKOV(1);
geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)
geant3->SetLOSS(2);
geant3->SetMULS(1);
geant3->SetRAYL(1);
geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0)
geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks
geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2)
geant3->SetERAN(5.e-7);
Float_t cut = 1.e-3; // 1MeV cut by default
Float_t tofmax = 1.e10;
// GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX
geant3->SetCUTS(cut,cut, cut, cut, cut, cut, cut, cut, cut, cut, tofmax);
//
//=======================================================================
// ************* STEERING parameters FOR ALICE SIMULATION **************
// --- Specify event type to be tracked through the ALICE setup
// --- All positions are in cm, angles in degrees, and P and E in GeV
AliGenHIJINGpara *gener = new AliGenHIJINGpara(50);
gener->SetMomentumRange(0,999);
gener->SetPhiRange(0,360);
gener->SetThetaRange(10,170);
gener->SetOrigin(0,0,0); //vertex position
gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->Init();
//
// Activate this line if you want the vertex smearing to happen
// track by track
//
//gener->SetVertexSmear(perTrack);
gAlice->SetField(-999,2); //Specify maximum magnetic field in Tesla (neg. ==> default field)
Int_t iMAG=1;
Int_t iITS=1;
Int_t iTPC=1;
Int_t iTOF=1;
Int_t iRICH=1;
Int_t iZDC=0;
Int_t iCASTOR=1;
Int_t iTRD=1;
Int_t iABSO=1;
Int_t iDIPO=1;
Int_t iHALL=1;
Int_t iFRAME=1;
Int_t iSHIL=1;
Int_t iPIPE=1;
Int_t iFMD=1;
Int_t iMUON=1;
Int_t iPHOS=1;
Int_t iPMD=1;
Int_t iSTART=0;
//=================== Alice BODY parameters =============================
AliBODY *BODY = new AliBODY("BODY","Alice envelop");
if(iMAG) {
//=================== MAG parameters ============================
// --- Start with Magnet since detector layouts may be depending ---
// --- on the selected Magnet dimensions ---
AliMAG *MAG = new AliMAG("MAG","Magnet");
}
if(iABSO) {
//=================== ABSO parameters ============================
AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber");
}
if(iDIPO) {
//=================== DIPO parameters ============================
AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2");
}
if(iHALL) {
//=================== HALL parameters ============================
AliHALL *HALL = new AliHALL("HALL","Alice Hall");
}
if(iFRAME) {
//=================== FRAME parameters ============================
AliFRAME *FRAME = new AliFRAMEv1("FRAME","Space Frame");
}
if(iSHIL) {
//=================== SHIL parameters ============================
AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding");
}
if(iPIPE) {
//=================== PIPE parameters ============================
AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe");
}
if(iITS) {
//=================== ITS parameters ============================
//
// EUCLID is a flag to output (=1) both geometry and media to two ASCII files
// (called by default ITSgeometry.euc and ITSgeometry.tme) in a format
// understandable to the CAD system EUCLID. The default (=0) means that you
// dont want to use this facility.
//
AliITS *ITS = new AliITSv5("ITS","normal ITS");
ITS->SetEUCLID(0);
}
if(iTPC) {
//============================ TPC parameters ================================
// --- This allows the user to specify sectors for the SLOW (TPC geometry 2)
// --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper)
// --- sectors are specified, any value other than that requires at least one
// --- sector (lower or upper)to be specified!
// --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0)
// --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0)
// --- SecLows - number of lower sectors specified (up to 6)
// --- SecUps - number of upper sectors specified (up to 12)
// --- Sens - sensitive strips for the Slow Simulator !!!
// --- This does NOT work if all S or L-sectors are specified, i.e.
// --- if SecAL or SecAU < 0
//
//
//-----------------------------------------------------------------------------
// gROOT->LoadMacro("SetTPCParam.C");
// AliTPCParam *param = SetTPCParam();
AliTPC *TPC = new AliTPCv1("TPC","Default"); //v1 is default
// TPC->SetParam(param); // pass the parameter object to the TPC
// set gas mixture
//TPC->SetGasMixt(2,20,10,-1,0.9,0.1,0.);
//TPC->SetSecAL(4);
//TPC->SetSecAU(4);
//TPC->SetSecLows(1, 2, 3, 19, 20, 21);
//TPC->SetSecUps(37, 38, 39, 37+18, 38+18, 39+18, -1, -1, -1, -1, -1, -1);
//TPC->SetSens(1);
//if (TPC->IsVersion()==1) param->Write(param->GetTitle());
}
if(iTOF) {
//=================== TOF parameters ============================
AliTOF *TOF = new AliTOFv1("TOF","normal TOF");
}
if(iRICH) {
//=================== RICH parameters ===========================
AliRICH *RICH = new AliRICHv1("RICH","normal RICH");
}
if(iZDC) {
//=================== ZDC parameters ============================
AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC");
}
if(iCASTOR) {
//=================== CASTOR parameters ============================
AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR");
}
if(iTRD) {
//=================== TRD parameters ============================
AliTRD *TRD = new AliTRDv0("TRD","TRD fast simulator");
//TRD->SetHits();
//AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator");
//TRD->SetSensPlane(0);
//TRD->SetSensChamber(2);
//TRD->SetSensSector(17);
// Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2)
TRD->SetGasMix(1);
// With hole in front of PHOS
TRD->SetPHOShole();
// With hole in front of RICH
TRD->SetRICHhole();
}
if(iFMD) {
//=================== FMD parameters ============================
AliFMD *FMD = new AliFMDv1("FMD","normal FMD");
}
if(iMUON) {
//=================== MUON parameters ===========================
AliMUON *MUON = new AliMUONv0("MUON","normal MUON");
}
//=================== PHOS parameters ===========================
if(iPHOS) {
AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2");
}
if(iPMD) {
//=================== PMD parameters ============================
AliPMD *PMD = new AliPMDv0("PMD","normal PMD");
PMD->SetPAR(1., 1., 0.8, 0.02);
PMD->SetIN(6., 18., -580., 27., 27.);
PMD->SetGEO(0.0, 0.2, 4.);
PMD->SetPadSize(0.8, 1.0, 1.0, 1.5);
}
if(iSTART) {
//=================== START parameters ============================
AliSTART *START = new AliSTARTv0("START","START Detector");
}
}
<commit_msg>Add configuration of external decayer.<commit_after>void Config()
{
new AliGeant3("C++ Interface to Geant3");
//=======================================================================
// Create the output file
TFile *rootfile = new TFile("galice.root","recreate");
rootfile->SetCompressionLevel(2);
TGeant3 *geant3 = (TGeant3*)gMC;
//
// Set External decayer
AliDecayer* decayer = new AliDecayerPythia();
decayer->SetForceDecay(all);
decayer->Init();
gMC->SetExternalDecayer(decayer);
//
//
//=======================================================================
// ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
geant3->SetTRIG(1); //Number of events to be processed
geant3->SetSWIT(4,10);
geant3->SetDEBU(0,0,1);
//geant3->SetSWIT(2,2);
geant3->SetDCAY(1);
geant3->SetPAIR(1);
geant3->SetCOMP(1);
geant3->SetPHOT(1);
geant3->SetPFIS(0);
geant3->SetDRAY(0);
geant3->SetANNI(1);
geant3->SetBREM(1);
geant3->SetMUNU(1);
geant3->SetCKOV(1);
geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)
geant3->SetLOSS(2);
geant3->SetMULS(1);
geant3->SetRAYL(1);
geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0)
geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks
geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2)
geant3->SetERAN(5.e-7);
Float_t cut = 1.e-3; // 1MeV cut by default
Float_t tofmax = 1.e10;
// GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX
geant3->SetCUTS(cut,cut, cut, cut, cut, cut, cut, cut, cut, cut, tofmax);
//
//=======================================================================
// ************* STEERING parameters FOR ALICE SIMULATION **************
// --- Specify event type to be tracked through the ALICE setup
// --- All positions are in cm, angles in degrees, and P and E in GeV
AliGenHIJINGpara *gener = new AliGenHIJINGpara(50);
gener->SetMomentumRange(0,999);
gener->SetPhiRange(0,360);
gener->SetThetaRange(10,170);
gener->SetOrigin(0,0,0); //vertex position
gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->Init();
//
// Activate this line if you want the vertex smearing to happen
// track by track
//
//gener->SetVertexSmear(perTrack);
gAlice->SetField(-999,2); //Specify maximum magnetic field in Tesla (neg. ==> default field)
Int_t iMAG=1;
Int_t iITS=1;
Int_t iTPC=1;
Int_t iTOF=1;
Int_t iRICH=1;
Int_t iZDC=0;
Int_t iCASTOR=1;
Int_t iTRD=1;
Int_t iABSO=1;
Int_t iDIPO=1;
Int_t iHALL=1;
Int_t iFRAME=1;
Int_t iSHIL=1;
Int_t iPIPE=1;
Int_t iFMD=1;
Int_t iMUON=1;
Int_t iPHOS=1;
Int_t iPMD=1;
Int_t iSTART=0;
//=================== Alice BODY parameters =============================
AliBODY *BODY = new AliBODY("BODY","Alice envelop");
if(iMAG) {
//=================== MAG parameters ============================
// --- Start with Magnet since detector layouts may be depending ---
// --- on the selected Magnet dimensions ---
AliMAG *MAG = new AliMAG("MAG","Magnet");
}
if(iABSO) {
//=================== ABSO parameters ============================
AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber");
}
if(iDIPO) {
//=================== DIPO parameters ============================
AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2");
}
if(iHALL) {
//=================== HALL parameters ============================
AliHALL *HALL = new AliHALL("HALL","Alice Hall");
}
if(iFRAME) {
//=================== FRAME parameters ============================
AliFRAME *FRAME = new AliFRAMEv1("FRAME","Space Frame");
}
if(iSHIL) {
//=================== SHIL parameters ============================
AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding");
}
if(iPIPE) {
//=================== PIPE parameters ============================
AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe");
}
if(iITS) {
//=================== ITS parameters ============================
//
// EUCLID is a flag to output (=1) both geometry and media to two ASCII files
// (called by default ITSgeometry.euc and ITSgeometry.tme) in a format
// understandable to the CAD system EUCLID. The default (=0) means that you
// dont want to use this facility.
//
AliITS *ITS = new AliITSv5("ITS","normal ITS");
ITS->SetEUCLID(0);
}
if(iTPC) {
//============================ TPC parameters ================================
// --- This allows the user to specify sectors for the SLOW (TPC geometry 2)
// --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper)
// --- sectors are specified, any value other than that requires at least one
// --- sector (lower or upper)to be specified!
// --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0)
// --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0)
// --- SecLows - number of lower sectors specified (up to 6)
// --- SecUps - number of upper sectors specified (up to 12)
// --- Sens - sensitive strips for the Slow Simulator !!!
// --- This does NOT work if all S or L-sectors are specified, i.e.
// --- if SecAL or SecAU < 0
//
//
//-----------------------------------------------------------------------------
// gROOT->LoadMacro("SetTPCParam.C");
// AliTPCParam *param = SetTPCParam();
AliTPC *TPC = new AliTPCv1("TPC","Default"); //v1 is default
// TPC->SetParam(param); // pass the parameter object to the TPC
// set gas mixture
//TPC->SetGasMixt(2,20,10,-1,0.9,0.1,0.);
//TPC->SetSecAL(4);
//TPC->SetSecAU(4);
//TPC->SetSecLows(1, 2, 3, 19, 20, 21);
//TPC->SetSecUps(37, 38, 39, 37+18, 38+18, 39+18, -1, -1, -1, -1, -1, -1);
//TPC->SetSens(1);
//if (TPC->IsVersion()==1) param->Write(param->GetTitle());
}
if(iTOF) {
//=================== TOF parameters ============================
AliTOF *TOF = new AliTOFv1("TOF","normal TOF");
}
if(iRICH) {
//=================== RICH parameters ===========================
AliRICH *RICH = new AliRICHv1("RICH","normal RICH");
}
if(iZDC) {
//=================== ZDC parameters ============================
AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC");
}
if(iCASTOR) {
//=================== CASTOR parameters ============================
AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR");
}
if(iTRD) {
//=================== TRD parameters ============================
AliTRD *TRD = new AliTRDv0("TRD","TRD fast simulator");
//TRD->SetHits();
//AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator");
//TRD->SetSensPlane(0);
//TRD->SetSensChamber(2);
//TRD->SetSensSector(17);
// Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2)
TRD->SetGasMix(1);
// With hole in front of PHOS
TRD->SetPHOShole();
// With hole in front of RICH
TRD->SetRICHhole();
}
if(iFMD) {
//=================== FMD parameters ============================
AliFMD *FMD = new AliFMDv1("FMD","normal FMD");
}
if(iMUON) {
//=================== MUON parameters ===========================
AliMUON *MUON = new AliMUONv0("MUON","normal MUON");
}
//=================== PHOS parameters ===========================
if(iPHOS) {
AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2");
}
if(iPMD) {
//=================== PMD parameters ============================
AliPMD *PMD = new AliPMDv0("PMD","normal PMD");
PMD->SetPAR(1., 1., 0.8, 0.02);
PMD->SetIN(6., 18., -580., 27., 27.);
PMD->SetGEO(0.0, 0.2, 4.);
PMD->SetPadSize(0.8, 1.0, 1.0, 1.5);
}
if(iSTART) {
//=================== START parameters ============================
AliSTART *START = new AliSTARTv0("START","START Detector");
}
}
<|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/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLUTF8Transcoder.hpp>
#include <util/UTFDataFormatException.hpp>
// ---------------------------------------------------------------------------
// Local static data
//
// gUTFBytes
// A list of counts of trailing bytes for each initial byte in the input.
//
// gUTFOffsets
// A list of values to offset each result char type, according to how
// many source bytes when into making it.
// ---------------------------------------------------------------------------
static const XMLByte gUTFBytes[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
};
static const XMLUInt32 gUTFOffsets[6] =
{
0, 0x3080, 0xE2080, 0x3C82080, 0xFA082080, 0x82022080
};
// ---------------------------------------------------------------------------
// XMLUTF8Transcoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLUTF8Transcoder::XMLUTF8Transcoder(const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
, fSpareCh(0)
{
}
XMLUTF8Transcoder::~XMLUTF8Transcoder()
{
}
// ---------------------------------------------------------------------------
// XMLUTF8Transcoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
bool XMLUTF8Transcoder::supportsSrcOfs() const
{
// Yes we support this
return true;
}
XMLCh
XMLUTF8Transcoder::transcodeOne(const XMLByte* const srcData
, const unsigned int srcBytes
, unsigned int& bytesEaten)
{
// If there is a spare char, then do that first
if (fSpareCh)
{
const XMLCh retCh = fSpareCh;
fSpareCh = 0;
return retCh;
}
// If there are no bytes, then give up now
if (!srcBytes)
return 0;
// Just call the other version with a max of one output character
XMLCh chTarget;
unsigned char dummy;
if (!transcodeXML(srcData, srcBytes, &chTarget, 1, bytesEaten, &dummy))
return 0;
return chTarget;
}
unsigned int
XMLUTF8Transcoder::transcodeXML(const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
// This will track the target chars we've transcoded out so far
unsigned int charsRead = 0;
//
// If we have a spare, then store it first and zero out the spare.
// Be sure to bump the count of chars read.
//
if (fSpareCh)
{
//
// A spare is a trailing surrogate. So it actually takes up no
// space in the source data. Its leading surrogate accounted for
// all the bytes eaten.
//
charSizes[charsRead] = 0;
toFill[charsRead++] = fSpareCh;
fSpareCh = 0;
}
//
// Just loop until we run out of input or hit the max chars that
// was requested.
//
bytesEaten = 0;
const XMLByte* srcPtr = srcData;
while (charsRead < maxChars)
{
// See how many trailing src bytes this sequence is going to require
const unsigned int trailingBytes = gUTFBytes[*srcPtr];
//
// If there are not enough source bytes to do this one, then we
// are done.
//
if (bytesEaten + trailingBytes >= srcCount)
break;
// Looks ok, so lets build up the value
XMLUInt32 tmpVal = 0;
switch(trailingBytes)
{
case 5 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 4 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 3 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 2 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 1 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 0 : tmpVal += *srcPtr++;
}
tmpVal -= gUTFOffsets[trailingBytes];
//
// If it will fit into a single char, then put it in. Otherwise
// encode it as a surrogate pair. If its not valid, use the
// replacement char.
//
if (!(tmpVal & 0xFFFF0000))
{
charSizes[charsRead] = trailingBytes + 1;
toFill[charsRead++] = XMLCh(tmpVal);
}
else if (tmpVal > 0x10FFFF)
{
//
// If we've gotten more than 32 chars so far, then just break
// out for now and lets process those. When we come back in
// here again, we'll get no chars and throw an exception. This
// way, the error will have a line and col number closer to
// the real problem area.
//
if (charsRead > 32)
break;
ThrowXML(UTFDataFormatException, XMLExcepts::Reader_BadUTF8Seq);
}
else
{
// Store the leading surrogate char
tmpVal -= 0x10000;
charSizes[charsRead] = trailingBytes + 1;
toFill[charsRead++] = XMLCh((tmpVal >> 10) + 0xD800);
//
// If we don't have room for the trailing one, then store
// it in the spare char. Else store it in the buffer.
//
if (charsRead >= maxChars)
{
fSpareCh = XMLCh(tmpVal & 0x3FF) + 0xDC00;
}
else
{
// This one accounts for no bytes eaten
charSizes[charsRead] = 0;
toFill[charsRead++] = XMLCh(tmpVal & 0x3FF) + 0xDC00;
}
}
// Update the bytes eaten
bytesEaten += trailingBytes + 1;
}
// Return the characters read
return charsRead;
}
<commit_msg>Optimize the transcode loop for ascii chars.<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/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLUTF8Transcoder.hpp>
#include <util/UTFDataFormatException.hpp>
// ---------------------------------------------------------------------------
// Local static data
//
// gUTFBytes
// A list of counts of trailing bytes for each initial byte in the input.
//
// gUTFOffsets
// A list of values to offset each result char type, according to how
// many source bytes when into making it.
// ---------------------------------------------------------------------------
static const XMLByte gUTFBytes[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
};
static const XMLUInt32 gUTFOffsets[6] =
{
0, 0x3080, 0xE2080, 0x3C82080, 0xFA082080, 0x82022080
};
// ---------------------------------------------------------------------------
// XMLUTF8Transcoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLUTF8Transcoder::XMLUTF8Transcoder(const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
, fSpareCh(0)
{
}
XMLUTF8Transcoder::~XMLUTF8Transcoder()
{
}
// ---------------------------------------------------------------------------
// XMLUTF8Transcoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
bool XMLUTF8Transcoder::supportsSrcOfs() const
{
// Yes we support this
return true;
}
XMLCh
XMLUTF8Transcoder::transcodeOne(const XMLByte* const srcData
, const unsigned int srcBytes
, unsigned int& bytesEaten)
{
// If there is a spare char, then do that first
if (fSpareCh)
{
const XMLCh retCh = fSpareCh;
fSpareCh = 0;
return retCh;
}
// If there are no bytes, then give up now
if (!srcBytes)
return 0;
// Just call the other version with a max of one output character
XMLCh chTarget;
unsigned char dummy;
if (!transcodeXML(srcData, srcBytes, &chTarget, 1, bytesEaten, &dummy))
return 0;
return chTarget;
}
unsigned int
XMLUTF8Transcoder::transcodeXML(const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
// This will track the target chars we've transcoded out so far
unsigned int charsRead = 0;
//
// If we have a spare, then store it first and zero out the spare.
// Be sure to bump the count of chars read.
//
if (fSpareCh)
{
//
// A spare is a trailing surrogate. So it actually takes up no
// space in the source data. Its leading surrogate accounted for
// all the bytes eaten.
//
charSizes[charsRead] = 0;
toFill[charsRead++] = fSpareCh;
fSpareCh = 0;
}
//
// Just loop until we run out of input or hit the max chars that
// was requested.
//
bytesEaten = 0;
const XMLByte* srcPtr = srcData;
while (charsRead < maxChars)
{
// Special-case ASCII, which is a leading byte value of <= 127
const XMLByte firstByte = *srcPtr;
if (firstByte <= 127)
{
toFill[charsRead++] = XMLCh(firstByte);
srcPtr++;
bytesEaten++;
if (bytesEaten >= srcCount)
break;
continue;
}
// See how many trailing src bytes this sequence is going to require
const unsigned int trailingBytes = gUTFBytes[*srcPtr];
//
// If there are not enough source bytes to do this one, then we
// are done.
//
if (bytesEaten + trailingBytes >= srcCount)
break;
// Looks ok, so lets build up the value
XMLUInt32 tmpVal = 0;
switch(trailingBytes)
{
case 5 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 4 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 3 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 2 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 1 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 0 : tmpVal += *srcPtr++;
}
tmpVal -= gUTFOffsets[trailingBytes];
//
// If it will fit into a single char, then put it in. Otherwise
// encode it as a surrogate pair. If its not valid, use the
// replacement char.
//
if (!(tmpVal & 0xFFFF0000))
{
charSizes[charsRead] = trailingBytes + 1;
toFill[charsRead++] = XMLCh(tmpVal);
}
else if (tmpVal > 0x10FFFF)
{
//
// If we've gotten more than 32 chars so far, then just break
// out for now and lets process those. When we come back in
// here again, we'll get no chars and throw an exception. This
// way, the error will have a line and col number closer to
// the real problem area.
//
if (charsRead > 32)
break;
ThrowXML(UTFDataFormatException, XMLExcepts::Reader_BadUTF8Seq);
}
else
{
// Store the leading surrogate char
tmpVal -= 0x10000;
charSizes[charsRead] = trailingBytes + 1;
toFill[charsRead++] = XMLCh((tmpVal >> 10) + 0xD800);
//
// If we don't have room for the trailing one, then store
// it in the spare char. Else store it in the buffer.
//
if (charsRead >= maxChars)
{
fSpareCh = XMLCh(tmpVal & 0x3FF) + 0xDC00;
}
else
{
// This one accounts for no bytes eaten
charSizes[charsRead] = 0;
toFill[charsRead++] = XMLCh(tmpVal & 0x3FF) + 0xDC00;
}
}
// Update the bytes eaten
bytesEaten += trailingBytes + 1;
}
// Return the characters read
return charsRead;
}
<|endoftext|> |
<commit_before>#include <iostream>
using std::cerr;
using std::cout;
#define SDL_MAIN_HANDLED
#include <SDL/SDL.h>
int main ()
{
SDL_SetMainReady ();
/* Init SDL... */
int init_res = SDL_Init (SDL_INIT_VIDEO);
if (0 != init_res)
{
cerr << "[ERROR] SDL init failed: " << SDL_GetError() << "\n";
return 1;
}
/* Create window... */
SDL_Window * window = SDL_CreateWindow (
"Blacknot SDL Blit Test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 400,
0
);
if (nullptr == window)
{
cerr << "[ERROR] Window creation failed: " << SDL_GetError() << "\n";
SDL_Quit ();
return 2;
}
/* Create renderer... */
SDL_Renderer * renderer = SDL_CreateRenderer (window, 0, SDL_RENDERER_ACCELERATED);
if (nullptr == renderer)
{
cerr << "[ERROR] Renderer creation failed: " << SDL_GetError() << "\n";
SDL_DestroyWindow (window);
SDL_Quit ();
return 3;
}
/* Into the event loop we go... */
SDL_Event ev;
while (true)
{
int poll_res = SDL_PollEvent(&ev);
if (0 != poll_res) // We actually do have an event to process
{
cout << "[INFO] " << ev.common.timestamp << ", " << ev.type << "\n";
if (SDL_QUIT == ev.type)
break;
}
else
{
// Do the render here...
}
}
SDL_DestroyRenderer (renderer);
SDL_DestroyWindow (window);
SDL_Quit ();
return 0;
}
<commit_msg>Created and rendered an SDL texture!<commit_after>#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iostream>
using std::cerr;
using std::cout;
#define SDL_MAIN_HANDLED
#include <SDL/SDL.h>
//======================================================================
SDL_Texture * CreateSolidColorTexture (SDL_Renderer * renderer, int w, int h, uint32_t color);
//======================================================================
int main ()
{
SDL_SetMainReady ();
/* Init SDL... */
int init_res = SDL_Init (SDL_INIT_VIDEO);
if (0 != init_res)
{
cerr << "[ERROR] SDL init failed: " << SDL_GetError() << "\n";
return 1;
}
/* Create window... */
SDL_Window * window = SDL_CreateWindow (
"Blacknot SDL Blit Test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 400,
0
);
if (nullptr == window)
{
cerr << "[ERROR] Window creation failed: " << SDL_GetError() << "\n";
SDL_Quit ();
return 2;
}
/* Create renderer... */
SDL_Renderer * renderer = SDL_CreateRenderer (window, 0, SDL_RENDERER_ACCELERATED);
if (nullptr == renderer)
{
cerr << "[ERROR] Renderer creation failed: " << SDL_GetError() << "\n";
SDL_DestroyWindow (window);
SDL_Quit ();
return 3;
}
SDL_Texture * texture = CreateSolidColorTexture (renderer, 2, 2, 0x0000FFFF);
SDL_SetRenderDrawColor (renderer, 5, 5, 20, 255);
/* Into the event loop we go... */
SDL_Event ev;
for (;;)
{
int poll_res = SDL_PollEvent(&ev);
if (0 != poll_res) // We actually do have an event to process
{
cout << "[INFO] " << ev.common.timestamp << ", " << ev.type << "\n";
if (SDL_QUIT == ev.type)
break;
}
else
{
SDL_RenderClear (renderer);
// Do the render here...
SDL_Rect from {0, 0, 2, 2};
SDL_Rect to {10, 10, 20, 20};
SDL_RenderCopy (renderer, texture, &from, &to);
SDL_RenderPresent (renderer);
}
}
SDL_DestroyTexture (texture);
SDL_DestroyRenderer (renderer);
SDL_DestroyWindow (window);
SDL_Quit ();
return 0;
}
//======================================================================
SDL_Texture * CreateSolidColorTexture (SDL_Renderer * renderer, int w, int h, uint32_t color)
{
uint32_t * pixels = new uint32_t [h * w];
std::fill (pixels, pixels + h * w, color);
SDL_Surface * surface = SDL_CreateRGBSurfaceFrom (pixels, w, h, 32, w * sizeof(*pixels), 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
if (nullptr == surface)
{
delete[] pixels;
return nullptr;
}
SDL_Texture * ret = SDL_CreateTextureFromSurface (renderer, surface);
SDL_FreeSurface (surface);
delete[] pixels;
return ret;
}
//----------------------------------------------------------------------
//======================================================================
<|endoftext|> |
<commit_before>#pragma once
#include "mpmc_bounded_queue.hpp"
#include <atomic>
#include <limits>
namespace tp
{
/**
* @brief The Slotted Bag is a lockless container which tracks membership by id.
* The bag is divided into slots, each with a unique id, and each slot can be full or empty.
* The bag supports filling and emptying slots, as well as the unordered emptying of any full slot.
* The bag supports multiple consumers, and a single producer per slot.
*/
template <template<typename> class Queue>
class SlottedBag final
{
/**
* @brief The implementation of a single slot of the bag. Maintains state and id.
* @details State Machine:
*
* +------ TryRemoveAny -------+-------------------------------+
* | | |
* v | |
* +-----------+ +-------------+ +---------------+
* | NotQueued | -- add() --> | QueuedValid | -- remove() --> | QueuedInvalid |
* +-----------+ +-------------+ +---------------+
* ^ |
* | |
* +------------- add() -----------+
*/
struct Slot
{
enum class State
{
NotQueued,
QueuedValid,
QueuedInvalid,
};
std::atomic<State> state;
size_t id;
Slot()
: state(State::NotQueued)
, id(0)
{
}
Slot(const Slot&) = delete;
Slot& operator=(const Slot&) = delete;
Slot(Slot&& rhs) = default;
Slot& operator=(Slot&& rhs) = default;
};
public:
/**
* @brief SlottedBag Constructor.
* @param size Power of 2 number - queue length.
* @throws std::invalid_argument if size is not a power of 2.
*/
explicit SlottedBag(size_t size);
/**
* @brief Copy ctor implementation.
*/
SlottedBag(SlottedBag& rhs) = delete;
/**
* @brief Copy assignment operator implementation.
*/
SlottedBag& operator=(SlottedBag& rhs) = delete;
/**
* @brief Move ctor implementation.
*/
SlottedBag(SlottedBag&& rhs) = default;
/**
* @brief Move assignment operator implementation.
*/
SlottedBag& operator=(SlottedBag&& rhs) = default;
/**
* @brief SlottedBag destructor.
*/
~SlottedBag() = default;
/**
* @brief fill Fill the specified slot.
* @param id The id of the slot to fill.
* @throws std::runtime_error if the slot is already full.
* @note Other exceptions may be thrown if the single-producer-per-slot
* semantics are violated.
*/
void fill(size_t id);
/**
* @brief empty Empties the slot with the specified id.
* @param id The id of the slot to empty.
* @returns true if the state of the bag was changed, false otherwise.
* @note The slot will be empty after the call regardless of the return value.
*/
bool empty(size_t id);
/**
* @brief tryEmptyAny Try to empty any slot in the bag.
* @return a pair containing true upon success along with the id of the emptied slot,
* false otherwise with an id of std::numeric_limits<size_t>::max().
* @note Other exceptions may be thrown if the single-producer-per-slot
* semantics are violated.
*/
std::pair<bool, size_t> tryEmptyAny();
private:
Queue<Slot*> m_queue;
std::vector<Slot> m_slots;
};
template <template<typename> class Queue>
inline SlottedBag<Queue>::SlottedBag(size_t size)
: m_queue(size)
, m_slots(size)
{
for (auto i = 0u; i < size; i++)
m_slots[i].id = i;
}
template <template<typename> class Queue>
inline void SlottedBag<Queue>::fill(size_t id)
{
switch (m_slots[id].state.exchange(Slot::State::QueuedValid, std::memory_order_acq_rel))
{
case Slot::State::NotQueued:
// No race, single producer per slot.
while (!m_queue.push(&m_slots[id])); // Queue should never overflow.
break;
case Slot::State::QueuedValid:
throw std::runtime_error("The item has already been added to the bag.");
case Slot::State::QueuedInvalid:
// Item will still be in the queue. We are done.
break;
}
}
template <template<typename> class Queue>
inline bool SlottedBag<Queue>::empty(size_t id)
{
// This consumer action is solely responsible for an indiscriminant QueuedValid -> QueuedInvalid state transition.
auto state = Slot::State::QueuedValid;
return m_slots[id].state.compare_exchange_strong(state, Slot::State::QueuedInvalid, std::memory_order_acq_rel, std::std::memory_order_relaxed);
}
template <template<typename> class Queue>
inline std::pair<bool, size_t> SlottedBag<Queue>::tryEmptyAny()
{
Slot* slot;
while (m_queue.pop(slot))
{
// Once a consumer pops a slot, they are the sole controller of that object's membership to the queue
// (i.e. they are solely responsible for the transition back into the NotQueued state) by virtue of the
// MPMCBoundedQueue's atomicity semantics.
// In other words, only one consumer can hold a popped slot before it its state is set to NotQueued.
switch (slot->state.exchange(Slot::State::NotQueued, std::memory_order_acq_rel))
{
case Slot::State::NotQueued:
throw std::logic_error("State machine logic violation.");
case Slot::State::QueuedValid:
return std::make_pair(true, slot->id);
case Slot::State::QueuedInvalid:
// Try again.
break;
}
}
// Queue empty.
return std::make_pair(false, std::numeric_limits<size_t>::max());
}
}<commit_msg>fix std<commit_after>#pragma once
#include "mpmc_bounded_queue.hpp"
#include <atomic>
#include <limits>
namespace tp
{
/**
* @brief The Slotted Bag is a lockless container which tracks membership by id.
* The bag is divided into slots, each with a unique id, and each slot can be full or empty.
* The bag supports filling and emptying slots, as well as the unordered emptying of any full slot.
* The bag supports multiple consumers, and a single producer per slot.
*/
template <template<typename> class Queue>
class SlottedBag final
{
/**
* @brief The implementation of a single slot of the bag. Maintains state and id.
* @details State Machine:
*
* +------ TryRemoveAny -------+-------------------------------+
* | | |
* v | |
* +-----------+ +-------------+ +---------------+
* | NotQueued | -- add() --> | QueuedValid | -- remove() --> | QueuedInvalid |
* +-----------+ +-------------+ +---------------+
* ^ |
* | |
* +------------- add() -----------+
*/
struct Slot
{
enum class State
{
NotQueued,
QueuedValid,
QueuedInvalid,
};
std::atomic<State> state;
size_t id;
Slot()
: state(State::NotQueued)
, id(0)
{
}
Slot(const Slot&) = delete;
Slot& operator=(const Slot&) = delete;
Slot(Slot&& rhs) = default;
Slot& operator=(Slot&& rhs) = default;
};
public:
/**
* @brief SlottedBag Constructor.
* @param size Power of 2 number - queue length.
* @throws std::invalid_argument if size is not a power of 2.
*/
explicit SlottedBag(size_t size);
/**
* @brief Copy ctor implementation.
*/
SlottedBag(SlottedBag& rhs) = delete;
/**
* @brief Copy assignment operator implementation.
*/
SlottedBag& operator=(SlottedBag& rhs) = delete;
/**
* @brief Move ctor implementation.
*/
SlottedBag(SlottedBag&& rhs) = default;
/**
* @brief Move assignment operator implementation.
*/
SlottedBag& operator=(SlottedBag&& rhs) = default;
/**
* @brief SlottedBag destructor.
*/
~SlottedBag() = default;
/**
* @brief fill Fill the specified slot.
* @param id The id of the slot to fill.
* @throws std::runtime_error if the slot is already full.
* @note Other exceptions may be thrown if the single-producer-per-slot
* semantics are violated.
*/
void fill(size_t id);
/**
* @brief empty Empties the slot with the specified id.
* @param id The id of the slot to empty.
* @returns true if the state of the bag was changed, false otherwise.
* @note The slot will be empty after the call regardless of the return value.
*/
bool empty(size_t id);
/**
* @brief tryEmptyAny Try to empty any slot in the bag.
* @return a pair containing true upon success along with the id of the emptied slot,
* false otherwise with an id of std::numeric_limits<size_t>::max().
* @note Other exceptions may be thrown if the single-producer-per-slot
* semantics are violated.
*/
std::pair<bool, size_t> tryEmptyAny();
private:
Queue<Slot*> m_queue;
std::vector<Slot> m_slots;
};
template <template<typename> class Queue>
inline SlottedBag<Queue>::SlottedBag(size_t size)
: m_queue(size)
, m_slots(size)
{
for (auto i = 0u; i < size; i++)
m_slots[i].id = i;
}
template <template<typename> class Queue>
inline void SlottedBag<Queue>::fill(size_t id)
{
switch (m_slots[id].state.exchange(Slot::State::QueuedValid, std::memory_order_acq_rel))
{
case Slot::State::NotQueued:
// No race, single producer per slot.
while (!m_queue.push(&m_slots[id])); // Queue should never overflow.
break;
case Slot::State::QueuedValid:
throw std::runtime_error("The item has already been added to the bag.");
case Slot::State::QueuedInvalid:
// Item will still be in the queue. We are done.
break;
}
}
template <template<typename> class Queue>
inline bool SlottedBag<Queue>::empty(size_t id)
{
// This consumer action is solely responsible for an indiscriminant QueuedValid -> QueuedInvalid state transition.
auto state = Slot::State::QueuedValid;
return m_slots[id].state.compare_exchange_strong(state, Slot::State::QueuedInvalid, std::memory_order_acq_rel, std::memory_order_relaxed);
}
template <template<typename> class Queue>
inline std::pair<bool, size_t> SlottedBag<Queue>::tryEmptyAny()
{
Slot* slot;
while (m_queue.pop(slot))
{
// Once a consumer pops a slot, they are the sole controller of that object's membership to the queue
// (i.e. they are solely responsible for the transition back into the NotQueued state) by virtue of the
// MPMCBoundedQueue's atomicity semantics.
// In other words, only one consumer can hold a popped slot before it its state is set to NotQueued.
switch (slot->state.exchange(Slot::State::NotQueued, std::memory_order_acq_rel))
{
case Slot::State::NotQueued:
throw std::logic_error("State machine logic violation.");
case Slot::State::QueuedValid:
return std::make_pair(true, slot->id);
case Slot::State::QueuedInvalid:
// Try again.
break;
}
}
// Queue empty.
return std::make_pair(false, std::numeric_limits<size_t>::max());
}
}<|endoftext|> |
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. 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)
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_dht_router_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_start_lsd_doc;
extern char const* session_stop_lsd_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
extern char const* session_set_ip_filter_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
if (params.has_key("ti"))
p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));
std::string url;
if (params.has_key("tracker_url"))
{
url = extract<std::string>(params["tracker_url"]);
p.tracker_url = url.c_str();
}
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
std::string name;
if (params.has_key("name"))
{
name = extract<std::string>(params["name"]);
p.name = name.c_str();
}
p.save_path = fs::path(extract<std::string>(params["save_path"]));
std::vector<char> resume_buf;
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
resume_buf.resize(resume.size());
std::memcpy(&resume_buf[0], &resume[0], resume.size());
p.resume_data = &resume_buf;
}
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
p.paused = params["paused"];
p.auto_managed = params["auto_managed"];
p.duplicate_is_error = params["duplicate_is_error"];
return s.add_torrent(p);
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
return;
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
return;
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents = s.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
#ifndef TORRENT_DISABLE_GEO_IP
bool load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_asnum_db(file.c_str());
}
bool load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_country_db(file.c_str());
}
#endif
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
.value("storage_mode_compact", storage_mode_compact)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
, session_add_dht_router_doc
)
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("add_torrent", &add_torrent, session_add_torrent_doc)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
, session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", allow_threads(&session::load_state))
.def("state", allow_threads(&session::state))
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("start_upnp", &start_upnp, session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc)
.def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc)
.def("start_natpmp", &start_natpmp, session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
.def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
.def("pause", allow_threads(&session::pause))
.def("resume", allow_threads(&session::resume))
.def("is_paused", allow_threads(&session::is_paused))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<commit_msg>Add session::settings() and ability to set outgoing_ports in session<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. 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)
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_dht_router_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_start_lsd_doc;
extern char const* session_stop_lsd_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
extern char const* session_set_ip_filter_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
void outgoing_ports(session& s, int _min, int _max)
{
allow_threading_guard guard;
session_settings settings = s.settings();
settings.outgoing_ports = std::make_pair(_min, _max);
s.set_settings(settings);
return;
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
if (params.has_key("ti"))
p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));
std::string url;
if (params.has_key("tracker_url"))
{
url = extract<std::string>(params["tracker_url"]);
p.tracker_url = url.c_str();
}
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
std::string name;
if (params.has_key("name"))
{
name = extract<std::string>(params["name"]);
p.name = name.c_str();
}
p.save_path = fs::path(extract<std::string>(params["save_path"]));
std::vector<char> resume_buf;
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
resume_buf.resize(resume.size());
std::memcpy(&resume_buf[0], &resume[0], resume.size());
p.resume_data = &resume_buf;
}
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
p.paused = params["paused"];
p.auto_managed = params["auto_managed"];
p.duplicate_is_error = params["duplicate_is_error"];
return s.add_torrent(p);
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
return;
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
return;
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents = s.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
#ifndef TORRENT_DISABLE_GEO_IP
bool load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_asnum_db(file.c_str());
}
bool load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_country_db(file.c_str());
}
#endif
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
.value("storage_mode_compact", storage_mode_compact)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("outgoing_ports", &outgoing_ports)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
, session_add_dht_router_doc
)
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("add_torrent", &add_torrent, session_add_torrent_doc)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
, session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
.def("settings", allow_threads(&session::settings), return_value_policy<copy_const_reference>())
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", allow_threads(&session::load_state))
.def("state", allow_threads(&session::state))
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("start_upnp", &start_upnp, session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc)
.def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc)
.def("start_natpmp", &start_natpmp, session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
.def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
.def("pause", allow_threads(&session::pause))
.def("resume", allow_threads(&session::resume))
.def("is_paused", allow_threads(&session::is_paused))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<|endoftext|> |
<commit_before>// SendDlg.cpp : ʵļ
//
#include "stdafx.h"
#include "DacrsUI.h"
#include "SendDlg.h"
#include "afxdialogex.h"
// CSendDlg Ի
IMPLEMENT_DYNAMIC(CSendDlg, CDialogBar)
CSendDlg::CSendDlg()
{
m_pBmp = NULL ;
}
CSendDlg::~CSendDlg()
{
if( NULL != m_pBmp ) {
DeleteObject(m_pBmp) ;
m_pBmp = NULL ;
}
}
void CSendDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogBar::DoDataExchange(pDX);
DDX_Control(pDX, IDC_BUTTON_ADDBOOK , m_rBtnAddbook);
DDX_Control(pDX, IDC_SENDTRNSFER , m_rBtnSend);
DDX_Control(pDX, IDC_STATIC_XM , m_strTx1);
DDX_Control(pDX, IDC_COMBO_ADDR_OUT , m_addrbook);
}
BEGIN_MESSAGE_MAP(CSendDlg, CDialogBar)
ON_BN_CLICKED(IDC_SENDTRNSFER, &CSendDlg::OnBnClickedSendtrnsfer)
ON_CBN_SELCHANGE(IDC_COMBO_ADDR_OUT, &CSendDlg::OnCbnSelchangeCombo1)
ON_MESSAGE(MSG_USER_SEND_UI , &CSendDlg::OnShowListaddrData )
ON_WM_CREATE()
ON_WM_ERASEBKGND()
ON_BN_CLICKED(IDC_BUTTON_ADDBOOK, &CSendDlg::OnBnClickedButtonAddbook)
END_MESSAGE_MAP()
// CTransfer Ϣ
void CSendDlg::SetBkBmpNid( UINT nBitmapIn )
{
if( NULL != m_pBmp ) {
::DeleteObject( m_pBmp ) ;
m_pBmp = NULL ;
}
m_pBmp = NULL ;
HINSTANCE hInstResource = NULL;
hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP);
if( NULL != hInstResource ) {
m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0);
}
}
void CSendDlg::OnBnClickedSendtrnsfer()
{
// TODO: ڴӿؼ֪ͨ
if (m_mapAddrInfo.size() == 0)
{
::MessageBox( this->GetSafeHwnd() ,_T("͵ַ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
CString text;
m_addrbook.GetWindowText(text) ;
uistruct::LISTADDR_t data;
if(text!=_T(""))
{
ASSERT(m_mapAddrInfo.count(text)>0);
//uistruct::LISTADDR_t te = m_pListaddrInfo[text];
data = m_mapAddrInfo[text];
}
CString strCommand , strMaddress , strMoney;
if(!data.bSign)
{
::MessageBox( this->GetSafeHwnd() ,_T("͵ַδ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
GetDlgItem(IDC_EDIT_DESADDRESS)->GetWindowTextA(strMaddress);
if (strMaddress == _T(""))
{
::MessageBox( this->GetSafeHwnd() ,_T("ַܵδ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
if(!strcmp(strMaddress.GetString(), data.address))
{
::MessageBox( this->GetSafeHwnd() ,_T("͵ַĿĵַͬ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
GetDlgItem(IDC_EDIT_MONEY)->GetWindowTextA(strMoney);
double dSendMoney = atof(strMoney);
if(dSendMoney > data.fMoney || ( data.fMoney>-0.0000001 && data.fMoney< 0.000001 ))
{
::MessageBox( this->GetSafeHwnd() ,_T("˻") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
if(_T("") == strMoney.GetString() || (dSendMoney >-0.0000001 && dSendMoney< 0.000001))
{
::MessageBox( this->GetSafeHwnd() ,_T("ͽΪ0") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
strCommand.Format(_T("%s %s %s %lld"),_T("sendtoaddress") ,data.address ,strMaddress ,REAL_MONEY(dSendMoney));
CStringA strShowData ;
CSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);
Json::Reader reader;
Json::Value root;
if (!reader.parse(strShowData.GetString(), root))
{
::MessageBox( this->GetSafeHwnd() ,strShowData , _T("ʾ") , MB_ICONINFORMATION ) ;
return ;
}
BOOL bRes = FALSE ;
CString strGettxdetail;
int pos = strShowData.Find("hash");
if ( pos >=0 ) {
//뵽ݿ
CString strHash,strHash1 ;
strHash.Format(_T("'%s'") , root["hash"].asCString() );
strHash1.Format(_T("%s") , root["hash"].asCString() );
theApp.cs_SqlData.Lock();
int nItem = theApp.m_SqliteDeal.FindDB(_T("revtransaction") , strHash1 ,_T("hash") ) ;
theApp.cs_SqlData.Unlock();
if ( 0 == nItem ) {
CPostMsg postmsg(MSG_USER_GET_UPDATABASE,WM_REVTRANSACTION);
postmsg.SetData(strHash);
theApp.m_MsgQueue.push(postmsg);
}
}
CString strData;
if ( pos >=0 ) {
strData.Format( _T("ת˳ɹ\n%s") , root["hash"].asCString() ) ;
}else{
strData.Format( _T("תʧ!") ) ;
}
::MessageBox( this->GetSafeHwnd() ,strData , _T("ʾ") , MB_ICONINFORMATION ) ;
}
void CSendDlg::OnCbnSelchangeCombo1()
{
// TODO: ڴӿؼ֪ͨ
if (m_mapAddrInfo.size() == 0)
{
return;
}
CString text;
m_addrbook.GetWindowText(text) ;
if(text!=_T(""))
{
ASSERT(m_mapAddrInfo.count(text)>0);
//uistruct::LISTADDR_t te = m_pListaddrInfo[text];
CString strshow;
strshow.Format(_T("%.8f"),m_mapAddrInfo[text].fMoney);
((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);
Invalidate();
}
}
BOOL CSendDlg::AddListaddrDataBox(){
theApp.cs_SqlData.Lock();
theApp.m_SqliteDeal.GetListaddrData(&m_mapAddrInfo);
theApp.cs_SqlData.Unlock();
if ( 0 == m_mapAddrInfo.size() ) return FALSE ;
//ComBoxؼ
((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->ResetContent();
//صComBoxؼ
int nItem = 0;
std::map<CString,uistruct::LISTADDR_t>::const_iterator const_it;
for ( const_it = m_mapAddrInfo.begin() ; const_it != m_mapAddrInfo.end() ; const_it++ ) {
((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->InsertString(nItem , const_it->first );
//((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetItemData(nItem, (DWORD_PTR)&(*const_it));
nItem++;
}
((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetCurSel(0);
CString address;
m_addrbook.GetWindowText(address);
std::map<CString,uistruct::LISTADDR_t>::const_iterator item = m_mapAddrInfo.find(address);
//uistruct::LISTADDR_t pListAddr = m_pListaddrInfo.find(address);
uistruct::LISTADDR_t *pListAddr = (uistruct::LISTADDR_t*)(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetItemData(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetCurSel())) ;
if ( m_mapAddrInfo.end()!= item ) {
uistruct::LISTADDR_t addrstruc = item->second;
// double money = CSoyPayHelp::getInstance()->GetAccountBalance(pListAddr->address);
CString strshow;
strshow.Format(_T("%.8f"),addrstruc.fMoney);
m_strTx1.SetWindowText(strshow);
//((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);
Invalidate();
}
return TRUE ;
}
LRESULT CSendDlg::OnShowListaddrData( WPARAM wParam, LPARAM lParam )
{
//
int type = (int)wParam;
switch(type)
{
case WM_UP_ADDRESS:
{
ModifyComboxItem();
break;
}
break;
case WM_UP_NEWADDRESS:
{
InsertComboxIitem();
break;
}
break;
default:
break;
}
return 0 ;
}
// CSendDlg Ϣ
BOOL CSendDlg::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID)
{
// TODO: ڴרô/û
BOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID);
if (bRes)
{
//m_rBtnSend.LoadBitmaps(IDB_BITMAP_BOTTON_SEND1,IDB_BITMAP_BOTTON_SEND2,IDB_BITMAP_BOTTON_SEND3,IDB_BITMAP_BOTTON_SEND3);
m_rBtnAddbook.LoadBitmaps(IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK);
UpdateData(0);
m_strTx1.SetFont(120, _T("")); //ʾʹС
AddListaddrDataBox();
m_rBtnSend.SetBitmaps( IDB_BITMAP_BUTTON , RGB(255, 255, 0) , IDB_BITMAP_BUTTON , RGB(255, 255, 255) );
m_rBtnSend.SetAlign(CButtonST::ST_ALIGN_OVERLAP);
m_rBtnSend.SetWindowText("") ;
m_rBtnSend.SetFontEx(24 , _T("ź"));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));
m_rBtnSend.SizeToContent();
theApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_SEND_UI ) ;
((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);
}
return bRes;
}
int CSendDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogBar::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: ڴרõĴ
SetBkBmpNid(IDB_BITMAP_SENDUI_BJ);
return 0;
}
BOOL CSendDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: ڴϢ/Ĭֵ
CRect rect;
GetClientRect(&rect);
if(m_pBmp != NULL) {
BITMAP bm;
CDC dcMem;
::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm);
dcMem.CreateCompatibleDC(NULL);
HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp);
pDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY);
dcMem.SelectObject(pOldBitmap);
dcMem.DeleteDC();
} else
CWnd::OnEraseBkgnd(pDC);
return 1;
}
void CSendDlg::OnBnClickedButtonAddbook()
{
// TODO: ڴӿؼ֪ͨ
}
void CSendDlg::ModifyComboxItem(){
CPostMsg postmsg;
if (!theApp.m_UiSendDlgQueue.pop(postmsg))
{
return ;
}
uistruct::LISTADDR_t addr;
string strTemp = postmsg.GetData();
addr.JsonToStruct(strTemp.c_str());
CString addressd;
addressd.Format(_T("%s"),addr.address);
ASSERT(m_mapAddrInfo.count(addressd) > 0);
m_mapAddrInfo[addressd]=addr;
}
void CSendDlg::InsertComboxIitem()
{
CPostMsg postmsg;
if (!theApp.m_UiSendDlgQueue.pop(postmsg))
{
return ;
}
uistruct::LISTADDR_t addr;
string strTemp = postmsg.GetData();
addr.JsonToStruct(strTemp.c_str());
CString addressd;
addressd.Format(_T("%s"),addr.address);
ASSERT(m_mapAddrInfo.count(addressd) == 0);
m_mapAddrInfo[addressd]=addr;
int item = m_addrbook.GetCount();
m_addrbook.InsertString(item,addressd);
}
<commit_msg>init clear balance font<commit_after>// SendDlg.cpp : ʵļ
//
#include "stdafx.h"
#include "DacrsUI.h"
#include "SendDlg.h"
#include "afxdialogex.h"
// CSendDlg Ի
IMPLEMENT_DYNAMIC(CSendDlg, CDialogBar)
CSendDlg::CSendDlg()
{
m_pBmp = NULL ;
}
CSendDlg::~CSendDlg()
{
if( NULL != m_pBmp ) {
DeleteObject(m_pBmp) ;
m_pBmp = NULL ;
}
}
void CSendDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogBar::DoDataExchange(pDX);
DDX_Control(pDX, IDC_BUTTON_ADDBOOK , m_rBtnAddbook);
DDX_Control(pDX, IDC_SENDTRNSFER , m_rBtnSend);
DDX_Control(pDX, IDC_STATIC_XM , m_strTx1);
DDX_Control(pDX, IDC_COMBO_ADDR_OUT , m_addrbook);
}
BEGIN_MESSAGE_MAP(CSendDlg, CDialogBar)
ON_BN_CLICKED(IDC_SENDTRNSFER, &CSendDlg::OnBnClickedSendtrnsfer)
ON_CBN_SELCHANGE(IDC_COMBO_ADDR_OUT, &CSendDlg::OnCbnSelchangeCombo1)
ON_MESSAGE(MSG_USER_SEND_UI , &CSendDlg::OnShowListaddrData )
ON_WM_CREATE()
ON_WM_ERASEBKGND()
ON_BN_CLICKED(IDC_BUTTON_ADDBOOK, &CSendDlg::OnBnClickedButtonAddbook)
END_MESSAGE_MAP()
// CTransfer Ϣ
void CSendDlg::SetBkBmpNid( UINT nBitmapIn )
{
if( NULL != m_pBmp ) {
::DeleteObject( m_pBmp ) ;
m_pBmp = NULL ;
}
m_pBmp = NULL ;
HINSTANCE hInstResource = NULL;
hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP);
if( NULL != hInstResource ) {
m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0);
}
}
void CSendDlg::OnBnClickedSendtrnsfer()
{
// TODO: ڴӿؼ֪ͨ
if (m_mapAddrInfo.size() == 0)
{
::MessageBox( this->GetSafeHwnd() ,_T("͵ַ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
CString text;
m_addrbook.GetWindowText(text) ;
uistruct::LISTADDR_t data;
if(text!=_T(""))
{
ASSERT(m_mapAddrInfo.count(text)>0);
//uistruct::LISTADDR_t te = m_pListaddrInfo[text];
data = m_mapAddrInfo[text];
}
CString strCommand , strMaddress , strMoney;
if(!data.bSign)
{
::MessageBox( this->GetSafeHwnd() ,_T("͵ַδ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
GetDlgItem(IDC_EDIT_DESADDRESS)->GetWindowTextA(strMaddress);
if (strMaddress == _T(""))
{
::MessageBox( this->GetSafeHwnd() ,_T("ַܵδ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
if(!strcmp(strMaddress.GetString(), data.address))
{
::MessageBox( this->GetSafeHwnd() ,_T("͵ַĿĵַͬ") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
GetDlgItem(IDC_EDIT_MONEY)->GetWindowTextA(strMoney);
double dSendMoney = atof(strMoney);
if(dSendMoney > data.fMoney || ( data.fMoney>-0.0000001 && data.fMoney< 0.000001 ))
{
::MessageBox( this->GetSafeHwnd() ,_T("˻") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
if(_T("") == strMoney.GetString() || (dSendMoney >-0.0000001 && dSendMoney< 0.000001))
{
::MessageBox( this->GetSafeHwnd() ,_T("ͽΪ0") , _T("ʾ") , MB_ICONINFORMATION ) ;
return;
}
strCommand.Format(_T("%s %s %s %lld"),_T("sendtoaddress") ,data.address ,strMaddress ,REAL_MONEY(dSendMoney));
CStringA strShowData ;
CSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);
Json::Reader reader;
Json::Value root;
if (!reader.parse(strShowData.GetString(), root))
{
::MessageBox( this->GetSafeHwnd() ,strShowData , _T("ʾ") , MB_ICONINFORMATION ) ;
return ;
}
BOOL bRes = FALSE ;
CString strGettxdetail;
int pos = strShowData.Find("hash");
if ( pos >=0 ) {
//뵽ݿ
CString strHash,strHash1 ;
strHash.Format(_T("'%s'") , root["hash"].asCString() );
strHash1.Format(_T("%s") , root["hash"].asCString() );
theApp.cs_SqlData.Lock();
int nItem = theApp.m_SqliteDeal.FindDB(_T("revtransaction") , strHash1 ,_T("hash") ) ;
theApp.cs_SqlData.Unlock();
if ( 0 == nItem ) {
CPostMsg postmsg(MSG_USER_GET_UPDATABASE,WM_REVTRANSACTION);
postmsg.SetData(strHash);
theApp.m_MsgQueue.push(postmsg);
}
}
CString strData;
if ( pos >=0 ) {
strData.Format( _T("ת˳ɹ\n%s") , root["hash"].asCString() ) ;
}else{
strData.Format( _T("תʧ!") ) ;
}
::MessageBox( this->GetSafeHwnd() ,strData , _T("ʾ") , MB_ICONINFORMATION ) ;
}
void CSendDlg::OnCbnSelchangeCombo1()
{
// TODO: ڴӿؼ֪ͨ
if (m_mapAddrInfo.size() == 0)
{
return;
}
CString text;
m_addrbook.GetWindowText(text) ;
if(text!=_T(""))
{
ASSERT(m_mapAddrInfo.count(text)>0);
//uistruct::LISTADDR_t te = m_pListaddrInfo[text];
CString strshow;
strshow.Format(_T("%.8f"),m_mapAddrInfo[text].fMoney);
((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);
Invalidate();
}
}
BOOL CSendDlg::AddListaddrDataBox(){
theApp.cs_SqlData.Lock();
theApp.m_SqliteDeal.GetListaddrData(&m_mapAddrInfo);
theApp.cs_SqlData.Unlock();
if ( 0 == m_mapAddrInfo.size() ) return FALSE ;
//ComBoxؼ
((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->ResetContent();
//صComBoxؼ
int nItem = 0;
std::map<CString,uistruct::LISTADDR_t>::const_iterator const_it;
for ( const_it = m_mapAddrInfo.begin() ; const_it != m_mapAddrInfo.end() ; const_it++ ) {
((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->InsertString(nItem , const_it->first );
//((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetItemData(nItem, (DWORD_PTR)&(*const_it));
nItem++;
}
((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->SetCurSel(0);
CString address;
m_addrbook.GetWindowText(address);
std::map<CString,uistruct::LISTADDR_t>::const_iterator item = m_mapAddrInfo.find(address);
//uistruct::LISTADDR_t pListAddr = m_pListaddrInfo.find(address);
uistruct::LISTADDR_t *pListAddr = (uistruct::LISTADDR_t*)(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetItemData(((CComboBox*)GetDlgItem(IDC_COMBO_ADDR_OUT))->GetCurSel())) ;
if ( m_mapAddrInfo.end()!= item ) {
uistruct::LISTADDR_t addrstruc = item->second;
// double money = CSoyPayHelp::getInstance()->GetAccountBalance(pListAddr->address);
CString strshow;
strshow.Format(_T("%.8f"),addrstruc.fMoney);
m_strTx1.SetWindowText(strshow);
//((CStatic*)GetDlgItem(IDC_STATIC_XM))->SetWindowText(strshow);
Invalidate();
}
return TRUE ;
}
LRESULT CSendDlg::OnShowListaddrData( WPARAM wParam, LPARAM lParam )
{
//
int type = (int)wParam;
switch(type)
{
case WM_UP_ADDRESS:
{
ModifyComboxItem();
break;
}
break;
case WM_UP_NEWADDRESS:
{
InsertComboxIitem();
break;
}
break;
default:
break;
}
return 0 ;
}
// CSendDlg Ϣ
BOOL CSendDlg::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID)
{
// TODO: ڴרô/û
BOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID);
if (bRes)
{
//m_rBtnSend.LoadBitmaps(IDB_BITMAP_BOTTON_SEND1,IDB_BITMAP_BOTTON_SEND2,IDB_BITMAP_BOTTON_SEND3,IDB_BITMAP_BOTTON_SEND3);
m_rBtnAddbook.LoadBitmaps(IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK,IDB_BITMAP_ADDBOOK);
UpdateData(0);
m_strTx1.SetFont(120, _T("")); //ʾʹС
m_strTx1.SetWindowText(_T(""));
AddListaddrDataBox();
m_rBtnSend.SetBitmaps( IDB_BITMAP_BUTTON , RGB(255, 255, 0) , IDB_BITMAP_BUTTON , RGB(255, 255, 255) );
m_rBtnSend.SetAlign(CButtonST::ST_ALIGN_OVERLAP);
m_rBtnSend.SetWindowText("") ;
m_rBtnSend.SetFontEx(24 , _T("ź"));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));
m_rBtnSend.SizeToContent();
theApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_SEND_UI ) ;
((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);
}
return bRes;
}
int CSendDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogBar::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: ڴרõĴ
SetBkBmpNid(IDB_BITMAP_SENDUI_BJ);
return 0;
}
BOOL CSendDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: ڴϢ/Ĭֵ
CRect rect;
GetClientRect(&rect);
if(m_pBmp != NULL) {
BITMAP bm;
CDC dcMem;
::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm);
dcMem.CreateCompatibleDC(NULL);
HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp);
pDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY);
dcMem.SelectObject(pOldBitmap);
dcMem.DeleteDC();
} else
CWnd::OnEraseBkgnd(pDC);
return 1;
}
void CSendDlg::OnBnClickedButtonAddbook()
{
// TODO: ڴӿؼ֪ͨ
}
void CSendDlg::ModifyComboxItem(){
CPostMsg postmsg;
if (!theApp.m_UiSendDlgQueue.pop(postmsg))
{
return ;
}
uistruct::LISTADDR_t addr;
string strTemp = postmsg.GetData();
addr.JsonToStruct(strTemp.c_str());
CString addressd;
addressd.Format(_T("%s"),addr.address);
ASSERT(m_mapAddrInfo.count(addressd) > 0);
m_mapAddrInfo[addressd]=addr;
}
void CSendDlg::InsertComboxIitem()
{
CPostMsg postmsg;
if (!theApp.m_UiSendDlgQueue.pop(postmsg))
{
return ;
}
uistruct::LISTADDR_t addr;
string strTemp = postmsg.GetData();
addr.JsonToStruct(strTemp.c_str());
CString addressd;
addressd.Format(_T("%s"),addr.address);
ASSERT(m_mapAddrInfo.count(addressd) == 0);
m_mapAddrInfo[addressd]=addr;
int item = m_addrbook.GetCount();
m_addrbook.InsertString(item,addressd);
}
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. 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)
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, torrent_info const& ti
, boost::filesystem::path const& save, entry const& resume
, storage_mode_t storage_mode, bool paused)
{
allow_threading_guard guard;
return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
}
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_compact", storage_mode_compact)
.value("storage_mode_sparse", storage_mode_sparse)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
#endif
.def(
"add_torrent", &add_torrent
, (
arg("resume_data") = entry(), arg("compact_mode") = true
, arg("paused") = false
)
, session_add_torrent_doc
)
.def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
#ifndef TORRENT_DISABLE_DHT
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<commit_msg>python binding fix<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. 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)
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, torrent_info const& ti
, boost::filesystem::path const& save, entry const& resume
, storage_mode_t storage_mode, bool paused)
{
allow_threading_guard guard;
return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
}
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_compact", storage_mode_compact)
.value("storage_mode_sparse", storage_mode_sparse)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
#endif
.def(
"add_torrent", &add_torrent
, (
arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse,
arg("paused") = false
)
, session_add_torrent_doc
)
.def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
#ifndef TORRENT_DISABLE_DHT
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file AlphaFilter.hpp
*
* @brief First order "alpha" IIR digital filter also known as leaky integrator or forgetting average.
*
* @author Mathieu Bresciani <[email protected]>
* @author Matthias Grob <[email protected]>
*/
#pragma once
template <typename T>
class AlphaFilter {
public:
AlphaFilter() = default;
~AlphaFilter() = default;
/**
* Set filter parameters for time abstraction
*
* Both parameters have to be provided in the same units.
*
* @param sample_interval interval between two samples
* @param time_constant filter time constant determining convergence
*/
void setParameters(float sample_interval, float time_constant) {
setAlpha(sample_interval / (time_constant + sample_interval));
}
/**
* Set filter parameter alpha directly without time abstraction
*
* @param alpha [0,1] filter weight for the previous state. High value - long time constant.
*/
void setAlpha(float alpha) { _alpha = alpha; }
/**
* Set filter state to an initial value
*
* @param sample new initial value
*/
void reset(const T &sample) { _filter_state = sample; }
/**
* Add a new raw value to the filter
*
* @return retrieve the filtered result
*/
void update(const T &sample) { _filter_state = updateCalculation(sample); }
const T &getState() const { return _filter_state; }
protected:
T updateCalculation(const T &sample) { return (1.f - _alpha) * _filter_state + _alpha * sample; }
float _alpha{0.f};
T _filter_state{};
};
<commit_msg>AlphaFilter: prevent setParameters division by zero<commit_after>/****************************************************************************
*
* Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file AlphaFilter.hpp
*
* @brief First order "alpha" IIR digital filter also known as leaky integrator or forgetting average.
*
* @author Mathieu Bresciani <[email protected]>
* @author Matthias Grob <[email protected]>
*/
#pragma once
#include "../ecl.h"
template <typename T>
class AlphaFilter {
public:
AlphaFilter() = default;
~AlphaFilter() = default;
/**
* Set filter parameters for time abstraction
*
* Both parameters have to be provided in the same units.
*
* @param sample_interval interval between two samples
* @param time_constant filter time constant determining convergence
*/
void setParameters(float sample_interval, float time_constant) {
setAlpha(sample_interval / (time_constant + sample_interval));
}
/**
* Set filter parameter alpha directly without time abstraction
*
* @param alpha [0,1] filter weight for the previous state. High value - long time constant.
*/
void setAlpha(float alpha) {
if (ISFINITE(alpha)) {
_alpha = alpha;
}
}
/**
* Set filter state to an initial value
*
* @param sample new initial value
*/
void reset(const T &sample) { _filter_state = sample; }
/**
* Add a new raw value to the filter
*
* @return retrieve the filtered result
*/
void update(const T &sample) { _filter_state = updateCalculation(sample); }
const T &getState() const { return _filter_state; }
protected:
T updateCalculation(const T &sample) { return (1.f - _alpha) * _filter_state + _alpha * sample; }
float _alpha{0.f};
T _filter_state{};
};
<|endoftext|> |
<commit_before>#include "qc.h"
namespace qclib {
static QString createLocalServerPath()
{
return QString("/tmp/qclserver_%1_%2").arg(qgetenv("USER").data()).arg(qApp->applicationPid());
}
QCChannel::QCChannel(QIODevice *socket)
: socket_(socket)
, id_(nextId_++)
, lastError_("<no last error string set yet>")
{
}
void QCChannel::initSocket()
{
Q_ASSERT(socket_);
connect(socket_, SIGNAL(disconnected()), SIGNAL(socketDisconnected()));
connect(socket_, SIGNAL(readyRead()), SLOT(readyRead()));
}
QString QCChannel::lastError() const
{
return lastError_;
}
void QCChannel::setLastError(const QString &lastError_)
{
this->lastError_ = lastError_;
}
// Sends the variant map \a msg as a message on the channel.
void QCChannel::sendMessage(const QVariantMap &msg)
{
if (!isConnected()) {
const char *emsg = "socket not connected";
qWarning("WARNING: %s", emsg);
setLastError(emsg);
return;
}
// serialize into byte array
QByteArray ba;
QDataStream dstream(&ba, QIODevice::Append);
dstream << msg;
// send as newline-terminated base64
socket_->write(ba.toBase64());
socket_->write("\n");
socket_->waitForBytesWritten(-1);
}
void QCChannel::readyRead()
{
if (socket_->bytesAvailable() == 0) {
qDebug() << "WARNING: readyRead() called with no bytes available";
return;
}
msgbuf_.append(socket_->read(socket_->bytesAvailable()));
while (true) {
const int nlPos = msgbuf_.indexOf('\n');
if (nlPos == -1)
return; // no complete message in buffer at this point
// extract first message from buffer
QByteArray ba = QByteArray::fromBase64(msgbuf_.left(nlPos)); // decode
msgbuf_ = msgbuf_.mid(nlPos + 1);
// deserialize into variant map
QDataStream dstream(ba);
QVariantMap msg;
dstream >> msg;
// qDebug() << "msg arrived:" << msg;
emit messageArrived(id(), msg);
}
}
qint64 QCChannel::nextId_ = 0;
QCLocalChannel::QCLocalChannel(QLocalSocket * socket)
: QCChannel(socket)
{
if (socket_)
initSocket();
}
QCLocalChannel::~QCLocalChannel()
{
if (socket_)
delete socket_;
}
bool QCLocalChannel::connectToServer(const QString &serverPath)
{
if (socket_) {
setLastError("socket already connected, please disconnect first");
return false;
}
QLocalSocket *lsocket = new QLocalSocket;
socket_ = lsocket;
lsocket->connectToServer(serverPath);
if (!lsocket->waitForConnected(-1)) {
setLastError(QString("waitForConnected() failed: %1").arg(socket_->errorString()));
delete socket_;
socket_ = 0;
return false;
}
initSocket();
return true;
}
void QCLocalChannel::initSocket()
{
QLocalSocket *lsocket = qobject_cast<QLocalSocket *>(socket_);
Q_ASSERT(lsocket);
connect(
lsocket, SIGNAL(error(QLocalSocket::LocalSocketError)),
SLOT(handleSocketError(QLocalSocket::LocalSocketError)));
QCChannel::initSocket();
}
bool QCLocalChannel::isConnected() const
{
return socket_ != 0;
}
void QCLocalChannel::handleSocketError(QLocalSocket::LocalSocketError e)
{
if (e != QLocalSocket::PeerClosedError) // for now, don't consider this an error
emit error(socket_->errorString());
}
QCTcpChannel::QCTcpChannel(QTcpSocket *socket)
: QCChannel(socket)
{
if (socket_)
initSocket();
}
QCTcpChannel::~QCTcpChannel()
{
if (socket_)
delete socket_;
}
// Connects the channel to a server on \a host listening on \a port.
bool QCTcpChannel::connectToServer(const QString &host, const quint16 port)
{
if (socket_) {
setLastError("socket already connected, please disconnect first");
return false;
}
QTcpSocket *tsocket = new QTcpSocket;
socket_ = tsocket;
tsocket->connectToHost(host, port);
if (!tsocket->waitForConnected(-1)) {
setLastError(QString("waitForConnected() failed: %1").arg(socket_->errorString()));
delete socket_;
socket_ = 0;
return false;
}
initSocket();
return true;
}
void QCTcpChannel::initSocket()
{
QTcpSocket *tsocket = qobject_cast<QTcpSocket *>(socket_);
Q_ASSERT(tsocket);
connect(
tsocket, SIGNAL(error(QAbstractSocket::SocketError)),
SLOT(handleSocketError(QAbstractSocket::SocketError)));
QCChannel::initSocket();
Q_ASSERT(!tsocket->peerAddress().isNull());
Q_ASSERT(tsocket->peerPort() != 0);
peerInfo_ = QString("%1:%2")
.arg(QHostInfo::fromName(tsocket->peerAddress().toString()).hostName())
.arg(tsocket->peerPort());
}
bool QCTcpChannel::isConnected() const
{
return socket_ != 0;
}
void QCTcpChannel::handleSocketError(QAbstractSocket::SocketError e)
{
if (e != QAbstractSocket::RemoteHostClosedError) // for now, don't consider this an error
emit error(socket_->errorString());
}
QCChannelServer::QCChannelServer()
: lastError_("<no last error string set yet>")
{
}
QString QCChannelServer::lastError() const
{
return lastError_;
}
void QCChannelServer::setLastError(const QString &lastError_)
{
this->lastError_ = lastError_;
}
QCLocalChannelServer::QCLocalChannelServer()
{
connect(&fileSysWatcher_, SIGNAL(fileChanged(const QString &)), SIGNAL(serverFileChanged(const QString &)));
}
QCLocalChannelServer::~QCLocalChannelServer()
{
const QString serverPath = server_.fullServerName();
if (!QLocalServer::removeServer(serverPath))
qWarning("WARNING: failed to remove server file upon cleanup: %s", serverPath.toLatin1().data());
else
qDebug() << "removed server file:" << serverPath;
}
bool QCLocalChannelServer::listen()
{
QString serverPath;
if (localServerFileExists(&serverPath)) {
setLastError(QString("QCLocalChannelServer::listen(): server file already exists: %1").arg(serverPath));
return false;
}
if (!fileSysWatcher_.files().empty()) {
setLastError(
QString("QCLocalChannelServer::listen(): file system watcher already watching %1 other server file(s): %2 ...")
.arg(fileSysWatcher_.files().size()).arg(fileSysWatcher_.files().first()));
return false;
}
serverPath = createLocalServerPath();
if (!server_.listen(serverPath)) {
setLastError(QString("QCLocalChannelServer::listen(): listen() failed: %1").arg(server_.errorString()));
return false;
}
fileSysWatcher_.addPath(serverPath);
connect(&server_, SIGNAL(newConnection()), SLOT(newConnection()));
// qDebug() << "accepting client connections on path" << serverPath << "...";
return true;
}
void QCLocalChannelServer::newConnection()
{
emit channelConnected(new QCLocalChannel(server_.nextPendingConnection()));
}
bool QCTcpChannelServer::listen(quint16 port)
{
if (!server_.listen(QHostAddress::Any, port)) {
setLastError(QString("QCTcpChannelServer::listen(): listen() failed: %1").arg(server_.errorString()));
return false;
}
connect(&server_, SIGNAL(newConnection()), SLOT(newConnection()));
// qDebug() << "accepting client connections on port" << port << "...";
return true;
}
void QCTcpChannelServer::newConnection()
{
emit channelConnected(new QCTcpChannel(server_.nextPendingConnection()));
}
} // namespace qclib
<commit_msg>Removed debug output + added notes<commit_after>#include "qc.h"
namespace qclib {
static QString createLocalServerPath()
{
return QString("/tmp/qclserver_%1_%2").arg(qgetenv("USER").data()).arg(qApp->applicationPid());
}
QCChannel::QCChannel(QIODevice *socket)
: socket_(socket)
, id_(nextId_++)
, lastError_("<no last error string set yet>")
{
}
void QCChannel::initSocket()
{
Q_ASSERT(socket_);
connect(socket_, SIGNAL(disconnected()), SIGNAL(socketDisconnected()));
connect(socket_, SIGNAL(readyRead()), SLOT(readyRead()));
}
QString QCChannel::lastError() const
{
return lastError_;
}
void QCChannel::setLastError(const QString &lastError_)
{
this->lastError_ = lastError_;
}
// Sends the variant map \a msg as a message on the channel.
void QCChannel::sendMessage(const QVariantMap &msg)
{
if (!isConnected()) {
const char *emsg = "socket not connected";
qWarning("WARNING: %s", emsg); // ### log via log4cpp instead!
setLastError(emsg);
return;
}
// serialize into byte array
QByteArray ba;
QDataStream dstream(&ba, QIODevice::Append);
dstream << msg;
// send as newline-terminated base64
socket_->write(ba.toBase64());
socket_->write("\n");
socket_->waitForBytesWritten(-1);
}
void QCChannel::readyRead()
{
if (socket_->bytesAvailable() == 0) {
qWarning("WARNING: readyRead() called with no bytes available"); // ### Log via log4cpp instead!
return;
}
msgbuf_.append(socket_->read(socket_->bytesAvailable()));
while (true) {
const int nlPos = msgbuf_.indexOf('\n');
if (nlPos == -1)
return; // no complete message in buffer at this point
// extract first message from buffer
QByteArray ba = QByteArray::fromBase64(msgbuf_.left(nlPos)); // decode
msgbuf_ = msgbuf_.mid(nlPos + 1);
// deserialize into variant map
QDataStream dstream(ba);
QVariantMap msg;
dstream >> msg;
// qDebug() << "msg arrived:" << msg;
emit messageArrived(id(), msg);
}
}
qint64 QCChannel::nextId_ = 0;
QCLocalChannel::QCLocalChannel(QLocalSocket * socket)
: QCChannel(socket)
{
if (socket_)
initSocket();
}
QCLocalChannel::~QCLocalChannel()
{
if (socket_)
delete socket_;
}
bool QCLocalChannel::connectToServer(const QString &serverPath)
{
if (socket_) {
setLastError("socket already connected, please disconnect first");
return false;
}
QLocalSocket *lsocket = new QLocalSocket;
socket_ = lsocket;
lsocket->connectToServer(serverPath);
if (!lsocket->waitForConnected(-1)) {
setLastError(QString("waitForConnected() failed: %1").arg(socket_->errorString()));
delete socket_;
socket_ = 0;
return false;
}
initSocket();
return true;
}
void QCLocalChannel::initSocket()
{
QLocalSocket *lsocket = qobject_cast<QLocalSocket *>(socket_);
Q_ASSERT(lsocket);
connect(
lsocket, SIGNAL(error(QLocalSocket::LocalSocketError)),
SLOT(handleSocketError(QLocalSocket::LocalSocketError)));
QCChannel::initSocket();
}
bool QCLocalChannel::isConnected() const
{
return socket_ != 0;
}
void QCLocalChannel::handleSocketError(QLocalSocket::LocalSocketError e)
{
if (e != QLocalSocket::PeerClosedError) // for now, don't consider this an error
emit error(socket_->errorString());
}
QCTcpChannel::QCTcpChannel(QTcpSocket *socket)
: QCChannel(socket)
{
if (socket_)
initSocket();
}
QCTcpChannel::~QCTcpChannel()
{
if (socket_)
delete socket_;
}
// Connects the channel to a server on \a host listening on \a port.
bool QCTcpChannel::connectToServer(const QString &host, const quint16 port)
{
if (socket_) {
setLastError("socket already connected, please disconnect first");
return false;
}
QTcpSocket *tsocket = new QTcpSocket;
socket_ = tsocket;
tsocket->connectToHost(host, port);
if (!tsocket->waitForConnected(-1)) {
setLastError(QString("waitForConnected() failed: %1").arg(socket_->errorString()));
delete socket_;
socket_ = 0;
return false;
}
initSocket();
return true;
}
void QCTcpChannel::initSocket()
{
QTcpSocket *tsocket = qobject_cast<QTcpSocket *>(socket_);
Q_ASSERT(tsocket);
connect(
tsocket, SIGNAL(error(QAbstractSocket::SocketError)),
SLOT(handleSocketError(QAbstractSocket::SocketError)));
QCChannel::initSocket();
Q_ASSERT(!tsocket->peerAddress().isNull());
Q_ASSERT(tsocket->peerPort() != 0);
peerInfo_ = QString("%1:%2")
.arg(QHostInfo::fromName(tsocket->peerAddress().toString()).hostName())
.arg(tsocket->peerPort());
}
bool QCTcpChannel::isConnected() const
{
return socket_ != 0;
}
void QCTcpChannel::handleSocketError(QAbstractSocket::SocketError e)
{
if (e != QAbstractSocket::RemoteHostClosedError) // for now, don't consider this an error
emit error(socket_->errorString());
}
QCChannelServer::QCChannelServer()
: lastError_("<no last error string set yet>")
{
}
QString QCChannelServer::lastError() const
{
return lastError_;
}
void QCChannelServer::setLastError(const QString &lastError_)
{
this->lastError_ = lastError_;
}
QCLocalChannelServer::QCLocalChannelServer()
{
connect(&fileSysWatcher_, SIGNAL(fileChanged(const QString &)), SIGNAL(serverFileChanged(const QString &)));
}
QCLocalChannelServer::~QCLocalChannelServer()
{
const QString serverPath = server_.fullServerName();
if (!QLocalServer::removeServer(serverPath))
// ### log via log4cpp instead!
qWarning("WARNING: failed to remove server file upon cleanup: %s", serverPath.toLatin1().data());
else
; // qDebug() << "removed server file:" << serverPath;
}
bool QCLocalChannelServer::listen()
{
QString serverPath;
if (localServerFileExists(&serverPath)) {
setLastError(QString("QCLocalChannelServer::listen(): server file already exists: %1").arg(serverPath));
return false;
}
if (!fileSysWatcher_.files().empty()) {
setLastError(
QString("QCLocalChannelServer::listen(): file system watcher already watching %1 other server file(s): %2 ...")
.arg(fileSysWatcher_.files().size()).arg(fileSysWatcher_.files().first()));
return false;
}
serverPath = createLocalServerPath();
if (!server_.listen(serverPath)) {
setLastError(QString("QCLocalChannelServer::listen(): listen() failed: %1").arg(server_.errorString()));
return false;
}
fileSysWatcher_.addPath(serverPath);
connect(&server_, SIGNAL(newConnection()), SLOT(newConnection()));
// qDebug() << "accepting client connections on path" << serverPath << "...";
return true;
}
void QCLocalChannelServer::newConnection()
{
emit channelConnected(new QCLocalChannel(server_.nextPendingConnection()));
}
bool QCTcpChannelServer::listen(quint16 port)
{
if (!server_.listen(QHostAddress::Any, port)) {
setLastError(QString("QCTcpChannelServer::listen(): listen() failed: %1").arg(server_.errorString()));
return false;
}
connect(&server_, SIGNAL(newConnection()), SLOT(newConnection()));
// qDebug() << "accepting client connections on port" << port << "...";
return true;
}
void QCTcpChannelServer::newConnection()
{
emit channelConnected(new QCTcpChannel(server_.nextPendingConnection()));
}
} // namespace qclib
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "printing/backend/print_backend.h"
#include <algorithm>
#include "third_party/icu/public/common/unicode/uchar.h"
#include "ui/base/text/text_elider.h"
namespace {
const wchar_t kDefaultDocumentTitle[] = L"Untitled Document";
const int kMaxDocumentTitleLength = 50;
} // namespace
namespace printing {
PrinterBasicInfo::PrinterBasicInfo()
: printer_status(0),
is_default(false) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterSemanticCapsAndDefaults::PrinterSemanticCapsAndDefaults()
: color_capable(false),
duplex_capable(false),
color_default(false),
duplex_default(UNKNOWN_DUPLEX_MODE) {}
PrinterSemanticCapsAndDefaults::~PrinterSemanticCapsAndDefaults() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
string16 PrintBackend::SimplifyDocumentTitle(const string16& title) {
string16 no_controls(title);
no_controls.erase(
std::remove_if(no_controls.begin(), no_controls.end(), &u_iscntrl),
no_controls.end());
string16 result;
ui::ElideString(no_controls, kMaxDocumentTitleLength, &result);
return result;
}
} // namespace printing
<commit_msg>Revert 158193 - Set max title size to 50<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "printing/backend/print_backend.h"
#include <algorithm>
#include "third_party/icu/public/common/unicode/uchar.h"
#include "ui/base/text/text_elider.h"
namespace {
const wchar_t kDefaultDocumentTitle[] = L"Untitled Document";
const int kMaxDocumentTitleLength = 25;
} // namespace
namespace printing {
PrinterBasicInfo::PrinterBasicInfo()
: printer_status(0),
is_default(false) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterSemanticCapsAndDefaults::PrinterSemanticCapsAndDefaults()
: color_capable(false),
duplex_capable(false),
color_default(false),
duplex_default(UNKNOWN_DUPLEX_MODE) {}
PrinterSemanticCapsAndDefaults::~PrinterSemanticCapsAndDefaults() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
string16 PrintBackend::SimplifyDocumentTitle(const string16& title) {
string16 no_controls(title);
no_controls.erase(
std::remove_if(no_controls.begin(), no_controls.end(), &u_iscntrl),
no_controls.end());
string16 result;
ui::ElideString(no_controls, kMaxDocumentTitleLength, &result);
return result;
}
} // namespace printing
<|endoftext|> |
<commit_before>#include "Endian.h"
#include "os.h"
#if defined( __POSIX__ )
#include <arpa/inet.h>
#include <machine/endian.h>
#elif defined( __WIN_API__ )
#include <WinSock2.h>
#endif
#if defined( __OS_X__ )
#if ( __DARWIN_BYTE_ORDER == __DARWIN_LITTLE_ENDIAN )
#define ntohll( x ) __DARWIN_OSSwapInt64( x )
#define htonll( x ) ntohll( x )
#elif ( __DARWIN_BYTE_ORDER == __DARWIN_BIG_ENDIAN )
#define ntohll( x ) ( x )
#define htonll( x ) ( x )
#endif
#elif defined( __WIN_API__ )
#define ntohll( x ) ( ( ( int64_t )( ntohl( ( int32_t )( ( x << 32 ) >> 32 ) ) ) << 32) | ( uint32_t )ntohl( ( ( int32_t )( x >> 32 ) ) ) )
#define htonll( x ) ntohll( x )
#endif
/*
====================
Endian::NetworkToHost
Converts a network-order byte to the host's order
====================
*/
int64_t Endian::NetworkToHost( const int64_t networkInt, const uint8_t length ) {
int64_t result = 0;
switch ( length ) {
case 2:
result = ntohs( ( uint16_t )networkInt );
break;
case 4:
result = ntohl( ( uint32_t )networkInt );
break;
case 8:
result = ntohll( networkInt );
break;
default:
result = networkInt;
}
return result;
}
/*
====================
Endian::HostToNetwork
Converts a host-order byte to the network's order
====================
*/
int64_t Endian::HostToNetwork( const int64_t hostInt, const uint8_t length ) {
int64_t result = 0;
switch ( length ) {
case 2:
result = htons( ( uint16_t )hostInt );
break;
case 4:
result = htonl( ( uint32_t )hostInt );
break;
case 8:
result = htonll( hostInt );
break;
default:
result = hostInt;
}
return result;
}
/*
====================
Endian::NetworkToHostUnsigned
Same as ::NetworkToHost but returns the unsigned value
====================
*/
uint64_t Endian::NetworkToHostUnsigned( const uint64_t networkInt, const uint8_t length ) {
int64_t signedNum = *( int64_t * )&networkInt;
signedNum = Endian::NetworkToHost( signedNum, length );
const uint64_t result = *( int64_t * )&signedNum;
return result;
}
/*
====================
Endian::HostToNetworkUnsigned
Same as ::HostToNetwork but returns the unsigned value
====================
*/
uint64_t Endian::HostToNetworkUnsigned( const uint64_t hostInt, const uint8_t length ) {
int64_t signedNum = *( int64_t * )&hostInt;
signedNum = Endian::HostToNetwork( signedNum, length );
const uint64_t result = *( int64_t * )&signedNum;
return result;
}
<commit_msg>Fixed 4 spaces being used where real tabs belong<commit_after>#include "Endian.h"
#include "os.h"
#if defined( __POSIX__ )
#include <arpa/inet.h>
#include <machine/endian.h>
#elif defined( __WIN_API__ )
#include <WinSock2.h>
#endif
#if defined( __OS_X__ )
#if ( __DARWIN_BYTE_ORDER == __DARWIN_LITTLE_ENDIAN )
#define ntohll( x ) __DARWIN_OSSwapInt64( x )
#define htonll( x ) ntohll( x )
#elif ( __DARWIN_BYTE_ORDER == __DARWIN_BIG_ENDIAN )
#define ntohll( x ) ( x )
#define htonll( x ) ( x )
#endif
#elif defined( __WIN_API__ )
#define ntohll( x ) ( ( ( int64_t )( ntohl( ( int32_t )( ( x << 32 ) >> 32 ) ) ) << 32) | ( uint32_t )ntohl( ( ( int32_t )( x >> 32 ) ) ) )
#define htonll( x ) ntohll( x )
#endif
/*
====================
Endian::NetworkToHost
Converts a network-order byte to the host's order
====================
*/
int64_t Endian::NetworkToHost( const int64_t networkInt, const uint8_t length ) {
int64_t result = 0;
switch ( length ) {
case 2:
result = ntohs( ( uint16_t )networkInt );
break;
case 4:
result = ntohl( ( uint32_t )networkInt );
break;
case 8:
result = ntohll( networkInt );
break;
default:
result = networkInt;
}
return result;
}
/*
====================
Endian::HostToNetwork
Converts a host-order byte to the network's order
====================
*/
int64_t Endian::HostToNetwork( const int64_t hostInt, const uint8_t length ) {
int64_t result = 0;
switch ( length ) {
case 2:
result = htons( ( uint16_t )hostInt );
break;
case 4:
result = htonl( ( uint32_t )hostInt );
break;
case 8:
result = htonll( hostInt );
break;
default:
result = hostInt;
}
return result;
}
/*
====================
Endian::NetworkToHostUnsigned
Same as ::NetworkToHost but returns the unsigned value
====================
*/
uint64_t Endian::NetworkToHostUnsigned( const uint64_t networkInt, const uint8_t length ) {
int64_t signedNum = *( int64_t * )&networkInt;
signedNum = Endian::NetworkToHost( signedNum, length );
const uint64_t result = *( int64_t * )&signedNum;
return result;
}
/*
====================
Endian::HostToNetworkUnsigned
Same as ::HostToNetwork but returns the unsigned value
====================
*/
uint64_t Endian::HostToNetworkUnsigned( const uint64_t hostInt, const uint8_t length ) {
int64_t signedNum = *( int64_t * )&hostInt;
signedNum = Endian::HostToNetwork( signedNum, length );
const uint64_t result = *( int64_t * )&signedNum;
return result;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 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.3 1999/11/12 20:36:51 rahulj
* Changed library name to xerces-c.lib.
*
* Revision 1.1.1.1 1999/11/09 01:07:31 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:22 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT
// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#define NO_NATIVE_BOOL
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
typedef unsigned short XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int XMLUInt32;
// ---------------------------------------------------------------------------
// Force on the XML4C debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if 0
#define XML4C_DEBUG
#endif
// ---------------------------------------------------------------------------
// Provide some common string ops that are different/notavail on CSet
// ---------------------------------------------------------------------------
inline char toupper(const char toUpper)
{
if ((toUpper >= 'a') && (toUpper <= 'z'))
return char(toUpper - 0x20);
return toUpper;
}
inline char tolower(const char toLower)
{
if ((toLower >= 'A') && (toLower <= 'Z'))
return char(toLower + 0x20);
return toLower;
}
int stricmp(const char* const str1, const char* const str2);
int strnicmp(const char* const str1, const char* const str2, const unsigned int count);
// ---------------------------------------------------------------------------
// The name of the DLL that is built by the CSet C++ version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<commit_msg>XMLCh now defined to wchar_t<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 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.4 2000/01/12 19:11:49 aruna1
* XMLCh now defined to wchar_t
*
* Revision 1.3 1999/11/12 20:36:51 rahulj
* Changed library name to xerces-c.lib.
*
* Revision 1.1.1.1 1999/11/09 01:07:31 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:22 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT
// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#define NO_NATIVE_BOOL
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
//typedef unsigned short XMLCh;
typedef wchar_t XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short XMLUInt16;
typedef unsigned int XMLUInt32;
// ---------------------------------------------------------------------------
// Force on the XML4C debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if 0
#define XML4C_DEBUG
#endif
// ---------------------------------------------------------------------------
// Provide some common string ops that are different/notavail on CSet
// ---------------------------------------------------------------------------
inline char toupper(const char toUpper)
{
if ((toUpper >= 'a') && (toUpper <= 'z'))
return char(toUpper - 0x20);
return toUpper;
}
inline char tolower(const char toLower)
{
if ((toLower >= 'A') && (toLower <= 'Z'))
return char(toLower + 0x20);
return toLower;
}
int stricmp(const char* const str1, const char* const str2);
int strnicmp(const char* const str1, const char* const str2, const unsigned int count);
// ---------------------------------------------------------------------------
// The name of the DLL that is built by the CSet C++ version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<|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/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/TranscodingException.hpp>
#include <util/XML88591Transcoder.hpp>
#include <util/XMLString.hpp>
#include <string.h>
// ---------------------------------------------------------------------------
// XML88591Transcoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XML88591Transcoder::XML88591Transcoder( const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
{
}
XML88591Transcoder::~XML88591Transcoder()
{
}
// ---------------------------------------------------------------------------
// XML88591Transcoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
unsigned int
XML88591Transcoder::transcodeFrom( const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the number of bytes in the source.
//
const unsigned int countToDo = srcCount < maxChars ? srcCount : maxChars;
//
// Loop through the bytes to do and convert over each byte. Its just
// a cast to the wide char type.
//
const XMLByte* srcPtr = srcData;
XMLCh* destPtr = toFill;
const XMLByte* srcEnd = srcPtr + countToDo;
while (srcPtr < srcEnd)
*destPtr++ = XMLCh(*srcPtr++);
// Set the bytes eaten, and set the char size array to the fixed size
bytesEaten = countToDo;
memset(charSizes, 1, countToDo);
// Return the chars we transcoded
return countToDo;
}
unsigned int
XML88591Transcoder::transcodeTo(const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxBytes);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output bytes and the number of chars in the source.
//
const unsigned int countToDo = srcCount < maxBytes ? srcCount : maxBytes;
//
// Loop through the bytes to do and convert over each byte. Its just
// a downcast of the wide char, checking for unrepresentable chars.
//
const XMLCh* srcPtr = srcData;
const XMLCh* srcEnd = srcPtr + countToDo;
XMLByte* destPtr = toFill;
while (srcPtr < srcEnd)
{
// If its legal, take it and jump back to top
if (*srcPtr < 0x256)
{
*destPtr++ = XMLByte(*srcPtr++);
continue;
}
//
// Its not representable so use a replacement char. According to
// the options, either throw or use the replacement.
//
if (options == UnRep_Throw)
{
XMLCh tmpBuf[16];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
*destPtr++ = 0x1A;
srcPtr++;
}
// Set the chars eaten
charsEaten = countToDo;
// Return the bytes we transcoded
return countToDo;
}
bool XML88591Transcoder::canTranscodeTo(const unsigned int toCheck) const
{
return (toCheck < 256);
}
<commit_msg>fix bug[1393]: Converting from Unicode to iso8859<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/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/TranscodingException.hpp>
#include <util/XML88591Transcoder.hpp>
#include <util/XMLString.hpp>
#include <string.h>
// ---------------------------------------------------------------------------
// XML88591Transcoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XML88591Transcoder::XML88591Transcoder( const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
{
}
XML88591Transcoder::~XML88591Transcoder()
{
}
// ---------------------------------------------------------------------------
// XML88591Transcoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
unsigned int
XML88591Transcoder::transcodeFrom( const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the number of bytes in the source.
//
const unsigned int countToDo = srcCount < maxChars ? srcCount : maxChars;
//
// Loop through the bytes to do and convert over each byte. Its just
// a cast to the wide char type.
//
const XMLByte* srcPtr = srcData;
XMLCh* destPtr = toFill;
const XMLByte* srcEnd = srcPtr + countToDo;
while (srcPtr < srcEnd)
*destPtr++ = XMLCh(*srcPtr++);
// Set the bytes eaten, and set the char size array to the fixed size
bytesEaten = countToDo;
memset(charSizes, 1, countToDo);
// Return the chars we transcoded
return countToDo;
}
unsigned int
XML88591Transcoder::transcodeTo(const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxBytes);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output bytes and the number of chars in the source.
//
const unsigned int countToDo = srcCount < maxBytes ? srcCount : maxBytes;
//
// Loop through the bytes to do and convert over each byte. Its just
// a downcast of the wide char, checking for unrepresentable chars.
//
const XMLCh* srcPtr = srcData;
const XMLCh* srcEnd = srcPtr + countToDo;
XMLByte* destPtr = toFill;
while (srcPtr < srcEnd)
{
// If its legal, take it and jump back to top
if (*srcPtr < 256)
{
*destPtr++ = XMLByte(*srcPtr++);
continue;
}
//
// Its not representable so use a replacement char. According to
// the options, either throw or use the replacement.
//
if (options == UnRep_Throw)
{
XMLCh tmpBuf[16];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
*destPtr++ = 0x1A;
srcPtr++;
}
// Set the chars eaten
charsEaten = countToDo;
// Return the bytes we transcoded
return countToDo;
}
bool XML88591Transcoder::canTranscodeTo(const unsigned int toCheck) const
{
return (toCheck < 256);
}
<|endoftext|> |
<commit_before>/***************************************************************************
wpprotocol.cpp - WP Plugin
-------------------
begin : Fri Apr 26 2002
copyright : (C) 2002 by Gav Wood
email : [email protected]
Based on code from : (C) 2002 by Duncan Mac-Vicar Prett
email : [email protected]
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
// QT Includes
#include <qcursor.h>
#include <qprocess.h>
#include <qfile.h>
#include <qregexp.h>
// KDE Includes
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpopupmenu.h>
#include <kpushbutton.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <kstdguiitem.h>
// Local Includes
#include "wpprotocol.h"
#include "wpdebug.h"
#include "wpcontact.h"
#include "wpaddcontact.h"
#include "wppreferences.h"
// Kopete Includes
#include "kopetemetacontact.h"
class KPopupMenu;
//WPProtocol *WPProtocol::sProtocol = 0;
K_EXPORT_COMPONENT_FACTORY(kopete_wp, KGenericFactory<WPProtocol>);
// WP Protocol
WPProtocol::WPProtocol(QObject *parent, QString name, QStringList) : KopeteProtocol(parent, name)
{
DEBUG(WPDMETHOD, "WPProtocol::WPProtocol()");
theInterface = 0;
// Load Status Actions
initActions();
// Set up initial settings
KGlobal::config()->setGroup("WinPopup");
QString theSMBClientPath = KGlobal::config()->readEntry("SMBClientPath", "/usr/bin/smbclient");
QString theInitialSearchHost = KGlobal::config()->readEntry("InitialSearchHost", "127.0.0.1");
QString theHostName = KGlobal::config()->readEntry("HostName", "");
QString theAwayMessage = KGlobal::config()->readEntry("AwayMessage", i18n("Sorry, I'm not here right now."));
int theHostCheckFrequency = KGlobal::config()->readNumEntry("HostCheckFrequency", 60);
int theMessageCheckFrequency = KGlobal::config()->readNumEntry("MessageCheckFrequency", 5);
bool theSendAwayMessage = KGlobal::config()->readBoolEntry("SendAwayMessage", true);
bool theEmailDefault = KGlobal::config()->readBoolEntry("EmailDefault", true);
if(theHostName == "")
{ QFile infile("/etc/hostname");
if(infile.open(IO_ReadOnly))
{ QTextStream in(&infile);
char c;
for(in >> c; c != '.' && (!infile.atEnd()); in >> c)
theHostName = theHostName + char((c >= 65 && c < 91) ? c : (c - 32));
infile.close();
}
else
theHostName = "LOCALHOST";
}
KGlobal::config()->writeEntry("HostName", theHostName);
KGlobal::config()->writeEntry("SMBClientPath", theSMBClientPath);
KGlobal::config()->writeEntry("InitialSearchHost", theInitialSearchHost);
KGlobal::config()->writeEntry("AwayMessage", theAwayMessage);
KGlobal::config()->writeEntry("SendAwayMessage", theSendAwayMessage);
KGlobal::config()->writeEntry("EmailDefault", theEmailDefault);
KGlobal::config()->writeEntry("HostCheckFrequency", theHostCheckFrequency);
KGlobal::config()->writeEntry("MessageCheckFrequency", theMessageCheckFrequency);
// Create preferences menu
mPrefs = new WPPreferences("wp_icon", this);
QObject::connect( mPrefs, SIGNAL(saved(void)), this, SLOT(slotSettingsChanged(void)));
// ask for installation.
if(KMessageBox::questionYesNo(mPrefs, i18n("The Samba configuration file needs to be modified in order for Kopete to receive WinPopup messages. Would you like to do this now?"), i18n("Modify Samba Configuration Now?"), KGuiItem(), KGuiItem(), "WPFirstTime") == KMessageBox::Yes)
installSamba();
// Create the interface...
theInterface = new KopeteWinPopup(theSMBClientPath, theInitialSearchHost, theHostName, theHostCheckFrequency, theMessageCheckFrequency);
// Call slotSettingsChanged() to get it all registered.
slotSettingsChanged();
setAvailable();
QObject::connect( );
// FIXME: I guess 'myself' should be a metacontact as well...
theMyself = new WPContact(theHostName, this, 0L); // XXX: Should be from config file!!!
QObject::connect( theInterface, SIGNAL(newMessage(const QString &, const QDateTime &, const QString &)), this, SLOT(slotGotNewMessage(const QString &, const QDateTime &, const QString &)));
}
// Destructor
WPProtocol::~WPProtocol()
{
DEBUG(WPDMETHOD, "WPProtocol::~WPProtocol()");
//contacts are now deleted himself when the protocol unload. this code is obsolete
/*
QPtrList<KopeteMetaContact> metaContacts = KopeteContactList::contactList()->metaContacts();
for(KopeteMetaContact *i = metaContacts.first(); i; i = metaContacts.next())
{ DEBUG(WPDINFO, "Checking metacontact: " << i->displayName());
QPtrList<KopeteContact> contacts = i->contacts();
for(KopeteContact *j = contacts.first(); j; j = contacts.next())
{ DEBUG(WPDINFO, "Checking contact " << j->displayName() << " of type: " << j->protocol());
if(j->protocol() == "WPProtocol")
{ contacts.remove(j);
delete j;
}
}
}
delete theMyself;
DEBUG(WPDINFO, "Deleted OK.");*/
}
QStringList WPProtocol::addressBookFields() const
{
DEBUG(WPDMETHOD, "WPProtocol::addressBookFields()");
return QStringList("messaging/winpopup");
}
void WPProtocol::serialize(KopeteMetaContact *metaContact)
{
// DEBUG(WPDMETHOD, "WPProtocol::serialize(metaContact => " << metaContact->displayName() << ", <strList>)");
QStringList strList;
QStringList addressList;
QPtrList<KopeteContact> contacts = metaContact->contacts();
for(KopeteContact *c = contacts.first(); c; c = contacts.next())
if(c->protocol()->pluginId() == this->pluginId())
{
WPContact *curContact = static_cast<WPContact*>(c);
DEBUG(WPDINFO, "Sub-Contact " << curContact->host() << " is ours - serialising.");
strList << curContact->host();
// addressList << curContact->host();
}
// QString addresses = addressList.join(",");
// if(!addresses.isEmpty())
// metaContact->setAddressBookField(WPProtocol::protocol(), "messaging/winpopup", addresses);
metaContact->setPluginData(this , strList);
// DEBUG(WPDINFO, "Finished with strList = " << strList.join(","));
}
void WPProtocol::deserialize(KopeteMetaContact *metaContact, const QStringList &strList)
{
DEBUG(WPDMETHOD, "WPProtocol::deserialize(metaContact => " << metaContact->displayName() << ", " << strList.join(",") << ")");
// not using the kabc thingy for now it would seem...
// QStringList hosts = QStringList::split("\n", metaContact->addressBookField(this, "messaging/winpopup"));
for(unsigned i = 0; i < strList.count(); i++)
{
QString host = strList[i];
DEBUG(WPDINFO, "Sub-Contact " << host << " is deserialised.");
WPContact *newContact = new WPContact(host, this, metaContact);
metaContact->addContact(newContact);
}
}
WPContact *WPProtocol::getContact(const QString &Name, KopeteMetaContact* theMetaContact)
{
DEBUG(WPDMETHOD, "WPProtocol::getContact(" << Name << ", " << theMetaContact << ")");
KopeteContactList *l = KopeteContactList::contactList();
if(!theMetaContact)
{
// Should really ask to see if they want the contact adding to their list first...
theMetaContact = l->findContact(this->pluginId(), Name, "smb://" + Name);
if(!theMetaContact)
{ DEBUG(WPDINFO, "Adding " << Name << " to the contact list...");
theMetaContact = new KopeteMetaContact();
l->addMetaContact(theMetaContact);
}
}
KopeteContact *theContact = theMetaContact->findContact(this->pluginId(), Name, "smb://" + Name);
if(!theContact)
{ theContact = new WPContact(Name, this, theMetaContact);
theMetaContact->addContact(theContact);
}
return dynamic_cast<WPContact *>(theContact);
}
void WPProtocol::slotGotNewMessage(const QString &Body, const QDateTime &Arrival, const QString &From)
{
DEBUG(WPDMETHOD, "WPProtocol::slotGotNewMessage(" << Body << ", " << Arrival.toString() << ", " << From << ")");
if(online)
if(available)
getContact(From)->slotNewMessage(Body, Arrival);
else
{
// add message quietly?
// send away message - TODO: should be taken from global settings
KGlobal::config()->setGroup("WinPopup");
theInterface->slotSendMessage(KGlobal::config()->readEntry("AwayMessage"), From);
}
}
bool WPProtocol::unload()
{
DEBUG(WPDMETHOD, "WPProtocol::unload()");
delete theInterface;
return KopeteProtocol::unload();
}
void WPProtocol::connect()
{
DEBUG(WPDMETHOD, "WPProtocol::Connect()");
online = true;
theInterface->goOnline();
available = true;
setStatusIcon( "wp_available" );
}
void WPProtocol::disconnect()
{
DEBUG(WPDMETHOD, "WPProtocol::Disconnect()");
online = false;
theInterface->goOffline();
setStatusIcon( "wp_offline" );
}
void WPProtocol::setAvailable()
{
DEBUG(WPDMETHOD, "WPProtocol::setAvailable()");
online = true;
theInterface->goOnline();
available = true;
setStatusIcon( "wp_available" );
// do any other stuff?
}
void WPProtocol::setAway()
{
DEBUG(WPDMETHOD, "WPProtocol::setAway()");
available = false;
online = true;
theInterface->goOnline();
setStatusIcon( "wp_away" );
// do any other stuff?
}
KActionMenu* WPProtocol::protocolActions()
{
return actionStatusMenu;
}
void WPProtocol::slotSendMessage(const QString &Body, const QString &Destination)
{
DEBUG(WPDMETHOD, "WPProtocol::slotSendMessage(" << Body << ", " << Destination << ")");
theInterface->sendMessage(Body, Destination);
}
void WPProtocol::slotSettingsChanged()
{
DEBUG(WPDMETHOD, "WPProtocol::slotSettingsChanged()");
KGlobal::config()->setGroup("WinPopup");
theInterface->setSMBClientPath(KGlobal::config()->readEntry("SMBClientPath", "/usr/bin/smbclient"));
theInterface->setInitialSearchHost(KGlobal::config()->readEntry("InitialSearchHost", "127.0.0.1"));
theInterface->setHostName(KGlobal::config()->readEntry("HostName", "LOCAL"));
theInterface->setHostCheckFrequency(KGlobal::config()->readNumEntry("HostCheckFrequency", 60));
theInterface->setMessageCheckFrequency(KGlobal::config()->readNumEntry("MessageCheckFrequency", 5));
}
void WPProtocol::initActions()
{
DEBUG(WPDMETHOD, "WPProtocol::initActions()");
actionGoAvailable = new KAction("Online", "wp_available", 0, this, SLOT(connect()), this, "actionGoAvailable");
actionGoOffline = new KAction("Offline", "wp_offline", 0, this, SLOT(disconnect()), this, "actionGoOffline");
actionGoAway = new KAction("Away", "wp_away", 0, this, SLOT(setAway()), this, "actionGoAway");
KGlobal::config()->setGroup("WinPopup");
QString handle = "WinPopup (" + KGlobal::config()->readEntry("HostName", "") + ")";
actionStatusMenu = new KActionMenu("WinPopup", this);
actionStatusMenu->popupMenu()->insertTitle(
SmallIcon( statusIcon() ), handle );
actionStatusMenu->insert(actionGoAvailable);
actionStatusMenu->insert(actionGoAway);
actionStatusMenu->insert(actionGoOffline);
}
void WPProtocol::installSamba()
{
DEBUG(WPDMETHOD, "WPPreferences::installSamba()");
QStringList args;
args += KStandardDirs::findExe("winpopup-install.sh");
args += KStandardDirs::findExe("winpopup-send.sh");
KApplication::kdeinitExecWait("kdesu", args);
}
#include "wpprotocol.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>compile<commit_after>/***************************************************************************
wpprotocol.cpp - WP Plugin
-------------------
begin : Fri Apr 26 2002
copyright : (C) 2002 by Gav Wood
email : [email protected]
Based on code from : (C) 2002 by Duncan Mac-Vicar Prett
email : [email protected]
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
// QT Includes
#include <qcursor.h>
#include <qprocess.h>
#include <qfile.h>
#include <qregexp.h>
// KDE Includes
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpopupmenu.h>
#include <kpushbutton.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <kstdguiitem.h>
// Local Includes
#include "wpprotocol.h"
#include "wpdebug.h"
#include "wpcontact.h"
#include "wpaddcontact.h"
#include "wppreferences.h"
// Kopete Includes
#include "kopetemetacontact.h"
class KPopupMenu;
//WPProtocol *WPProtocol::sProtocol = 0;
K_EXPORT_COMPONENT_FACTORY(kopete_wp, KGenericFactory<WPProtocol>);
// WP Protocol
WPProtocol::WPProtocol(QObject *parent, QString name, QStringList) : KopeteProtocol(parent, name)
{
DEBUG(WPDMETHOD, "WPProtocol::WPProtocol()");
theInterface = 0;
// Load Status Actions
initActions();
// Set up initial settings
KGlobal::config()->setGroup("WinPopup");
QString theSMBClientPath = KGlobal::config()->readEntry("SMBClientPath", "/usr/bin/smbclient");
QString theInitialSearchHost = KGlobal::config()->readEntry("InitialSearchHost", "127.0.0.1");
QString theHostName = KGlobal::config()->readEntry("HostName", "");
QString theAwayMessage = KGlobal::config()->readEntry("AwayMessage", i18n("Sorry, I'm not here right now."));
int theHostCheckFrequency = KGlobal::config()->readNumEntry("HostCheckFrequency", 60);
int theMessageCheckFrequency = KGlobal::config()->readNumEntry("MessageCheckFrequency", 5);
bool theSendAwayMessage = KGlobal::config()->readBoolEntry("SendAwayMessage", true);
bool theEmailDefault = KGlobal::config()->readBoolEntry("EmailDefault", true);
if(theHostName == "")
{ QFile infile("/etc/hostname");
if(infile.open(IO_ReadOnly))
{ QTextStream in(&infile);
char c;
for(in >> c; c != '.' && (!infile.atEnd()); in >> c)
theHostName = theHostName + char((c >= 65 && c < 91) ? c : (c - 32));
infile.close();
}
else
theHostName = "LOCALHOST";
}
KGlobal::config()->writeEntry("HostName", theHostName);
KGlobal::config()->writeEntry("SMBClientPath", theSMBClientPath);
KGlobal::config()->writeEntry("InitialSearchHost", theInitialSearchHost);
KGlobal::config()->writeEntry("AwayMessage", theAwayMessage);
KGlobal::config()->writeEntry("SendAwayMessage", theSendAwayMessage);
KGlobal::config()->writeEntry("EmailDefault", theEmailDefault);
KGlobal::config()->writeEntry("HostCheckFrequency", theHostCheckFrequency);
KGlobal::config()->writeEntry("MessageCheckFrequency", theMessageCheckFrequency);
// Create preferences menu
mPrefs = new WPPreferences("wp_icon", this);
QObject::connect( mPrefs, SIGNAL(saved(void)), this, SLOT(slotSettingsChanged(void)));
// ask for installation.
if(KMessageBox::questionYesNo(mPrefs, i18n("The Samba configuration file needs to be modified in order for Kopete to receive WinPopup messages. Would you like to do this now?"), i18n("Modify Samba Configuration Now?"), KGuiItem(), KGuiItem(), "WPFirstTime") == KMessageBox::Yes)
installSamba();
// Create the interface...
theInterface = new KopeteWinPopup(theSMBClientPath, theInitialSearchHost, theHostName, theHostCheckFrequency, theMessageCheckFrequency);
// Call slotSettingsChanged() to get it all registered.
slotSettingsChanged();
setAvailable();
connect();
// FIXME: I guess 'myself' should be a metacontact as well...
theMyself = new WPContact(theHostName, this, 0L); // XXX: Should be from config file!!!
QObject::connect( theInterface, SIGNAL(newMessage(const QString &, const QDateTime &, const QString &)), this, SLOT(slotGotNewMessage(const QString &, const QDateTime &, const QString &)));
}
// Destructor
WPProtocol::~WPProtocol()
{
DEBUG(WPDMETHOD, "WPProtocol::~WPProtocol()");
//contacts are now deleted himself when the protocol unload. this code is obsolete
/*
QPtrList<KopeteMetaContact> metaContacts = KopeteContactList::contactList()->metaContacts();
for(KopeteMetaContact *i = metaContacts.first(); i; i = metaContacts.next())
{ DEBUG(WPDINFO, "Checking metacontact: " << i->displayName());
QPtrList<KopeteContact> contacts = i->contacts();
for(KopeteContact *j = contacts.first(); j; j = contacts.next())
{ DEBUG(WPDINFO, "Checking contact " << j->displayName() << " of type: " << j->protocol());
if(j->protocol() == "WPProtocol")
{ contacts.remove(j);
delete j;
}
}
}
delete theMyself;
DEBUG(WPDINFO, "Deleted OK.");*/
}
QStringList WPProtocol::addressBookFields() const
{
DEBUG(WPDMETHOD, "WPProtocol::addressBookFields()");
return QStringList("messaging/winpopup");
}
void WPProtocol::serialize(KopeteMetaContact *metaContact)
{
// DEBUG(WPDMETHOD, "WPProtocol::serialize(metaContact => " << metaContact->displayName() << ", <strList>)");
QStringList strList;
QStringList addressList;
QPtrList<KopeteContact> contacts = metaContact->contacts();
for(KopeteContact *c = contacts.first(); c; c = contacts.next())
if(c->protocol()->pluginId() == this->pluginId())
{
WPContact *curContact = static_cast<WPContact*>(c);
DEBUG(WPDINFO, "Sub-Contact " << curContact->host() << " is ours - serialising.");
strList << curContact->host();
// addressList << curContact->host();
}
// QString addresses = addressList.join(",");
// if(!addresses.isEmpty())
// metaContact->setAddressBookField(WPProtocol::protocol(), "messaging/winpopup", addresses);
metaContact->setPluginData(this , strList);
// DEBUG(WPDINFO, "Finished with strList = " << strList.join(","));
}
void WPProtocol::deserialize(KopeteMetaContact *metaContact, const QStringList &strList)
{
DEBUG(WPDMETHOD, "WPProtocol::deserialize(metaContact => " << metaContact->displayName() << ", " << strList.join(",") << ")");
// not using the kabc thingy for now it would seem...
// QStringList hosts = QStringList::split("\n", metaContact->addressBookField(this, "messaging/winpopup"));
for(unsigned i = 0; i < strList.count(); i++)
{
QString host = strList[i];
DEBUG(WPDINFO, "Sub-Contact " << host << " is deserialised.");
WPContact *newContact = new WPContact(host, this, metaContact);
metaContact->addContact(newContact);
}
}
WPContact *WPProtocol::getContact(const QString &Name, KopeteMetaContact* theMetaContact)
{
DEBUG(WPDMETHOD, "WPProtocol::getContact(" << Name << ", " << theMetaContact << ")");
KopeteContactList *l = KopeteContactList::contactList();
if(!theMetaContact)
{
// Should really ask to see if they want the contact adding to their list first...
theMetaContact = l->findContact(this->pluginId(), Name, "smb://" + Name);
if(!theMetaContact)
{ DEBUG(WPDINFO, "Adding " << Name << " to the contact list...");
theMetaContact = new KopeteMetaContact();
l->addMetaContact(theMetaContact);
}
}
KopeteContact *theContact = theMetaContact->findContact(this->pluginId(), Name, "smb://" + Name);
if(!theContact)
{ theContact = new WPContact(Name, this, theMetaContact);
theMetaContact->addContact(theContact);
}
return dynamic_cast<WPContact *>(theContact);
}
void WPProtocol::slotGotNewMessage(const QString &Body, const QDateTime &Arrival, const QString &From)
{
DEBUG(WPDMETHOD, "WPProtocol::slotGotNewMessage(" << Body << ", " << Arrival.toString() << ", " << From << ")");
if(online)
if(available)
getContact(From)->slotNewMessage(Body, Arrival);
else
{
// add message quietly?
// send away message - TODO: should be taken from global settings
KGlobal::config()->setGroup("WinPopup");
theInterface->slotSendMessage(KGlobal::config()->readEntry("AwayMessage"), From);
}
}
bool WPProtocol::unload()
{
DEBUG(WPDMETHOD, "WPProtocol::unload()");
delete theInterface;
return KopeteProtocol::unload();
}
void WPProtocol::connect()
{
DEBUG(WPDMETHOD, "WPProtocol::Connect()");
online = true;
theInterface->goOnline();
available = true;
setStatusIcon( "wp_available" );
}
void WPProtocol::disconnect()
{
DEBUG(WPDMETHOD, "WPProtocol::Disconnect()");
online = false;
theInterface->goOffline();
setStatusIcon( "wp_offline" );
}
void WPProtocol::setAvailable()
{
DEBUG(WPDMETHOD, "WPProtocol::setAvailable()");
online = true;
theInterface->goOnline();
available = true;
setStatusIcon( "wp_available" );
// do any other stuff?
}
void WPProtocol::setAway()
{
DEBUG(WPDMETHOD, "WPProtocol::setAway()");
available = false;
online = true;
theInterface->goOnline();
setStatusIcon( "wp_away" );
// do any other stuff?
}
KActionMenu* WPProtocol::protocolActions()
{
return actionStatusMenu;
}
void WPProtocol::slotSendMessage(const QString &Body, const QString &Destination)
{
DEBUG(WPDMETHOD, "WPProtocol::slotSendMessage(" << Body << ", " << Destination << ")");
theInterface->sendMessage(Body, Destination);
}
void WPProtocol::slotSettingsChanged()
{
DEBUG(WPDMETHOD, "WPProtocol::slotSettingsChanged()");
KGlobal::config()->setGroup("WinPopup");
theInterface->setSMBClientPath(KGlobal::config()->readEntry("SMBClientPath", "/usr/bin/smbclient"));
theInterface->setInitialSearchHost(KGlobal::config()->readEntry("InitialSearchHost", "127.0.0.1"));
theInterface->setHostName(KGlobal::config()->readEntry("HostName", "LOCAL"));
theInterface->setHostCheckFrequency(KGlobal::config()->readNumEntry("HostCheckFrequency", 60));
theInterface->setMessageCheckFrequency(KGlobal::config()->readNumEntry("MessageCheckFrequency", 5));
}
void WPProtocol::initActions()
{
DEBUG(WPDMETHOD, "WPProtocol::initActions()");
actionGoAvailable = new KAction("Online", "wp_available", 0, this, SLOT(connect()), this, "actionGoAvailable");
actionGoOffline = new KAction("Offline", "wp_offline", 0, this, SLOT(disconnect()), this, "actionGoOffline");
actionGoAway = new KAction("Away", "wp_away", 0, this, SLOT(setAway()), this, "actionGoAway");
KGlobal::config()->setGroup("WinPopup");
QString handle = "WinPopup (" + KGlobal::config()->readEntry("HostName", "") + ")";
actionStatusMenu = new KActionMenu("WinPopup", this);
actionStatusMenu->popupMenu()->insertTitle(
SmallIcon( statusIcon() ), handle );
actionStatusMenu->insert(actionGoAvailable);
actionStatusMenu->insert(actionGoAway);
actionStatusMenu->insert(actionGoOffline);
}
void WPProtocol::installSamba()
{
DEBUG(WPDMETHOD, "WPPreferences::installSamba()");
QStringList args;
args += KStandardDirs::findExe("winpopup-install.sh");
args += KStandardDirs::findExe("winpopup-send.sh");
KApplication::kdeinitExecWait("kdesu", args);
}
#include "wpprotocol.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2012-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file init.c
*
* PX4FMU-specific early startup code. This file implements the
* board_app_initialize() function that is called early by nsh during startup.
*
* Code here is run before the rcS script is invoked; it should start required
* subsystems and perform board-specific initialization.
*/
/****************************************************************************
* Included Files
****************************************************************************/
#include "board_config.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <debug.h>
#include <errno.h>
#include <nuttx/config.h>
extern "C" {
#include <nuttx/board.h>
}
#include <nuttx/spi/spi.h>
#include <nuttx/sdio.h>
#include <nuttx/mmcsd.h>
#include <nuttx/analog/adc.h>
#include <nuttx/mm/gran.h>
#include <chip.h>
#include <stm32_uart.h>
#include <arch/board/board.h>
#include "arm_internal.h"
#include <drivers/drv_hrt.h>
#include <drivers/drv_board_led.h>
#include <systemlib/px4_macros.h>
#include <px4_arch/io_timer.h>
#include <px4_platform_common/init.h>
#include <px4_platform/gpio.h>
#include <px4_platform/board_determine_hw_info.h>
#include <px4_platform/board_dma_alloc.h>
#include <px4_platform/gpio/mcp23009.hpp>
/****************************************************************************
* Pre-Processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/*
* Ideally we'd be able to get these from arm_internal.h,
* but since we want to be able to disable the NuttX use
* of leds for system indication at will and there is no
* separate switch, we need to build independent of the
* CONFIG_ARCH_LEDS configuration switch.
*/
__BEGIN_DECLS
extern void led_init(void);
extern void led_on(int led);
extern void led_off(int led);
__END_DECLS
/************************************************************************************
* Name: board_peripheral_reset
*
* Description:
*
************************************************************************************/
__EXPORT void board_peripheral_reset(int ms)
{
/* set the peripheral rails off */
VDD_5V_PERIPH_EN(false);
board_control_spi_sensors_power(false, 0xffff);
VDD_3V3_SENSORS4_EN(false);
bool last = READ_VDD_3V3_SPEKTRUM_POWER_EN();
/* Keep Spektum on to discharge rail*/
VDD_3V3_SPEKTRUM_POWER_EN(false);
/* wait for the peripheral rail to reach GND */
usleep(ms * 1000);
syslog(LOG_DEBUG, "reset done, %d ms\n", ms);
/* re-enable power */
/* switch the peripheral rail back on */
VDD_3V3_SPEKTRUM_POWER_EN(last);
board_control_spi_sensors_power(true, 0xffff);
VDD_3V3_SENSORS4_EN(true);
VDD_5V_PERIPH_EN(true);
}
/************************************************************************************
* Name: board_on_reset
*
* Description:
* Optionally provided function called on entry to board_system_reset
* It should perform any house keeping prior to the rest.
*
* status - 1 if resetting to boot loader
* 0 if just resetting
*
************************************************************************************/
__EXPORT void board_on_reset(int status)
{
for (int i = 0; i < DIRECT_PWM_OUTPUT_CHANNELS; ++i) {
px4_arch_configgpio(PX4_MAKE_GPIO_INPUT(io_timer_channel_get_as_pwm_input(i)));
}
if (status >= 0) {
up_mdelay(6);
}
}
/************************************************************************************
* Name: stm32_boardinitialize
*
* Description:
* All STM32 architectures must provide the following entry point. This entry point
* is called early in the initialization -- after all memory has been configured
* and mapped but before any devices have been initialized.
*
************************************************************************************/
extern "C" __EXPORT void
stm32_boardinitialize(void)
{
board_on_reset(-1); /* Reset PWM first thing */
/* configure LEDs */
board_autoled_initialize();
/* configure pins */
const uint32_t gpio[] = PX4_GPIO_INIT_LIST;
px4_gpio_init(gpio, arraySize(gpio));
/* configure SPI interfaces (we can do this here as long as we only have a single SPI hw config version -
* otherwise we need to move this after board_determine_hw_info()) */
static_assert(BOARD_NUM_SPI_CFG_HW_VERSIONS == 1, "Need to move the SPI initialization for multi-version support");
stm32_spiinitialize();
/* configure USB interfaces */
stm32_usbinitialize();
VDD_3V3_ETH_POWER_EN(true);
}
/****************************************************************************
* Name: board_app_initialize
*
* Description:
* Perform application specific initialization. This function is never
* called directly from application code, but only indirectly via the
* (non-standard) boardctl() interface using the command BOARDIOC_INIT.
*
* Input Parameters:
* arg - The boardctl() argument is passed to the board_app_initialize()
* implementation without modification. The argument has no
* meaning to NuttX; the meaning of the argument is a contract
* between the board-specific initalization logic and the the
* matching application logic. The value cold be such things as a
* mode enumeration value, a set of DIP switch switch settings, a
* pointer to configuration data read from a file or serial FLASH,
* or whatever you would like to do with it. Every implementation
* should accept zero/NULL as a default configuration.
*
* Returned Value:
* Zero (OK) is returned on success; a negated errno value is returned on
* any failure to indicate the nature of the failure.
*
****************************************************************************/
__EXPORT int board_app_initialize(uintptr_t arg)
{
/* Power on Interfaces */
VDD_3V3_SD_CARD_EN(true);
VDD_5V_PERIPH_EN(true);
VDD_5V_HIPOWER_EN(true);
board_spi_reset(10, 0xffff);
VDD_3V3_SENSORS4_EN(true);
VDD_3V3_SPEKTRUM_POWER_EN(true);
/* Need hrt running before using the ADC */
px4_platform_init();
if (OK == board_determine_hw_info()) {
syslog(LOG_INFO, "[boot] Rev 0x%1x : Ver 0x%1x %s\n", board_get_hw_revision(), board_get_hw_version(),
board_get_hw_type_name());
} else {
syslog(LOG_ERR, "[boot] Failed to read HW revision and version\n");
}
/* configure the DMA allocator */
if (board_dma_alloc_init() < 0) {
syslog(LOG_ERR, "[boot] DMA alloc FAILED\n");
}
/* set up the serial DMA polling */
static struct hrt_call serial_dma_call;
struct timespec ts;
/*
* Poll at 1ms intervals for received bytes that have not triggered
* a DMA event.
*/
ts.tv_sec = 0;
ts.tv_nsec = 1000000;
hrt_call_every(&serial_dma_call,
ts_to_abstime(&ts),
ts_to_abstime(&ts),
(hrt_callout)stm32_serial_dma_poll,
NULL);
/* initial LED state */
drv_led_start();
led_off(LED_RED);
led_on(LED_GREEN); // Indicate Power.
led_off(LED_BLUE);
if (board_hardfault_init(2, true) != 0) {
led_on(LED_RED);
}
#ifdef CONFIG_MMCSD
int ret = stm32_sdio_initialize();
if (ret != OK) {
led_on(LED_RED);
return ret;
}
#endif /* CONFIG_MMCSD */
/* Configure the HW based on the manifest */
px4_platform_configure();
int hw_version = board_get_hw_version();
if (hw_version == 0x9 || hw_version == 0xa) {
static MCP23009 mcp23009{3, 0x25};
// No USB
if (hw_version == 0x9) {
// < P8
ret = mcp23009.init(0xf0, 0xf0, 0x0f);
// >= P8
//ret = mcp23009.init(0xf1, 0xf0, 0x0f);
}
if (hw_version == 0xa) {
// < P6
//ret = mcp23009.init(0xf0, 0xf0, 0x0f);
// >= P6
ret = mcp23009.init(0xf1, 0xf0, 0x0f);
}
if (ret != OK) {
led_on(LED_RED);
return ret;
}
}
return OK;
}
<commit_msg>px4_fmu-v5x: Initalize PWM as input with Pull Downs<commit_after>/****************************************************************************
*
* Copyright (c) 2012-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file init.c
*
* PX4FMU-specific early startup code. This file implements the
* board_app_initialize() function that is called early by nsh during startup.
*
* Code here is run before the rcS script is invoked; it should start required
* subsystems and perform board-specific initialization.
*/
/****************************************************************************
* Included Files
****************************************************************************/
#include "board_config.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <debug.h>
#include <errno.h>
#include <nuttx/config.h>
extern "C" {
#include <nuttx/board.h>
}
#include <nuttx/spi/spi.h>
#include <nuttx/sdio.h>
#include <nuttx/mmcsd.h>
#include <nuttx/analog/adc.h>
#include <nuttx/mm/gran.h>
#include <chip.h>
#include <stm32_uart.h>
#include <arch/board/board.h>
#include "arm_internal.h"
#include <drivers/drv_hrt.h>
#include <drivers/drv_board_led.h>
#include <systemlib/px4_macros.h>
#include <px4_arch/io_timer.h>
#include <px4_platform_common/init.h>
#include <px4_platform/gpio.h>
#include <px4_platform/board_determine_hw_info.h>
#include <px4_platform/board_dma_alloc.h>
#include <px4_platform/gpio/mcp23009.hpp>
/****************************************************************************
* Pre-Processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/*
* Ideally we'd be able to get these from arm_internal.h,
* but since we want to be able to disable the NuttX use
* of leds for system indication at will and there is no
* separate switch, we need to build independent of the
* CONFIG_ARCH_LEDS configuration switch.
*/
__BEGIN_DECLS
extern void led_init(void);
extern void led_on(int led);
extern void led_off(int led);
__END_DECLS
/************************************************************************************
* Name: board_peripheral_reset
*
* Description:
*
************************************************************************************/
__EXPORT void board_peripheral_reset(int ms)
{
/* set the peripheral rails off */
VDD_5V_PERIPH_EN(false);
board_control_spi_sensors_power(false, 0xffff);
VDD_3V3_SENSORS4_EN(false);
bool last = READ_VDD_3V3_SPEKTRUM_POWER_EN();
/* Keep Spektum on to discharge rail*/
VDD_3V3_SPEKTRUM_POWER_EN(false);
/* wait for the peripheral rail to reach GND */
usleep(ms * 1000);
syslog(LOG_DEBUG, "reset done, %d ms\n", ms);
/* re-enable power */
/* switch the peripheral rail back on */
VDD_3V3_SPEKTRUM_POWER_EN(last);
board_control_spi_sensors_power(true, 0xffff);
VDD_3V3_SENSORS4_EN(true);
VDD_5V_PERIPH_EN(true);
}
/************************************************************************************
* Name: board_on_reset
*
* Description:
* Optionally provided function called on entry to board_system_reset
* It should perform any house keeping prior to the rest.
*
* status - 1 if resetting to boot loader
* 0 if just resetting
*
************************************************************************************/
__EXPORT void board_on_reset(int status)
{
for (int i = 0; i < DIRECT_PWM_OUTPUT_CHANNELS; ++i) {
px4_arch_configgpio(PX4_MAKE_GPIO_INPUT_PULL_DOWN(io_timer_channel_get_as_pwm_input(i)));
}
if (status >= 0) {
up_mdelay(6);
}
}
/************************************************************************************
* Name: stm32_boardinitialize
*
* Description:
* All STM32 architectures must provide the following entry point. This entry point
* is called early in the initialization -- after all memory has been configured
* and mapped but before any devices have been initialized.
*
************************************************************************************/
extern "C" __EXPORT void
stm32_boardinitialize(void)
{
board_on_reset(-1); /* Reset PWM first thing */
/* configure LEDs */
board_autoled_initialize();
/* configure pins */
const uint32_t gpio[] = PX4_GPIO_INIT_LIST;
px4_gpio_init(gpio, arraySize(gpio));
/* configure SPI interfaces (we can do this here as long as we only have a single SPI hw config version -
* otherwise we need to move this after board_determine_hw_info()) */
static_assert(BOARD_NUM_SPI_CFG_HW_VERSIONS == 1, "Need to move the SPI initialization for multi-version support");
stm32_spiinitialize();
/* configure USB interfaces */
stm32_usbinitialize();
VDD_3V3_ETH_POWER_EN(true);
}
/****************************************************************************
* Name: board_app_initialize
*
* Description:
* Perform application specific initialization. This function is never
* called directly from application code, but only indirectly via the
* (non-standard) boardctl() interface using the command BOARDIOC_INIT.
*
* Input Parameters:
* arg - The boardctl() argument is passed to the board_app_initialize()
* implementation without modification. The argument has no
* meaning to NuttX; the meaning of the argument is a contract
* between the board-specific initalization logic and the the
* matching application logic. The value cold be such things as a
* mode enumeration value, a set of DIP switch switch settings, a
* pointer to configuration data read from a file or serial FLASH,
* or whatever you would like to do with it. Every implementation
* should accept zero/NULL as a default configuration.
*
* Returned Value:
* Zero (OK) is returned on success; a negated errno value is returned on
* any failure to indicate the nature of the failure.
*
****************************************************************************/
__EXPORT int board_app_initialize(uintptr_t arg)
{
/* Power on Interfaces */
VDD_3V3_SD_CARD_EN(true);
VDD_5V_PERIPH_EN(true);
VDD_5V_HIPOWER_EN(true);
board_spi_reset(10, 0xffff);
VDD_3V3_SENSORS4_EN(true);
VDD_3V3_SPEKTRUM_POWER_EN(true);
/* Need hrt running before using the ADC */
px4_platform_init();
if (OK == board_determine_hw_info()) {
syslog(LOG_INFO, "[boot] Rev 0x%1x : Ver 0x%1x %s\n", board_get_hw_revision(), board_get_hw_version(),
board_get_hw_type_name());
} else {
syslog(LOG_ERR, "[boot] Failed to read HW revision and version\n");
}
/* configure the DMA allocator */
if (board_dma_alloc_init() < 0) {
syslog(LOG_ERR, "[boot] DMA alloc FAILED\n");
}
/* set up the serial DMA polling */
static struct hrt_call serial_dma_call;
struct timespec ts;
/*
* Poll at 1ms intervals for received bytes that have not triggered
* a DMA event.
*/
ts.tv_sec = 0;
ts.tv_nsec = 1000000;
hrt_call_every(&serial_dma_call,
ts_to_abstime(&ts),
ts_to_abstime(&ts),
(hrt_callout)stm32_serial_dma_poll,
NULL);
/* initial LED state */
drv_led_start();
led_off(LED_RED);
led_on(LED_GREEN); // Indicate Power.
led_off(LED_BLUE);
if (board_hardfault_init(2, true) != 0) {
led_on(LED_RED);
}
#ifdef CONFIG_MMCSD
int ret = stm32_sdio_initialize();
if (ret != OK) {
led_on(LED_RED);
return ret;
}
#endif /* CONFIG_MMCSD */
/* Configure the HW based on the manifest */
px4_platform_configure();
int hw_version = board_get_hw_version();
if (hw_version == 0x9 || hw_version == 0xa) {
static MCP23009 mcp23009{3, 0x25};
// No USB
if (hw_version == 0x9) {
// < P8
ret = mcp23009.init(0xf0, 0xf0, 0x0f);
// >= P8
//ret = mcp23009.init(0xf1, 0xf0, 0x0f);
}
if (hw_version == 0xa) {
// < P6
//ret = mcp23009.init(0xf0, 0xf0, 0x0f);
// >= P6
ret = mcp23009.init(0xf1, 0xf0, 0x0f);
}
if (ret != OK) {
led_on(LED_RED);
return ret;
}
}
return OK;
}
<|endoftext|> |
<commit_before>// Random access pseudorandom permutations
#include <other/core/random/permute.h>
#include <other/core/random/counter.h>
#include <other/core/math/integer_log.h>
#include <other/core/python/module.h>
namespace other {
// For details, see
// John Black and Phillip Rogaway, Ciphers with Arbitrary Finite Domains.
// Mihir Bellare, Thomas Ristenpart, Phillip Rogaway, and Till Stegers, Format-Preserving Encryption.
// http://blog.notdot.net/2007/9/Damn-Cool-Algorithms-Part-2-Secure-permutations-with-block-ciphers
// Specifically, we use the FE2 construction with a = 2^k, b = 2^k or 2^(k+1), three rounds, and threefry
// as the round function. Then we use cycle walking to turn this into a permutation on [0,n-1].
// An earlier version used TEA, but the quality of this was questionable and it didn't work for small n.
static inline uint64_t fe2_encrypt(const int bits, const uint128_t key, const uint64_t x) {
assert(bits==64 || x<(uint64_t(1)<<bits));
// Prepare for FE2
const int a = bits>>1, b = bits-a; // logs of a,b in the paper
const uint32_t ma = (uint64_t(1)<<a)-1, // bit masks
mb = (uint64_t(1)<<b)-1;
uint32_t L(x>>b), R = x&mb;
// Three rounds of FE2
L = ma&(L+cast_uint128<uint32_t>(threefry(key,uint64_t(1)<<32|R))); // round 1: s = a
R = mb&(R+cast_uint128<uint32_t>(threefry(key,uint64_t(2)<<32|L))); // round 2: s = b
L = ma&(L+cast_uint128<uint32_t>(threefry(key,uint64_t(3)<<32|R))); // round 3: s = a
return uint64_t(L)<<b|R;
}
// The inverse of fe2_encrypt
static inline uint64_t fe2_decrypt(const int bits, const uint128_t key, const uint64_t x) {
assert(bits==64 || x<(uint64_t(1)<<bits));
// Prepare for FE2
const int a = bits>>1, b = bits-a; // logs of a,b in the paper
const uint32_t ma = (uint64_t(1)<<a)-1, // bit masks
mb = (uint64_t(1)<<b)-1;
uint32_t L(x>>b), R = x&mb;
// Three rounds of FE2
L = ma&(L-cast_uint128<uint32_t>(threefry(key,uint64_t(3)<<32|R))); // round 3: s = a
R = mb&(R-cast_uint128<uint32_t>(threefry(key,uint64_t(2)<<32|L))); // round 2: s = b
L = ma&(L-cast_uint128<uint32_t>(threefry(key,uint64_t(1)<<32|R))); // round 1: s = a
return uint64_t(L)<<b|R;
}
// Find a power of two strictly larger than n. By insisting on strictly larger, we avoid the weakness
// that Feistel permutations are always even (apparently). This would be detectable for small n.
static inline int next_log(const uint64_t n) {
return integer_log(n)+1;
}
// Since we use the next power of two for the FE2 block cipher, the cycle walking construction
// needs an average of at most 2 iterations. This amounts to 6 calls to threefry, or a couple
// hundred cycles.
uint64_t random_permute(const uint64_t n, const uint128_t key, uint64_t x) {
assert(x<n);
const int bits = next_log(n);
do { // Repeatedly encrypt until we're back in the right range
x = fe2_encrypt(bits,key,x);
} while (x>=n);
return x;
}
uint64_t random_unpermute(const uint64_t n, const uint128_t key, uint64_t x) {
assert(x<n);
const int bits = next_log(n);
do { // Repeatedly decrypt until we're back in the right range
x = fe2_decrypt(bits,key,x);
} while (x>=n);
return x;
}
}
using namespace other;
void wrap_permute() {
OTHER_FUNCTION(random_permute)
OTHER_FUNCTION(random_unpermute)
}
<commit_msg>permute: Revert back to Martin's way<commit_after>// Random access pseudorandom permutations
#include <other/core/random/permute.h>
#include <other/core/random/counter.h>
#include <other/core/math/integer_log.h>
#include <other/core/python/module.h>
namespace other {
// For details, see
// John Black and Phillip Rogaway, Ciphers with Arbitrary Finite Domains.
// Mihir Bellare, Thomas Ristenpart, Phillip Rogaway, and Till Stegers, Format-Preserving Encryption.
// http://blog.notdot.net/2007/9/Damn-Cool-Algorithms-Part-2-Secure-permutations-with-block-ciphers
// Specifically, we use the FE2 construction with a = 2^k, b = 2^k or 2^(k+1), three rounds, and threefry
// as the round function. Then we use cycle walking to turn this into a permutation on [0,n-1].
// An earlier version used TEA, but the quality of this was questionable and it didn't work for small n.
static inline uint64_t fe2_encrypt(const int bits, const uint128_t key, const uint64_t x) {
assert(bits==64 || x<(uint64_t(1)<<bits));
// Prepare for FE2
const int a = bits>>1, b = bits-a; // logs of a,b in the paper
const uint32_t ma = (uint64_t(1)<<a)-1, // bit masks
mb = (uint64_t(1)<<b)-1;
uint32_t L = uint32_t(x>>b), R = x&mb;
// Three rounds of FE2
L = ma&(L+cast_uint128<uint32_t>(threefry(key,uint64_t(1)<<32|R))); // round 1: s = a
R = mb&(R+cast_uint128<uint32_t>(threefry(key,uint64_t(2)<<32|L))); // round 2: s = b
L = ma&(L+cast_uint128<uint32_t>(threefry(key,uint64_t(3)<<32|R))); // round 3: s = a
return uint64_t(L)<<b|R;
}
// The inverse of fe2_encrypt
static inline uint64_t fe2_decrypt(const int bits, const uint128_t key, const uint64_t x) {
assert(bits==64 || x<(uint64_t(1)<<bits));
// Prepare for FE2
const int a = bits>>1, b = bits-a; // logs of a,b in the paper
const uint32_t ma = (uint64_t(1)<<a)-1, // bit masks
mb = (uint64_t(1)<<b)-1;
uint32_t L = uint32_t(x>>b), R = x&mb;
// Three rounds of FE2
L = ma&(L-cast_uint128<uint32_t>(threefry(key,uint64_t(3)<<32|R))); // round 3: s = a
R = mb&(R-cast_uint128<uint32_t>(threefry(key,uint64_t(2)<<32|L))); // round 2: s = b
L = ma&(L-cast_uint128<uint32_t>(threefry(key,uint64_t(1)<<32|R))); // round 1: s = a
return uint64_t(L)<<b|R;
}
// Find a power of two strictly larger than n. By insisting on strictly larger, we avoid the weakness
// that Feistel permutations are always even (apparently). This would be detectable for small n.
static inline int next_log(const uint64_t n) {
return integer_log(n)+1;
}
// Since we use the next power of two for the FE2 block cipher, the cycle walking construction
// needs an average of at most 2 iterations. This amounts to 6 calls to threefry, or a couple
// hundred cycles.
uint64_t random_permute(const uint64_t n, const uint128_t key, uint64_t x) {
assert(x<n);
const int bits = next_log(n);
do { // Repeatedly encrypt until we're back in the right range
x = fe2_encrypt(bits,key,x);
} while (x>=n);
return x;
}
uint64_t random_unpermute(const uint64_t n, const uint128_t key, uint64_t x) {
assert(x<n);
const int bits = next_log(n);
do { // Repeatedly decrypt until we're back in the right range
x = fe2_decrypt(bits,key,x);
} while (x>=n);
return x;
}
}
using namespace other;
void wrap_permute() {
OTHER_FUNCTION(random_permute)
OTHER_FUNCTION(random_unpermute)
}
<|endoftext|> |
<commit_before><commit_msg>Move most used pages to front.<commit_after><|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <random>
// class bernoulli_distribution
// template<class _URNG> result_type operator()(_URNG& g);
#include <random>
#include <cassert>
int main()
{
{
typedef std::uniform_int_distribution<> D;
typedef std::minstd_rand0 G;
G g;
D d(.75);
int count = 0;
for (int i = 0; i < 10000; ++i)
{
bool u = d(g);
if (u)
++count;
}
assert(count > 7400);
}
}
<commit_msg>[rand.dist.bern.bin]. The evaluation function for this binomial distribution is hopefully just a placeholder. It is using the simplest and slowest method for computing the distribution and needs to be upgraded.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <random>
// class bernoulli_distribution
// template<class _URNG> result_type operator()(_URNG& g);
#include <random>
#include <cassert>
int main()
{
{
typedef std::bernoulli_distribution D;
typedef std::minstd_rand0 G;
G g;
D d(.75);
int count = 0;
for (int i = 0; i < 10000; ++i)
{
bool u = d(g);
if (u)
++count;
}
assert(count > 7400);
}
}
<|endoftext|> |
<commit_before>#include "Players/CECP_Mediator.h"
#include <string>
#include <future>
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Players/Player.h"
#include "Exceptions/Illegal_Move.h"
#include "Exceptions/Game_Ended.h"
#include "Utility/String.h"
CECP_Mediator::CECP_Mediator(const Player& local_player)
{
std::string expected = "protover 2";
if(receive_command() == expected)
{
send_command("feature "
"usermove=1 "
"sigint=0 "
"reuse=1 "
"myname=\"" + local_player.name() + "\" "
"name=1 "
"ping=1 "
"setboard=1 "
"colors=0 "
"done=1");
}
else
{
log("ERROR: Expected \"" + expected + "\"");
throw std::runtime_error("Error in communicating with CECP program.");
}
}
void CECP_Mediator::setup_turn(Board& board, Clock& clock)
{
while(true)
{
auto command = receive_cecp_command(board, clock, false);
if(command == "go")
{
set_indent_level(board.whose_turn() == WHITE ? 2 : 3);
log("telling local AI to move at leisure and accepting move");
in_force_mode = false;
board.choose_move_at_leisure();
return;
}
else if (String::starts_with(command, "setboard "))
{
auto fen = String::split(command, " ", 1).back();
try
{
// Handle stateless GUIs that send the next board position
// instead of a move.
board.submit_move(board.create_move(fen));
log("Derived move: " + board.game_record().back()->coordinate_move());
}
catch(const Illegal_Move&)
{
log("Rearranging board to: " + fen);
board = Board(fen);
}
}
else if(String::starts_with(command, "usermove "))
{
auto move = String::split(command).back();
try
{
log("Applying move: " + move);
auto result = board.submit_move(board.create_move(move));
if(result.game_has_ended())
{
report_end_of_game(result);
}
if( ! in_force_mode)
{
set_indent_level(board.whose_turn() == WHITE ? 2 : 3);
log("Local AI now chooses a move");
board.choose_move_at_leisure();
return;
}
}
catch(const Illegal_Move& e)
{
send_command("Illegal move (" + std::string(e.what()) + ") " + move);
}
}
else if(String::starts_with(command, "time ") || String::starts_with(command, "otim "))
{
auto time = std::stod(String::split(command, " ")[1])/100; // time specified in centiseconds
auto ai_color = board.whose_turn();
auto clock_color = String::starts_with(command, "time ") ? ai_color : opposite(ai_color);
clock.set_time(clock_color, time);
log("setting " + color_text(clock_color) + "'s time to " + std::to_string(time) + " seconds.");
}
}
}
void CECP_Mediator::listen(Board& board, Clock& clock)
{
last_listening_command = std::async(std::launch::async, &CECP_Mediator::listener, this, std::ref(board), std::ref(clock));
}
Game_Result CECP_Mediator::handle_move(Board& board, const Move& move)
{
if(in_force_mode)
{
log("Ignoring move: " + move.coordinate_move());
return {};
}
else
{
send_command("move " + move.coordinate_move());
auto result = board.submit_move(move);
if(result.game_has_ended())
{
report_end_of_game(result);
}
return result;
}
}
bool CECP_Mediator::pondering_allowed() const
{
return thinking_on_opponent_time;
}
std::string CECP_Mediator::receive_cecp_command(Board& board, Clock& clock, bool while_listening)
{
while(true)
{
std::string command;
if(while_listening)
{
command = receive_command();
}
else
{
command = last_listening_command.valid() ? last_listening_command.get() : receive_command();
}
if(String::starts_with(command, "ping "))
{
command[1] = 'o'; // change "ping" to "pong"
send_command(command);
}
else if(String::starts_with(command, "result "))
{
auto result = String::split(command).at(1);
auto reason = String::split(String::split(command, "{", 1)[1], "}", 1)[0];
report_end_of_game(result, reason);
}
else if(command == "force")
{
log("Entering force mode");
board.pick_move_now();
clock.stop();
in_force_mode = true;
}
else if(String::starts_with(command, "level "))
{
log("got time specs: " + command);
auto split = String::split(command);
log("moves to reset clock = " + split[1]);
auto reset_moves = String::string_to_size_t(split[1]);
auto time_split = String::split(split[2], ":");
auto game_time = 0;
if(time_split.size() == 1)
{
log("game time = " + time_split[0] + " minutes");
game_time = 60*std::stoi(time_split[0]);
}
else
{
log("game time = " + time_split[0] + " minutes and " + time_split[1] + " seconds");
game_time = 60*std::stoi(time_split[0]) + std::stoi(time_split[1]);
}
log("increment = " + split[3]);
auto increment = std::stod(split[3]);
clock = Clock(game_time, reset_moves, increment, WHITE, false);
}
else if(String::starts_with(command, "st "))
{
log("got time specs: " + command);
auto split = String::split(command);
auto time_per_move = std::stoi(split[1]);
auto reset_moves = 1;
auto increment = 0;
auto game_time = time_per_move;
clock = Clock(game_time, reset_moves, increment, WHITE, false);
}
else if(command == "post")
{
if(board.thinking_mode() == CECP)
{
board.set_thinking_mode(NO_THINKING);
log("Disabling thinking output for CECP");
}
else
{
board.set_thinking_mode(CECP);
log("turning on thinking output for CECP");
}
}
else if(command == "nopost")
{
board.set_thinking_mode(NO_THINKING);
log("turning off thinking output for CECP");
}
else if(command == "easy")
{
log("Turning off pondering");
thinking_on_opponent_time = false;
}
else if(command == "hard")
{
log("Turning on pondering");
thinking_on_opponent_time = true;
}
else if(command == "new")
{
log("Setting board to standard start position and resetting clock");
board = Board{};
clock = Clock(clock.initial_time(), clock.moves_per_time_period(), clock.increment(WHITE), WHITE, false);
in_force_mode = false;
}
else if(String::starts_with(command, "name "))
{
log("Getting other player's name");
set_other_player_name(String::split(command, " ", 1).back());
}
else
{
return command;
}
}
}
std::string CECP_Mediator::listener(Board& board, Clock& clock)
{
while(true)
{
auto command = receive_cecp_command(board, clock, true);
if(command == "?")
{
log("Forcing local AI to pick move and accepting it");
board.pick_move_now();
}
else
{
return command;
}
}
}
void CECP_Mediator::report_end_of_game(const std::string& result, const std::string& reason) const
{
send_command(result + " {" + reason + "}");
throw Game_Ended();
}
void CECP_Mediator::report_end_of_game(const Game_Result& result) const
{
report_end_of_game(result.game_ending_annotation(), result.ending_reason());
}
<commit_msg>Tell GUI that program quits after game<commit_after>#include "Players/CECP_Mediator.h"
#include <string>
#include <future>
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Players/Player.h"
#include "Exceptions/Illegal_Move.h"
#include "Exceptions/Game_Ended.h"
#include "Utility/String.h"
CECP_Mediator::CECP_Mediator(const Player& local_player)
{
std::string expected = "protover 2";
if(receive_command() == expected)
{
send_command("feature "
"usermove=1 "
"sigint=0 "
"reuse=0 "
"myname=\"" + local_player.name() + "\" "
"name=1 "
"ping=1 "
"setboard=1 "
"colors=0 "
"done=1");
}
else
{
log("ERROR: Expected \"" + expected + "\"");
throw std::runtime_error("Error in communicating with CECP program.");
}
}
void CECP_Mediator::setup_turn(Board& board, Clock& clock)
{
while(true)
{
auto command = receive_cecp_command(board, clock, false);
if(command == "go")
{
set_indent_level(board.whose_turn() == WHITE ? 2 : 3);
log("telling local AI to move at leisure and accepting move");
in_force_mode = false;
board.choose_move_at_leisure();
return;
}
else if (String::starts_with(command, "setboard "))
{
auto fen = String::split(command, " ", 1).back();
try
{
// Handle stateless GUIs that send the next board position
// instead of a move.
board.submit_move(board.create_move(fen));
log("Derived move: " + board.game_record().back()->coordinate_move());
}
catch(const Illegal_Move&)
{
log("Rearranging board to: " + fen);
board = Board(fen);
}
}
else if(String::starts_with(command, "usermove "))
{
auto move = String::split(command).back();
try
{
log("Applying move: " + move);
auto result = board.submit_move(board.create_move(move));
if(result.game_has_ended())
{
report_end_of_game(result);
}
if( ! in_force_mode)
{
set_indent_level(board.whose_turn() == WHITE ? 2 : 3);
log("Local AI now chooses a move");
board.choose_move_at_leisure();
return;
}
}
catch(const Illegal_Move& e)
{
send_command("Illegal move (" + std::string(e.what()) + ") " + move);
}
}
else if(String::starts_with(command, "time ") || String::starts_with(command, "otim "))
{
auto time = std::stod(String::split(command, " ")[1])/100; // time specified in centiseconds
auto ai_color = board.whose_turn();
auto clock_color = String::starts_with(command, "time ") ? ai_color : opposite(ai_color);
clock.set_time(clock_color, time);
log("setting " + color_text(clock_color) + "'s time to " + std::to_string(time) + " seconds.");
}
}
}
void CECP_Mediator::listen(Board& board, Clock& clock)
{
last_listening_command = std::async(std::launch::async, &CECP_Mediator::listener, this, std::ref(board), std::ref(clock));
}
Game_Result CECP_Mediator::handle_move(Board& board, const Move& move)
{
if(in_force_mode)
{
log("Ignoring move: " + move.coordinate_move());
return {};
}
else
{
send_command("move " + move.coordinate_move());
auto result = board.submit_move(move);
if(result.game_has_ended())
{
report_end_of_game(result);
}
return result;
}
}
bool CECP_Mediator::pondering_allowed() const
{
return thinking_on_opponent_time;
}
std::string CECP_Mediator::receive_cecp_command(Board& board, Clock& clock, bool while_listening)
{
while(true)
{
std::string command;
if(while_listening)
{
command = receive_command();
}
else
{
command = last_listening_command.valid() ? last_listening_command.get() : receive_command();
}
if(String::starts_with(command, "ping "))
{
command[1] = 'o'; // change "ping" to "pong"
send_command(command);
}
else if(String::starts_with(command, "result "))
{
auto result = String::split(command).at(1);
auto reason = String::split(String::split(command, "{", 1)[1], "}", 1)[0];
report_end_of_game(result, reason);
}
else if(command == "force")
{
log("Entering force mode");
board.pick_move_now();
clock.stop();
in_force_mode = true;
}
else if(String::starts_with(command, "level "))
{
log("got time specs: " + command);
auto split = String::split(command);
log("moves to reset clock = " + split[1]);
auto reset_moves = String::string_to_size_t(split[1]);
auto time_split = String::split(split[2], ":");
auto game_time = 0;
if(time_split.size() == 1)
{
log("game time = " + time_split[0] + " minutes");
game_time = 60*std::stoi(time_split[0]);
}
else
{
log("game time = " + time_split[0] + " minutes and " + time_split[1] + " seconds");
game_time = 60*std::stoi(time_split[0]) + std::stoi(time_split[1]);
}
log("increment = " + split[3]);
auto increment = std::stod(split[3]);
clock = Clock(game_time, reset_moves, increment, WHITE, false);
}
else if(String::starts_with(command, "st "))
{
log("got time specs: " + command);
auto split = String::split(command);
auto time_per_move = std::stoi(split[1]);
auto reset_moves = 1;
auto increment = 0;
auto game_time = time_per_move;
clock = Clock(game_time, reset_moves, increment, WHITE, false);
}
else if(command == "post")
{
if(board.thinking_mode() == CECP)
{
board.set_thinking_mode(NO_THINKING);
log("Disabling thinking output for CECP");
}
else
{
board.set_thinking_mode(CECP);
log("turning on thinking output for CECP");
}
}
else if(command == "nopost")
{
board.set_thinking_mode(NO_THINKING);
log("turning off thinking output for CECP");
}
else if(command == "easy")
{
log("Turning off pondering");
thinking_on_opponent_time = false;
}
else if(command == "hard")
{
log("Turning on pondering");
thinking_on_opponent_time = true;
}
else if(command == "new")
{
log("Setting board to standard start position and resetting clock");
board = Board{};
clock = Clock(clock.initial_time(), clock.moves_per_time_period(), clock.increment(WHITE), WHITE, false);
in_force_mode = false;
}
else if(String::starts_with(command, "name "))
{
log("Getting other player's name");
set_other_player_name(String::split(command, " ", 1).back());
}
else
{
return command;
}
}
}
std::string CECP_Mediator::listener(Board& board, Clock& clock)
{
while(true)
{
auto command = receive_cecp_command(board, clock, true);
if(command == "?")
{
log("Forcing local AI to pick move and accepting it");
board.pick_move_now();
}
else
{
return command;
}
}
}
void CECP_Mediator::report_end_of_game(const std::string& result, const std::string& reason) const
{
send_command(result + " {" + reason + "}");
throw Game_Ended();
}
void CECP_Mediator::report_end_of_game(const Game_Result& result) const
{
report_end_of_game(result.game_ending_annotation(), result.ending_reason());
}
<|endoftext|> |
<commit_before>// $Header$
#include "RMacro.h"
#include <TSystem.h>
#include <TROOT.h>
#include <G__ci.h>
using namespace Reve;
//______________________________________________________________________
// RMacro
//
// Sub-class of TMacro, overriding Exec to unload the previous verison
// and cleanup after the execution.
ClassImp(RMacro)
RMacro::RMacro() : TMacro() {}
RMacro::RMacro(const RMacro& m) : TMacro(m) {}
RMacro::RMacro(const char* name, const char* /*title*/) : TMacro(name, "") {}
/**************************************************************************/
void RMacro::Exec(const char* params)
{
if(Reve::CheckMacro(fName))
G__unloadfile(fTitle.Data());
// Copy from TMacro::Exec. Difference is that the file is really placed
// into the /tmp.
TString fname = "/tmp/";
{
//the current implementation uses a file in the current directory.
//should be replaced by a direct execution from memory by CINT
fname += GetName();
fname += ".Cexec";
SaveSource(fname);
//disable a possible call to gROOT->Reset from the executed script
gROOT->SetExecutingMacro(kTRUE);
//execute script in /tmp
TString exec = ".x " + fname;
TString p = params;
if (p == "") p = fParams;
if (p != "")
exec += "(" + p + ")";
gROOT->ProcessLine(exec);
//enable gROOT->Reset
gROOT->SetExecutingMacro(kFALSE);
//delete the temporary file
gSystem->Unlink(fname);
}
G__unloadfile(fname);
}
<commit_msg>Check for macro via full-path (fTitle); save macro as '.C' not '.Cexec'.<commit_after>// $Header$
#include "RMacro.h"
#include <TSystem.h>
#include <TROOT.h>
#include <G__ci.h>
using namespace Reve;
//______________________________________________________________________
// RMacro
//
// Sub-class of TMacro, overriding Exec to unload the previous verison
// and cleanup after the execution.
ClassImp(RMacro)
RMacro::RMacro() : TMacro() {}
RMacro::RMacro(const RMacro& m) : TMacro(m) {}
RMacro::RMacro(const char* name, const char* /*title*/) : TMacro(name, "") {}
/**************************************************************************/
void RMacro::Exec(const char* params)
{
if(Reve::CheckMacro(fTitle.Data()))
G__unloadfile(fTitle.Data());
// Copy from TMacro::Exec. Difference is that the file is really placed
// into the /tmp.
TString fname = "/tmp/";
{
//the current implementation uses a file in the current directory.
//should be replaced by a direct execution from memory by CINT
fname += GetName();
fname += ".C";
SaveSource(fname);
//disable a possible call to gROOT->Reset from the executed script
gROOT->SetExecutingMacro(kTRUE);
//execute script in /tmp
TString exec = ".x " + fname;
TString p = params;
if (p == "") p = fParams;
if (p != "")
exec += "(" + p + ")";
gROOT->ProcessLine(exec);
//enable gROOT->Reset
gROOT->SetExecutingMacro(kFALSE);
//delete the temporary file
gSystem->Unlink(fname);
}
G__unloadfile(fname);
}
<|endoftext|> |
<commit_before>// SFMLWidget.cpp
// GTK widget containing an SFML OpenGL drawing context
// Based on example from SFML github wiki: https://github.com/LaurentGomila/SFML/wiki/Source%3A-GTK-SFMLWidget
// - changed to use SFML window instead of RenderWindow
// Code is public domain
#include "SFMLWidget.hpp"
// Tested on Linux Mint 12.4 and Windows 7
#if defined(SFML_SYSTEM_WINDOWS)
#include <gdk/gdkwin32.h>
#define GET_WINDOW_HANDLE_FROM_GDK GDK_WINDOW_HANDLE
#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
#include <gdk/gdkx.h>
#define GET_WINDOW_HANDLE_FROM_GDK GDK_WINDOW_XID
#elif defined(SFML_SYSTEM_MACOS)
#error Note: You have to figure out an analogue way to access the handle of the widget on a Mac-System
#else
#error Unsupported Operating System
#endif
SFMLWidget::SFMLWidget(const sf::VideoMode & mode, int size_request, const sf::ContextSettings & context_settings): gl_context_settings(context_settings)
{
if(size_request<=0)
size_request = std::max<int>(1, std::min<int>(mode.width, mode.height) / 2);
set_size_request(size_request, size_request);
set_has_window(false); // Makes this behave like an interal object rather then a parent window.
}
SFMLWidget::~SFMLWidget()
{
}
void SFMLWidget::on_size_allocate(Gtk::Allocation& allocation)
{
// Do something with the space that we have actually been given:
// (We will not be given heights or widths less than we have requested, though
// we might get more)
this->set_allocation(allocation);
if(m_refGdkWindow)
{
m_refGdkWindow->move_resize(allocation.get_x(),
allocation.get_y(),
allocation.get_width(),
allocation.get_height());
glWindow.setSize(sf::Vector2u(allocation.get_width(),
allocation.get_height()));
}
}
void SFMLWidget::on_realize()
{
Gtk::Widget::on_realize();
if(!m_refGdkWindow)
{
//Create the GdkWindow:
GdkWindowAttr attributes;
memset(&attributes, 0, sizeof(attributes));
Gtk::Allocation allocation = get_allocation();
//Set initial position and size of the Gdk::Window:
attributes.x = allocation.get_x();
attributes.y = allocation.get_y();
attributes.width = allocation.get_width();
attributes.height = allocation.get_height();
attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.wclass = GDK_INPUT_OUTPUT;
m_refGdkWindow = Gdk::Window::create(get_window(), &attributes,
GDK_WA_X | GDK_WA_Y);
set_has_window(true);
set_window(m_refGdkWindow);
// transparent background
#if GTK_VERSION_GE(3, 0)
this->unset_background_color();
#else
this->get_window()->set_back_pixmap(Glib::RefPtr<Gdk::Pixmap>());
#endif
this->set_double_buffered(false);
//make the widget receive expose events
m_refGdkWindow->set_user_data(gobj());
glWindow.create(GET_WINDOW_HANDLE_FROM_GDK(m_refGdkWindow->gobj()), gl_context_settings);
}
}
void SFMLWidget::on_unrealize()
{
m_refGdkWindow.clear();
//Call base class:
Gtk::Widget::on_unrealize();
}
void SFMLWidget::display()
{
if(m_refGdkWindow)
{
glWindow.display();
}
}
void SFMLWidget::invalidate()
{
if(m_refGdkWindow)
{
m_refGdkWindow->invalidate(true);
}
}
<commit_msg>make SFMLWidget work on windows<commit_after>// SFMLWidget.cpp
// GTK widget containing an SFML OpenGL drawing context
// Based on example from SFML github wiki: https://github.com/LaurentGomila/SFML/wiki/Source%3A-GTK-SFMLWidget
// - changed to use SFML window instead of RenderWindow
// Code is public domain
#include "SFMLWidget.hpp"
// Tested on Linux Mint 12.4 and Windows 7
#if defined(SFML_SYSTEM_WINDOWS)
#include <gdk/gdkwin32.h>
#define GET_WINDOW_HANDLE_FROM_GDK GDK_WINDOW_HWND
#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
#include <gdk/gdkx.h>
#define GET_WINDOW_HANDLE_FROM_GDK GDK_WINDOW_XID
#elif defined(SFML_SYSTEM_MACOS)
#error Note: You have to figure out an analogue way to access the handle of the widget on a Mac-System
#else
#error Unsupported Operating System
#endif
SFMLWidget::SFMLWidget(const sf::VideoMode & mode, int size_request, const sf::ContextSettings & context_settings): gl_context_settings(context_settings)
{
if(size_request<=0)
size_request = std::max<int>(1, std::min<int>(mode.width, mode.height) / 2);
set_size_request(size_request, size_request);
set_has_window(false); // Makes this behave like an interal object rather then a parent window.
}
SFMLWidget::~SFMLWidget()
{
}
void SFMLWidget::on_size_allocate(Gtk::Allocation& allocation)
{
// Do something with the space that we have actually been given:
// (We will not be given heights or widths less than we have requested, though
// we might get more)
this->set_allocation(allocation);
if(m_refGdkWindow)
{
m_refGdkWindow->move_resize(allocation.get_x(),
allocation.get_y(),
allocation.get_width(),
allocation.get_height());
glWindow.setSize(sf::Vector2u(allocation.get_width(),
allocation.get_height()));
}
}
void SFMLWidget::on_realize()
{
Gtk::Widget::on_realize();
if(!m_refGdkWindow)
{
//Create the GdkWindow:
GdkWindowAttr attributes;
memset(&attributes, 0, sizeof(attributes));
Gtk::Allocation allocation = get_allocation();
//Set initial position and size of the Gdk::Window:
attributes.x = allocation.get_x();
attributes.y = allocation.get_y();
attributes.width = allocation.get_width();
attributes.height = allocation.get_height();
attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.wclass = GDK_INPUT_OUTPUT;
m_refGdkWindow = Gdk::Window::create(get_window(), &attributes,
GDK_WA_X | GDK_WA_Y);
set_has_window(true);
set_window(m_refGdkWindow);
// transparent background
#if GTK_VERSION_GE(3, 0)
this->unset_background_color();
#else
this->get_window()->set_back_pixmap(Glib::RefPtr<Gdk::Pixmap>());
#endif
this->set_double_buffered(false);
//make the widget receive expose events
m_refGdkWindow->set_user_data(gobj());
glWindow.create(static_cast<sf::WindowHandle>(GET_WINDOW_HANDLE_FROM_GDK(m_refGdkWindow->gobj())));
}
}
void SFMLWidget::on_unrealize()
{
m_refGdkWindow.clear();
//Call base class:
Gtk::Widget::on_unrealize();
}
void SFMLWidget::display()
{
if(m_refGdkWindow)
{
glWindow.display();
}
}
void SFMLWidget::invalidate()
{
if(m_refGdkWindow)
{
m_refGdkWindow->invalidate(true);
}
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2006-2012, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
#include <memory>
#include <numeric>
#include <gtest/gtest_VW.h>
#include <vw/Core/Cache.h>
#include <vw/Core/FundamentalTypes.h>
#include <vw/Core/ThreadPool.h>
#include <boost/shared_array.hpp>
using namespace vw;
// A dummy BlockGenerator that generates blocks of 1-byte data.
class BlockGenerator {
protected:
int m_dimension;
vw::uint8 m_fill_value;
public:
BlockGenerator(int dimension, vw::uint8 fill_value = 0) :
m_dimension(dimension), m_fill_value(fill_value) {}
typedef vw::uint8 value_type;
size_t size() const {
return m_dimension * m_dimension * sizeof(vw::uint8);
}
boost::shared_ptr< value_type > generate() const {
boost::shared_ptr< value_type > ptr(new vw::uint8[m_dimension*m_dimension], boost::checked_array_deleter<value_type>());
(&(*ptr))[0] = m_fill_value;
return ptr;
}
};
class CacheTest : public ::testing::Test {
public:
typedef Cache::Handle<BlockGenerator> HandleT;
typedef std::vector<HandleT> ContainerT;
vw::Cache cache;
ContainerT cache_handles;
const static int dimension = 1024;
const static int num_actual_blocks = 10;
const static int num_cache_blocks = 3;
CacheTest() :
cache( num_cache_blocks*dimension*dimension ), cache_handles( num_actual_blocks ) {
for (uint8 i = 0; i < num_actual_blocks; ++i) {
cache_handles[i] = cache.insert( BlockGenerator( dimension, i ) );
}
}
};
TEST_F(CacheTest, CacheLineLRU) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
for (int i = 0; i < num_actual_blocks; ++i) {
Cache::Handle<BlockGenerator> &h = cache_handles[i];
ASSERT_EQ(h.size(), dimension*dimension*sizeof(BlockGenerator::value_type));
ASSERT_FALSE(h.valid());
EXPECT_EQ(i, *h);
EXPECT_NO_THROW( h.release() );
EXPECT_TRUE(h.valid());
boost::shared_ptr<BlockGenerator::value_type> ptr = h;
EXPECT_EQ(i, *ptr);
h.release();
// LRU cache, so the last num_cache_blocks should still be valid
for (int j = 0; i-j >= 0; ++j)
{
SCOPED_TRACE(::testing::Message() << "Cache block " << i);
if (j < num_cache_blocks) {
EXPECT_TRUE(cache_handles[i-j].valid());
} else {
EXPECT_FALSE(cache_handles[i-j].valid());
}
}
}
}
TEST_F(CacheTest, Priority) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
// prime the cache
for (int i = 0; i < num_actual_blocks; ++i) {
EXPECT_EQ(i, *cache_handles[i]);
EXPECT_NO_THROW( cache_handles[i].release() );
}
//make sure last element is valid
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// deprioritize the last element, and ensure it's still valid
cache_handles[num_actual_blocks-1].deprioritize();
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// bring the first element back into cache
ASSERT_FALSE(cache_handles[0].valid());
EXPECT_EQ( 0, *cache_handles[0] );
EXPECT_NO_THROW( cache_handles[0].release() );
EXPECT_TRUE(cache_handles[0].valid());
// make sure that the deprioritized element dropped out of cache
EXPECT_FALSE(cache_handles[num_actual_blocks-1].valid());
}
// Every copy increases the fill_value by one
class GenGen : public BlockGenerator {
public:
GenGen() : BlockGenerator(1, 0) {}
GenGen(const GenGen& obj) :
BlockGenerator(obj.m_dimension, boost::numeric_cast<uint8>(obj.m_fill_value+1)) {}
};
TEST(Cache, Types) {
// This test makes sure cache handles can hold polymorphic types
// and gives the user control over copying vs. not.
typedef Cache::Handle<GenGen> obj_t;
typedef Cache::Handle<boost::shared_ptr<GenGen> > sptr_t;
vw::Cache cache(sizeof(vw::uint8));
GenGen value;
boost::shared_ptr<GenGen> shared(new GenGen());
obj_t h1 = cache.insert(value);
sptr_t h2 = cache.insert(shared);
// Make sure the value hasn't generated yet
ASSERT_FALSE(h1.valid());
ASSERT_FALSE(h2.valid());
// value should have copied once
EXPECT_EQ(1, *h1);
EXPECT_NO_THROW( h1.release() );
// shared_ptr should not have copied
EXPECT_EQ(0, *h2);
EXPECT_NO_THROW( h2.release() );
}
TEST(Cache, Stats) {
typedef Cache::Handle<BlockGenerator> handle_t;
// Cache can hold 2 items
vw::Cache cache(2*sizeof(handle_t::value_type));
handle_t h[3] = {
cache.insert(BlockGenerator(1, 0)),
cache.insert(BlockGenerator(1, 1)),
cache.insert(BlockGenerator(1, 2))};
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(0, *h[0]);
EXPECT_NO_THROW( h[0].release() );
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(0, *h[0]);
EXPECT_NO_THROW( h[0].release() );
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(1, *h[1]);
EXPECT_NO_THROW( h[1].release() );
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_NO_THROW( h[1].release() );
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss, eviction
EXPECT_EQ(2, *h[2]);
EXPECT_NO_THROW( h[2].release() );
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(2, *h[2]);
EXPECT_NO_THROW( h[2].release() );
EXPECT_EQ(3u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_NO_THROW( h[1].release() );
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// miss, eviction
EXPECT_EQ(0, *h[0]);
EXPECT_NO_THROW( h[0].release() );
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(4u, cache.misses());
EXPECT_EQ(2u, cache.evictions());
cache.clear_stats();
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
}
// Here's a more aggressive test that uses many threads plus a good
// chunk of memory (24k).
class ArrayDataGenerator {
public:
typedef std::vector<char> value_type;
ArrayDataGenerator() {}
size_t size() const { return 1024; }
boost::shared_ptr<value_type> generate() const {
char number = rand() % 255;
boost::shared_ptr<value_type> ptr( new value_type(1024,number) );
return ptr;
}
};
class TestTask : public vw::Task {
std::vector<Cache::Handle<ArrayDataGenerator> > m_handles;
public:
TestTask( std::vector<Cache::Handle<ArrayDataGenerator> > const& handles ) : m_handles( handles ) {}
virtual ~TestTask() {}
virtual void operator()() {
size_t index_a = rand() % m_handles.size(),
index_b = rand() % m_handles.size();
std::vector<uint8> a( (const std::vector<uint8>&)(*m_handles[index_a]) );
m_handles[index_a].release();
std::vector<uint8> b( (const std::vector<uint8>&)(*m_handles[index_b]) );
m_handles[index_b].release();
VW_ASSERT( a.size() != 0, IOErr() << "Size is wrong!" );
VW_ASSERT( b.size() != 0, IOErr() << "Size is wrong!" );
std::vector<uint8> c( a.size() );
for ( size_t i = 0; i < a.size(); i++ ) {
c[i] = a[i] + b[i];
}
// Don't let the compiler optimize this away.
volatile int result = std::accumulate(c.begin(), c.end(), 0 );
}
};
TEST(Cache, StressTest) {
typedef Cache::Handle<ArrayDataGenerator> handle_t;
vw::Cache cache( 6*1024 );
// Creating handles for our data
std::vector<handle_t> handles;
for ( size_t i = 0; i < 24; i++ ) {
handles.push_back( cache.insert( ArrayDataGenerator() ) );
}
// Create a FIFO buffer with a 1000 threads ... 12 running at
// anytime that try to access the cache randomly.
FifoWorkQueue queue(12);
for ( size_t i = 0; i < 1000; i++ ) {
boost::shared_ptr<Task> task( new TestTask(handles) );
queue.add_task( task );
}
// If this test fails ... it will deadlock. Maybe we should have
// this entire test case in a different thread where I can measure
// its time?
EXPECT_NO_THROW( queue.join_all(); );
}
<commit_msg>TestCache: Rm compiler warning<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2006-2012, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
#include <memory>
#include <numeric>
#include <gtest/gtest_VW.h>
#include <vw/Core/Cache.h>
#include <vw/Core/FundamentalTypes.h>
#include <vw/Core/ThreadPool.h>
#include <boost/shared_array.hpp>
using namespace vw;
// A dummy BlockGenerator that generates blocks of 1-byte data.
class BlockGenerator {
protected:
int m_dimension;
vw::uint8 m_fill_value;
public:
BlockGenerator(int dimension, vw::uint8 fill_value = 0) :
m_dimension(dimension), m_fill_value(fill_value) {}
typedef vw::uint8 value_type;
size_t size() const {
return m_dimension * m_dimension * sizeof(vw::uint8);
}
boost::shared_ptr< value_type > generate() const {
boost::shared_ptr< value_type > ptr(new vw::uint8[m_dimension*m_dimension], boost::checked_array_deleter<value_type>());
(&(*ptr))[0] = m_fill_value;
return ptr;
}
};
class CacheTest : public ::testing::Test {
public:
typedef Cache::Handle<BlockGenerator> HandleT;
typedef std::vector<HandleT> ContainerT;
vw::Cache cache;
ContainerT cache_handles;
const static int dimension = 1024;
const static int num_actual_blocks = 10;
const static int num_cache_blocks = 3;
CacheTest() :
cache( num_cache_blocks*dimension*dimension ), cache_handles( num_actual_blocks ) {
for (uint8 i = 0; i < num_actual_blocks; ++i) {
cache_handles[i] = cache.insert( BlockGenerator( dimension, i ) );
}
}
};
TEST_F(CacheTest, CacheLineLRU) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
for (int i = 0; i < num_actual_blocks; ++i) {
Cache::Handle<BlockGenerator> &h = cache_handles[i];
ASSERT_EQ(h.size(), dimension*dimension*sizeof(BlockGenerator::value_type));
ASSERT_FALSE(h.valid());
EXPECT_EQ(i, *h);
EXPECT_NO_THROW( h.release() );
EXPECT_TRUE(h.valid());
boost::shared_ptr<BlockGenerator::value_type> ptr = h;
EXPECT_EQ(i, *ptr);
h.release();
// LRU cache, so the last num_cache_blocks should still be valid
for (int j = 0; i-j >= 0; ++j)
{
SCOPED_TRACE(::testing::Message() << "Cache block " << i);
if (j < num_cache_blocks) {
EXPECT_TRUE(cache_handles[i-j].valid());
} else {
EXPECT_FALSE(cache_handles[i-j].valid());
}
}
}
}
TEST_F(CacheTest, Priority) {
// Test assumes cache size less than total data
ASSERT_LT(+num_cache_blocks, +num_actual_blocks);
// prime the cache
for (int i = 0; i < num_actual_blocks; ++i) {
EXPECT_EQ(i, *cache_handles[i]);
EXPECT_NO_THROW( cache_handles[i].release() );
}
//make sure last element is valid
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// deprioritize the last element, and ensure it's still valid
cache_handles[num_actual_blocks-1].deprioritize();
ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());
// bring the first element back into cache
ASSERT_FALSE(cache_handles[0].valid());
EXPECT_EQ( 0, *cache_handles[0] );
EXPECT_NO_THROW( cache_handles[0].release() );
EXPECT_TRUE(cache_handles[0].valid());
// make sure that the deprioritized element dropped out of cache
EXPECT_FALSE(cache_handles[num_actual_blocks-1].valid());
}
// Every copy increases the fill_value by one
class GenGen : public BlockGenerator {
public:
GenGen() : BlockGenerator(1, 0) {}
GenGen(const GenGen& obj) :
BlockGenerator(obj.m_dimension, boost::numeric_cast<uint8>(obj.m_fill_value+1)) {}
};
TEST(Cache, Types) {
// This test makes sure cache handles can hold polymorphic types
// and gives the user control over copying vs. not.
typedef Cache::Handle<GenGen> obj_t;
typedef Cache::Handle<boost::shared_ptr<GenGen> > sptr_t;
vw::Cache cache(sizeof(vw::uint8));
GenGen value;
boost::shared_ptr<GenGen> shared(new GenGen());
obj_t h1 = cache.insert(value);
sptr_t h2 = cache.insert(shared);
// Make sure the value hasn't generated yet
ASSERT_FALSE(h1.valid());
ASSERT_FALSE(h2.valid());
// value should have copied once
EXPECT_EQ(1, *h1);
EXPECT_NO_THROW( h1.release() );
// shared_ptr should not have copied
EXPECT_EQ(0, *h2);
EXPECT_NO_THROW( h2.release() );
}
TEST(Cache, Stats) {
typedef Cache::Handle<BlockGenerator> handle_t;
// Cache can hold 2 items
vw::Cache cache(2*sizeof(handle_t::value_type));
handle_t h[3] = {
cache.insert(BlockGenerator(1, 0)),
cache.insert(BlockGenerator(1, 1)),
cache.insert(BlockGenerator(1, 2))};
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(0, *h[0]);
EXPECT_NO_THROW( h[0].release() );
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(0, *h[0]);
EXPECT_NO_THROW( h[0].release() );
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(1u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss
EXPECT_EQ(1, *h[1]);
EXPECT_NO_THROW( h[1].release() );
EXPECT_EQ(1u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_NO_THROW( h[1].release() );
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(2u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
// miss, eviction
EXPECT_EQ(2, *h[2]);
EXPECT_NO_THROW( h[2].release() );
EXPECT_EQ(2u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(2, *h[2]);
EXPECT_NO_THROW( h[2].release() );
EXPECT_EQ(3u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// hit
EXPECT_EQ(1, *h[1]);
EXPECT_NO_THROW( h[1].release() );
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(3u, cache.misses());
EXPECT_EQ(1u, cache.evictions());
// miss, eviction
EXPECT_EQ(0, *h[0]);
EXPECT_NO_THROW( h[0].release() );
EXPECT_EQ(4u, cache.hits());
EXPECT_EQ(4u, cache.misses());
EXPECT_EQ(2u, cache.evictions());
cache.clear_stats();
EXPECT_EQ(0u, cache.hits());
EXPECT_EQ(0u, cache.misses());
EXPECT_EQ(0u, cache.evictions());
}
// Here's a more aggressive test that uses many threads plus a good
// chunk of memory (24k).
class ArrayDataGenerator {
public:
typedef std::vector<char> value_type;
ArrayDataGenerator() {}
size_t size() const { return 1024; }
boost::shared_ptr<value_type> generate() const {
char number = rand() % 255;
boost::shared_ptr<value_type> ptr( new value_type(1024,number) );
return ptr;
}
};
class TestTask : public vw::Task {
std::vector<Cache::Handle<ArrayDataGenerator> > m_handles;
public:
TestTask( std::vector<Cache::Handle<ArrayDataGenerator> > const& handles ) : m_handles( handles ) {}
virtual ~TestTask() {}
virtual void operator()() {
size_t index_a = rand() % m_handles.size(),
index_b = rand() % m_handles.size();
std::vector<uint8> a( (const std::vector<uint8>&)(*m_handles[index_a]) );
m_handles[index_a].release();
std::vector<uint8> b( (const std::vector<uint8>&)(*m_handles[index_b]) );
m_handles[index_b].release();
VW_ASSERT( a.size() != 0, IOErr() << "Size is wrong!" );
VW_ASSERT( b.size() != 0, IOErr() << "Size is wrong!" );
std::vector<uint8> c( a.size() );
for ( size_t i = 0; i < a.size(); i++ ) {
c[i] = a[i] + b[i];
}
// Don't let the compiler optimize this away.
volatile int result = std::accumulate(c.begin(), c.end(), 0 );
EXPECT_EQ(result, result); // Rm compiler warning due to unused variable
}
};
TEST(Cache, StressTest) {
typedef Cache::Handle<ArrayDataGenerator> handle_t;
vw::Cache cache( 6*1024 );
// Creating handles for our data
std::vector<handle_t> handles;
for ( size_t i = 0; i < 24; i++ ) {
handles.push_back( cache.insert( ArrayDataGenerator() ) );
}
// Create a FIFO buffer with a 1000 threads ... 12 running at
// anytime that try to access the cache randomly.
FifoWorkQueue queue(12);
for ( size_t i = 0; i < 1000; i++ ) {
boost::shared_ptr<Task> task( new TestTask(handles) );
queue.add_task( task );
}
// If this test fails ... it will deadlock. Maybe we should have
// this entire test case in a different thread where I can measure
// its time?
EXPECT_NO_THROW( queue.join_all(); );
}
<|endoftext|> |
<commit_before>/* Copyright 2015 Peter Goodman ([email protected]), all rights reserved. */
#include <glog/logging.h>
#include <sstream>
#include <system_error>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/ToolOutputFile.h>
#include "mcsema/BC/Util.h"
namespace mcsema {
llvm::Function *&BlockMap::operator[](uintptr_t pc) {
return this->std::unordered_map<uintptr_t, llvm::Function *>::operator[](pc);
}
llvm::Function *BlockMap::operator[](uintptr_t pc) const {
const auto block_it = this->find(pc);
if (this->end() == block_it) {
LOG(WARNING) << "No block associated with PC " << pc;
return nullptr;
} else {
return block_it->second;
}
}
// Initialize the attributes for a lifted function.
void InitFunctionAttributes(llvm::Function *F) {
// This affects code generation. Our functions only take one argument (the
// machine state pointer) and they all tail-call to each-other. Therefore,
// it makes no sense to save/restore callee-saved registers because there
// are no real callers to care about!
F->addFnAttr(llvm::Attribute::Naked);
// Make sure functions are treated as if they return. LLVM doesn't like
// mixing must-tail-calls with no-return.
F->removeFnAttr(llvm::Attribute::NoReturn);
// Don't use any exception stuff.
F->addFnAttr(llvm::Attribute::NoUnwind);
F->removeFnAttr(llvm::Attribute::UWTable);
// To use must-tail-calls everywhere we need to use the `fast` calling
// convention, where it's up the LLVM to decide how to pass arguments.
F->setCallingConv(llvm::CallingConv::Fast);
// Mark everything for inlining.
F->addFnAttr(llvm::Attribute::InlineHint);
}
// Create a tail-call from one lifted function to another.
void AddTerminatingTailCall(llvm::Function *From, llvm::Function *To) {
if (From->isDeclaration()) {
llvm::BasicBlock::Create(From->getContext(), "entry", From);
}
AddTerminatingTailCall(&(From->back()), To);
}
void AddTerminatingTailCall(llvm::BasicBlock *B, llvm::Function *To) {
LOG_IF(ERROR, B->getTerminator() || B->getTerminatingMustTailCall())
<< "Block already has a terminator; not adding fall-through call to: "
<< (To ? To->getName().str() : "<unreachable>");
LOG_IF(FATAL, !To) << "Target block does not exist!";
llvm::IRBuilder<> ir(B);
llvm::Function *F = B->getParent();
llvm::CallInst *C = ir.CreateCall(To, {FindStatePointer(F)});
// Make sure we tail-call from one block method to another.
C->setTailCallKind(llvm::CallInst::TCK_MustTail);
C->setCallingConv(llvm::CallingConv::Fast);
ir.CreateRetVoid();
}
// Find a local variable defined in the entry block of the function. We use
// this to find register variables.
llvm::Value *FindVarInFunction(llvm::Function *F, std::string name) {
for (auto &I : F->getEntryBlock()) {
if (I.getName() == name) {
return &I;
}
}
LOG(FATAL) << "Could not find variable " << name << " in function "
<< F->getName().str();
return nullptr;
}
// Find the machine state pointer.
llvm::Value *FindStatePointer(llvm::Function *F) {
return &*F->getArgumentList().begin();
}
namespace {
// Returns a symbol name that is "correct" for the host OS.
std::string CanonicalName(const llvm::Module *M, std::string name) {
const auto &DL = M->getDataLayout();
const char prefix = DL.getGlobalPrefix();
std::stringstream name_ss;
name_ss << &prefix << name;
return name_ss.str();
}
} // namespace
// Find a function with name `name` in the module `M`.
llvm::Function *FindFunction(const llvm::Module *M, std::string name) {
auto func_name = CanonicalName(M, name);
return M->getFunction(func_name);
}
// Find a global variable with name `name` in the module `M`.
llvm::GlobalVariable *FindGlobaVariable(const llvm::Module *M,
std::string name) {
auto var_name = CanonicalName(M, name);
return M->getGlobalVariable(var_name);
}
// Reads an LLVM module from a file.
llvm::Module *LoadModuleFromFile(std::string file_name) {
llvm::SMDiagnostic err;
auto mod_ptr = llvm::parseIRFile(file_name, err, llvm::getGlobalContext());
auto module = mod_ptr.get();
mod_ptr.release();
CHECK(nullptr != module) << "Unable to parse module file: " << file_name;
module->materializeAll(); // Just in case.
return module;
}
// Store an LLVM module into a file.
void StoreModuleToFile(llvm::Module *module, std::string file_name) {
std::error_code ec;
llvm::tool_output_file bc(file_name.c_str(), ec, llvm::sys::fs::F_None);
CHECK(!ec)
<< "Unable to open output bitcode file for writing: " << file_name;
llvm::WriteBitcodeToFile(module, bc.os());
bc.keep();
CHECK(!ec)
<< "Error writing bitcode to file: " << file_name;
}
} // namespace mcsema
<commit_msg>Going back to basing the _ on the os flag rather than the DataLayout::getGlobalPrefix.<commit_after>/* Copyright 2015 Peter Goodman ([email protected]), all rights reserved. */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <sstream>
#include <system_error>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/ToolOutputFile.h>
#include "mcsema/BC/Util.h"
DECLARE_string(os);
namespace mcsema {
llvm::Function *&BlockMap::operator[](uintptr_t pc) {
return this->std::unordered_map<uintptr_t, llvm::Function *>::operator[](pc);
}
llvm::Function *BlockMap::operator[](uintptr_t pc) const {
const auto block_it = this->find(pc);
if (this->end() == block_it) {
LOG(WARNING) << "No block associated with PC " << pc;
return nullptr;
} else {
return block_it->second;
}
}
// Initialize the attributes for a lifted function.
void InitFunctionAttributes(llvm::Function *F) {
// This affects code generation. Our functions only take one argument (the
// machine state pointer) and they all tail-call to each-other. Therefore,
// it makes no sense to save/restore callee-saved registers because there
// are no real callers to care about!
F->addFnAttr(llvm::Attribute::Naked);
// Make sure functions are treated as if they return. LLVM doesn't like
// mixing must-tail-calls with no-return.
F->removeFnAttr(llvm::Attribute::NoReturn);
// Don't use any exception stuff.
F->addFnAttr(llvm::Attribute::NoUnwind);
F->removeFnAttr(llvm::Attribute::UWTable);
// To use must-tail-calls everywhere we need to use the `fast` calling
// convention, where it's up the LLVM to decide how to pass arguments.
F->setCallingConv(llvm::CallingConv::Fast);
// Mark everything for inlining.
F->addFnAttr(llvm::Attribute::InlineHint);
}
// Create a tail-call from one lifted function to another.
void AddTerminatingTailCall(llvm::Function *From, llvm::Function *To) {
if (From->isDeclaration()) {
llvm::BasicBlock::Create(From->getContext(), "entry", From);
}
AddTerminatingTailCall(&(From->back()), To);
}
void AddTerminatingTailCall(llvm::BasicBlock *B, llvm::Function *To) {
LOG_IF(ERROR, B->getTerminator() || B->getTerminatingMustTailCall())
<< "Block already has a terminator; not adding fall-through call to: "
<< (To ? To->getName().str() : "<unreachable>");
LOG_IF(FATAL, !To) << "Target block does not exist!";
llvm::IRBuilder<> ir(B);
llvm::Function *F = B->getParent();
llvm::CallInst *C = ir.CreateCall(To, {FindStatePointer(F)});
// Make sure we tail-call from one block method to another.
C->setTailCallKind(llvm::CallInst::TCK_MustTail);
C->setCallingConv(llvm::CallingConv::Fast);
ir.CreateRetVoid();
}
// Find a local variable defined in the entry block of the function. We use
// this to find register variables.
llvm::Value *FindVarInFunction(llvm::Function *F, std::string name) {
for (auto &I : F->getEntryBlock()) {
if (I.getName() == name) {
return &I;
}
}
LOG(FATAL) << "Could not find variable " << name << " in function "
<< F->getName().str();
return nullptr;
}
// Find the machine state pointer.
llvm::Value *FindStatePointer(llvm::Function *F) {
return &*F->getArgumentList().begin();
}
namespace {
// Returns a symbol name that is "correct" for the host OS.
std::string CanonicalName(const llvm::Module *M, std::string name) {
std::stringstream name_ss;
if (FLAGS_os == "mac") {
name_ss << "_";
}
name_ss << name;
return name_ss.str();
}
} // namespace
// Find a function with name `name` in the module `M`.
llvm::Function *FindFunction(const llvm::Module *M, std::string name) {
auto func_name = CanonicalName(M, name);
return M->getFunction(func_name);
}
// Find a global variable with name `name` in the module `M`.
llvm::GlobalVariable *FindGlobaVariable(const llvm::Module *M,
std::string name) {
auto var_name = CanonicalName(M, name);
return M->getGlobalVariable(var_name);
}
// Reads an LLVM module from a file.
llvm::Module *LoadModuleFromFile(std::string file_name) {
llvm::SMDiagnostic err;
auto mod_ptr = llvm::parseIRFile(file_name, err, llvm::getGlobalContext());
auto module = mod_ptr.get();
mod_ptr.release();
CHECK(nullptr != module) << "Unable to parse module file: " << file_name;
module->materializeAll(); // Just in case.
return module;
}
// Store an LLVM module into a file.
void StoreModuleToFile(llvm::Module *module, std::string file_name) {
std::error_code ec;
llvm::tool_output_file bc(file_name.c_str(), ec, llvm::sys::fs::F_None);
CHECK(!ec)
<< "Unable to open output bitcode file for writing: " << file_name;
llvm::WriteBitcodeToFile(module, bc.os());
bc.keep();
CHECK(!ec)
<< "Error writing bitcode to file: " << file_name;
}
} // namespace mcsema
<|endoftext|> |
<commit_before>#include "style.h"
#include <Tempest/Platform>
#include <Tempest/Application>
#include <Tempest/Painter>
#include <Tempest/Widget>
#include <Tempest/Button>
#include <Tempest/Icon>
#include <Tempest/TextEdit>
#include <Tempest/Label>
// #include <Tempest/CheckBox>
#include <cassert>
using namespace Tempest;
Style::UiMetrics::UiMetrics() {
#ifdef __MOBILE_PLATFORM__
buttonSize = 48;
#else
buttonSize = 27;
#endif
}
const Margin Style::Extra::emptyMargin;
const Icon Style::Extra::emptyIcon;
const Font Style::Extra::emptyFont;
const Color Style::Extra::emptyColor;
Style::Extra::Extra(const Widget &owner)
: margin(owner.margins()), icon(emptyIcon), fontColor(emptyColor), spacing(owner.spacing()) {
}
Style::Extra::Extra(const Button &owner)
: margin(owner.margins()), icon(owner.icon()), fontColor(emptyColor), spacing(owner.spacing()) {
}
Style::Extra::Extra(const Label &owner)
: margin(owner.margins()), icon(emptyIcon), fontColor(owner.textColor()), spacing(owner.spacing()) {
}
Style::Extra::Extra(const AbstractTextInput& owner)
: margin(owner.margins()), icon(emptyIcon), fontColor(owner.textColor()), spacing(owner.spacing()),
selectionStart(owner.selectionStart()), selectionEnd(owner.selectionEnd()){
}
Style::Style() {
}
Style::~Style() {
assert(polished==0);
}
Style::UIIntefaceIdiom Style::idiom() const {
#ifdef __MOBILE_PLATFORM__
return UIIntefaceIdiom(UIIntefacePhone);
#else
return UIIntefaceIdiom(UIIntefaceUnspecified);
#endif
}
void Style::polish (Widget&) const {
polished++;
}
void Style::unpolish(Widget&) const {
polished--;
}
const Tempest::Sprite &Style::iconSprite(const Icon& icon,const WidgetState &st, const Rect &r) {
const int sz = std::min(r.w,r.h);
return icon.sprite(sz,sz,st.disabled ? Icon::ST_Disabled : Icon::ST_Normal);
}
void Style::draw(Painter& ,Widget*, Element, const WidgetState&, const Rect &, const Extra&) const {
}
void Style::draw(Painter &p, Panel* w, Element e, const WidgetState &st, const Rect &r, const Extra& extra) const {
(void)w;
(void)st;
(void)e;
(void)extra;
p.translate(r.x,r.y);
p.setBrush(Color(0.8f,0.8f,0.85f,0.75f));
p.drawRect(0,0,r.w,r.h);
p.setPen(Color(0.25,0.25,0.25,1));
p.drawLine(0,0, r.w-1,0);
p.drawLine(0,r.h-1,r.w-1,r.h-1);
p.drawLine(0, 0,0 ,r.h-1);
p.drawLine(r.w-1,0,r.w-1,r.h );
p.translate(-r.x,-r.y);
}
void Style::draw(Painter& p, Dialog* w, Style::Element e,
const WidgetState& st, const Rect& r, const Style::Extra& extra) const {
draw(p,reinterpret_cast<Panel*>(w),e,st,r,extra);
}
void Style::draw(Painter& p, Button *w, Element e, const WidgetState &st, const Rect &r, const Extra &extra) const {
(void)w;
(void)e;
(void)extra;
auto pen = p.pen();
auto brush = p.brush();
p.translate(r.x,r.y);
const Button::Type buttonType=st.button;
const bool drawBackFrame = (buttonType!=Button::T_ToolButton || st.moveOver) &&
(buttonType!=Button::T_FlatButton || st.pressed) &&
(e!=E_MenuItemBackground);
if( drawBackFrame ) {
if(st.pressed || st.checked!=WidgetState::Unchecked)
p.setBrush(Color(0.4f,0.4f,0.45f,0.75f)); else
if(st.moveOver)
p.setBrush(Color(0.5f,0.5f,0.55f,0.75f)); else
p.setBrush(Color(0.8f,0.8f,0.85f,0.75f));
p.drawRect(0,0,r.w,r.h);
p.setPen(Color(0.25,0.25,0.25,1));
p.drawLine(0,0, r.w-1,0 );
p.drawLine(0,r.h-1,r.w-1,r.h-1);
p.drawLine(0, 0, 0,r.h-1);
p.drawLine(r.w-1, 0,r.w-1,r.h );
}
if( e==E_ArrowUp || e==E_ArrowDown || e==E_ArrowLeft || e==E_ArrowRight ){
p.setPen(Color(0.1f,0.1f,0.15f,1));
int cx=r.w/2;
int cy=r.h/2;
const int dx=(r.w-4)/2;
const int dy=(r.h-4)/2;
if(e==E_ArrowUp) {
cy-=dy/2;
p.drawLine(cx-dx,cy+dy, cx,cy);
p.drawLine(cx,cy, cx+dx,cy+dy);
} else
if(e==E_ArrowDown) {
cy+=dy/2;
p.drawLine(cx-dx,cy-dy, cx,cy);
p.drawLine(cx,cy, cx+dx,cy-dy);
} else
if(e==E_ArrowLeft) {
cx-=dx/2;
p.drawLine(cx+dx, cy-dy, cx, cy);
p.drawLine(cx, cy, cx+dx, cy+dy);
} else
if(e==E_ArrowRight) {
cx+=dx/2;
p.drawLine(cx-dx,cy-dy, cx,cy);
p.drawLine(cx,cy, cx-dx,cy+dy);
}
}
p.translate(-r.x,-r.y);
p.setBrush(brush);
p.setPen(pen);
}
void Style::draw(Painter &p, CheckBox *w, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)w;
(void)e;
(void)extra;
const int s = std::min(r.w,r.h);
const Size sz = Size(s,s);
p.translate(r.x,r.y);
p.setBrush(Color(0.25,0.25,0.25,1));
p.drawLine(0, 0,sz.w-1, 0);
p.drawLine(0,sz.h-1,sz.w-1,sz.h-1);
p.drawLine( 0,0, 0,sz.h-1);
p.drawLine(sz.w-1,0,sz.w-1,sz.h );
p.setBrush(Color(1));
if( st.checked==WidgetState::Checked ) {
int x = 0,
y = (r.h-sz.h)/2;
int d = st.pressed ? 2 : 4;
if( st.pressed ) {
p.drawLine(x+d, y+d, x+sz.w-d, y+sz.h-d);
p.drawLine(x+sz.w-d, y+d, x+d, y+sz.h-d);
} else {
p.drawLine(x, y, x+sz.w, y+sz.h);
p.drawLine(x+sz.w, y, x, y+sz.h);
}
} else
if( st.checked==WidgetState::PartiallyChecked ) {
int x = 0,
y = (r.h-sz.h)/2;
int d = st.pressed ? 2 : 4;
p.drawLine(x+d, y+d, x+sz.w-d, y+d);
p.drawLine(x+d, y+sz.h+d, x+sz.w-d, y+sz.h+d);
p.drawLine(x+d, y+d, x+d, y+sz.h-d);
p.drawLine(x+sz.w+d, y+d, x+sz.w+d, y+sz.h-d);
}
p.translate(-r.x,-r.y);
}
void Style::draw(Painter &p, Label *w, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)p;
(void)w;
(void)e;
(void)st;
(void)r;
(void)extra;
// nop
}
void Style::draw(Painter &p, AbstractTextInput* w, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)p;
(void)w;
(void)e;
(void)st;
(void)r;
(void)extra;
}
void Style::draw(Painter &p, ScrollBar*, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
if(e==E_Background)
return;
draw(p,static_cast<Button*>(nullptr),e,st,r,extra);
}
void Style::draw(Painter &p, const std::u16string &text, Style::TextElement e,
const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
/*
const Margin& m = extra.margin;
p.translate(r.x,r.y);
const Sprite& icon = iconSprite(extra.icon,st,r);
int dX=0;
if( !icon.size().isEmpty() ){
p.setBrush(icon);
if( text.empty() ) {
p.drawRect( (r.w-icon.w())/2, (r.h-icon.h())/2, icon.w(), icon.h() );
} else {
p.drawRect( m.left, (r.h-icon.h())/2, icon.w(), icon.h() );
dX=icon.w();
}
}
if(e==TE_CheckboxTitle){
const int s = std::min(r.w,r.h);
if( dX<s )
dX=s;
}
if(dX!=0)
dX+=8; // padding
auto& fnt = textFont(text,st);
p.setFont (extra.font);
p.setBrush(extra.fontColor);
const int h=extra.font.textSize(text).h;
int flag=AlignBottom;
if(e==TE_ButtonTitle)
flag |= AlignHCenter;
p.drawText( m.left+dX, (r.h-h)/2, r.w-m.xMargin()-dX, h, text, flag );
p.translate(-r.x,-r.y);*/
}
void Style::draw(Painter &p, const TextModel &text, Style::TextElement e,
const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)e;
const Margin& m = extra.margin;
const Rect sc = p.scissor();
p.setScissor(sc.intersected(Rect(m.left, 0, r.w-m.xMargin(), r.h)));
p.translate(m.left,m.top);
const Sprite& icon = iconSprite(extra.icon,st,r);
int dX = 0;
if(!icon.size().isEmpty()){
p.setBrush(icon);
if( text.isEmpty() ) {
p.drawRect( (r.w-icon.w())/2, (r.h-icon.h())/2, icon.w(), icon.h() );
} else {
p.drawRect( 0, (r.h-icon.h())/2, icon.w(), icon.h() );
dX=icon.w();
}
}
if(e==TE_CheckboxTitle) {
const int s = std::min(r.w,r.h);
if( dX<s )
dX=s;
}
if(dX!=0)
dX+=extra.spacing;
auto& fnt = text.font();
const int fntSz = int(fnt.metrics().ascent);
Point at;
if(e!=TE_TextEditContent && e!=TE_LineEditContent && false) {
const int h = text.wrapSize().h;
at = {dX, r.h-(r.h-h)/2};
} else {
at = { 0, fntSz};
}
if(st.focus && extra.selectionStart==extra.selectionEnd) {
if((Application::tickCount()/cursorFlashTime)%2)
text.drawCursor(p,at.x,at.y-fntSz,extra.selectionStart);
}
if(extra.selectionStart!=extra.selectionEnd) {
text.drawCursor(p,at.x,at.y-fntSz,extra.selectionStart,extra.selectionEnd);
}
text.paint(p, fnt, at.x, at.y);
p.translate(-m.left,-m.top);
p.setScissor(sc);
}
Size Style::sizeHint(Widget*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
(void)text;
(void)extra;
return Size();
}
Size Style::sizeHint(Panel*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
(void)text;
(void)extra;
return Size();
}
Size Style::sizeHint(Button*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
Size sz = text!=nullptr ? text->sizeHint() : Size();
auto& icon = extra.icon.sprite(SizePolicy::maxWidgetSize().w,
sz.h+extra.margin.yMargin(),
Icon::ST_Normal);
Size is = icon.size();
if(is.w>0)
sz.w = sz.w+is.w+extra.spacing;
sz.h = std::max(sz.h,is.h);
return sz;
}
Size Style::sizeHint(Label*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
(void)extra;
Size sz = text!=nullptr ? text->sizeHint() : Size();
return sz;
}
const Style::UiMetrics& Style::metrics() const {
static UiMetrics m;
return m;
}
Style::Element Style::visibleElements() const {
return E_All;
}
void Style::drawCursor(Painter &p,const WidgetState &st,int x,int h,bool animState) const {
if( st.editable && animState && st.focus ){
p.setBrush( Brush(Color(0,0,1,1),Painter::NoBlend) );
p.drawRect( x-1, 0, 2, h );
return;
}
}
void Style::implDecRef() const {
refCnt--;
if(refCnt==0)
delete this;
}
Style::UIIntefaceIdiom::UIIntefaceIdiom(Style::UIIntefaceCategory category):category(category){
touch=(category==UIIntefacePad || category==UIIntefacePhone);
}
<commit_msg>fixup<commit_after>#include "style.h"
#include <Tempest/Platform>
#include <Tempest/Application>
#include <Tempest/Painter>
#include <Tempest/Widget>
#include <Tempest/Button>
#include <Tempest/Icon>
#include <Tempest/TextEdit>
#include <Tempest/Label>
// #include <Tempest/CheckBox>
#include <cassert>
using namespace Tempest;
Style::UiMetrics::UiMetrics() {
#ifdef __MOBILE_PLATFORM__
buttonSize = 48;
#else
buttonSize = 27;
#endif
}
const Margin Style::Extra::emptyMargin;
const Icon Style::Extra::emptyIcon;
const Font Style::Extra::emptyFont;
const Color Style::Extra::emptyColor;
Style::Extra::Extra(const Widget &owner)
: margin(owner.margins()), icon(emptyIcon), fontColor(emptyColor), spacing(owner.spacing()) {
}
Style::Extra::Extra(const Button &owner)
: margin(owner.margins()), icon(owner.icon()), fontColor(emptyColor), spacing(owner.spacing()) {
}
Style::Extra::Extra(const Label &owner)
: margin(owner.margins()), icon(emptyIcon), fontColor(owner.textColor()), spacing(owner.spacing()) {
}
Style::Extra::Extra(const AbstractTextInput& owner)
: margin(owner.margins()), icon(emptyIcon), fontColor(owner.textColor()), spacing(owner.spacing()),
selectionStart(owner.selectionStart()), selectionEnd(owner.selectionEnd()){
}
Style::Style() {
}
Style::~Style() {
assert(polished==0);
}
Style::UIIntefaceIdiom Style::idiom() const {
#ifdef __MOBILE_PLATFORM__
return UIIntefaceIdiom(UIIntefacePhone);
#else
return UIIntefaceIdiom(UIIntefaceUnspecified);
#endif
}
void Style::polish (Widget&) const {
polished++;
}
void Style::unpolish(Widget&) const {
polished--;
}
const Tempest::Sprite &Style::iconSprite(const Icon& icon,const WidgetState &st, const Rect &r) {
const int sz = std::min(r.w,r.h);
return icon.sprite(sz,sz,st.disabled ? Icon::ST_Disabled : Icon::ST_Normal);
}
void Style::draw(Painter& ,Widget*, Element, const WidgetState&, const Rect &, const Extra&) const {
}
void Style::draw(Painter &p, Panel* w, Element e, const WidgetState &st, const Rect &r, const Extra& extra) const {
(void)w;
(void)st;
(void)e;
(void)extra;
p.translate(r.x,r.y);
p.setBrush(Color(0.8f,0.8f,0.85f,0.75f));
p.drawRect(0,0,r.w,r.h);
p.setPen(Color(0.25,0.25,0.25,1));
p.drawLine(0,0, r.w-1,0);
p.drawLine(0,r.h-1,r.w-1,r.h-1);
p.drawLine(0, 0,0 ,r.h-1);
p.drawLine(r.w-1,0,r.w-1,r.h );
p.translate(-r.x,-r.y);
}
void Style::draw(Painter& p, Dialog* w, Style::Element e,
const WidgetState& st, const Rect& r, const Style::Extra& extra) const {
draw(p,reinterpret_cast<Panel*>(w),e,st,r,extra);
}
void Style::draw(Painter& p, Button *w, Element e, const WidgetState &st, const Rect &r, const Extra &extra) const {
(void)w;
(void)e;
(void)extra;
auto pen = p.pen();
auto brush = p.brush();
p.translate(r.x,r.y);
const Button::Type buttonType=st.button;
const bool drawBackFrame = (buttonType!=Button::T_ToolButton || st.moveOver) &&
(buttonType!=Button::T_FlatButton || st.pressed) &&
(e!=E_MenuItemBackground);
if( drawBackFrame ) {
if(st.pressed || st.checked!=WidgetState::Unchecked)
p.setBrush(Color(0.4f,0.4f,0.45f,0.75f)); else
if(st.moveOver)
p.setBrush(Color(0.5f,0.5f,0.55f,0.75f)); else
p.setBrush(Color(0.8f,0.8f,0.85f,0.75f));
p.drawRect(0,0,r.w,r.h);
p.setPen(Color(0.25,0.25,0.25,1));
p.drawLine(0,0, r.w-1,0 );
p.drawLine(0,r.h-1,r.w-1,r.h-1);
p.drawLine(0, 0, 0,r.h-1);
p.drawLine(r.w-1, 0,r.w-1,r.h );
}
if( e==E_ArrowUp || e==E_ArrowDown || e==E_ArrowLeft || e==E_ArrowRight ){
p.setPen(Color(0.1f,0.1f,0.15f,1));
int cx=r.w/2;
int cy=r.h/2;
const int dx=(r.w-4)/2;
const int dy=(r.h-4)/2;
if(e==E_ArrowUp) {
cy-=dy/2;
p.drawLine(cx-dx,cy+dy, cx,cy);
p.drawLine(cx,cy, cx+dx,cy+dy);
} else
if(e==E_ArrowDown) {
cy+=dy/2;
p.drawLine(cx-dx,cy-dy, cx,cy);
p.drawLine(cx,cy, cx+dx,cy-dy);
} else
if(e==E_ArrowLeft) {
cx-=dx/2;
p.drawLine(cx+dx, cy-dy, cx, cy);
p.drawLine(cx, cy, cx+dx, cy+dy);
} else
if(e==E_ArrowRight) {
cx+=dx/2;
p.drawLine(cx-dx,cy-dy, cx,cy);
p.drawLine(cx,cy, cx-dx,cy+dy);
}
}
p.translate(-r.x,-r.y);
p.setBrush(brush);
p.setPen(pen);
}
void Style::draw(Painter &p, CheckBox *w, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)w;
(void)e;
(void)extra;
const int s = std::min(r.w,r.h);
const Size sz = Size(s,s);
p.translate(r.x,r.y);
p.setBrush(Color(0.25,0.25,0.25,1));
p.drawLine(0, 0,sz.w-1, 0);
p.drawLine(0,sz.h-1,sz.w-1,sz.h-1);
p.drawLine( 0,0, 0,sz.h-1);
p.drawLine(sz.w-1,0,sz.w-1,sz.h );
p.setBrush(Color(1));
if( st.checked==WidgetState::Checked ) {
int x = 0,
y = (r.h-sz.h)/2;
int d = st.pressed ? 2 : 4;
if( st.pressed ) {
p.drawLine(x+d, y+d, x+sz.w-d, y+sz.h-d);
p.drawLine(x+sz.w-d, y+d, x+d, y+sz.h-d);
} else {
p.drawLine(x, y, x+sz.w, y+sz.h);
p.drawLine(x+sz.w, y, x, y+sz.h);
}
} else
if( st.checked==WidgetState::PartiallyChecked ) {
int x = 0,
y = (r.h-sz.h)/2;
int d = st.pressed ? 2 : 4;
p.drawLine(x+d, y+d, x+sz.w-d, y+d);
p.drawLine(x+d, y+sz.h+d, x+sz.w-d, y+sz.h+d);
p.drawLine(x+d, y+d, x+d, y+sz.h-d);
p.drawLine(x+sz.w+d, y+d, x+sz.w+d, y+sz.h-d);
}
p.translate(-r.x,-r.y);
}
void Style::draw(Painter &p, Label *w, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)p;
(void)w;
(void)e;
(void)st;
(void)r;
(void)extra;
// nop
}
void Style::draw(Painter &p, AbstractTextInput* w, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)p;
(void)w;
(void)e;
(void)st;
(void)r;
(void)extra;
}
void Style::draw(Painter &p, ScrollBar*, Element e, const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
if(e==E_Background)
return;
draw(p,static_cast<Button*>(nullptr),e,st,r,extra);
}
void Style::draw(Painter &p, const std::u16string &text, Style::TextElement e,
const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
/*
const Margin& m = extra.margin;
p.translate(r.x,r.y);
const Sprite& icon = iconSprite(extra.icon,st,r);
int dX=0;
if( !icon.size().isEmpty() ){
p.setBrush(icon);
if( text.empty() ) {
p.drawRect( (r.w-icon.w())/2, (r.h-icon.h())/2, icon.w(), icon.h() );
} else {
p.drawRect( m.left, (r.h-icon.h())/2, icon.w(), icon.h() );
dX=icon.w();
}
}
if(e==TE_CheckboxTitle){
const int s = std::min(r.w,r.h);
if( dX<s )
dX=s;
}
if(dX!=0)
dX+=8; // padding
auto& fnt = textFont(text,st);
p.setFont (extra.font);
p.setBrush(extra.fontColor);
const int h=extra.font.textSize(text).h;
int flag=AlignBottom;
if(e==TE_ButtonTitle)
flag |= AlignHCenter;
p.drawText( m.left+dX, (r.h-h)/2, r.w-m.xMargin()-dX, h, text, flag );
p.translate(-r.x,-r.y);*/
}
void Style::draw(Painter &p, const TextModel &text, Style::TextElement e,
const WidgetState &st, const Rect &r, const Style::Extra &extra) const {
(void)e;
const Margin& m = extra.margin;
const Rect sc = p.scissor();
p.setScissor(sc.intersected(Rect(m.left, 0, r.w-m.xMargin(), r.h)));
p.translate(m.left,m.top);
const Sprite& icon = iconSprite(extra.icon,st,r);
int dX = 0;
if(!icon.size().isEmpty()){
p.setBrush(icon);
if( text.isEmpty() ) {
p.drawRect( (r.w-icon.w())/2, (r.h-icon.h())/2, icon.w(), icon.h() );
} else {
p.drawRect( 0, (r.h-icon.h())/2, icon.w(), icon.h() );
dX=icon.w();
}
}
if(e==TE_CheckboxTitle) {
const int s = std::min(r.w,r.h);
if( dX<s )
dX=s;
}
if(dX!=0)
dX+=extra.spacing;
auto& fnt = text.font();
const int fntSz = int(fnt.metrics().ascent);
Point at;
if(e!=TE_TextEditContent && e!=TE_LineEditContent) {
const int h = text.wrapSize().h;
at = {dX, r.h-(r.h-h)/2};
} else {
at = { 0, fntSz};
}
if(st.focus && extra.selectionStart==extra.selectionEnd) {
if((Application::tickCount()/cursorFlashTime)%2)
text.drawCursor(p,at.x,at.y-fntSz,extra.selectionStart);
}
if(extra.selectionStart!=extra.selectionEnd) {
text.drawCursor(p,at.x,at.y-fntSz,extra.selectionStart,extra.selectionEnd);
}
text.paint(p, fnt, at.x, at.y);
p.translate(-m.left,-m.top);
p.setScissor(sc);
}
Size Style::sizeHint(Widget*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
(void)text;
(void)extra;
return Size();
}
Size Style::sizeHint(Panel*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
(void)text;
(void)extra;
return Size();
}
Size Style::sizeHint(Button*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
Size sz = text!=nullptr ? text->sizeHint() : Size();
auto& icon = extra.icon.sprite(SizePolicy::maxWidgetSize().w,
sz.h+extra.margin.yMargin(),
Icon::ST_Normal);
Size is = icon.size();
if(is.w>0)
sz.w = sz.w+is.w+extra.spacing;
sz.h = std::max(sz.h,is.h);
return sz;
}
Size Style::sizeHint(Label*, Style::Element e, const TextModel* text, const Style::Extra& extra) const {
(void)e;
(void)extra;
Size sz = text!=nullptr ? text->sizeHint() : Size();
return sz;
}
const Style::UiMetrics& Style::metrics() const {
static UiMetrics m;
return m;
}
Style::Element Style::visibleElements() const {
return E_All;
}
void Style::drawCursor(Painter &p,const WidgetState &st,int x,int h,bool animState) const {
if( st.editable && animState && st.focus ){
p.setBrush( Brush(Color(0,0,1,1),Painter::NoBlend) );
p.drawRect( x-1, 0, 2, h );
return;
}
}
void Style::implDecRef() const {
refCnt--;
if(refCnt==0)
delete this;
}
Style::UIIntefaceIdiom::UIIntefaceIdiom(Style::UIIntefaceCategory category):category(category){
touch=(category==UIIntefacePad || category==UIIntefacePhone);
}
<|endoftext|> |
<commit_before>#include "apf.h"
#include "apfConvert.h"
#include "apfMesh.h"
#include "apfMesh2.h"
#include "apfShape.h"
#include <PCU.h>
#include <map>
namespace apf {
class Converter
{
public:
Converter(Mesh *a, Mesh2 *b)
{
inMesh = a;
outMesh = b;
}
void run()
{
createVertices();
createEntities();
for (int i = 0; i <= inMesh->getDimension(); ++i)
createRemotes(i);
if (inMesh->hasMatching())
for (int i = 0; i <= inMesh->getDimension(); ++i)
createMatches(i);
convertQuadratic();
}
ModelEntity* getNewModelFromOld(ModelEntity* oldC)
{
int type = inMesh->getModelType(oldC);
int tag = inMesh->getModelTag(oldC);
return outMesh->findModelEntity(type,tag);
}
void createVertices()
{
MeshIterator* it = inMesh->begin(0);
MeshEntity *oldV;
while ((oldV = inMesh->iterate(it)))
{
ModelEntity *oldC = inMesh->toModel(oldV);
ModelEntity *newC = getNewModelFromOld(oldC);
Vector3 xyz;
inMesh->getPoint(oldV, 0, xyz);
Vector3 param(0,0,0);
inMesh->getParam(oldV,param);
MeshEntity* newV = outMesh->createVertex(newC, xyz, param);
newFromOld[oldV] = newV;
}
inMesh->end(it);
assert(outMesh->count(0) == inMesh->count(0));
}
void createEntities()
{
for (int i = 1; i < (inMesh->getDimension())+1; ++i)
createDimension(i);
}
void createDimension(int dim)
{
MeshIterator* it = inMesh->begin(dim);
MeshEntity *oldE;
while ((oldE = inMesh->iterate(it)))
{
int type = inMesh->getType(oldE);
ModelEntity *oldC = inMesh->toModel(oldE);
ModelEntity *newC = getNewModelFromOld(oldC);
Downward down;
int ne = inMesh->getDownward(oldE, dim-1, down);
Downward new_down;
for(int i=0; i<ne; ++i)
{
new_down[i]=newFromOld[down[i]];
}
MeshEntity *newE = outMesh->createEntity(type, newC, new_down);
newFromOld[oldE] = newE;
}
inMesh->end(it);
assert(outMesh->count(dim) == inMesh->count(dim));
}
void createRemotes(int dim)
{
/* O-------------|---|----->O
^old left | | ^old right
|MPI|
O<------------|---|------O
^new left | | ^new right */
/* creating links backwards is OK because
they go both ways; as long as every link
gets a backward copy they will all get copies */
PCU_Comm_Begin();
MeshIterator* it = inMesh->begin(dim);
MeshEntity *oldLeft;
while ((oldLeft = inMesh->iterate(it)))
{
MeshEntity *newLeft = newFromOld[oldLeft];
Copies remotes;
inMesh->getRemotes(oldLeft, remotes);
APF_ITERATE(Copies,remotes,it)
{
int rightPart = it->first;
MeshEntity* oldRight = it->second;
PCU_COMM_PACK(rightPart,oldRight);
PCU_COMM_PACK(rightPart,newLeft);
}
}
inMesh->end(it);
PCU_Comm_Send();
/* accumulation of residence sets... we could also constantly reclassify... */
std::map<MeshEntity*, std::vector<int> > map_ent;
while (PCU_Comm_Listen())
{
int leftPart = PCU_Comm_Sender();
while ( ! PCU_Comm_Unpacked())
{
MeshEntity* oldRight;
PCU_COMM_UNPACK(oldRight);
MeshEntity* newLeft;
PCU_COMM_UNPACK(newLeft);
MeshEntity *newRight = newFromOld[oldRight];
outMesh->addRemote(newRight, leftPart, newLeft);
map_ent[newRight].push_back(leftPart);
}
}
/* assign accumulated residence sets */
std::map <MeshEntity*, std::vector<int> >::iterator mit;
for(mit=map_ent.begin(); mit!=map_ent.end(); ++mit)
{
MeshEntity* newE;
newE = mit->first;
std::vector<int>& vecEnt = mit->second;
Copies remotes;
Parts parts;
parts.insert(vecEnt.begin(), vecEnt.end());
parts.insert(PCU_Comm_Self());
outMesh->setResidence(newE, parts);
}
}
void convertField(apf::Field* in, apf::Field* out)
{
apf::FieldShape* s = apf::getShape(in);
apf::NewArray<double> data(apf::countComponents(in));
for (int d = 0; d <= 3; ++d)
{
if (s->hasNodesIn(d))
{
apf::MeshIterator* it = inMesh->begin(d);
apf::MeshEntity* e;
while ((e = inMesh->iterate(it)))
{
int n = s->countNodesOn(inMesh->getType(e));
for (int i = 0; i < n; ++i)
{
apf::getComponents(in,e,i,&(data[0]));
apf::setComponents(out,newFromOld[e],i,&(data[0]));
}
}
inMesh->end(it);
}
}
}
void convertQuadratic()
{
if (inMesh->getShape() != apf::getLagrange(2))
return;
if ( ! PCU_Comm_Self())
fprintf(stderr,"transferring quadratic mesh\n");
apf::changeMeshShape(outMesh,getLagrange(2),/*project=*/false);
convertField(inMesh->getCoordinateField(),outMesh->getCoordinateField());
}
void createMatches(int dim)
{
/* see createRemotes for the algorithm comments */
PCU_Comm_Begin();
MeshIterator* it = inMesh->begin(dim);
MeshEntity *oldLeft;
while ((oldLeft = inMesh->iterate(it)))
{
MeshEntity *newLeft = newFromOld[oldLeft];
Matches matches;
inMesh->getMatches(oldLeft, matches);
for (size_t i = 0; i < matches.getSize(); ++i)
{
int rightPart = matches[i].peer;
MeshEntity* oldRight = matches[i].entity;
PCU_COMM_PACK(rightPart,oldRight);
PCU_COMM_PACK(rightPart,newLeft);
}
}
inMesh->end(it);
PCU_Comm_Send();
while (PCU_Comm_Listen())
{
int leftPart = PCU_Comm_Sender();
while ( ! PCU_Comm_Unpacked())
{
MeshEntity* oldRight;
PCU_COMM_UNPACK(oldRight);
MeshEntity* newLeft;
PCU_COMM_UNPACK(newLeft);
MeshEntity *newRight = newFromOld[oldRight];
outMesh->addMatch(newRight, leftPart, newLeft);
}
}
}
private:
Mesh *inMesh;
Mesh2 *outMesh;
std::map<MeshEntity*,MeshEntity*> newFromOld;
};
void convert(Mesh *in, Mesh2 *out)
{
Converter c(in,out);
c.run();
}
}
<commit_msg>moving acceptChanges into apfConvert<commit_after>#include "apf.h"
#include "apfConvert.h"
#include "apfMesh.h"
#include "apfMesh2.h"
#include "apfShape.h"
#include <PCU.h>
#include <map>
namespace apf {
class Converter
{
public:
Converter(Mesh *a, Mesh2 *b)
{
inMesh = a;
outMesh = b;
}
void run()
{
createVertices();
createEntities();
for (int i = 0; i <= inMesh->getDimension(); ++i)
createRemotes(i);
if (inMesh->hasMatching())
for (int i = 0; i <= inMesh->getDimension(); ++i)
createMatches(i);
convertQuadratic();
outMesh->acceptChanges();
}
ModelEntity* getNewModelFromOld(ModelEntity* oldC)
{
int type = inMesh->getModelType(oldC);
int tag = inMesh->getModelTag(oldC);
return outMesh->findModelEntity(type,tag);
}
void createVertices()
{
MeshIterator* it = inMesh->begin(0);
MeshEntity *oldV;
while ((oldV = inMesh->iterate(it)))
{
ModelEntity *oldC = inMesh->toModel(oldV);
ModelEntity *newC = getNewModelFromOld(oldC);
Vector3 xyz;
inMesh->getPoint(oldV, 0, xyz);
Vector3 param(0,0,0);
inMesh->getParam(oldV,param);
MeshEntity* newV = outMesh->createVertex(newC, xyz, param);
newFromOld[oldV] = newV;
}
inMesh->end(it);
assert(outMesh->count(0) == inMesh->count(0));
}
void createEntities()
{
for (int i = 1; i < (inMesh->getDimension())+1; ++i)
createDimension(i);
}
void createDimension(int dim)
{
MeshIterator* it = inMesh->begin(dim);
MeshEntity *oldE;
while ((oldE = inMesh->iterate(it)))
{
int type = inMesh->getType(oldE);
ModelEntity *oldC = inMesh->toModel(oldE);
ModelEntity *newC = getNewModelFromOld(oldC);
Downward down;
int ne = inMesh->getDownward(oldE, dim-1, down);
Downward new_down;
for(int i=0; i<ne; ++i)
{
new_down[i]=newFromOld[down[i]];
}
MeshEntity *newE = outMesh->createEntity(type, newC, new_down);
newFromOld[oldE] = newE;
}
inMesh->end(it);
assert(outMesh->count(dim) == inMesh->count(dim));
}
void createRemotes(int dim)
{
/* O-------------|---|----->O
^old left | | ^old right
|MPI|
O<------------|---|------O
^new left | | ^new right */
/* creating links backwards is OK because
they go both ways; as long as every link
gets a backward copy they will all get copies */
PCU_Comm_Begin();
MeshIterator* it = inMesh->begin(dim);
MeshEntity *oldLeft;
while ((oldLeft = inMesh->iterate(it)))
{
MeshEntity *newLeft = newFromOld[oldLeft];
Copies remotes;
inMesh->getRemotes(oldLeft, remotes);
APF_ITERATE(Copies,remotes,it)
{
int rightPart = it->first;
MeshEntity* oldRight = it->second;
PCU_COMM_PACK(rightPart,oldRight);
PCU_COMM_PACK(rightPart,newLeft);
}
}
inMesh->end(it);
PCU_Comm_Send();
/* accumulation of residence sets... we could also constantly reclassify... */
std::map<MeshEntity*, std::vector<int> > map_ent;
while (PCU_Comm_Listen())
{
int leftPart = PCU_Comm_Sender();
while ( ! PCU_Comm_Unpacked())
{
MeshEntity* oldRight;
PCU_COMM_UNPACK(oldRight);
MeshEntity* newLeft;
PCU_COMM_UNPACK(newLeft);
MeshEntity *newRight = newFromOld[oldRight];
outMesh->addRemote(newRight, leftPart, newLeft);
map_ent[newRight].push_back(leftPart);
}
}
/* assign accumulated residence sets */
std::map <MeshEntity*, std::vector<int> >::iterator mit;
for(mit=map_ent.begin(); mit!=map_ent.end(); ++mit)
{
MeshEntity* newE;
newE = mit->first;
std::vector<int>& vecEnt = mit->second;
Copies remotes;
Parts parts;
parts.insert(vecEnt.begin(), vecEnt.end());
parts.insert(PCU_Comm_Self());
outMesh->setResidence(newE, parts);
}
}
void convertField(apf::Field* in, apf::Field* out)
{
apf::FieldShape* s = apf::getShape(in);
apf::NewArray<double> data(apf::countComponents(in));
for (int d = 0; d <= 3; ++d)
{
if (s->hasNodesIn(d))
{
apf::MeshIterator* it = inMesh->begin(d);
apf::MeshEntity* e;
while ((e = inMesh->iterate(it)))
{
int n = s->countNodesOn(inMesh->getType(e));
for (int i = 0; i < n; ++i)
{
apf::getComponents(in,e,i,&(data[0]));
apf::setComponents(out,newFromOld[e],i,&(data[0]));
}
}
inMesh->end(it);
}
}
}
void convertQuadratic()
{
if (inMesh->getShape() != apf::getLagrange(2))
return;
if ( ! PCU_Comm_Self())
fprintf(stderr,"transferring quadratic mesh\n");
apf::changeMeshShape(outMesh,getLagrange(2),/*project=*/false);
convertField(inMesh->getCoordinateField(),outMesh->getCoordinateField());
}
void createMatches(int dim)
{
/* see createRemotes for the algorithm comments */
PCU_Comm_Begin();
MeshIterator* it = inMesh->begin(dim);
MeshEntity *oldLeft;
while ((oldLeft = inMesh->iterate(it)))
{
MeshEntity *newLeft = newFromOld[oldLeft];
Matches matches;
inMesh->getMatches(oldLeft, matches);
for (size_t i = 0; i < matches.getSize(); ++i)
{
int rightPart = matches[i].peer;
MeshEntity* oldRight = matches[i].entity;
PCU_COMM_PACK(rightPart,oldRight);
PCU_COMM_PACK(rightPart,newLeft);
}
}
inMesh->end(it);
PCU_Comm_Send();
while (PCU_Comm_Listen())
{
int leftPart = PCU_Comm_Sender();
while ( ! PCU_Comm_Unpacked())
{
MeshEntity* oldRight;
PCU_COMM_UNPACK(oldRight);
MeshEntity* newLeft;
PCU_COMM_UNPACK(newLeft);
MeshEntity *newRight = newFromOld[oldRight];
outMesh->addMatch(newRight, leftPart, newLeft);
}
}
}
private:
Mesh *inMesh;
Mesh2 *outMesh;
std::map<MeshEntity*,MeshEntity*> newFromOld;
};
void convert(Mesh *in, Mesh2 *out)
{
Converter c(in,out);
c.run();
}
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2005, Thorvald Natvig <[email protected]>
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 Mumble Developers 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 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 "AudioInput.h"
#include "ServerHandler.h"
AudioInput *g_aiInput;
AudioInput::AudioInput()
{
speex_bits_init(&m_sbBits);
m_esEncState=speex_encoder_init(&speex_wb_mode);
speex_encoder_ctl(m_esEncState,SPEEX_GET_FRAME_SIZE,&m_iFrameSize);
m_iByteSize=m_iFrameSize * 2;
int iarg=1;
speex_encoder_ctl(m_esEncState,SPEEX_SET_VBR, &iarg);
iarg = 0;
speex_encoder_ctl(m_esEncState,SPEEX_SET_VAD, &iarg);
speex_encoder_ctl(m_esEncState,SPEEX_SET_DTX, &iarg);
m_bResetProcessor = true;
m_sppPreprocess = NULL;
m_psMic = new short[m_iFrameSize];
m_bRunning = false;
}
AudioInput::~AudioInput()
{
m_bRunning = false;
wait();
speex_bits_destroy(&m_sbBits);
speex_encoder_destroy(m_esEncState);
if (m_sppPreprocess)
speex_preprocess_state_destroy(m_sppPreprocess);
delete [] m_psMic;
}
void AudioInput::encodeAudioFrame() {
int iArg;
float fArg;
int iLen;
if (! m_bRunning) {
return;
}
if (m_bResetProcessor) {
if (m_sppPreprocess)
speex_preprocess_state_destroy(m_sppPreprocess);
m_sppPreprocess = speex_preprocess_state_init(m_iFrameSize, SAMPLE_RATE);
m_bResetProcessor = false;
}
fArg = 8;
speex_encoder_ctl(m_esEncState,SPEEX_SET_VBR_QUALITY, &fArg);
iArg = 5;
speex_encoder_ctl(m_esEncState,SPEEX_SET_COMPLEXITY, &iArg);
iArg = 1;
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_VAD, &iArg);
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg);
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_AGC, &iArg);
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_DEREVERB, &iArg);
fArg = 12000;
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_AGC_LEVEL, &fArg);
int iIsSpeech;
iIsSpeech=speex_preprocess(m_sppPreprocess, m_psMic, NULL);
if (m_sppPreprocess->loudness2 < 4000)
m_sppPreprocess->loudness2 = 4000;
speex_bits_reset(&m_sbBits);
speex_encode_int(m_esEncState, m_psMic, &m_sbBits);
iLen=speex_bits_nbytes(&m_sbBits);
QByteArray qbaPacket(iLen, 0);
speex_bits_write(&m_sbBits, qbaPacket.data(), iLen);
MessageSpeex *msPacket = new MessageSpeex();
msPacket->m_qbaSpeexPacket = qbaPacket;
if (g_shServer)
g_shServer->sendMessage(msPacket);
}
<commit_msg>Fix memory leak, it's now safe to pass stack-allocated messages<commit_after>/* Copyright (C) 2005, Thorvald Natvig <[email protected]>
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 Mumble Developers 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 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 "AudioInput.h"
#include "ServerHandler.h"
AudioInput *g_aiInput;
AudioInput::AudioInput()
{
speex_bits_init(&m_sbBits);
m_esEncState=speex_encoder_init(&speex_wb_mode);
speex_encoder_ctl(m_esEncState,SPEEX_GET_FRAME_SIZE,&m_iFrameSize);
m_iByteSize=m_iFrameSize * 2;
int iarg=1;
speex_encoder_ctl(m_esEncState,SPEEX_SET_VBR, &iarg);
iarg = 0;
speex_encoder_ctl(m_esEncState,SPEEX_SET_VAD, &iarg);
speex_encoder_ctl(m_esEncState,SPEEX_SET_DTX, &iarg);
m_bResetProcessor = true;
m_sppPreprocess = NULL;
m_psMic = new short[m_iFrameSize];
m_bRunning = false;
}
AudioInput::~AudioInput()
{
m_bRunning = false;
wait();
speex_bits_destroy(&m_sbBits);
speex_encoder_destroy(m_esEncState);
if (m_sppPreprocess)
speex_preprocess_state_destroy(m_sppPreprocess);
delete [] m_psMic;
}
void AudioInput::encodeAudioFrame() {
int iArg;
float fArg;
int iLen;
if (! m_bRunning) {
return;
}
if (m_bResetProcessor) {
if (m_sppPreprocess)
speex_preprocess_state_destroy(m_sppPreprocess);
m_sppPreprocess = speex_preprocess_state_init(m_iFrameSize, SAMPLE_RATE);
m_bResetProcessor = false;
}
fArg = 8;
speex_encoder_ctl(m_esEncState,SPEEX_SET_VBR_QUALITY, &fArg);
iArg = 5;
speex_encoder_ctl(m_esEncState,SPEEX_SET_COMPLEXITY, &iArg);
iArg = 1;
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_VAD, &iArg);
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg);
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_AGC, &iArg);
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_DEREVERB, &iArg);
fArg = 12000;
speex_preprocess_ctl(m_sppPreprocess, SPEEX_PREPROCESS_SET_AGC_LEVEL, &fArg);
int iIsSpeech;
iIsSpeech=speex_preprocess(m_sppPreprocess, m_psMic, NULL);
if (m_sppPreprocess->loudness2 < 4000)
m_sppPreprocess->loudness2 = 4000;
speex_bits_reset(&m_sbBits);
speex_encode_int(m_esEncState, m_psMic, &m_sbBits);
iLen=speex_bits_nbytes(&m_sbBits);
QByteArray qbaPacket(iLen, 0);
speex_bits_write(&m_sbBits, qbaPacket.data(), iLen);
MessageSpeex msPacket;
msPacket.m_qbaSpeexPacket = qbaPacket;
if (g_shServer)
g_shServer->sendMessage(&msPacket);
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2012 Stanford University
* Copyright (c) 2015 Diego Ongaro
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cassert>
#include <getopt.h>
#include <iostream>
#include <iterator>
#include <sstream>
#include <LogCabin/Client.h>
#include <LogCabin/Debug.h>
#include <LogCabin/Util.h>
#include <zconf.h>
#include "../RedisServer/RedisServer.h"
namespace {
using LogCabin::Client::Cluster;
using LogCabin::Client::Tree;
using LogCabin::Client::Util::parseNonNegativeDuration;
enum class Command {
MKDIR,
LIST,
DUMP,
RMDIR,
WRITE,
READ,
REMOVE,
SUBSCRIBE,
UNSUBSCRIBE
};
/**
* Parses argv for the main function.
*/
class OptionParser {
public:
OptionParser(int& argc, char**& argv)
: argc(argc)
, argv(argv)
, cluster("localhost:5254")
, command()
, condition()
, dir()
, logPolicy("")
, path()
, timeout(parseNonNegativeDuration("0s"))
{
while (true) {
static struct option longOptions[] = {
{"cluster", required_argument, NULL, 'c'},
{"dir", required_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"condition", required_argument, NULL, 'p'},
{"quiet", no_argument, NULL, 'q'},
{"timeout", required_argument, NULL, 't'},
{"verbose", no_argument, NULL, 'v'},
{"verbosity", required_argument, NULL, 256},
{0, 0, 0, 0}
};
int c = getopt_long(argc, argv, "c:d:p:t:hqv", longOptions, NULL);
// Detect the end of the options.
if (c == -1)
break;
switch (c) {
case 'c':
cluster = optarg;
break;
case 'd':
dir = optarg;
break;
case 'h':
usage();
exit(0);
case 'p': {
std::istringstream stream(optarg);
std::string path;
std::string value;
std::getline(stream, path, ':');
std::getline(stream, value);
condition = {path, value};
break;
}
case 'q':
logPolicy = "WARNING";
break;
case 't':
timeout = parseNonNegativeDuration(optarg);
break;
case 'v':
logPolicy = "VERBOSE";
break;
case 256:
logPolicy = optarg;
break;
case '?':
default:
// getopt_long already printed an error message.
usage();
exit(1);
}
}
// Additional command line arguments are required.
if (optind == argc) {
usage();
exit(1);
}
std::string cmdStr = argv[optind];
++optind;
if (cmdStr == "mkdir") {
command = Command::MKDIR;
} else if (cmdStr == "list" || cmdStr == "ls") {
command = Command::LIST;
} else if (cmdStr == "dump") {
command = Command::DUMP;
path = "/";
} else if (cmdStr == "rmdir" || cmdStr == "removeDir") {
command = Command::RMDIR;
} else if (cmdStr == "write" || cmdStr == "create" ||
cmdStr == "set") {
command = Command::WRITE;
} else if (cmdStr == "read" || cmdStr == "get") {
command = Command::READ;
} else if (cmdStr == "remove" || cmdStr == "rm" ||
cmdStr == "removeFile") {
command = Command::REMOVE;
} else if (cmdStr == "sub" || cmdStr == "subscribe") {
command = Command::SUBSCRIBE;
} else if (cmdStr == "unsub" || cmdStr == "unsubscribe") {
command = Command ::UNSUBSCRIBE;
} else {
std::cout << "Unknown command: " << cmdStr << std::endl;
usage();
exit(1);
}
if (optind < argc) {
path = argv[optind];
++optind;
}
if (path.empty()) {
std::cout << "No path given" << std::endl;
usage();
exit(1);
}
if (optind < argc) {
std::cout << "Unexpected positional argument: " << argv[optind]
<< std::endl;
usage();
exit(1);
}
}
void usage() {
std::cout << "Run various operations on a LogCabin replicated state "
<< "machine."
<< std::endl
<< std::endl
<< "This program was released in LogCabin v1.0.0."
<< std::endl;
std::cout << std::endl;
std::cout << "Usage: " << argv[0] << " [options] <command> [<args>]"
<< std::endl;
std::cout << std::endl;
std::cout << "Commands:" << std::endl;
std::cout
<< " mkdir <path> If no directory exists at <path>, create it."
<< std::endl
<< " list <path> List keys within directory at <path>. "
<< "Alias: ls."
<< std::endl
<< " dump [<path>] Recursively print keys and values within "
<< "directory at <path>."
<< std::endl
<< " Defaults to printing all keys and values "
<< "from root of tree."
<< std::endl
<< " rmdir <path> Recursively remove directory at <path>, if "
<< "any."
<< std::endl
<< " Alias: removedir."
<< std::endl
<< " write <path> Set/create value of file at <path> to "
<< "stdin."
<< std::endl
<< " Alias: create, set."
<< std::endl
<< " read <path> Print value of file at <path>. Alias: get."
<< std::endl
<< " remove <path> Remove file at <path>, if any. Alias: rm, "
<< "removefile."
<< std::endl
<< std::endl;
std::cout << "Options:" << std::endl;
std::cout
<< " -c <addresses>, --cluster=<addresses> "
<< "Network addresses of the LogCabin"
<< std::endl
<< " "
<< "servers, comma-separated"
<< std::endl
<< " "
<< "[default: localhost:5254]"
<< std::endl
<< " -d <path>, --dir=<path> "
<< "Set working directory [default: /]"
<< std::endl
<< " -h, --help "
<< "Print this usage information"
<< std::endl
<< " -p <pred>, --condition=<pred> "
<< "Set predicate on the operation of the"
<< std::endl
<< " "
<< "form <path>:<value>, indicating that the key"
<< std::endl
<< " "
<< "at <path> must have the given value."
<< std::endl
<< " -q, --quiet "
<< "Same as --verbosity=WARNING"
<< std::endl
<< " -t <time>, --timeout=<time> "
<< "Set timeout for the operation"
<< std::endl
<< " "
<< "(0 means wait forever) [default: 0s]"
<< std::endl
<< " -v, --verbose "
<< "Same as --verbosity=VERBOSE (added in v1.1.0)"
<< std::endl
<< " --verbosity=<policy> "
<< "Set which log messages are shown."
<< std::endl
<< " "
<< "Comma-separated LEVEL or PATTERN@LEVEL rules."
<< std::endl
<< " "
<< "Levels: SILENT ERROR WARNING NOTICE VERBOSE."
<< std::endl
<< " "
<< "Patterns match filename prefixes or suffixes."
<< std::endl
<< " "
<< "Example: Client@NOTICE,Test.cc@SILENT,VERBOSE."
<< std::endl
<< " "
<< "(added in v1.1.0)"
<< std::endl;
}
int& argc;
char**& argv;
std::string cluster;
Command command;
std::pair<std::string, std::string> condition;
std::string dir;
std::string logPolicy;
std::string path;
uint64_t timeout;
};
/**
* Depth-first search tree traversal, dumping out contents of all files
*/
void
dumpTree(const Tree& tree, std::string path)
{
std::cout << path << std::endl;
std::vector<std::string> children = tree.listDirectoryEx(path);
for (auto it = children.begin(); it != children.end(); ++it) {
std::string child = path + *it;
if (*child.rbegin() == '/') { // directory
dumpTree(tree, child);
} else { // file
std::cout << child << ": " << std::endl;
std::cout << " " << tree.readEx(child) << std::endl;
}
}
}
std::string
readStdin()
{
std::cin >> std::noskipws;
std::istream_iterator<char> it(std::cin);
std::istream_iterator<char> end;
std::string results(it, end);
return results;
}
} // anonymous namespace
int
main(int argc, char** argv)
{
try {
OptionParser options(argc, argv);
LogCabin::Client::Debug::setLogPolicy(
LogCabin::Client::Debug::logPolicyFromString(
options.logPolicy));
Cluster cluster(options.cluster);
Tree tree = cluster.getTree();
if (options.timeout > 0) {
tree.setTimeout(options.timeout);
}
if (!options.dir.empty()) {
tree.setWorkingDirectoryEx(options.dir);
}
if (!options.condition.first.empty()) {
tree.setConditionEx(options.condition.first,
options.condition.second);
}
std::string& path = options.path;
switch (options.command) {
case Command::MKDIR:
tree.makeDirectoryEx(path);
break;
case Command::LIST: {
std::vector<std::string> keys = tree.listDirectoryEx(path);
for (auto it = keys.begin(); it != keys.end(); ++it)
std::cout << *it << std::endl;
break;
}
case Command::DUMP: {
if (path.empty() || path.at(path.size() - 1) != '/')
path.append("/");
dumpTree(tree, path);
break;
}
case Command::RMDIR:
tree.removeDirectoryEx(path);
break;
case Command::WRITE:
tree.writeEx(path, readStdin());
break;
case Command::READ: {
try {
std::string contents = tree.readEx(path);
std::cout << contents;
if (contents.empty() ||
contents.at(contents.size() - 1) != '\n') {
std::cout << std::endl;
} else {
std::cout.flush();
}
} catch (const LogCabin::Client::Exception& e) {
std::cerr << "LogCabin::Client::Exception: "
<< e.what()
<< std::endl;
}
break;
}
case Command::REMOVE:
tree.removeFileEx(path);
break;
}
// return 0;
RedisServer redis(tree);
redis.Init();
std::string pass = "shahe22f";
redis.SetPassword(pass);
redis.Start("127.0.0.1", 6479);
while (1) {
usleep(1000);
}
} catch (const LogCabin::Client::Exception& e) {
std::cerr << "Exiting due to LogCabin::Client::Exception: "
<< e.what()
<< std::endl;
exit(1);
}
return 0;
}
<commit_msg>more prompt<commit_after>/* Copyright (c) 2012 Stanford University
* Copyright (c) 2015 Diego Ongaro
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cassert>
#include <getopt.h>
#include <iostream>
#include <iterator>
#include <sstream>
#include <LogCabin/Client.h>
#include <LogCabin/Debug.h>
#include <LogCabin/Util.h>
#include <zconf.h>
#include "../RedisServer/RedisServer.h"
namespace {
using LogCabin::Client::Cluster;
using LogCabin::Client::Tree;
using LogCabin::Client::Util::parseNonNegativeDuration;
enum class Command {
MKDIR,
LIST,
DUMP,
RMDIR,
WRITE,
READ,
REMOVE,
SUBSCRIBE,
UNSUBSCRIBE
};
/**
* Parses argv for the main function.
*/
class OptionParser {
public:
OptionParser(int& argc, char**& argv)
: argc(argc)
, argv(argv)
, cluster("localhost:5254")
, command()
, condition()
, dir()
, logPolicy("")
, path()
, timeout(parseNonNegativeDuration("0s"))
{
while (true) {
static struct option longOptions[] = {
{"cluster", required_argument, NULL, 'c'},
{"dir", required_argument, NULL, 'd'},
{"help", no_argument, NULL, 'h'},
{"condition", required_argument, NULL, 'p'},
{"quiet", no_argument, NULL, 'q'},
{"timeout", required_argument, NULL, 't'},
{"verbose", no_argument, NULL, 'v'},
{"verbosity", required_argument, NULL, 256},
{0, 0, 0, 0}
};
int c = getopt_long(argc, argv, "c:d:p:t:hqv", longOptions, NULL);
// Detect the end of the options.
if (c == -1)
break;
switch (c) {
case 'c':
cluster = optarg;
break;
case 'd':
dir = optarg;
break;
case 'h':
usage();
exit(0);
case 'p': {
std::istringstream stream(optarg);
std::string path;
std::string value;
std::getline(stream, path, ':');
std::getline(stream, value);
condition = {path, value};
break;
}
case 'q':
logPolicy = "WARNING";
break;
case 't':
timeout = parseNonNegativeDuration(optarg);
break;
case 'v':
logPolicy = "VERBOSE";
break;
case 256:
logPolicy = optarg;
break;
case '?':
default:
// getopt_long already printed an error message.
usage();
exit(1);
}
}
// Additional command line arguments are required.
if (optind == argc) {
usage();
exit(1);
}
std::string cmdStr = argv[optind];
++optind;
if (cmdStr == "mkdir") {
command = Command::MKDIR;
} else if (cmdStr == "list" || cmdStr == "ls") {
command = Command::LIST;
} else if (cmdStr == "dump") {
command = Command::DUMP;
path = "/";
} else if (cmdStr == "rmdir" || cmdStr == "removeDir") {
command = Command::RMDIR;
} else if (cmdStr == "write" || cmdStr == "create" ||
cmdStr == "set") {
command = Command::WRITE;
} else if (cmdStr == "read" || cmdStr == "get") {
command = Command::READ;
} else if (cmdStr == "remove" || cmdStr == "rm" ||
cmdStr == "removeFile") {
command = Command::REMOVE;
} else if (cmdStr == "sub" || cmdStr == "subscribe") {
command = Command::SUBSCRIBE;
} else if (cmdStr == "unsub" || cmdStr == "unsubscribe") {
command = Command ::UNSUBSCRIBE;
} else {
std::cout << "Unknown command: " << cmdStr << std::endl;
usage();
exit(1);
}
if (optind < argc) {
path = argv[optind];
++optind;
}
if (path.empty()) {
std::cout << "No path given" << std::endl;
usage();
exit(1);
}
if (optind < argc) {
std::cout << "Unexpected positional argument: " << argv[optind]
<< std::endl;
usage();
exit(1);
}
}
void usage() {
std::cout << "Run various operations on a LogCabin replicated state "
<< "machine."
<< std::endl
<< std::endl
<< "This program was released in LogCabin v1.0.0."
<< std::endl;
std::cout << std::endl;
std::cout << "Usage: " << argv[0] << " [options] <command> [<args>]"
<< std::endl;
std::cout << std::endl;
std::cout << "Commands:" << std::endl;
std::cout
<< " mkdir <path> If no directory exists at <path>, create it."
<< std::endl
<< " list <path> List keys within directory at <path>. "
<< "Alias: ls."
<< std::endl
<< " dump [<path>] Recursively print keys and values within "
<< "directory at <path>."
<< std::endl
<< " Defaults to printing all keys and values "
<< "from root of tree."
<< std::endl
<< " rmdir <path> Recursively remove directory at <path>, if "
<< "any."
<< std::endl
<< " Alias: removedir."
<< std::endl
<< " write <path> Set/create value of file at <path> to "
<< "stdin."
<< std::endl
<< " Alias: create, set."
<< std::endl
<< " read <path> Print value of file at <path>. Alias: get."
<< std::endl
<< " remove <path> Remove file at <path>, if any. Alias: rm, "
<< "removefile."
<< std::endl
<< std::endl;
std::cout << "Options:" << std::endl;
std::cout
<< " -c <addresses>, --cluster=<addresses> "
<< "Network addresses of the LogCabin"
<< std::endl
<< " "
<< "servers, comma-separated"
<< std::endl
<< " "
<< "[default: localhost:5254]"
<< std::endl
<< " -d <path>, --dir=<path> "
<< "Set working directory [default: /]"
<< std::endl
<< " -h, --help "
<< "Print this usage information"
<< std::endl
<< " -p <pred>, --condition=<pred> "
<< "Set predicate on the operation of the"
<< std::endl
<< " "
<< "form <path>:<value>, indicating that the key"
<< std::endl
<< " "
<< "at <path> must have the given value."
<< std::endl
<< " -q, --quiet "
<< "Same as --verbosity=WARNING"
<< std::endl
<< " -t <time>, --timeout=<time> "
<< "Set timeout for the operation"
<< std::endl
<< " "
<< "(0 means wait forever) [default: 0s]"
<< std::endl
<< " -v, --verbose "
<< "Same as --verbosity=VERBOSE (added in v1.1.0)"
<< std::endl
<< " --verbosity=<policy> "
<< "Set which log messages are shown."
<< std::endl
<< " "
<< "Comma-separated LEVEL or PATTERN@LEVEL rules."
<< std::endl
<< " "
<< "Levels: SILENT ERROR WARNING NOTICE VERBOSE."
<< std::endl
<< " "
<< "Patterns match filename prefixes or suffixes."
<< std::endl
<< " "
<< "Example: Client@NOTICE,Test.cc@SILENT,VERBOSE."
<< std::endl
<< " "
<< "(added in v1.1.0)"
<< std::endl;
}
int& argc;
char**& argv;
std::string cluster;
Command command;
std::pair<std::string, std::string> condition;
std::string dir;
std::string logPolicy;
std::string path;
uint64_t timeout;
};
/**
* Depth-first search tree traversal, dumping out contents of all files
*/
void
dumpTree(const Tree& tree, std::string path)
{
std::cout << path << std::endl;
std::vector<std::string> children = tree.listDirectoryEx(path);
for (auto it = children.begin(); it != children.end(); ++it) {
std::string child = path + *it;
if (*child.rbegin() == '/') { // directory
dumpTree(tree, child);
} else { // file
std::cout << child << ": " << std::endl;
std::cout << " " << tree.readEx(child) << std::endl;
}
}
}
std::string
readStdin()
{
std::cin >> std::noskipws;
std::istream_iterator<char> it(std::cin);
std::istream_iterator<char> end;
std::string results(it, end);
return results;
}
} // anonymous namespace
int
main(int argc, char** argv)
{
try {
OptionParser options(argc, argv);
LogCabin::Client::Debug::setLogPolicy(
LogCabin::Client::Debug::logPolicyFromString(
options.logPolicy));
Cluster cluster(options.cluster);
Tree tree = cluster.getTree();
if (options.timeout > 0) {
tree.setTimeout(options.timeout);
}
if (!options.dir.empty()) {
tree.setWorkingDirectoryEx(options.dir);
}
if (!options.condition.first.empty()) {
tree.setConditionEx(options.condition.first,
options.condition.second);
}
std::string& path = options.path;
switch (options.command) {
case Command::MKDIR:
tree.makeDirectoryEx(path);
break;
case Command::LIST: {
std::vector<std::string> keys = tree.listDirectoryEx(path);
for (auto it = keys.begin(); it != keys.end(); ++it)
std::cout << *it << std::endl;
break;
}
case Command::DUMP: {
if (path.empty() || path.at(path.size() - 1) != '/')
path.append("/");
dumpTree(tree, path);
break;
}
case Command::RMDIR:
tree.removeDirectoryEx(path);
break;
case Command::WRITE:
tree.writeEx(path, readStdin());
break;
case Command::READ: {
try {
std::string contents = tree.readEx(path);
std::cout << contents;
if (contents.empty() ||
contents.at(contents.size() - 1) != '\n') {
std::cout << std::endl;
} else {
std::cout.flush();
}
} catch (const LogCabin::Client::Exception& e) {
std::cerr << "LogCabin::Client::Exception: "
<< e.what()
<< std::endl;
}
break;
}
case Command::REMOVE:
tree.removeFileEx(path);
break;
}
// return 0;
RedisServer redis(tree);
redis.Init();
std::string pass = "shahe22f";
redis.SetPassword(pass);
int port = 6479;
std::cout << "Listen port " << port << std::endl;
redis.Start("127.0.0.1", port);
while (1) {
usleep(1000);
}
} catch (const LogCabin::Client::Exception& e) {
std::cerr << "Exiting due to LogCabin::Client::Exception: "
<< e.what()
<< std::endl;
exit(1);
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_OPENCL_REV_LDEXP_HPP
#define STAN_MATH_OPENCL_REV_LDEXP_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of.hpp>
namespace stan {
namespace math {
/**
* Returns the elementwise `ldexp()` of the input
* `var_value<matrix_cl<double>>` and kernel generator expression.
*
* @param a input rev kernel generator expression representing
* significands
* @param b input kernel generator expression representing
* the integer exponents.
* @return Elementwise `ldexp()` of the input argument.
*/
template <typename T_a, typename T_b,
require_all_kernel_expressions_and_none_scalar_t<T_a>* = nullptr,
require_all_kernel_expressions_t<T_b>* = nullptr>
inline var_value<matrix_cl<double>> ldexp(const var_value<matrix_cl<T_a>>& a,
const T_b& b) {
const arena_t<T_b>& b_arena = b;
var_value<matrix_cl<double>> res = ldexp(a.val(), b);
reverse_pass_callback([a, b_arena, res]() mutable {
a.adj() = a.adj() + ldexp(res.adj(), value_of(b_arena));
});
return res;
}
/**
* Returns the elementwise `ldexp()` of the input
* `var_value<matrix_cl<double>>` and kernel generator expression.
*
* @param a input rev kernel generator expression representing
* significands
* @param b input kernel generator expression representing
* the integer exponents.
* @return Elementwise `ldexp()` of the input argument.
*/
template <typename T_a, typename T_b,
require_all_kernel_expressions_and_none_scalar_t<T_a, T_b>* = nullptr>
inline var_value<matrix_cl<double>> ldexp(const var_value<matrix_cl<T_a>>& a,
const T_b& b) {
const arena_t<T_b>& b_arena = b;
var_value<matrix_cl<double>> res = ldexp(a.val(), b);
reverse_pass_callback([a, b_arena, res]() mutable {
a.adj() = a.adj() + sum(ldexp(res.adj(), value_of(b_arena)));
});
return res;
}
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>fix requires<commit_after>#ifndef STAN_MATH_OPENCL_REV_LDEXP_HPP
#define STAN_MATH_OPENCL_REV_LDEXP_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of.hpp>
namespace stan {
namespace math {
/**
* Returns the elementwise `ldexp()` of the input
* `var_value<matrix_cl<double>>` and kernel generator expression.
*
* @param a input rev kernel generator expression representing
* significands
* @param b input kernel generator expression representing
* the integer exponents.
* @return Elementwise `ldexp()` of the input argument.
*/
template <typename T_a, typename T_b,
require_all_kernel_expressions_and_none_scalar_t<T_a>* = nullptr,
require_all_kernel_expressions_t<T_b>* = nullptr>
inline var_value<matrix_cl<double>> ldexp(const var_value<T_a>& a,
const T_b& b) {
const arena_t<T_b>& b_arena = b;
var_value<matrix_cl<double>> res = ldexp(a.val(), b);
reverse_pass_callback([a, b_arena, res]() mutable {
a.adj() = a.adj() + ldexp(res.adj(), value_of(b_arena));
});
return res;
}
/**
* Returns the elementwise `ldexp()` of the input
* `var_value<matrix_cl<double>>` and kernel generator expression.
*
* @param a input rev kernel generator expression representing
* significands
* @param b input kernel generator expression representing
* the integer exponents.
* @return Elementwise `ldexp()` of the input argument.
*/
template <typename T_b,
require_all_kernel_expressions_and_none_scalar_t<T_b>* = nullptr>
inline var_value<matrix_cl<double>> ldexp(const var_value<double>& a,
const T_b& b) {
const arena_t<T_b>& b_arena = b;
var_value<matrix_cl<double>> res = ldexp(a.val(), b);
reverse_pass_callback([a, b_arena, res]() mutable {
a.adj() = a.adj() + sum(ldexp(res.adj(), value_of(b_arena)));
});
return res;
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_FUN_MULTIPLY_HPP
#define STAN_MATH_REV_FUN_MULTIPLY_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/prim/fun.hpp>
#include <type_traits>
namespace stan {
namespace math {
/**
* Return the product of two matrices.
*
* This version does not handle row vector times column vector
*
* @tparam T1 type of first matrix
* @tparam T2 type of second matrix
*
* @param[in] A first matrix
* @param[in] B second matrix
* @return A * B
*/
template <typename T1, typename T2, require_all_matrix_t<T1, T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_return_type_t<is_var, T1, T2>* = nullptr,
require_not_row_and_col_vector_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
check_multiplicable("multiply", "A", A, "B", B);
if (!is_constant<T2>::value && !is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = to_ref(A);
arena_t<promote_scalar_t<var, T2>> arena_B = to_ref(B);
arena_t<promote_scalar_t<double, T1>> arena_A_val = value_of(arena_A);
arena_t<promote_scalar_t<double, T2>> arena_B_val = value_of(arena_B);
using return_t
= return_var_matrix_t<decltype(arena_A_val * arena_B_val), T1, T2>;
arena_t<return_t> res = arena_A_val * arena_B_val;
reverse_pass_callback(
[arena_A, arena_B, arena_A_val, arena_B_val, res]() mutable {
auto res_adj = res.adj().eval();
arena_A.adj() += res_adj * arena_B_val.transpose();
arena_B.adj() += arena_A_val.transpose() * res_adj;
});
return return_t(res);
} else if (!is_constant<T2>::value) {
arena_t<promote_scalar_t<double, T1>> arena_A_val = value_of(to_ref(A));
arena_t<promote_scalar_t<var, T2>> arena_B = to_ref(B);
using return_t
= return_var_matrix_t<decltype(arena_A_val * value_of(B).eval()), T1,
T2>;
arena_t<return_t> res = arena_A_val * value_of(arena_B);
reverse_pass_callback([arena_B, arena_A_val, res]() mutable {
arena_B.adj() += arena_A_val.transpose() * res.adj_op();
});
return return_t(res);
} else {
arena_t<promote_scalar_t<var, T1>> arena_A = to_ref(A);
arena_t<promote_scalar_t<double, T2>> arena_B_val = value_of(to_ref(B));
using return_t
= return_var_matrix_t<decltype(value_of(arena_A).eval() * arena_B_val),
T1, T2>;
arena_t<return_t> res = value_of(arena_A) * arena_B_val;
reverse_pass_callback([arena_A, arena_B_val, res]() mutable {
arena_A.adj() += res.adj_op() * arena_B_val.transpose();
});
return return_t(res);
}
}
/**
* Return the product of a row vector times a column vector as a scalar
*
* @tparam T1 type of row vector
* @tparam T2 type of column vector
*
* @param[in] A row vector
* @param[in] B column vector
* @return A * B as a scalar
*/
template <typename T1, typename T2, require_all_matrix_t<T1, T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_row_and_col_vector_t<T1, T2>* = nullptr>
inline var multiply(const T1& A, const T2& B) {
check_multiplicable("multiply", "A", A, "B", B);
if (!is_constant<T2>::value && !is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = to_ref(A);
arena_t<promote_scalar_t<var, T2>> arena_B = to_ref(B);
arena_t<promote_scalar_t<double, T1>> arena_A_val = value_of(arena_A);
arena_t<promote_scalar_t<double, T2>> arena_B_val = value_of(arena_B);
var res = arena_A_val.dot(arena_B_val);
reverse_pass_callback(
[arena_A, arena_B, arena_A_val, arena_B_val, res]() mutable {
auto res_adj = res.adj();
arena_A.adj().array() += res_adj * arena_B_val.transpose().array();
arena_B.adj().array() += arena_A_val.transpose().array() * res_adj;
});
return res;
} else if (!is_constant<T2>::value) {
arena_t<promote_scalar_t<var, T2>> arena_B = to_ref(B);
arena_t<promote_scalar_t<double, T1>> arena_A_val = value_of(A);
var res = arena_A_val.dot(value_of(arena_B));
reverse_pass_callback([arena_B, arena_A_val, res]() mutable {
arena_B.adj().array() += arena_A_val.transpose().array() * res.adj();
});
return res;
} else {
arena_t<promote_scalar_t<var, T1>> arena_A = to_ref(A);
arena_t<promote_scalar_t<double, T2>> arena_B_val = value_of(B);
var res = value_of(arena_A).dot(arena_B_val);
reverse_pass_callback([arena_A, arena_B_val, res]() mutable {
arena_A.adj().array() += res.adj() * arena_B_val.transpose().array();
});
return res;
}
}
/**
* Return specified matrix multiplied by specified scalar where at least one
* input has a scalar type of a `var_value`.
*
* @tparam T1 type of the scalar
* @tparam T2 type of the matrix or expression
*
* @param A scalar
* @param B matrix
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_not_matrix_t<T1>* = nullptr,
require_matrix_t<T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_not_row_and_col_vector_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
if (!is_constant<T2>::value && !is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<var, T2>> arena_B = B;
using return_t = return_var_matrix_t<T2, T1, T2>;
arena_t<return_t> res = arena_A.val() * arena_B.val().array();
reverse_pass_callback([arena_A, arena_B, res]() mutable {
const auto a_val = arena_A.val();
for (Eigen::Index j = 0; j < res.cols(); ++j) {
for (Eigen::Index i = 0; i < res.rows(); ++i) {
const auto res_adj = res.adj().coeffRef(i, j);
arena_A.adj() += res_adj * arena_B.val().coeff(i, j);
arena_B.adj().coeffRef(i, j) += a_val * res_adj;
}
}
});
return return_t(res);
} else if (!is_constant<T2>::value) {
arena_t<promote_scalar_t<double, T1>> arena_A = value_of(A);
arena_t<promote_scalar_t<var, T2>> arena_B = B;
using return_t = return_var_matrix_t<T2, T1, T2>;
arena_t<return_t> res = arena_A * arena_B.val().array();
reverse_pass_callback([arena_A, arena_B, res]() mutable {
arena_B.adj().array() += arena_A * res.adj().array();
});
return return_t(res);
} else {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<double, T2>> arena_B = value_of(B);
using return_t = return_var_matrix_t<T2, T1, T2>;
arena_t<return_t> res = arena_A.val() * arena_B.array();
reverse_pass_callback([arena_A, arena_B, res]() mutable {
arena_A.adj() += (res.adj().array() * arena_B.array()).sum();
});
return return_t(res);
}
}
/**
* Return specified matrix multiplied by specified scalar where at least one
* input has a scalar type of a `var_value`.
*
* @tparam T1 type of the matrix or expression
* @tparam T2 type of the scalar
*
* @param A matrix
* @param B scalar
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_matrix_t<T1>* = nullptr,
require_not_matrix_t<T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_not_row_and_col_vector_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
return multiply(B, A);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>fixup multiply<commit_after>#ifndef STAN_MATH_REV_FUN_MULTIPLY_HPP
#define STAN_MATH_REV_FUN_MULTIPLY_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/prim/fun.hpp>
#include <type_traits>
namespace stan {
namespace math {
/**
* Return the product of two matrices.
*
* This version does not handle row vector times column vector
*
* @tparam T1 type of first matrix
* @tparam T2 type of second matrix
*
* @param[in] A first matrix
* @param[in] B second matrix
* @return A * B
*/
template <typename T1, typename T2, require_all_matrix_t<T1, T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_return_type_t<is_var, T1, T2>* = nullptr,
require_not_row_and_col_vector_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
check_multiplicable("multiply", "A", A, "B", B);
if (!is_constant<T2>::value && !is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<var, T2>> arena_B = B;
using return_t
= return_var_matrix_t<decltype(arena_A.val_op() * arena_B.val_op()), T1, T2>;
arena_t<return_t> res = arena_A.val_op() * arena_B.val_op();
reverse_pass_callback(
[arena_A, arena_B, arena_A_val, arena_B_val, res]() mutable {
if (is_var_matrix<T1>::value || is_var_matrix<T2>::value) {
arena_A.adj() += res.adj() * arena_B.val_op().transpose();
arena_B.adj() += arena_A.val_op().transpose() * res.adj();
} else {
auto res_adj = res.adj().eval();
arena_A.adj() += res_adj * arena_B_val.transpose();
arena_B.adj() += arena_A_val.transpose() * res_adj;
}
});
return return_t(res);
} else if (!is_constant<T2>::value) {
arena_t<promote_scalar_t<double, T1>> arena_A = value_of(A);
arena_t<promote_scalar_t<var, T2>> arena_B = B;
using return_t
= return_var_matrix_t<decltype(arena_A * value_of(B).eval()), T1,
T2>;
arena_t<return_t> res = arena_A * arena_B.val_op();
reverse_pass_callback([arena_B, arena_A_val, res]() mutable {
arena_B.adj() += arena_A.transpose() * res.adj_op();
});
return return_t(res);
} else {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<double, T2>> arena_B = value_of(B);
using return_t
= return_var_matrix_t<decltype(value_of(arena_A).eval() * arena_B),
T1, T2>;
arena_t<return_t> res = arena_A.val_op() * arena_B;
reverse_pass_callback([arena_A, arena_B_val, res]() mutable {
arena_A.adj() += res.adj_op() * arena_B.transpose();
});
return return_t(res);
}
}
/**
* Return the product of a row vector times a column vector as a scalar
*
* @tparam T1 type of row vector
* @tparam T2 type of column vector
*
* @param[in] A row vector
* @param[in] B column vector
* @return A * B as a scalar
*/
template <typename T1, typename T2, require_all_matrix_t<T1, T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_row_and_col_vector_t<T1, T2>* = nullptr>
inline var multiply(const T1& A, const T2& B) {
check_multiplicable("multiply", "A", A, "B", B);
if (!is_constant<T2>::value && !is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = to_ref(A);
arena_t<promote_scalar_t<var, T2>> arena_B = to_ref(B);
arena_t<promote_scalar_t<double, T1>> arena_A_val = value_of(arena_A);
arena_t<promote_scalar_t<double, T2>> arena_B_val = value_of(arena_B);
var res = arena_A_val.dot(arena_B_val);
reverse_pass_callback(
[arena_A, arena_B, arena_A_val, arena_B_val, res]() mutable {
auto res_adj = res.adj();
arena_A.adj().array() += res_adj * arena_B_val.transpose().array();
arena_B.adj().array() += arena_A_val.transpose().array() * res_adj;
});
return res;
} else if (!is_constant<T2>::value) {
arena_t<promote_scalar_t<var, T2>> arena_B = to_ref(B);
arena_t<promote_scalar_t<double, T1>> arena_A_val = value_of(A);
var res = arena_A_val.dot(value_of(arena_B));
reverse_pass_callback([arena_B, arena_A_val, res]() mutable {
arena_B.adj().array() += arena_A_val.transpose().array() * res.adj();
});
return res;
} else {
arena_t<promote_scalar_t<var, T1>> arena_A = to_ref(A);
arena_t<promote_scalar_t<double, T2>> arena_B_val = value_of(B);
var res = value_of(arena_A).dot(arena_B_val);
reverse_pass_callback([arena_A, arena_B_val, res]() mutable {
arena_A.adj().array() += res.adj() * arena_B_val.transpose().array();
});
return res;
}
}
/**
* Return specified matrix multiplied by specified scalar where at least one
* input has a scalar type of a `var_value`.
*
* @tparam T1 type of the scalar
* @tparam T2 type of the matrix or expression
*
* @param A scalar
* @param B matrix
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_not_matrix_t<T1>* = nullptr,
require_matrix_t<T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_not_row_and_col_vector_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
if (!is_constant<T2>::value && !is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<var, T2>> arena_B = B;
using return_t = return_var_matrix_t<T2, T1, T2>;
arena_t<return_t> res = arena_A.val() * arena_B.val().array();
reverse_pass_callback([arena_A, arena_B, res]() mutable {
const auto a_val = arena_A.val();
for (Eigen::Index j = 0; j < res.cols(); ++j) {
for (Eigen::Index i = 0; i < res.rows(); ++i) {
const auto res_adj = res.adj().coeffRef(i, j);
arena_A.adj() += res_adj * arena_B.val().coeff(i, j);
arena_B.adj().coeffRef(i, j) += a_val * res_adj;
}
}
});
return return_t(res);
} else if (!is_constant<T2>::value) {
arena_t<promote_scalar_t<double, T1>> arena_A = value_of(A);
arena_t<promote_scalar_t<var, T2>> arena_B = B;
using return_t = return_var_matrix_t<T2, T1, T2>;
arena_t<return_t> res = arena_A * arena_B.val().array();
reverse_pass_callback([arena_A, arena_B, res]() mutable {
arena_B.adj().array() += arena_A * res.adj().array();
});
return return_t(res);
} else {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<double, T2>> arena_B = value_of(B);
using return_t = return_var_matrix_t<T2, T1, T2>;
arena_t<return_t> res = arena_A.val() * arena_B.array();
reverse_pass_callback([arena_A, arena_B, res]() mutable {
arena_A.adj() += (res.adj().array() * arena_B.array()).sum();
});
return return_t(res);
}
}
/**
* Return specified matrix multiplied by specified scalar where at least one
* input has a scalar type of a `var_value`.
*
* @tparam T1 type of the matrix or expression
* @tparam T2 type of the scalar
*
* @param A matrix
* @param B scalar
* @return product of matrix and scalar
*/
template <typename T1, typename T2, require_matrix_t<T1>* = nullptr,
require_not_matrix_t<T2>* = nullptr,
require_any_st_var<T1, T2>* = nullptr,
require_not_row_and_col_vector_t<T1, T2>* = nullptr>
inline auto multiply(const T1& A, const T2& B) {
return multiply(B, A);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2009, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__UTILS_HPP
#define XPCC__UTILS_HPP
#include "detect.hpp"
#ifdef __DOXYGEN__
/**
* \brief Main function definition for microcontroller projects
*
* Inhibits some stack operations at the beginning of main for avr-gcc. May
* save up a few bytes of stack memory.
*
* Typical structure of an microcontroller program:
* \code
* #include <xpcc/architecture/platform.hpp>
*
* MAIN_FUNCTION
* {
* ...
*
* while (1)
* {
* ...
* }
* }
* \endcode
*
* \ingroup platform
*/
#define MAIN_FUNCTION
/**
* \brief Force inlining
*
* Macro to force inlining on functions if needed. Compiling with -Os does not
* always inline them when declared only \c inline.
*
* \ingroup platform
*/
#define ALWAYS_INLINE
/**
* \brief Convert the argument into a C-String
* \ingroup platform
*/
#define STRINGIFY(s) #s
/**
* \brief Concatenate the two arguments
* \ingroup platform
*/
#define CONCAT(a,b) a ## b
#else // !__DOXYGEN__
#define STRINGIFY(s) STRINGIFY_(s)
#define STRINGIFY_(s) STRINGIFY__(s)
#define STRINGIFY__(s) #s
#define CONCAT(a,b) CONCAT_(a,b)
#define CONCAT_(a,b) CONCAT__(a,b)
#define CONCAT__(a,b) a ## b
#define CONCAT3(a,b,c) CONCAT3_(a,b,c)
#define CONCAT3_(a,b,c) CONCAT3__(a,b,c)
#define CONCAT3__(a,b,c) a ## b ## c
#define CONCAT4(a,b,c,d) CONCAT4_(a,b,c,d)
#define CONCAT4_(a,b,c,d) CONCAT4__(a,b,c,d)
#define CONCAT4__(a,b,c,d) a ## b ## c ## d
#define CONCAT5(a,b,c,d,e) CONCAT5_(a,b,c,d,e)
#define CONCAT5_(a,b,c,d,e) CONCAT5__(a,b,c,d,e)
#define CONCAT5__(a,b,c,d,e) a ## b ## c ## d ## e
#ifdef XPCC__COMPILER_GCC
# define ALWAYS_INLINE inline __attribute__((always_inline))
# define ATTRIBUTE_UNUSED __attribute__((unused))
# define ATTRIBUTE_WEAK __attribute__ ((weak))
# define ATTRIBUTE_ALIGNED(n) __attribute__((aligned(n)))
# define ATTRIBUTE_PACKED __attribute__((packed))
// see http://dbp-consulting.com/tutorials/StrictAliasing.html
# define ATTRIBUTE_MAY_ALIAS __attribute__((__may_alias__))
#else
# define ALWAYS_INLINE inline
# define ATTRIBUTE_UNUSED
# define ATTRIBUTE_WEAK
# define ATTRIBUTE_ALIGNED(n)
# define ATTRIBUTE_PACKED
# define ATTRIBUTE_MAY_ALIAS
#endif
#ifdef XPCC__CPU_AVR
# define MAIN_FUNCTION int main(void) __attribute__((OS_main)); \
int main(void)
#elif defined XPCC__CPU_HOSTED
# define MAIN_FUNCTION int main( int argc, char* argv[] )
#else
# define MAIN_FUNCTION int main(void)
#endif
#define XPCC__ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
/**
* Makes it possible to use enum classes as bit flags.
* This disables some typesafety introduced by the enum class feature
* but it should still be more typesafe than using the traditional
* enum type.
* Use (for public enum classes after class definition) like this:
* ENUM_CLASS_FLAG(Adc{{ id }}::InterruptFlag)
*/
#define ENUM_CLASS_FLAG(name) \
inline name operator|(name a, name b) \
{return static_cast<name>(static_cast<uint32_t>(a) | static_cast<uint32_t>(b));} \
inline uint32_t operator&(name a, name b) \
{return (static_cast<uint32_t>(a) & static_cast<uint32_t>(b));} \
inline uint32_t operator&(uint32_t a, name b) \
{return ((a) & static_cast<uint32_t>(b));} \
inline uint32_t operator&(name a, uint32_t b) \
{return (static_cast<uint32_t>(a) & (b));}
#endif // !__DOXYGEN__
#endif // XPCC__UTILS_HPP
<commit_msg>Avoid warning about unused parameters in main<commit_after>// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2009, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__UTILS_HPP
#define XPCC__UTILS_HPP
#include "detect.hpp"
#ifdef __DOXYGEN__
/**
* \brief Main function definition for microcontroller projects
*
* Inhibits some stack operations at the beginning of main for avr-gcc. May
* save up a few bytes of stack memory.
*
* Typical structure of an microcontroller program:
* \code
* #include <xpcc/architecture/platform.hpp>
*
* MAIN_FUNCTION
* {
* ...
*
* while (1)
* {
* ...
* }
* }
* \endcode
*
* \ingroup platform
*/
#define MAIN_FUNCTION
/** Same as MAIN_FUNCTION but avoids warning about unused parameters */
#define MAIN_FUNCTION_NAKED
/**
* \brief Force inlining
*
* Macro to force inlining on functions if needed. Compiling with -Os does not
* always inline them when declared only \c inline.
*
* \ingroup platform
*/
#define ALWAYS_INLINE
/**
* \brief Convert the argument into a C-String
* \ingroup platform
*/
#define STRINGIFY(s) #s
/**
* \brief Concatenate the two arguments
* \ingroup platform
*/
#define CONCAT(a,b) a ## b
#else // !__DOXYGEN__
#define STRINGIFY(s) STRINGIFY_(s)
#define STRINGIFY_(s) STRINGIFY__(s)
#define STRINGIFY__(s) #s
#define CONCAT(a,b) CONCAT_(a,b)
#define CONCAT_(a,b) CONCAT__(a,b)
#define CONCAT__(a,b) a ## b
#define CONCAT3(a,b,c) CONCAT3_(a,b,c)
#define CONCAT3_(a,b,c) CONCAT3__(a,b,c)
#define CONCAT3__(a,b,c) a ## b ## c
#define CONCAT4(a,b,c,d) CONCAT4_(a,b,c,d)
#define CONCAT4_(a,b,c,d) CONCAT4__(a,b,c,d)
#define CONCAT4__(a,b,c,d) a ## b ## c ## d
#define CONCAT5(a,b,c,d,e) CONCAT5_(a,b,c,d,e)
#define CONCAT5_(a,b,c,d,e) CONCAT5__(a,b,c,d,e)
#define CONCAT5__(a,b,c,d,e) a ## b ## c ## d ## e
#ifdef XPCC__COMPILER_GCC
# define ALWAYS_INLINE inline __attribute__((always_inline))
# define ATTRIBUTE_UNUSED __attribute__((unused))
# define ATTRIBUTE_WEAK __attribute__ ((weak))
# define ATTRIBUTE_ALIGNED(n) __attribute__((aligned(n)))
# define ATTRIBUTE_PACKED __attribute__((packed))
// see http://dbp-consulting.com/tutorials/StrictAliasing.html
# define ATTRIBUTE_MAY_ALIAS __attribute__((__may_alias__))
#else
# define ALWAYS_INLINE inline
# define ATTRIBUTE_UNUSED
# define ATTRIBUTE_WEAK
# define ATTRIBUTE_ALIGNED(n)
# define ATTRIBUTE_PACKED
# define ATTRIBUTE_MAY_ALIAS
#endif
#ifdef XPCC__CPU_AVR
# define MAIN_FUNCTION int main(void) __attribute__((OS_main)); \
int main(void)
# define MAIN_FUNCTION_NAKED MAIN_FUNCTION
#elif defined XPCC__CPU_HOSTED
# define MAIN_FUNCTION int main( int argc, char* argv[] )
# define MAIN_FUNCTION_NAKED int main( int, char** )
#else
# define MAIN_FUNCTION int main(void)
# define MAIN_FUNCTION_NAKED MAIN_FUNCTION
#endif
#define XPCC__ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
/**
* Makes it possible to use enum classes as bit flags.
* This disables some typesafety introduced by the enum class feature
* but it should still be more typesafe than using the traditional
* enum type.
* Use (for public enum classes after class definition) like this:
* ENUM_CLASS_FLAG(Adc{{ id }}::InterruptFlag)
*/
#define ENUM_CLASS_FLAG(name) \
inline name operator|(name a, name b) \
{return static_cast<name>(static_cast<uint32_t>(a) | static_cast<uint32_t>(b));} \
inline uint32_t operator&(name a, name b) \
{return (static_cast<uint32_t>(a) & static_cast<uint32_t>(b));} \
inline uint32_t operator&(uint32_t a, name b) \
{return ((a) & static_cast<uint32_t>(b));} \
inline uint32_t operator&(name a, uint32_t b) \
{return (static_cast<uint32_t>(a) & (b));}
#endif // !__DOXYGEN__
#endif // XPCC__UTILS_HPP
<|endoftext|> |
<commit_before>#include "spiMaster.h"
#include "main.h"
#include <array>
#include "mirrorDriver.h"
/* *** Private Constants *** */
#define sizeofAdcSample (sizeof(adcSample) / 2)
#define ENABLE_MINUS_7_PIN 52
#define ENABLE_7_PIN 53
#define ADC_CS0 35
#define ADC_CS1 37
#define ADC_CS2 7
#define ADC_CS3 2
#define trigger_pin 26 // test point 17
#define sample_clock 29 // gpio1
#define sync_pin 3 // gpio0
#define ADC_OVERSAMPLING_RATE 64
const unsigned int control_word = 0b1000110000010000;
//void mirrorOutputSetup();
void adcReceiveSetup();
void init_FTM0();
/* *** Internal Telemetry -- SPI0 *** */
unsigned long lastSampleTime = 0;
volatile int numFail = 0;
volatile int numSuccess = 0;
volatile int numStartCalls = 0;
volatile int numSpi0Calls = 0;
volatile unsigned int numSamplesRead = 0;
/* *** SPI0 Adc Reading *** */
SPISettings adcSpiSettings(6250000, MSBFIRST, SPI_MODE0); // For SPI0
uint32_t frontOfBuffer = 0;
uint32_t backOfBuffer = 0;
adcSample adcSamplesRead[ADC_READ_BUFFER_SIZE + 1];
volatile adcSample nextSample;
volatile unsigned int adcIsrIndex = 0; // indexes into nextSample
/* *** SPI2 Mirror Driver *** */
mirrorOutput currentOutput;
volatile unsigned int mirrorOutputIndex = sizeof(mirrorOutput) / (16 / 8);
/* *** Adc Reading Public Functions *** */
uint32_t adcGetOffset() { // Returns number of samples in buffer
uint32_t offset;
if (frontOfBuffer >= backOfBuffer) {
offset = frontOfBuffer - backOfBuffer;
} else {
assert(frontOfBuffer + ADC_READ_BUFFER_SIZE >= backOfBuffer);
offset = frontOfBuffer + ADC_READ_BUFFER_SIZE - backOfBuffer;
}
return offset;
}
bool adcSampleReady() {
return adcGetOffset() >= 1;
}
int succ__ = 0;
int fail__ = 0;
volatile adcSample* adcGetSample() {
assert(adcSampleReady());
volatile adcSample* toReturn = &adcSamplesRead[backOfBuffer];
toReturn->correctFormat();
backOfBuffer = (backOfBuffer + 1) % ADC_READ_BUFFER_SIZE;
/*
if(!assert(toReturn->axis1 < 0)) {
debugPrintf("i %d toReturn %d\n", 1, toReturn->axis1);
}
if(!assert(toReturn->axis2 < 0)) {
debugPrintf("i %d toReturn %d\n", 2, toReturn->axis2);
}
if(!assert(toReturn->axis3 < 0)) {
debugPrintf("i %d toReturn %d\n", 3, toReturn->axis3);
}
if(!assert(toReturn->axis4 < 0)) {
fail__++;
debugPrintf("i %d toReturn %d succ %d fail %d\n", 4, toReturn->axis4, succ__, fail__);
} else {
succ__++;
}*/
return toReturn;
}
void adcStartSampling() { // Clears out old samples so the first sample you read is fresh
backOfBuffer = frontOfBuffer;
}
void spiMasterSetup() {
mirrorDriverSetup();
debugPrintf("Setting up dma, offset is %d\n", adcGetOffset());
adcReceiveSetup();
debugPrintf("Dma setup complete, offset is %d. Setting up ftm timers.\n", adcGetOffset());
init_FTM0();
debugPrintf("FTM timer setup complete.\n");
}
/* ********* Private Interrupt-based Adc Read Code ********* */
void checkChipSelect(void) {
if (adcIsrIndex == 0) {
// Take no chances
digitalWriteFast(ADC_CS0, LOW);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, HIGH);
} else if (adcIsrIndex == 2) {
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, LOW);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, HIGH);
} else if (adcIsrIndex == 4) {
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, LOW);
digitalWriteFast(ADC_CS3, HIGH);
} else if (adcIsrIndex == 6) {
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, LOW);
}
}
void spi0_isr(void) {
if(adcIsrIndex >= sizeofAdcSample) {
errors++;
}
uint16_t spiRead = SPI0_POPR;
(void) spiRead; // Clear spi interrupt
SPI0_SR |= SPI_SR_RFDF;
((volatile uint16_t *) &nextSample)[adcIsrIndex] = spiRead;
numSpi0Calls++;
adcIsrIndex++;
checkChipSelect();
if (!(adcIsrIndex < sizeofAdcSample)) {
digitalWriteFast(ADC_CS3, HIGH);
// Sample complete -- push to buffer
adcSamplesRead[frontOfBuffer] = nextSample;
frontOfBuffer = (frontOfBuffer + 1) % ADC_READ_BUFFER_SIZE;
numSamplesRead += 1;
adcIsrIndex++;
return;
} else {
SPI0_PUSHR = ((uint16_t) 0x0000) | SPI_PUSHR_CTAS(1);
}
}
/* Entry point to an adc read. This sends the first spi word, the rest of the work
* is done in spi0_isr interrupts
*/
void beginAdcRead(void) {
noInterrupts();
numStartCalls++;
long timeNow = micros();
// For debugging only; Check time since last sample
long diff = timeNow - lastSampleTime;
if (lastSampleTime != 0) {
lastSampleTime = timeNow;
if(!(diff >= 245 && diff <= 255)) { // 4kHz -> 250 microseconds
// debugPrintf("Diff is %d, %d success %d fail %d %d\n", diff, numSuccess, numFail, numStartCalls, numSpi0Calls); // A blocking print inside an interrupt can cascade errors I think
numFail++;
} else {
numSuccess++;
}
}
lastSampleTime = timeNow;
if (adcIsrIndex < (sizeof(adcSample) / (16 / 8)) && adcIsrIndex != 0) {
debugPrintf("Yikes -- we're reading adc already\n");
if (diff <= 245) {
interrupts();
return;
}
}
// Cleared for takeoff
adcIsrIndex = 0;
checkChipSelect();
SPI0_PUSHR = ((uint16_t) 0x0000) | SPI_PUSHR_CTAS(1);
interrupts();
}
void setupHighVoltage() {
pinMode(ENABLE_MINUS_7_PIN, OUTPUT);
pinMode(ENABLE_7_PIN, OUTPUT);
digitalWrite(ENABLE_MINUS_7_PIN, HIGH); // -7 driver enable
digitalWrite(ENABLE_7_PIN, HIGH); // +7 driver enable
}
void setupAdcChipSelects() {
pinMode(ADC_CS0, OUTPUT);
pinMode(ADC_CS1, OUTPUT);
pinMode(ADC_CS2, OUTPUT);
pinMode(ADC_CS3, OUTPUT);
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, HIGH);
}
void setupAdc() {
setupHighVoltage();
setupAdcChipSelects();
pinMode(sync_pin, OUTPUT);
digitalWrite(sync_pin, LOW);
digitalWrite(sync_pin, HIGH);
digitalWrite(sync_pin, LOW);
const uint8_t chipSelects[4] = {ADC_CS0, ADC_CS1, ADC_CS2, ADC_CS3};
for (int i = 0; i < 4; i++) {
delay(1);
digitalWrite(chipSelects[i], LOW);
uint16_t result = SPI.transfer16(control_word);
(void) result;
debugPrintf("Sent control word adc %d, received %x\n", i, result);
digitalWrite(chipSelects[i], HIGH);
}
// Clear pop register - we don't want to fire the spi interrupt
(void) SPI0_POPR; (void) SPI0_POPR;
SPI0_SR |= SPI_SR_RFDF;
}
void init_FTM0(){
pinMode(sample_clock, OUTPUT);
analogWriteFrequency(sample_clock, 4000 * ADC_OVERSAMPLING_RATE);
analogWrite(sample_clock, 5); // Low duty cycle - if we go too low it won't even turn on
}
void adcReceiveSetup() {
debugPrintln("Starting.");
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis1 = 0xdeadbeef;
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis2 = 0xdeadbeef;
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis3 = 0xdeadbeef;
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis4 = 0xdeadbeef;
SPI.begin();
SPI.beginTransaction(adcSpiSettings);
setupAdc();
SPI0_RSER = 0x00020000; // Transmit FIFO Fill Request Enable -- Interrupt on transmit complete
pinMode(trigger_pin, INPUT_PULLUP);
attachInterrupt(trigger_pin, beginAdcRead, FALLING);
NVIC_ENABLE_IRQ(IRQ_SPI0);
NVIC_SET_PRIORITY(IRQ_SPI0, 0);
NVIC_SET_PRIORITY(IRQ_PORTA, 0); // Trigger_pin should be port A
NVIC_SET_PRIORITY(IRQ_PORTE, 0); // Just in case it's E
debugPrintln("Done!");
}
/* ******** Mirror output code ********* */
/*void mirrorOutputSetup() {
debugPrintln("Mirror setup starting.");
SPI2.begin();
SPI2_RSER = 0x00020000; // Transmit FIFO Fill Request Enable -- Interrupt on transmit complete
NVIC_ENABLE_IRQ(IRQ_SPI2);
NVIC_SET_PRIORITY(IRQ_SPI2, 0);
debugPrintln("Done!");
}*/
// unsigned long timeOfLastOutput = 0;
//
// /* Entry point to outputting a mirrorOutput; sending from SPI2 will trigger spi2_isr,
// * which sends the rest of the mirrorOutput
// */
// void sendOutput(mirrorOutput& output) {
// long timeNow = micros();
// long diff = timeNow - timeOfLastOutput;
// assert(diff > 0);
// if (!mirrorOutputIndex == sizeof(mirrorOutput) / (16 / 8)) {
// if (diff % 100 == 0) {
// debugPrintf("spiMaster.cpp:254: mirrorIndex %d\n", mirrorOutputIndex);
// }
// bugs++;
// errors++;
// // Not done transmitting the last mirror output
// if (timeOfLastOutput != 0 && diff < 500) {
// return;
// } else {
// // The last mirror output is taking too long, reset it
// }
// }
// timeOfLastOutput = timeNow;
// noInterrupts();
// currentOutput = output;
// mirrorOutputIndex = 0;
// (void) SPI2_POPR;
// SPI2_PUSHR = ((uint16_t) mirrorOutputIndex) | SPI_PUSHR_CTAS(1);
// interrupts();
// }
//
// void spi2_isr(void) {
// if (mirrorOutputIndex >= sizeof(mirrorOutput) / (16 / 8)) {
// errors++;
// }
// (void) SPI2_POPR;
// uint16_t toWrite = ((volatile uint16_t *) ¤tOutput)[mirrorOutputIndex];
// SPI2_SR |= SPI_SR_RFDF; // Clear interrupt
// mirrorOutputIndex++;
// if (mirrorOutputIndex < sizeof(mirrorOutput) / (16 / 8)) {
// SPI2_PUSHR = ((uint16_t) toWrite) | SPI_PUSHR_CTAS(1);
// } else {
// // Done sending
// assert(mirrorOutputIndex == sizeof(mirrorOutput) / (16 / 8));
// }
// }
<commit_msg>Remove unused code for now<commit_after>#include "spiMaster.h"
#include "main.h"
#include <array>
#include "mirrorDriver.h"
/* *** Private Constants *** */
#define sizeofAdcSample (sizeof(adcSample) / 2)
#define ENABLE_MINUS_7_PIN 52
#define ENABLE_7_PIN 53
#define ADC_CS0 35
#define ADC_CS1 37
#define ADC_CS2 7
#define ADC_CS3 2
#define trigger_pin 26 // test point 17
#define sample_clock 29 // gpio1
#define sync_pin 3 // gpio0
#define ADC_OVERSAMPLING_RATE 64
const unsigned int control_word = 0b1000110000010000;
//void mirrorOutputSetup();
void adcReceiveSetup();
void init_FTM0();
/* *** Internal Telemetry -- SPI0 *** */
unsigned long lastSampleTime = 0;
volatile int numFail = 0;
volatile int numSuccess = 0;
volatile int numStartCalls = 0;
volatile int numSpi0Calls = 0;
volatile unsigned int numSamplesRead = 0;
/* *** SPI0 Adc Reading *** */
SPISettings adcSpiSettings(6250000, MSBFIRST, SPI_MODE0); // For SPI0
uint32_t frontOfBuffer = 0;
uint32_t backOfBuffer = 0;
adcSample adcSamplesRead[ADC_READ_BUFFER_SIZE + 1];
volatile adcSample nextSample;
volatile unsigned int adcIsrIndex = 0; // indexes into nextSample
/* *** Adc Reading Public Functions *** */
uint32_t adcGetOffset() { // Returns number of samples in buffer
uint32_t offset;
if (frontOfBuffer >= backOfBuffer) {
offset = frontOfBuffer - backOfBuffer;
} else {
assert(frontOfBuffer + ADC_READ_BUFFER_SIZE >= backOfBuffer);
offset = frontOfBuffer + ADC_READ_BUFFER_SIZE - backOfBuffer;
}
return offset;
}
bool adcSampleReady() {
return adcGetOffset() >= 1;
}
int succ__ = 0;
int fail__ = 0;
volatile adcSample* adcGetSample() {
assert(adcSampleReady());
volatile adcSample* toReturn = &adcSamplesRead[backOfBuffer];
toReturn->correctFormat();
backOfBuffer = (backOfBuffer + 1) % ADC_READ_BUFFER_SIZE;
/*
if(!assert(toReturn->axis1 < 0)) {
debugPrintf("i %d toReturn %d\n", 1, toReturn->axis1);
}
if(!assert(toReturn->axis2 < 0)) {
debugPrintf("i %d toReturn %d\n", 2, toReturn->axis2);
}
if(!assert(toReturn->axis3 < 0)) {
debugPrintf("i %d toReturn %d\n", 3, toReturn->axis3);
}
if(!assert(toReturn->axis4 < 0)) {
fail__++;
debugPrintf("i %d toReturn %d succ %d fail %d\n", 4, toReturn->axis4, succ__, fail__);
} else {
succ__++;
}*/
return toReturn;
}
void adcStartSampling() { // Clears out old samples so the first sample you read is fresh
backOfBuffer = frontOfBuffer;
}
void spiMasterSetup() {
mirrorDriverSetup();
debugPrintf("Setting up dma, offset is %d\n", adcGetOffset());
adcReceiveSetup();
debugPrintf("Dma setup complete, offset is %d. Setting up ftm timers.\n", adcGetOffset());
init_FTM0();
debugPrintf("FTM timer setup complete.\n");
}
/* ********* Private Interrupt-based Adc Read Code ********* */
void checkChipSelect(void) {
if (adcIsrIndex == 0) {
// Take no chances
digitalWriteFast(ADC_CS0, LOW);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, HIGH);
} else if (adcIsrIndex == 2) {
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, LOW);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, HIGH);
} else if (adcIsrIndex == 4) {
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, LOW);
digitalWriteFast(ADC_CS3, HIGH);
} else if (adcIsrIndex == 6) {
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, LOW);
}
}
void spi0_isr(void) {
if(adcIsrIndex >= sizeofAdcSample) {
errors++;
}
uint16_t spiRead = SPI0_POPR;
(void) spiRead; // Clear spi interrupt
SPI0_SR |= SPI_SR_RFDF;
((volatile uint16_t *) &nextSample)[adcIsrIndex] = spiRead;
numSpi0Calls++;
adcIsrIndex++;
checkChipSelect();
if (!(adcIsrIndex < sizeofAdcSample)) {
digitalWriteFast(ADC_CS3, HIGH);
// Sample complete -- push to buffer
adcSamplesRead[frontOfBuffer] = nextSample;
frontOfBuffer = (frontOfBuffer + 1) % ADC_READ_BUFFER_SIZE;
numSamplesRead += 1;
adcIsrIndex++;
return;
} else {
SPI0_PUSHR = ((uint16_t) 0x0000) | SPI_PUSHR_CTAS(1);
}
}
/* Entry point to an adc read. This sends the first spi word, the rest of the work
* is done in spi0_isr interrupts
*/
void beginAdcRead(void) {
noInterrupts();
numStartCalls++;
long timeNow = micros();
// For debugging only; Check time since last sample
long diff = timeNow - lastSampleTime;
if (lastSampleTime != 0) {
lastSampleTime = timeNow;
if(!(diff >= 245 && diff <= 255)) { // 4kHz -> 250 microseconds
// debugPrintf("Diff is %d, %d success %d fail %d %d\n", diff, numSuccess, numFail, numStartCalls, numSpi0Calls); // A blocking print inside an interrupt can cascade errors I think
numFail++;
} else {
numSuccess++;
}
}
lastSampleTime = timeNow;
if (adcIsrIndex < (sizeof(adcSample) / (16 / 8)) && adcIsrIndex != 0) {
debugPrintf("Yikes -- we're reading adc already\n");
if (diff <= 245) {
interrupts();
return;
}
}
// Cleared for takeoff
adcIsrIndex = 0;
checkChipSelect();
SPI0_PUSHR = ((uint16_t) 0x0000) | SPI_PUSHR_CTAS(1);
interrupts();
}
void setupHighVoltage() {
pinMode(ENABLE_MINUS_7_PIN, OUTPUT);
pinMode(ENABLE_7_PIN, OUTPUT);
digitalWrite(ENABLE_MINUS_7_PIN, HIGH); // -7 driver enable
digitalWrite(ENABLE_7_PIN, HIGH); // +7 driver enable
}
void setupAdcChipSelects() {
pinMode(ADC_CS0, OUTPUT);
pinMode(ADC_CS1, OUTPUT);
pinMode(ADC_CS2, OUTPUT);
pinMode(ADC_CS3, OUTPUT);
digitalWriteFast(ADC_CS0, HIGH);
digitalWriteFast(ADC_CS1, HIGH);
digitalWriteFast(ADC_CS2, HIGH);
digitalWriteFast(ADC_CS3, HIGH);
}
void setupAdc() {
setupHighVoltage();
setupAdcChipSelects();
pinMode(sync_pin, OUTPUT);
digitalWrite(sync_pin, LOW);
digitalWrite(sync_pin, HIGH);
digitalWrite(sync_pin, LOW);
const uint8_t chipSelects[4] = {ADC_CS0, ADC_CS1, ADC_CS2, ADC_CS3};
for (int i = 0; i < 4; i++) {
delay(1);
digitalWrite(chipSelects[i], LOW);
uint16_t result = SPI.transfer16(control_word);
(void) result;
debugPrintf("Sent control word adc %d, received %x\n", i, result);
digitalWrite(chipSelects[i], HIGH);
}
// Clear pop register - we don't want to fire the spi interrupt
(void) SPI0_POPR; (void) SPI0_POPR;
SPI0_SR |= SPI_SR_RFDF;
}
void init_FTM0(){
pinMode(sample_clock, OUTPUT);
analogWriteFrequency(sample_clock, 4000 * ADC_OVERSAMPLING_RATE);
analogWrite(sample_clock, 5); // Low duty cycle - if we go too low it won't even turn on
}
void adcReceiveSetup() {
debugPrintln("Starting.");
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis1 = 0xdeadbeef;
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis2 = 0xdeadbeef;
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis3 = 0xdeadbeef;
adcSamplesRead[ADC_READ_BUFFER_SIZE].axis4 = 0xdeadbeef;
SPI.begin();
SPI.beginTransaction(adcSpiSettings);
setupAdc();
SPI0_RSER = 0x00020000; // Transmit FIFO Fill Request Enable -- Interrupt on transmit complete
pinMode(trigger_pin, INPUT_PULLUP);
attachInterrupt(trigger_pin, beginAdcRead, FALLING);
NVIC_ENABLE_IRQ(IRQ_SPI0);
NVIC_SET_PRIORITY(IRQ_SPI0, 0);
NVIC_SET_PRIORITY(IRQ_PORTA, 0); // Trigger_pin should be port A
NVIC_SET_PRIORITY(IRQ_PORTE, 0); // Just in case it's E
debugPrintln("Done!");
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_QUANTILE_HPP
#define STAN_MATH_PRIM_FUN_QUANTILE_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <algorithm>
#include <vector>
namespace stan {
namespace math {
/**
* Return sample quantiles corresponding to the given probabilities.
* The smallest observation corresponds to a probability of 0 and the largest to
* a probability of 1.
*
* Implements algorithm 7 from Hyndman, R. J. and Fan, Y.,
* Sample quantiles in Statistical Packages (R's default quantile function)
*
* @tparam T An Eigen type with either fixed rows or columns at compile time, or
* std::vector<double>
* @param samples_vec Numeric vector whose sample quantiles are wanted
* @param p Probability with value between 0 and 1.
* @return Sample quantile.
* @throw std::invalid_argument If any element of samples_vec is NaN, or size 0.
* @throw std::domain_error If `p<0` or `p>1`.
*/
template <typename T, require_vector_t<T>* = nullptr,
require_vector_vt<std::is_arithmetic, T>* = nullptr>
inline double quantile(const T& samples_vec, const double p) {
check_not_nan("quantile", "samples_vec", samples_vec);
check_nonzero_size("quantile", "samples_vec", samples_vec);
check_not_nan("quantile", "p", p);
check_bounded("quantile", "p", p, 0, 1);
const size_t n_sample = samples_vec.size();
Eigen::VectorXd x = as_array_or_scalar(samples_vec);
if (n_sample == 1)
return x.coeff(0);
else if (p == 0.)
return *std::min_element(x.data(), x.data() + n_sample);
else if (p == 1.)
return *std::max_element(x.data(), x.data() + n_sample);
double index = (n_sample - 1) * p;
size_t lo = std::floor(index);
size_t hi = std::ceil(index);
std::sort(x.data(), x.data() + n_sample, std::less<double>());
double h = index - lo;
return (1 - h) * x.coeff(lo) + h * x.coeff(hi);
}
/**
* Return sample quantiles corresponding to the given probabilities.
* The smallest observation corresponds to a probability of 0 and the largest to
* a probability of 1.
*
* Implements algorithm 7 from Hyndman, R. J. and Fan, Y.,
* Sample quantiles in Statistical Packages (R's default quantile function)
*
* @tparam T An Eigen type with either fixed rows or columns at compile time, or
* std::vector<double>
* @tparam Tp Type of probabilities vector
* @param samples_vec Numeric vector whose sample quantiles are wanted
* @param ps Vector of probability with value between 0 and 1.
* @return Sample quantiles, one for each p in ps.
* @throw std::invalid_argument If any of the values are NaN or size 0.
* @throw std::domain_error If `p<0` or `p>1` for any p in ps.
*/
template <typename T, typename Tp, require_all_vector_t<T, Tp>* = nullptr,
require_vector_vt<std::is_arithmetic, T>* = nullptr,
require_vector_vt<std::is_arithmetic, Tp>* = nullptr>
inline std::vector<double> quantile(const T& samples_vec, const Tp& ps) {
check_not_nan("quantile", "samples_vec", samples_vec);
check_not_nan("quantile", "ps", ps);
check_nonzero_size("quantile", "samples_vec", samples_vec);
check_nonzero_size("quantile", "ps", ps);
check_bounded("quantile", "ps", ps, 0, 1);
const size_t n_sample = samples_vec.size();
const size_t n_ps = ps.size();
Eigen::VectorXd x = as_array_or_scalar(samples_vec);
const auto& p = as_array_or_scalar(ps);
std::vector<double> ret(n_ps, 0.0);
std::sort(x.data(), x.data() + n_sample, std::less<double>());
Eigen::ArrayXd index = (n_sample - 1) * p;
for (size_t i = 0; i < n_ps; ++i) {
if (p[i] == 0.)
ret[i] = x.coeff(0);
else if (p[i] == 1.)
ret[i] = x.coeff(n_sample - 1);
else {
size_t lo = std::floor(index[i]);
size_t hi = std::ceil(index[i]);
double h = index[i] - lo;
ret[i] = (1 - h) * x.coeff(lo) + h * x.coeff(hi);
}
}
return ret;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>make cpplint<commit_after>#ifndef STAN_MATH_PRIM_FUN_QUANTILE_HPP
#define STAN_MATH_PRIM_FUN_QUANTILE_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <algorithm>
#include <vector>
namespace stan {
namespace math {
/**
* Return sample quantiles corresponding to the given probabilities.
* The smallest observation corresponds to a probability of 0 and the largest to
* a probability of 1.
*
* Implements algorithm 7 from Hyndman, R. J. and Fan, Y.,
* Sample quantiles in Statistical Packages (R's default quantile function)
*
* @tparam T An Eigen type with either fixed rows or columns at compile time, or
* std::vector<double>
* @param samples_vec Numeric vector whose sample quantiles are wanted
* @param p Probability with value between 0 and 1.
* @return Sample quantile.
* @throw std::invalid_argument If any element of samples_vec is NaN, or size 0.
* @throw std::domain_error If `p<0` or `p>1`.
*/
template <typename T, require_vector_t<T>* = nullptr,
require_vector_vt<std::is_arithmetic, T>* = nullptr>
inline double quantile(const T& samples_vec, const double p) {
check_not_nan("quantile", "samples_vec", samples_vec);
check_nonzero_size("quantile", "samples_vec", samples_vec);
check_not_nan("quantile", "p", p);
check_bounded("quantile", "p", p, 0, 1);
const size_t n_sample = samples_vec.size();
Eigen::VectorXd x = as_array_or_scalar(samples_vec);
if (n_sample == 1)
return x.coeff(0);
else if (p == 0.)
return *std::min_element(x.data(), x.data() + n_sample);
else if (p == 1.)
return *std::max_element(x.data(), x.data() + n_sample);
double index = (n_sample - 1) * p;
size_t lo = std::floor(index);
size_t hi = std::ceil(index);
std::sort(x.data(), x.data() + n_sample, std::less<double>());
double h = index - lo;
return (1 - h) * x.coeff(lo) + h * x.coeff(hi);
}
/**
* Return sample quantiles corresponding to the given probabilities.
* The smallest observation corresponds to a probability of 0 and the largest to
* a probability of 1.
*
* Implements algorithm 7 from Hyndman, R. J. and Fan, Y.,
* Sample quantiles in Statistical Packages (R's default quantile function)
*
* @tparam T An Eigen type with either fixed rows or columns at compile time, or
* std::vector<double>
* @tparam Tp Type of probabilities vector
* @param samples_vec Numeric vector whose sample quantiles are wanted
* @param ps Vector of probability with value between 0 and 1.
* @return Sample quantiles, one for each p in ps.
* @throw std::invalid_argument If any of the values are NaN or size 0.
* @throw std::domain_error If `p<0` or `p>1` for any p in ps.
*/
template <typename T, typename Tp, require_all_vector_t<T, Tp>* = nullptr,
require_vector_vt<std::is_arithmetic, T>* = nullptr,
require_vector_vt<std::is_arithmetic, Tp>* = nullptr>
inline std::vector<double> quantile(const T& samples_vec, const Tp& ps) {
check_not_nan("quantile", "samples_vec", samples_vec);
check_not_nan("quantile", "ps", ps);
check_nonzero_size("quantile", "samples_vec", samples_vec);
check_nonzero_size("quantile", "ps", ps);
check_bounded("quantile", "ps", ps, 0, 1);
const size_t n_sample = samples_vec.size();
const size_t n_ps = ps.size();
Eigen::VectorXd x = as_array_or_scalar(samples_vec);
const auto& p = as_array_or_scalar(ps);
std::vector<double> ret(n_ps, 0.0);
std::sort(x.data(), x.data() + n_sample, std::less<double>());
Eigen::ArrayXd index = (n_sample - 1) * p;
for (size_t i = 0; i < n_ps; ++i) {
if (p[i] == 0.) {
ret[i] = x.coeff(0);
} else if (p[i] == 1.) {
ret[i] = x.coeff(n_sample - 1);
} else {
size_t lo = std::floor(index[i]);
size_t hi = std::ceil(index[i]);
double h = index[i] - lo;
ret[i] = (1 - h) * x.coeff(lo) + h * x.coeff(hi);
}
}
return ret;
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace _enumerate_internal
{
template <class Iterator> struct enumerate_iterator
{
using iterator = Iterator;
using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
enumerate_iterator& operator++() { ++index; ++iter; return *this; }
bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
std::pair<index_type&, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <class Iterator> struct enumerate_range
{
using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator>;
enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
iterator begin() const { return iterator(initial, first); }
iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator> auto enumerate(Iterator first, Iterator last, typename std::iterator_traits<Iterator>::difference_type initial)
{
return _enumerate_internal::enumerate_range<Iterator>(first, last, initial);
}
template <typename Container> auto enumerate(Container& content)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type>(std::begin(content), std::end(content), 0);
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs::enumerate<commit_after>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace _enumerate_internal
{
template <class Iterator> struct enumerate_iterator
{
using iterator = Iterator;
using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
enumerate_iterator& operator++() { ++index; ++iter; return *this; }
bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
std::pair<index_type&, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <class Iterator> struct enumerate_range
{
using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator>;
enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
iterator begin() const { return iterator(initial, first); }
iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
namespace acmacs
{
template <typename Iterator> auto enumerate(Iterator first, Iterator last, typename std::iterator_traits<Iterator>::difference_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator>(first, last, initial);
}
template <typename Container> auto enumerate(Container& content)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type>(std::begin(content), std::end(content), 0);
}
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "GameState.h"
#include "DDSLoader.h"
#include "File.h"
#include "Math.h"
#include "OpenGL.h"
#include "StateMachine.h"
#include <cassert>
#include <cmath>
#include <cstring>
#include <list>
#include <vector>
#ifdef __APPLE__
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
static const char* glslVersion = "#version 300 es\n";
#else
static const char* glslVersion = "#version 330 core\n";
#endif
#endif
static vec2 windowToView(StateMachine* stateMachine, const vec2& p)
{
const float ww = stateMachine->getWindowWidth();
const float wh = stateMachine->getWindowHeight();
const float ws = (ww > wh) ? wh : ww;
return { (2.f * p.x - ww) / ws, (wh - 2.f * p.y) / ws };
}
static vec2 viewToWindow(StateMachine* stateMachine, const vec2& p)
{
const float ww = stateMachine->getWindowWidth();
const float wh = stateMachine->getWindowHeight();
const float ws = (ww > wh) ? wh : ww;
return { 0.5f * (p.x * ws + ww), 0.5f * (wh - p.y * ws) };
}
static GLuint createShader(GLenum type, const void* data, size_t size)
{
const GLchar* sources[] = { glslVersion, (const GLchar*)data };
const GLint sizes[] = { (GLint)strlen(sources[0]), (GLint)size };
GLuint shader = glCreateShader(type);
glShaderSource(shader, 2, sources, sizes);
glCompileShader(shader);
const GLsizei maxInfoLength = 1024;
GLchar info[maxInfoLength];
glGetShaderInfoLog(shader, maxInfoLength, 0, info);
if(info[0])
{
printf("shader info log:\n%s", info);
}
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
assert(status == GL_TRUE);
return shader;
}
static GLuint createProgram(GLuint vs, GLuint fs)
{
GLuint program = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
const GLsizei maxInfoLength = 1024;
GLchar info[maxInfoLength];
glGetProgramInfoLog(program, maxInfoLength, 0, info);
if(info[0])
{
printf("program info log:\n%s", info);
}
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
assert(status == GL_TRUE);
return program;
}
class Batcher
{
public:
struct Vertex
{
vec2 position;
vec2 uv;
vec4 colorMul;
vec3 colorAdd;
};
Batcher()
{
glGenVertexArrays(1, &m_vertexArray);
glBindVertexArray(m_vertexArray);
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, position));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, uv));
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, colorMul));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, colorAdd));
}
void addVertex(const vec2& position, const vec2& uv, const vec4& colorMul = { 1.f, 1.f, 1.f, 1.f }, const vec3& colorAdd = { 0.f, 0.f, 0.f } )
{
m_vertices.push_back( Vertex { position, uv, colorMul, colorAdd } );
}
void addCircle(const vec2& center, float radius, const vec4& colorMul = { 1.f, 1.f, 1.f, 1.f }, const vec3& colorAdd = { 0.f, 0.f, 0.f } )
{
const int n = 64;
for(int i = 0; i < n; i++)
{
float a0 = 2.f * float(M_PI) * float(i) / float(n);
float a1 = 2.f * float(M_PI) * float(i + 1) / float(n);
vec2 d0 { cosf(a0), sinf(a0) };
vec2 d1 { cosf(a1), sinf(a1) };
vec2 p0 = center + radius * d0;
vec2 p1 = center + radius * d1;
vec2 uvCenter { 0.5f, 0.5f };
vec2 uv0 = uvCenter + 0.5f * d0;
vec2 uv1 = uvCenter + 0.5f * d1;
addVertex(center, uvCenter, colorMul, colorAdd);
addVertex(p0, uv0, colorMul, colorAdd);
addVertex(p1, uv1, colorMul, colorAdd);
}
}
void flush()
{
glBindVertexArray(m_vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * m_vertices.size(), m_vertices.data(), GL_STREAM_DRAW);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glDrawArrays(GL_TRIANGLES, 0, (GLsizei)m_vertices.size());
m_vertices.clear();
}
private:
std::vector<Vertex> m_vertices;
GLuint m_vertexArray;
GLuint m_vertexBuffer;
};
class Game
{
public:
Game() : m_playerPosition(vec2::zero), m_playerVelocity(vec2::zero), m_playerControl(vec2::zero)
{
for(int i = 0; i < 300; i++)
{
float t = float(i);
float r = 3.f + t * 0.25f;
float a = 3.7f * t;
float s = 1.f + 0.5f * sinf(t);
m_enemies.push_back( { { cosf(a) * r, sinf(a) * r }, s, { 0.f, s - 0.5f, 1.f, 1.f } } );
}
}
void update(float dt)
{
m_playerVelocity = m_playerControl;
m_playerPosition += m_playerVelocity * dt;
for(std::list<Enemy>::iterator it = m_enemies.begin(); it != m_enemies.end();)
{
if(!it->update(dt))
{
it = m_enemies.erase(it);
}
else
{
++it;
}
}
}
void render(Batcher& batcher) const
{
batcher.addCircle(m_playerPosition, 0.05f, { 1.f, 0.f, 0.f, 1.f } );
for(std::list<Enemy>::const_iterator it = m_enemies.begin(); it != m_enemies.end(); ++it)
{
it->render(batcher);
}
}
void setControl(const vec2& control)
{
m_playerControl = control;
}
private:
vec2 m_playerPosition;
vec2 m_playerVelocity;
vec2 m_playerControl;
struct Enemy
{
bool update(float dt)
{
if(length(m_position) < m_speed * dt)
{
return false;
}
m_position -= normalize(m_position) * (m_speed * dt);
return true;
}
void render(Batcher& batcher) const
{
batcher.addCircle(m_position, 0.05f, m_color );
}
vec2 m_position;
float m_speed;
vec4 m_color;
};
std::list<Enemy> m_enemies;
};
struct GameState::PrivateData
{
GLuint shaderProgram;
GLuint texture;
GLuint whiteTexture;
Batcher batcher;
float joystickAreaRadius;
float joystickStickRadius;
float joystickMaxOffset;
bool joystickActive;
vec2 joystickCenter;
vec2 joystickPosition;
Game game;
};
GameState::GameState() : m(new PrivateData)
{
File vsFile("assets/shaders/game.vs");
GLuint vs = createShader(GL_VERTEX_SHADER, vsFile.getData(), vsFile.getSize());
File fsFile("assets/shaders/game.fs");
GLuint fs = createShader(GL_FRAGMENT_SHADER, fsFile.getData(), fsFile.getSize());
m->shaderProgram = createProgram(vs, fs);
glUseProgram(m->shaderProgram);
glUniform1i(glGetUniformLocation(m->shaderProgram, "u_sampler"), 0);
size_t width, height, depth;
GLenum bindTarget;
File textureFile("assets/images/lena.dds");
m->texture = loadDDS(textureFile.getData(), textureFile.getSize(), true, width, height, depth, bindTarget);
File whiteTextureFile("assets/images/white.dds");
m->whiteTexture = loadDDS(whiteTextureFile.getData(), whiteTextureFile.getSize(), true, width, height, depth, bindTarget);
m->joystickAreaRadius = 0.2f;
m->joystickStickRadius = 0.1f;
m->joystickMaxOffset = 0.1f;
}
GameState::~GameState()
{
delete m;
}
void GameState::enter(StateMachine* stateMachine)
{
m->joystickActive = false;
}
void GameState::leave(StateMachine* stateMachine)
{
}
void GameState::update(StateMachine* stateMachine)
{
if(m->joystickActive)
{
vec2 d = windowToView(stateMachine, m->joystickPosition) - windowToView(stateMachine, m->joystickCenter);
m->game.setControl(d / m->joystickMaxOffset);
}
else
{
m->game.setControl(vec2::zero);
}
m->game.update((float)stateMachine->getDeltaTime());
}
void GameState::render(StateMachine* stateMachine)
{
glViewport(0, 0, stateMachine->getFramebufferWidth(), stateMachine->getFramebufferHeight());
glClearColor(0.75f, 0.375f, 0.375f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glUseProgram(m->shaderProgram);
glBindTexture(GL_TEXTURE_2D, m->texture);
float sx, sy;
if(stateMachine->getFramebufferWidth() > stateMachine->getFramebufferHeight())
{
sx = float(stateMachine->getFramebufferHeight()) / float(stateMachine->getFramebufferWidth());
sy = 1.f;
}
else
{
sx = 1.f;
sy = float(stateMachine->getFramebufferWidth()) / float(stateMachine->getFramebufferHeight());
}
float mvp[] = {
sx, 0.f, 0.f, 0.f,
0.f, sy, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f
};
glUniformMatrix4fv(glGetUniformLocation(m->shaderProgram, "u_modelViewProjection"), 1, GL_FALSE, mvp);
const float w = 0.9f;
const float h = 0.9f;
m->batcher.addVertex( { -w, -h }, { 0.f, 0.f } );
m->batcher.addVertex( { w, -h }, { 1.f, 0.f } );
m->batcher.addVertex( { w, h }, { 1.f, 1.f } );
m->batcher.addVertex( { w, h }, { 1.f, 1.f } );
m->batcher.addVertex( { -w, h }, { 0.f, 1.f } );
m->batcher.addVertex( { -w, -h }, { 0.f, 0.f } );
m->batcher.flush();
glBindTexture(GL_TEXTURE_2D, m->whiteTexture);
m->game.render(m->batcher);
if(m->joystickActive)
{
vec2 c = windowToView(stateMachine, m->joystickCenter);
vec2 p = windowToView(stateMachine, m->joystickPosition);
m->batcher.addCircle(c, m->joystickAreaRadius, { 0.5f, 0.5f, 0.5f, 0.333f } );
m->batcher.addCircle(p, m->joystickStickRadius, { 0.75f, 0.75f, 0.75f, 0.333f } );
}
m->batcher.flush();
}
void GameState::mouseDown(StateMachine* stateMachine, float x, float y)
{
m->joystickActive = true;
m->joystickCenter = m->joystickPosition = { x, y };
}
void GameState::mouseUp(StateMachine* stateMachine, float x, float y)
{
m->joystickActive = false;
}
void GameState::mouseMove(StateMachine* stateMachine, float x, float y)
{
m->joystickPosition = { x, y };
if(m->joystickActive)
{
vec2 c = windowToView(stateMachine, m->joystickCenter);
vec2 p = windowToView(stateMachine, m->joystickPosition);
if(length(p - c) > m->joystickMaxOffset)
{
m->joystickCenter = viewToWindow(stateMachine, p + normalize(c - p) * m->joystickMaxOffset);
}
}
}
<commit_msg>Added collision detection.<commit_after>#include "GameState.h"
#include "DDSLoader.h"
#include "File.h"
#include "Math.h"
#include "OpenGL.h"
#include "StateMachine.h"
#include <cassert>
#include <cmath>
#include <cstring>
#include <list>
#include <vector>
#ifdef __APPLE__
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
static const char* glslVersion = "#version 300 es\n";
#else
static const char* glslVersion = "#version 330 core\n";
#endif
#endif
static vec2 windowToView(StateMachine* stateMachine, const vec2& p)
{
const float ww = stateMachine->getWindowWidth();
const float wh = stateMachine->getWindowHeight();
const float ws = (ww > wh) ? wh : ww;
return { (2.f * p.x - ww) / ws, (wh - 2.f * p.y) / ws };
}
static vec2 viewToWindow(StateMachine* stateMachine, const vec2& p)
{
const float ww = stateMachine->getWindowWidth();
const float wh = stateMachine->getWindowHeight();
const float ws = (ww > wh) ? wh : ww;
return { 0.5f * (p.x * ws + ww), 0.5f * (wh - p.y * ws) };
}
static GLuint createShader(GLenum type, const void* data, size_t size)
{
const GLchar* sources[] = { glslVersion, (const GLchar*)data };
const GLint sizes[] = { (GLint)strlen(sources[0]), (GLint)size };
GLuint shader = glCreateShader(type);
glShaderSource(shader, 2, sources, sizes);
glCompileShader(shader);
const GLsizei maxInfoLength = 1024;
GLchar info[maxInfoLength];
glGetShaderInfoLog(shader, maxInfoLength, 0, info);
if(info[0])
{
printf("shader info log:\n%s", info);
}
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
assert(status == GL_TRUE);
return shader;
}
static GLuint createProgram(GLuint vs, GLuint fs)
{
GLuint program = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
const GLsizei maxInfoLength = 1024;
GLchar info[maxInfoLength];
glGetProgramInfoLog(program, maxInfoLength, 0, info);
if(info[0])
{
printf("program info log:\n%s", info);
}
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
assert(status == GL_TRUE);
return program;
}
class Batcher
{
public:
struct Vertex
{
vec2 position;
vec2 uv;
vec4 colorMul;
vec3 colorAdd;
};
Batcher()
{
glGenVertexArrays(1, &m_vertexArray);
glBindVertexArray(m_vertexArray);
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, position));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, uv));
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, colorMul));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, colorAdd));
}
void addVertex(const vec2& position, const vec2& uv, const vec4& colorMul = { 1.f, 1.f, 1.f, 1.f }, const vec3& colorAdd = { 0.f, 0.f, 0.f } )
{
m_vertices.push_back( Vertex { position, uv, colorMul, colorAdd } );
}
void addCircle(const vec2& center, float radius, const vec4& colorMul = { 1.f, 1.f, 1.f, 1.f }, const vec3& colorAdd = { 0.f, 0.f, 0.f } )
{
const int n = 64;
for(int i = 0; i < n; i++)
{
float a0 = 2.f * float(M_PI) * float(i) / float(n);
float a1 = 2.f * float(M_PI) * float(i + 1) / float(n);
vec2 d0 { cosf(a0), sinf(a0) };
vec2 d1 { cosf(a1), sinf(a1) };
vec2 p0 = center + radius * d0;
vec2 p1 = center + radius * d1;
vec2 uvCenter { 0.5f, 0.5f };
vec2 uv0 = uvCenter + 0.5f * d0;
vec2 uv1 = uvCenter + 0.5f * d1;
addVertex(center, uvCenter, colorMul, colorAdd);
addVertex(p0, uv0, colorMul, colorAdd);
addVertex(p1, uv1, colorMul, colorAdd);
}
}
void flush()
{
glBindVertexArray(m_vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * m_vertices.size(), m_vertices.data(), GL_STREAM_DRAW);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glDrawArrays(GL_TRIANGLES, 0, (GLsizei)m_vertices.size());
m_vertices.clear();
}
private:
std::vector<Vertex> m_vertices;
GLuint m_vertexArray;
GLuint m_vertexBuffer;
};
class Game
{
public:
Game() : m_playerPosition(vec2::zero), m_playerVelocity(vec2::zero), m_playerControl(vec2::zero), m_playerRadius(0.05f)
{
for(int i = 0; i < 300; i++)
{
float t = float(i);
float r = 3.f + t * 0.25f;
float a = 3.7f * t;
float s = 1.f + 0.5f * sinf(t);
m_enemies.push_back( { { cosf(a) * r, sinf(a) * r }, s, 0.05f, { 0.f, s - 0.5f, 1.f, 1.f } } );
}
}
bool update(float dt)
{
m_playerVelocity = m_playerControl;
m_playerPosition += m_playerVelocity * dt;
for(std::list<Enemy>::iterator it = m_enemies.begin(); it != m_enemies.end();)
{
if(!it->update(dt))
{
it = m_enemies.erase(it);
}
else
{
if(length(it->m_position - m_playerPosition) < it->m_radius + m_playerRadius)
{
return false;
}
++it;
}
}
return true;
}
void render(Batcher& batcher) const
{
batcher.addCircle(m_playerPosition, 0.05f, { 1.f, 0.f, 0.f, 1.f } );
for(std::list<Enemy>::const_iterator it = m_enemies.begin(); it != m_enemies.end(); ++it)
{
it->render(batcher);
}
}
void setControl(const vec2& control)
{
m_playerControl = control;
}
private:
vec2 m_playerPosition;
vec2 m_playerVelocity;
vec2 m_playerControl;
float m_playerRadius;
struct Enemy
{
bool update(float dt)
{
if(length(m_position) < m_speed * dt)
{
return false;
}
m_position -= normalize(m_position) * (m_speed * dt);
return true;
}
void render(Batcher& batcher) const
{
batcher.addCircle(m_position, m_radius, m_color );
}
vec2 m_position;
float m_speed;
float m_radius;
vec4 m_color;
};
std::list<Enemy> m_enemies;
};
struct GameState::PrivateData
{
GLuint shaderProgram;
GLuint texture;
GLuint whiteTexture;
Batcher batcher;
float joystickAreaRadius;
float joystickStickRadius;
float joystickMaxOffset;
bool joystickActive;
vec2 joystickCenter;
vec2 joystickPosition;
Game* game;
};
GameState::GameState() : m(new PrivateData)
{
File vsFile("assets/shaders/game.vs");
GLuint vs = createShader(GL_VERTEX_SHADER, vsFile.getData(), vsFile.getSize());
File fsFile("assets/shaders/game.fs");
GLuint fs = createShader(GL_FRAGMENT_SHADER, fsFile.getData(), fsFile.getSize());
m->shaderProgram = createProgram(vs, fs);
glUseProgram(m->shaderProgram);
glUniform1i(glGetUniformLocation(m->shaderProgram, "u_sampler"), 0);
size_t width, height, depth;
GLenum bindTarget;
File textureFile("assets/images/lena.dds");
m->texture = loadDDS(textureFile.getData(), textureFile.getSize(), true, width, height, depth, bindTarget);
File whiteTextureFile("assets/images/white.dds");
m->whiteTexture = loadDDS(whiteTextureFile.getData(), whiteTextureFile.getSize(), true, width, height, depth, bindTarget);
m->joystickAreaRadius = 0.2f;
m->joystickStickRadius = 0.1f;
m->joystickMaxOffset = 0.1f;
m->game = nullptr;
}
GameState::~GameState()
{
delete m;
}
void GameState::enter(StateMachine* stateMachine)
{
m->joystickActive = false;
m->game = new Game;
}
void GameState::leave(StateMachine* stateMachine)
{
delete m->game;
m->game = nullptr;
}
void GameState::update(StateMachine* stateMachine)
{
if(m->joystickActive)
{
vec2 d = windowToView(stateMachine, m->joystickPosition) - windowToView(stateMachine, m->joystickCenter);
m->game->setControl(d / m->joystickMaxOffset);
}
else
{
m->game->setControl(vec2::zero);
}
if(!m->game->update((float)stateMachine->getDeltaTime()))
{
stateMachine->requestState("menu");
}
}
void GameState::render(StateMachine* stateMachine)
{
glViewport(0, 0, stateMachine->getFramebufferWidth(), stateMachine->getFramebufferHeight());
glClearColor(0.75f, 0.375f, 0.375f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glUseProgram(m->shaderProgram);
glBindTexture(GL_TEXTURE_2D, m->texture);
float sx, sy;
if(stateMachine->getFramebufferWidth() > stateMachine->getFramebufferHeight())
{
sx = float(stateMachine->getFramebufferHeight()) / float(stateMachine->getFramebufferWidth());
sy = 1.f;
}
else
{
sx = 1.f;
sy = float(stateMachine->getFramebufferWidth()) / float(stateMachine->getFramebufferHeight());
}
float mvp[] = {
sx, 0.f, 0.f, 0.f,
0.f, sy, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f
};
glUniformMatrix4fv(glGetUniformLocation(m->shaderProgram, "u_modelViewProjection"), 1, GL_FALSE, mvp);
const float w = 0.9f;
const float h = 0.9f;
m->batcher.addVertex( { -w, -h }, { 0.f, 0.f } );
m->batcher.addVertex( { w, -h }, { 1.f, 0.f } );
m->batcher.addVertex( { w, h }, { 1.f, 1.f } );
m->batcher.addVertex( { w, h }, { 1.f, 1.f } );
m->batcher.addVertex( { -w, h }, { 0.f, 1.f } );
m->batcher.addVertex( { -w, -h }, { 0.f, 0.f } );
m->batcher.flush();
glBindTexture(GL_TEXTURE_2D, m->whiteTexture);
m->game->render(m->batcher);
if(m->joystickActive)
{
vec2 c = windowToView(stateMachine, m->joystickCenter);
vec2 p = windowToView(stateMachine, m->joystickPosition);
m->batcher.addCircle(c, m->joystickAreaRadius, { 0.5f, 0.5f, 0.5f, 0.333f } );
m->batcher.addCircle(p, m->joystickStickRadius, { 0.75f, 0.75f, 0.75f, 0.333f } );
}
m->batcher.flush();
}
void GameState::mouseDown(StateMachine* stateMachine, float x, float y)
{
m->joystickActive = true;
m->joystickCenter = m->joystickPosition = { x, y };
}
void GameState::mouseUp(StateMachine* stateMachine, float x, float y)
{
m->joystickActive = false;
}
void GameState::mouseMove(StateMachine* stateMachine, float x, float y)
{
m->joystickPosition = { x, y };
if(m->joystickActive)
{
vec2 c = windowToView(stateMachine, m->joystickCenter);
vec2 p = windowToView(stateMachine, m->joystickPosition);
if(length(p - c) > m->joystickMaxOffset)
{
m->joystickCenter = viewToWindow(stateMachine, p + normalize(c - p) * m->joystickMaxOffset);
}
}
}
<|endoftext|> |
<commit_before>#ifndef FMO_DESKTOP_EVALUATOR_HPP
#define FMO_DESKTOP_EVALUATOR_HPP
#include "frameset.hpp"
#include <array>
#include <fmo/algorithm.hpp>
#include <fmo/assert.hpp>
#include <fmo/pointset.hpp>
#include <forward_list>
#include <iosfwd>
#include <map>
enum class Event { TP = 0, TN = 1, FP = 2, FN = 3 };
enum class Comparison { NONE, SAME, IMPROVEMENT, REGRESSION };
const std::string& eventName(Event e);
struct Evaluation {
Evaluation() : mEvents{{0, 0, 0, 0}} {}
int& operator[](Event e) { return mEvents[int(e)]; }
int operator[](Event e) const { return mEvents[int(e)]; }
void clear() { mEvents.fill(0); }
void operator+=(const Evaluation& rhs) {
for (int i = 0; i < 4; i++) { mEvents[i] += rhs.mEvents[i]; }
}
private:
std::array<int, 4> mEvents;
};
struct EvalResult {
Evaluation eval;
Comparison comp;
void clear() {
eval.clear();
comp = Comparison::NONE;
}
std::string str() const;
};
inline bool good(Evaluation r) { return r[Event::FN] + r[Event::FP] == 0; }
inline bool bad(Evaluation r) { return r[Event::TN] + r[Event::TP] == 0; }
/// Results of evaluation of a particular sequence.
struct FileResults {
static constexpr double IOU_STORAGE_FACTOR = 1e3;
std::vector<Evaluation> frames; ///< evaluation for each frame
std::vector<int> iou; ///< non-zero intersection-over-union values
/// Clears all data.
void clear() {
frames.clear();
iou.clear();
}
};
/// Responsible for storing and loading evaluation statistics.
struct Results {
using map_t = std::map<std::string, FileResults*>;
using const_iterator = map_t::const_iterator;
using size_type = map_t::size_type;
Results() = default;
/// Provides access to data regarding a specific file. A new data structure is created. If a
/// structure with the given name already exists, an exception is thrown.
FileResults& newFile(const std::string& name);
/// Provides access to data regatding a specific file. If there is no data, a reference to an
/// empty data structure is returned.
const FileResults& getFile(const std::string& name) const;
/// Loads results from file, previously saved with the save() method.
void load(const std::string& file);
/// Iterates over files in the results.
const_iterator begin() const { return mMap.begin(); }
/// Iterates over files in the results.
const_iterator end() const { return mMap.end(); }
/// Provides the number of files.
size_type size() const { return mMap.size(); }
/// Checks whether there are any files.
bool empty() const { return mMap.empty(); }
/// Calculate the histogram of intersection-over-union values.
std::vector<int> makeIOUHistogram(int bins) const;
private:
// data
std::forward_list<FileResults> mList;
std::map<std::string, FileResults*> mMap;
};
/// Responsible for calculating frame statistics for a single input file.
struct Evaluator {
static constexpr int FRAME_OFFSET = -1;
static constexpr double IOU_THRESHOLD = 0.5;
~Evaluator();
Evaluator(const std::string& gtFilename, fmo::Dims dims, Results& results,
const Results& baseline);
/// Decides whether the algorithm has been successful by comparing the objects it has provided
/// with the ground truth.
EvalResult evaluateFrame(const fmo::Algorithm::Output& out, int frameNum);
/// Provide the ground truth at the specified frame.
const std::vector<fmo::PointSet>& groundTruth(int frameNum) const {
return mGt.get(frameNum + FRAME_OFFSET);
}
/// Provides the number of frames in the ground truth file.
int numFrames() { return mGt.numFrames(); }
/// Provides the evaluation result that was last returned by evaluateFrame().
const EvalResult& getResult() const { return mResult; }
private:
// data
int mFrameNum = 0;
FileResults* mFile;
const FileResults* mBaseline;
FrameSet mGt;
std::string mName;
EvalResult mResult;
fmo::PointSet mPointsCache;
std::vector<double> mPsScores; ///< cached vector for storing IOUs of detected objects
std::vector<double> mGtScores; ///< cached vector for storing IOUs of GT objects
};
/// Extracts filename from path.
std::string extractFilename(const std::string& path);
/// Extracts name of sequence from path.
std::string extractSequenceName(const std::string& path);
#endif // FMO_DESKTOP_EVALUATOR_HPP
<commit_msg>Reduce IOU threshold<commit_after>#ifndef FMO_DESKTOP_EVALUATOR_HPP
#define FMO_DESKTOP_EVALUATOR_HPP
#include "frameset.hpp"
#include <array>
#include <fmo/algorithm.hpp>
#include <fmo/assert.hpp>
#include <fmo/pointset.hpp>
#include <forward_list>
#include <iosfwd>
#include <map>
enum class Event { TP = 0, TN = 1, FP = 2, FN = 3 };
enum class Comparison { NONE, SAME, IMPROVEMENT, REGRESSION };
const std::string& eventName(Event e);
struct Evaluation {
Evaluation() : mEvents{{0, 0, 0, 0}} {}
int& operator[](Event e) { return mEvents[int(e)]; }
int operator[](Event e) const { return mEvents[int(e)]; }
void clear() { mEvents.fill(0); }
void operator+=(const Evaluation& rhs) {
for (int i = 0; i < 4; i++) { mEvents[i] += rhs.mEvents[i]; }
}
private:
std::array<int, 4> mEvents;
};
struct EvalResult {
Evaluation eval;
Comparison comp;
void clear() {
eval.clear();
comp = Comparison::NONE;
}
std::string str() const;
};
inline bool good(Evaluation r) { return r[Event::FN] + r[Event::FP] == 0; }
inline bool bad(Evaluation r) { return r[Event::TN] + r[Event::TP] == 0; }
/// Results of evaluation of a particular sequence.
struct FileResults {
static constexpr double IOU_STORAGE_FACTOR = 1e3;
std::vector<Evaluation> frames; ///< evaluation for each frame
std::vector<int> iou; ///< non-zero intersection-over-union values
/// Clears all data.
void clear() {
frames.clear();
iou.clear();
}
};
/// Responsible for storing and loading evaluation statistics.
struct Results {
using map_t = std::map<std::string, FileResults*>;
using const_iterator = map_t::const_iterator;
using size_type = map_t::size_type;
Results() = default;
/// Provides access to data regarding a specific file. A new data structure is created. If a
/// structure with the given name already exists, an exception is thrown.
FileResults& newFile(const std::string& name);
/// Provides access to data regatding a specific file. If there is no data, a reference to an
/// empty data structure is returned.
const FileResults& getFile(const std::string& name) const;
/// Loads results from file, previously saved with the save() method.
void load(const std::string& file);
/// Iterates over files in the results.
const_iterator begin() const { return mMap.begin(); }
/// Iterates over files in the results.
const_iterator end() const { return mMap.end(); }
/// Provides the number of files.
size_type size() const { return mMap.size(); }
/// Checks whether there are any files.
bool empty() const { return mMap.empty(); }
/// Calculate the histogram of intersection-over-union values.
std::vector<int> makeIOUHistogram(int bins) const;
private:
// data
std::forward_list<FileResults> mList;
std::map<std::string, FileResults*> mMap;
};
/// Responsible for calculating frame statistics for a single input file.
struct Evaluator {
static constexpr int FRAME_OFFSET = -1;
static constexpr double IOU_THRESHOLD = 0.25;
~Evaluator();
Evaluator(const std::string& gtFilename, fmo::Dims dims, Results& results,
const Results& baseline);
/// Decides whether the algorithm has been successful by comparing the objects it has provided
/// with the ground truth.
EvalResult evaluateFrame(const fmo::Algorithm::Output& out, int frameNum);
/// Provide the ground truth at the specified frame.
const std::vector<fmo::PointSet>& groundTruth(int frameNum) const {
return mGt.get(frameNum + FRAME_OFFSET);
}
/// Provides the number of frames in the ground truth file.
int numFrames() { return mGt.numFrames(); }
/// Provides the evaluation result that was last returned by evaluateFrame().
const EvalResult& getResult() const { return mResult; }
private:
// data
int mFrameNum = 0;
FileResults* mFile;
const FileResults* mBaseline;
FrameSet mGt;
std::string mName;
EvalResult mResult;
fmo::PointSet mPointsCache;
std::vector<double> mPsScores; ///< cached vector for storing IOUs of detected objects
std::vector<double> mGtScores; ///< cached vector for storing IOUs of GT objects
};
/// Extracts filename from path.
std::string extractFilename(const std::string& path);
/// Extracts name of sequence from path.
std::string extractSequenceName(const std::string& path);
#endif // FMO_DESKTOP_EVALUATOR_HPP
<|endoftext|> |
<commit_before>#ifndef __STDAIR_STDAIR_TYPES_HPP
#define __STDAIR_STDAIR_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <string>
#include <vector>
#include <list>
// Boost (Extended STL)
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace stdair {
// ///////// Exceptions ///////////
class RootException : public std::exception {
};
class FileNotFoundException : public RootException {
};
class NonInitialisedServiceException : public RootException {
};
class MemoryAllocationException : public RootException {
};
class ObjectNotFoundException : public RootException {
};
class DocumentNotFoundException : public RootException {
};
// /////////////// Log /////////////
/** Level of logs. */
namespace LOG {
typedef enum {
CRITICAL = 0,
ERROR,
NOTIFICATION,
WARNING,
DEBUG,
VERBOSE,
LAST_VALUE
} EN_LogLevel;
}
// //////// Type definitions /////////
/** Define the type for airline codes. */
typedef std::string AirlineCode_T;
/** Define the type for flight numbers. */
typedef unsigned int FlightNumber_T;
/** Define the type for durations (e.g., elapsed in-flight time). */
typedef boost::posix_time::time_duration Duration_T;
/** Define the type for date (e.g., departure date of a flight). */
typedef boost::gregorian::date Date_T;
/** Define the type for airport codes. */
typedef std::string AirportCode_T;
}
#endif // __STDAIR_STDAIR_TYPES_HPP
<commit_msg>[Dev] Removed an emply line.<commit_after>#ifndef __STDAIR_STDAIR_TYPES_HPP
#define __STDAIR_STDAIR_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <string>
#include <vector>
#include <list>
// Boost (Extended STL)
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace stdair {
// ///////// Exceptions ///////////
class RootException : public std::exception {
};
class FileNotFoundException : public RootException {
};
class NonInitialisedServiceException : public RootException {
};
class MemoryAllocationException : public RootException {
};
class ObjectNotFoundException : public RootException {
};
class DocumentNotFoundException : public RootException {
};
// /////////////// Log /////////////
/** Level of logs. */
namespace LOG {
typedef enum {
CRITICAL = 0,
ERROR,
NOTIFICATION,
WARNING,
DEBUG,
VERBOSE,
LAST_VALUE
} EN_LogLevel;
}
// //////// Type definitions /////////
/** Define the type for airline codes. */
typedef std::string AirlineCode_T;
/** Define the type for flight numbers. */
typedef unsigned int FlightNumber_T;
/** Define the type for durations (e.g., elapsed in-flight time). */
typedef boost::posix_time::time_duration Duration_T;
/** Define the type for date (e.g., departure date of a flight). */
typedef boost::gregorian::date Date_T;
/** Define the type for airport codes. */
typedef std::string AirportCode_T;
}
#endif // __STDAIR_STDAIR_TYPES_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pelagicore AB
* All rights reserved.
*/
#include <iostream>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "controller.h"
Controller::Controller():
m_pid(0)
{
}
Controller::~Controller()
{
}
int Controller::runApp()
{
std::cout << "Will run app now..." << std::endl;
m_pid = fork();
if (m_pid == -1) {
perror("Error starting application: ");
return m_pid;
}
if (m_pid == 0) { // Child
// This path to containedapp makes sense inside the container
int ret = execlp("/appbin/containedapp", "containedapp", NULL);
if (ret == -1)
perror("exec error: ");
exit(1);
} // Parent
std::cout << "Started app with pid: " << "\"" << m_pid << "\"" << std::endl;
return m_pid;
}
void Controller::killApp()
{
std::cout << "Trying to kill: " << m_pid << std::endl;
if (m_pid == 0) {
std::cout << "Warning: Trying to kill an app without previously having started one" << std::endl;
return;
}
int ret = kill(m_pid, SIGINT);
if (ret == -1) {
perror("Error killing application: ");
} else {
int status;
waitpid(m_pid, &status, 0);
if (WIFEXITED(status))
std::cout << "Controller: wait: app exited (WIFEXITED)" << std::endl;
if (WIFSIGNALED(status))
std::cout << "Controller: wait: app shut down by signal: " <<
WTERMSIG(status) << " (WIFSIGNALED)" << std::endl;
}
}
void Controller::setEnvironmentVariable(const std::string &variable,
const std::string &value)
{
int ret = setenv(variable.c_str(), value.c_str(), 1);
if (ret == -1) {
perror("setenv: ");
}
std::cout << "Controller set \"" << variable << "=" << value << "\"" << std::endl;
}
void Controller::systemCall(const std::string &command)
{
system(command.c_str());
std::cout << "Controller executed command: " << command << std::endl;
}
<commit_msg>Don't continue execution in controller when failing to set environment variable<commit_after>/*
* Copyright (C) 2014 Pelagicore AB
* All rights reserved.
*/
#include <iostream>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "controller.h"
Controller::Controller():
m_pid(0)
{
}
Controller::~Controller()
{
}
int Controller::runApp()
{
std::cout << "Will run app now..." << std::endl;
m_pid = fork();
if (m_pid == -1) {
perror("Error starting application: ");
return m_pid;
}
if (m_pid == 0) { // Child
// This path to containedapp makes sense inside the container
int ret = execlp("/appbin/containedapp", "containedapp", NULL);
if (ret == -1)
perror("exec error: ");
exit(1);
} // Parent
std::cout << "Started app with pid: " << "\"" << m_pid << "\"" << std::endl;
return m_pid;
}
void Controller::killApp()
{
std::cout << "Trying to kill: " << m_pid << std::endl;
if (m_pid == 0) {
std::cout << "Warning: Trying to kill an app without previously having started one" << std::endl;
return;
}
int ret = kill(m_pid, SIGINT);
if (ret == -1) {
perror("Error killing application: ");
} else {
int status;
waitpid(m_pid, &status, 0);
if (WIFEXITED(status))
std::cout << "Controller: wait: app exited (WIFEXITED)" << std::endl;
if (WIFSIGNALED(status))
std::cout << "Controller: wait: app shut down by signal: " <<
WTERMSIG(status) << " (WIFSIGNALED)" << std::endl;
}
}
void Controller::setEnvironmentVariable(const std::string &variable,
const std::string &value)
{
int ret = setenv(variable.c_str(), value.c_str(), 1);
if (ret == -1) {
perror("setenv: ");
return;
}
std::cout << "Controller set \"" << variable << "=" << value << "\"" << std::endl;
}
void Controller::systemCall(const std::string &command)
{
system(command.c_str());
std::cout << "Controller executed command: " << command << std::endl;
}
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/barChart/qwt3dBars.cpp,v $
// $Revision: 1.2 $
// $Name: $
// $Author: akoenig $
// $Date: 2007/11/13 14:24:26 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <qbitmap.h>
#include "qwt3d_color.h"
#include "qwt3d_plot.h"
#include "qwt3dBars.h"
//#include <iostream>
Bar::Bar()
{
configure(0, -1, -1);
}
Bar::Bar(double rad, double showColumn, double showRow)
{
configure(rad, showColumn, showRow);
}
void Bar::configure(double rad, double showColumn, double showRow)
{
plot = 0;
radius_ = rad;
mShowColumn = showColumn;
mShowRow = showRow;
}
void Bar::drawBegin()
{
drawZero();
diag_ = radius_;
glLineWidth(0);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1, 1);
}
void Bar::drawEnd()
{}
void Bar::draw(Qwt3D::Triple const& pos)
{
Qwt3D::GLStateBewarer sb(GL_LINE_SMOOTH, true);
sb.turnOn();
//an option to add further labels
// if ((pos.x == mShowColumn) || (pos.y == mShowRow))
// {
// Label3D lb;
// lb.draw(pos, diag_, diag_ * 2);
//}
// set the zero level
GLdouble minz = 0; //plot->hull().minVertex.z;
Qwt3D::RGBA mTo = (*plot->dataColor())(pos);
Qwt3D::RGBA mFrom = (*plot->dataColor())(pos.x, pos.y, minz);
glBegin(GL_QUADS);
if ((pos.x == mShowColumn) || (pos.y == mShowRow))
glColor3d(0.71, 0.835, 1); //(1, 0, 0);
else
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glVertex3d(pos.x - diag_, pos.y + diag_, minz);
if ((pos.x == mShowColumn) || (pos.y == mShowRow))
glColor3d(0.71, 0.835, 1); //(1, 0, 0);
else
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y + diag_, minz);
glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y - diag_, minz);
glVertex3d(pos.x - diag_, pos.y + diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glEnd();
glColor3d(0, 0, 0);
glBegin(GL_LINES);
glVertex3d(pos.x - diag_, pos.y - diag_, minz); glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z); glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z); glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, minz); glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glVertex3d(pos.x - diag_, pos.y - diag_, minz); glVertex3d(pos.x - diag_, pos.y + diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, minz); glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z); glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z); glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, minz); glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y - diag_, minz); glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y + diag_, minz); glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, minz); glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glEnd();
}
void Bar::drawZero()
{
glColor3d(0, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex3d(plot->hull().minVertex.x, plot->hull().minVertex.y, 0);
glVertex3d(plot->hull().maxVertex.x, plot->hull().minVertex.y, 0);
glVertex3d(plot->hull().maxVertex.x, plot->hull().maxVertex.y, 0);
glVertex3d(plot->hull().minVertex.x, plot->hull().maxVertex.y, 0);
glEnd();
}
void Label3D::draw(Qwt3D::Triple const& pos, double w, double h)
{
double gap = 0.3;
double posZ;
if (pos.z < 0)
posZ = 0;
else
posZ = pos.z;
glColor3d(1, 1, 1);
glBegin(GL_QUADS);
glVertex3d(pos.x - w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap + h);
glVertex3d(pos.x - w, pos.y, posZ + gap + h);
glEnd();
glColor3d(0.4, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex3d(pos.x - w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap + h);
glVertex3d(pos.x - w, pos.y, posZ + gap + h);
glEnd();
glBegin(GL_LINES);
glVertex3d(pos.x, pos.y, posZ);
glVertex3d(pos.x, pos.y, posZ + gap);
glEnd();
}
<commit_msg>Better slider action function.<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/barChart/qwt3dBars.cpp,v $
// $Revision: 1.3 $
// $Name: $
// $Author: akoenig $
// $Date: 2007/11/16 14:42:05 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <qbitmap.h>
#include "qwt3d_color.h"
#include "qwt3d_plot.h"
#include "qwt3dBars.h"
//#include <iostream>
Bar::Bar()
{
configure(0, -1, -1);
}
Bar::Bar(double rad, double showColumn, double showRow)
{
configure(rad, showColumn, showRow);
}
void Bar::configure(double rad, double showColumn, double showRow)
{
plot = 0;
radius_ = rad;
mShowColumn = showColumn;
mShowRow = showRow;
}
void Bar::drawBegin()
{
drawZero();
diag_ = radius_;
glLineWidth(0);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1, 1);
}
void Bar::drawEnd()
{}
void Bar::draw(Qwt3D::Triple const& pos)
{
Qwt3D::GLStateBewarer sb(GL_LINE_SMOOTH, true);
sb.turnOn();
//an option to add further labels
// if ((pos.x == mShowColumn) || (pos.y == mShowRow))
// {
// Label3D lb;
// lb.draw(pos, diag_, diag_ * 2);
//}
// set the zero level
GLdouble minz = 0; //plot->hull().minVertex.z;
Qwt3D::RGBA mTo = (*plot->dataColor())(pos);
Qwt3D::RGBA mFrom = (*plot->dataColor())(pos.x, pos.y, minz);
glBegin(GL_QUADS);
if (((int)(100*pos.x) == (int)(100*mShowColumn)) || ((int)(100*pos.y) == (int)(100*mShowRow)))
glColor3d(0.71, 0.835, 1); //(1, 0, 0);
else
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glVertex3d(pos.x - diag_, pos.y + diag_, minz);
if (((int)(100*pos.x) == (int)(100*mShowColumn)) || ((int)(100*pos.y) == (int)(100*mShowRow)))
glColor3d(0.71, 0.835, 1); //(1, 0, 0);
else
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y + diag_, minz);
glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x - diag_, pos.y - diag_, minz);
glVertex3d(pos.x - diag_, pos.y + diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glColor4d(mFrom.r, mFrom.g, mFrom.b, mFrom.a);
glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glColor4d(mTo.r, mTo.g, mTo.b, mTo.a);
glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glEnd();
glColor3d(0, 0, 0);
glBegin(GL_LINES);
glVertex3d(pos.x - diag_, pos.y - diag_, minz); glVertex3d(pos.x + diag_, pos.y - diag_, minz);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z); glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, pos.z); glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, minz); glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glVertex3d(pos.x - diag_, pos.y - diag_, minz); glVertex3d(pos.x - diag_, pos.y + diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, minz); glVertex3d(pos.x + diag_, pos.y + diag_, minz);
glVertex3d(pos.x + diag_, pos.y - diag_, pos.z); glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, pos.z); glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y - diag_, minz); glVertex3d(pos.x - diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y - diag_, minz); glVertex3d(pos.x + diag_, pos.y - diag_, pos.z);
glVertex3d(pos.x + diag_, pos.y + diag_, minz); glVertex3d(pos.x + diag_, pos.y + diag_, pos.z);
glVertex3d(pos.x - diag_, pos.y + diag_, minz); glVertex3d(pos.x - diag_, pos.y + diag_, pos.z);
glEnd();
}
void Bar::drawZero()
{
glColor3d(0, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex3d(plot->hull().minVertex.x, plot->hull().minVertex.y, 0);
glVertex3d(plot->hull().maxVertex.x, plot->hull().minVertex.y, 0);
glVertex3d(plot->hull().maxVertex.x, plot->hull().maxVertex.y, 0);
glVertex3d(plot->hull().minVertex.x, plot->hull().maxVertex.y, 0);
glEnd();
}
void Label3D::draw(Qwt3D::Triple const& pos, double w, double h)
{
double gap = 0.3;
double posZ;
if (pos.z < 0)
posZ = 0;
else
posZ = pos.z;
glColor3d(1, 1, 1);
glBegin(GL_QUADS);
glVertex3d(pos.x - w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap + h);
glVertex3d(pos.x - w, pos.y, posZ + gap + h);
glEnd();
glColor3d(0.4, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex3d(pos.x - w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap);
glVertex3d(pos.x + w, pos.y, posZ + gap + h);
glVertex3d(pos.x - w, pos.y, posZ + gap + h);
glEnd();
glBegin(GL_LINES);
glVertex3d(pos.x, pos.y, posZ);
glVertex3d(pos.x, pos.y, posZ + gap);
glEnd();
}
<|endoftext|> |
<commit_before>/** @file Defines miscellaneous general purpose functor types.
* @author Ralph Tandetzky
*/
#pragma once
#include "swap.hpp"
#include <utility>
namespace cu
{
/// A functor class whose function call operator does nothing.
///
/// This is a class that is needed to work around the gcc bug, that the
/// lambda @c [](auto&&...){} required at least one argument.
struct NoOpFunctor
{
template <typename ...Ts>
void operator()( Ts&&... ) const
{
}
};
struct ForwardingFunctor
{
template <typename T>
decltype(auto) operator()( T && x ) const
{
return std::forward<T>(x);
}
};
template <typename Signature>
class Lambda;
template <typename Result, typename ... Args>
class Lambda<Result(Args...)>
{
public:
template <typename F>
Lambda( const F & functor )
: workLoad( &functor )
, f( []( const void * workLoad, Args &&... args ) -> Result
{
return (*(static_cast<const F*>(workLoad)))( std::forward<Args>(args)... );
} )
{
}
// disable copying
Lambda( const Lambda & ) = delete;
Lambda & operator=( Lambda ) = delete;
Result operator()( Args &&... args ) const
{
return f( workLoad, std::forward<Args>(args)... );
}
private:
const void * workLoad = nullptr;
Result (*f)(const void*,Args&&...) = nullptr;
};
namespace detail
{
template <typename ...Fs>
class OverloadedFunctor;
template <typename F>
class OverloadedFunctor<F> : public F
{
public:
OverloadedFunctor( const F & f ) : F( f ) {}
OverloadedFunctor( F && f ) : F( std::move(f) ) {}
using F::operator();
};
template <typename F, typename ...Fs>
class OverloadedFunctor<F,Fs...>
: public OverloadedFunctor<F>
, public OverloadedFunctor<Fs...>
{
public:
template <typename Arg,
typename ...Args>
OverloadedFunctor( Arg && arg,
Args &&... args )
: OverloadedFunctor<F >( std::forward<Arg >(arg ) )
, OverloadedFunctor<Fs...>( std::forward<Args>(args)... )
{}
using OverloadedFunctor<F >::operator();
using OverloadedFunctor<Fs...>::operator();
};
} // namespace detail
template <typename ...Fs>
auto makeOverloadedFunctor( Fs &&... fs )
{
return detail::OverloadedFunctor<std::decay_t<Fs>...>( std::forward<Fs>(fs)... );
}
/// This class mimics the behaviour of std::function, except that it
/// does not require the assigned functors to be copyable, but to be
/// movable only. Consequently, @c function_move_only objects are
/// MoveOnly as well.
template <typename T>
class function_move_only;
template <typename Res,
typename ...Args>
class function_move_only<Res(Args...)>
{
public:
function_move_only() noexcept
{}
function_move_only( std::nullptr_t ) noexcept
{}
function_move_only( function_move_only && other ) noexcept
{
swap( other );
}
template <typename F>
function_move_only( F && f )
: callPtr( makeCallPtr<F>() )
, cleanUpPtr( makeCleanUpPtr<F>() )
, payLoad( makePayLoad( CU_FWD(f) ) )
{}
~function_move_only()
{
cleanUp();
}
function_move_only & operator=( std::nullptr_t ) noexcept
{
cleanUp();
}
function_move_only & operator=( function_move_only && other ) noexcept
{
cleanUp();
swap( other );
}
template <typename F>
function_move_only & operator=( F && f )
{
function_move_only( CU_FWD(f) ).swap( *this );
}
void swap( function_move_only & other ) noexcept
{
cu::swap( callPtr , other.callPtr );
cu::swap( cleanUpPtr, other.cleanUpPtr );
cu::swap( payLoad , other.payLoad );
}
explicit operator bool() const noexcept;
Res operator()( Args...args ) const
{
callPtr( payLoad, CU_FWD(args)... );
}
private:
template <typename F>
static Res (*makeCallPtr())( void *, Args&&... )
{
return []( void * payLoad, Args&&...args )
{
(*static_cast<typename std::decay<F>::type*>(payLoad))( CU_FWD(args)... );
};
}
template <typename F>
static void (*makeCleanUpPtr())( void* )
{
return []( void * payLoad )
{
delete static_cast<typename std::decay<F>::type*>(payLoad);
};
}
template <typename F>
static void * makePayLoad( F && f )
{
return new typename std::decay<F>::type( CU_FWD(f) );
}
void cleanUp() noexcept
{
if ( cleanUpPtr )
cleanUpPtr( payLoad );
callPtr = nullptr;
cleanUpPtr = nullptr;
payLoad = nullptr;
}
Res (*callPtr)( void *, Args&&... ) = nullptr;
void (*cleanUpPtr)( void * ) = nullptr;
void * payLoad = nullptr;
};
} // namespace cu
<commit_msg>Reimplemented and renamed function_move_only to MoveFunction.<commit_after>/** @file Defines miscellaneous general purpose functor types.
* @author Ralph Tandetzky
*/
#pragma once
#include "swap.hpp"
#include <functional>
#include <memory>
#include <utility>
namespace cu
{
/// A functor class whose function call operator does nothing.
///
/// This is a class that is needed to work around the gcc bug, that the
/// lambda @c [](auto&&...){} required at least one argument.
struct NoOpFunctor
{
template <typename ...Ts>
void operator()( Ts&&... ) const
{
}
};
struct ForwardingFunctor
{
template <typename T>
decltype(auto) operator()( T && x ) const
{
return std::forward<T>(x);
}
};
template <typename Signature>
class Lambda;
template <typename Result, typename ... Args>
class Lambda<Result(Args...)>
{
public:
template <typename F>
Lambda( const F & functor )
: workLoad( &functor )
, f( []( const void * workLoad, Args &&... args ) -> Result
{
return (*(static_cast<const F*>(workLoad)))( std::forward<Args>(args)... );
} )
{
}
// disable copying
Lambda( const Lambda & ) = delete;
Lambda & operator=( Lambda ) = delete;
Result operator()( Args &&... args ) const
{
return f( workLoad, std::forward<Args>(args)... );
}
private:
const void * workLoad = nullptr;
Result (*f)(const void*,Args&&...) = nullptr;
};
namespace detail
{
template <typename ...Fs>
class OverloadedFunctor;
template <typename F>
class OverloadedFunctor<F> : public F
{
public:
OverloadedFunctor( const F & f ) : F( f ) {}
OverloadedFunctor( F && f ) : F( std::move(f) ) {}
using F::operator();
};
template <typename F, typename ...Fs>
class OverloadedFunctor<F,Fs...>
: public OverloadedFunctor<F>
, public OverloadedFunctor<Fs...>
{
public:
template <typename Arg,
typename ...Args>
OverloadedFunctor( Arg && arg,
Args &&... args )
: OverloadedFunctor<F >( std::forward<Arg >(arg ) )
, OverloadedFunctor<Fs...>( std::forward<Args>(args)... )
{}
using OverloadedFunctor<F >::operator();
using OverloadedFunctor<Fs...>::operator();
};
} // namespace detail
template <typename ...Fs>
auto makeOverloadedFunctor( Fs &&... fs )
{
return detail::OverloadedFunctor<std::decay_t<Fs>...>( std::forward<Fs>(fs)... );
}
/// This class mimics the behaviour of std::function, except that it
/// does not require the assigned functors to be copyable, but to be
/// movable only. Consequently, @c MoveFunction objects are
/// MoveOnly as well.
template <typename T>
class MoveFunction;
template <typename Res,
typename ...Args>
class MoveFunction<Res(Args...)>
{
public:
// constructors
MoveFunction() noexcept
: payLoad( nullptr, [](void*){} )
{}
MoveFunction( std::nullptr_t ) noexcept
: MoveFunction()
{}
MoveFunction( MoveFunction && other ) noexcept
: MoveFunction()
{
swap( other );
}
template <typename F>
MoveFunction( F && f )
: MoveFunction(
std::forward<F>(f),
typename std::conditional_t<
std::is_empty<std::decay_t<F>>::value,
EmptyPayLoadTag,
typename std::conditional_t<
std::is_convertible<F,Res(*)(Args...)>::value,
FunctionPointerTag,
NonEmptyPayLoadTag
>
>{} )
{}
// assignment and swap
MoveFunction & operator=( MoveFunction other ) noexcept
{
other.swap();
}
void swap( MoveFunction & other ) noexcept
{
std::swap( callPtr, other.callPtr );
std::swap( payLoad, other.payLoad );
}
// operators
explicit operator bool() const noexcept
{
return callPtr;
}
Res operator()( Args...args ) const
{
if ( *this )
return callPtr( payLoad.get(), std::forward<Args>(args)... );
else
throw std::bad_function_call{};
}
private:
struct EmptyPayLoadTag {};
struct FunctionPointerTag {};
struct NonEmptyPayLoadTag {};
template <typename F>
MoveFunction( F && f, EmptyPayLoadTag )
: callPtr
{
[]( void * payLoad, Args&&...args )
{
return (*static_cast<std::remove_reference_t<F>*>(payLoad))(
std::forward<Args>(args)...);
}
}
, payLoad{ &f, [](void*){} }
{}
template <typename F>
MoveFunction( F && f, FunctionPointerTag )
: callPtr
{
[]( void * payLoad, Args&&...args )
{
return reinterpret_cast<Res(*)(Args...)>(payLoad)(
std::forward<Args>(args)...);
}
}
, payLoad{
reinterpret_cast<void*>(static_cast<Res(*)(Args...)>(f)),
[](void*){}
}
{
static_assert( sizeof(Res(*)(Args...)) == sizeof(void*), "" );
}
template <typename F>
MoveFunction( F && f, NonEmptyPayLoadTag )
: callPtr
{
[]( void * payLoad, Args&&...args )
{
return (*static_cast<std::decay_t<F>*>(payLoad))(
std::forward<Args>(args)... );
}
}
, payLoad{
new typename std::decay_t<F>( std::forward<F>(f) ),
[]( void * payLoad )
{
delete static_cast<typename std::decay_t<F>*>(payLoad);
}
}
{}
Res (*callPtr)( void *, Args&&... ) = nullptr;
std::unique_ptr<void,void(*)(void*)> payLoad;
};
} // namespace cu
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBoostBreadthFirstSearch.cxx
Copyright 2007 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.
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.
=========================================================================*/
#include "vtkBoostBreadthFirstSearch.h"
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkMath.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkFloatArray.h>
#include <vtkDataArray.h>
#include <vtkSelection.h>
#include <vtkStringArray.h>
#include "vtkGraphToBoostAdapter.h"
#include "vtkGraph.h"
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/property_map.hpp>
#include <boost/vector_property_map.hpp>
#include <boost/pending/queue.hpp>
using namespace boost;
vtkCxxRevisionMacro(vtkBoostBreadthFirstSearch, "1.1");
vtkStandardNewMacro(vtkBoostBreadthFirstSearch);
// Redefine the bfs visitor, the only visitor we
// are using is the tree_edge visitor.
template <typename DistanceMap>
class my_distance_recorder : public default_bfs_visitor
{
public:
my_distance_recorder() { }
my_distance_recorder(DistanceMap dist, vtkIdType* far)
: d(dist), far_vertex(far), far_dist(-1) { *far_vertex = -1; }
template <typename Edge, typename Graph>
void tree_edge(Edge e, const Graph& g)
{
typename graph_traits<Graph>::vertex_descriptor
u = source(e, g), v = target(e, g);
put(d, v, get(d, u) + 1);
if (get(d, v) > far_dist)
{
*far_vertex = v;
far_dist = get(d, v);
}
}
private:
DistanceMap d;
vtkIdType* far_vertex;
vtkIdType far_dist;
};
#if 0
// Convenience function
template <typename DistanceMap>
my_distance_recorder<DistanceMap> my_distance_recorder_func(DistanceMap d)
{
return my_distance_recorder<DistanceMap>(d);
}
#endif
// Constructor/Destructor
vtkBoostBreadthFirstSearch::vtkBoostBreadthFirstSearch()
{
// Default values for the origin vertex
this->OriginVertexIndex = 0;
this->InputArrayName = 0;
this->OutputArrayName = 0;
this->OutputSelectionType = 0;
this->SetOutputSelectionType("MAX_DIST_FROM_ROOT");
this->OriginValue = -1;
this->OutputSelection = false;
this->OriginFromSelection = false;
this->SetNumberOfInputPorts(2);
this->SetNumberOfOutputPorts(2);
}
vtkBoostBreadthFirstSearch::~vtkBoostBreadthFirstSearch()
{
this->SetInputArrayName(0);
this->SetOutputArrayName(0);
}
// Description:
// Set the index (into the vertex array) of the
// breadth first search 'origin' vertex.
void vtkBoostBreadthFirstSearch::SetOriginVertex(vtkIdType index)
{
this->OriginVertexIndex = index;
this->InputArrayName = NULL; // Reset any origin set by another method
this->Modified();
}
// Description:
// Set the breadth first search 'origin' vertex.
// This method is basically the same as above
// but allows the application to simply specify
// an array name and value, instead of having to
// know the specific index of the vertex.
void vtkBoostBreadthFirstSearch::SetOriginVertex(
vtkStdString arrayName, vtkVariant value)
{
this->SetInputArrayName(arrayName);
this->OriginValue = value;
this->Modified();
}
vtkIdType vtkBoostBreadthFirstSearch::GetVertexIndex(
vtkAbstractArray *abstract,vtkVariant value)
{
// Okay now what type of array is it
if (abstract->IsNumeric())
{
vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract);
int intValue = value.ToInt();
for(int i=0; i<dataArray->GetNumberOfTuples(); ++i)
{
if (intValue == static_cast<int>(dataArray->GetTuple1(i)))
{
return i;
}
}
}
else
{
vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract);
vtkStdString stringValue(value.ToString());
for(int i=0; i<stringArray->GetNumberOfTuples(); ++i)
{
if (stringValue == stringArray->GetValue(i))
{
return i;
}
}
}
// Failed
vtkErrorMacro("Did not find a valid vertex index...");
return 0;
}
int vtkBoostBreadthFirstSearch::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkGraph *input = vtkGraph::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkGraph *output = vtkGraph::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
// Sanity check
// The Boost BFS likes to crash on empty datasets
if (input->GetNumberOfVertices() == 0)
{
vtkWarningMacro("Empty input into " << this->GetClassName());
return 0;
}
// Send the data to output.
output->ShallowCopy(input);
if (this->OriginFromSelection)
{
vtkSelection* selection = vtkSelection::GetData(inputVector[1], 0);
if (selection == NULL)
{
vtkErrorMacro("OriginFromSelection set but selection input undefined.");
return 0;
}
if (selection->GetProperties()->Get(vtkSelection::CONTENT_TYPE()) != vtkSelection::GLOBALIDS ||
selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) != vtkSelection::POINT)
{
vtkErrorMacro("Selection must be point ids.");
return 0;
}
vtkAbstractArray* arr = selection->GetSelectionList();
if (arr == NULL)
{
vtkErrorMacro("Selection array is null");
return 0;
}
vtkIdTypeArray* idArr = vtkIdTypeArray::SafeDownCast(arr);
if (idArr == NULL)
{
vtkErrorMacro("Selection array is not a vtkIdTypeArray");
return 0;
}
if (idArr->GetNumberOfTuples() == 0)
{
vtkErrorMacro("Selection array has no elements");
return 0;
}
this->OriginVertexIndex = idArr->GetValue(0);
}
else
{
// Now figure out the origin vertex of the
// breadth first search
if (this->InputArrayName)
{
vtkAbstractArray* abstract = input->GetVertexData()->GetAbstractArray(this->InputArrayName);
// Does the array exist at all?
if (abstract == NULL)
{
vtkErrorMacro("Could not find array named " << this->InputArrayName);
return 0;
}
this->OriginVertexIndex = this->GetVertexIndex(abstract,this->OriginValue);
}
}
// Create the attribute array
vtkIntArray* BFSArray = vtkIntArray::New();
if (this->OutputArrayName)
{
BFSArray->SetName(this->OutputArrayName);
}
else
{
BFSArray->SetName("BFS");
}
BFSArray->SetNumberOfTuples(output->GetNumberOfVertices());
// Initialize the BFS array to all 0's
for(int i=0;i< BFSArray->GetNumberOfTuples(); ++i)
{
BFSArray->SetValue(i,0);
}
// Create a color map (used for marking visited nodes)
vector_property_map<default_color_type> color;
// Create a queue to hand off to the BFS
boost::queue<int> Q;
vtkIdType maxFromRootVertex, Root = 0;
my_distance_recorder<vtkIntArray*> bfsVisitor(BFSArray, &maxFromRootVertex);
// Is the graph directed or undirected
if (output->GetDirected())
{
vtkBoostDirectedGraph g(output);
breadth_first_search(g, this->OriginVertexIndex, Q, bfsVisitor, color);
}
else
{
vtkBoostUndirectedGraph g(output);
breadth_first_search(g, this->OriginVertexIndex, Q, bfsVisitor, color);
}
// Add attribute array to the output
output->GetVertexData()->AddArray(BFSArray);
BFSArray->Delete();
if (this->OutputSelection)
{
vtkSelection* sel = vtkSelection::GetData(outputVector, 1);
vtkIdTypeArray* ids = vtkIdTypeArray::New();
// Set the output based on the output selection type
if (!strcmp(OutputSelectionType,"MAX_DIST_FROM_ROOT"))
{
ids->InsertNextValue(maxFromRootVertex);
}
sel->SetSelectionList(ids);
sel->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), vtkSelection::GLOBALIDS);
sel->GetProperties()->Set(vtkSelection::FIELD_TYPE(), vtkSelection::POINT);
ids->Delete();
}
return 1;
}
void vtkBoostBreadthFirstSearch::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "OriginVertexIndex: " << this->OriginVertexIndex << endl;
os << indent << "InputArrayName: "
<< (this->InputArrayName ? this->InputArrayName : "(none)") << endl;
os << indent << "OutputArrayName: "
<< (this->OutputArrayName ? this->OutputArrayName : "(none)") << endl;
os << indent << "OriginValue: " << this->OriginValue.ToString() << endl;
os << indent << "OutputSelection: "
<< (this->OutputSelection ? "on" : "off") << endl;
os << indent << "OriginFromSelection: "
<< (this->OriginFromSelection ? "on" : "off") << endl;
os << indent << "OutputSelectionType: "
<< (this->OutputSelectionType ? this->OutputSelectionType : "(none)") << endl;
}
//----------------------------------------------------------------------------
int vtkBoostBreadthFirstSearch::FillInputPortInformation(
int port, vtkInformation* info)
{
// now add our info
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph");
}
else if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
}
return 1;
}
//----------------------------------------------------------------------------
int vtkBoostBreadthFirstSearch::FillOutputPortInformation(
int port, vtkInformation* info)
{
// now add our info
if (port == 0)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkGraph");
}
else if (port == 1)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkSelection");
}
return 1;
}
<commit_msg>BUG: Corrected bug where it crashes when the start vertex has no edges attached to it.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBoostBreadthFirstSearch.cxx
Copyright 2007 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.
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.
=========================================================================*/
#include "vtkBoostBreadthFirstSearch.h"
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkMath.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkFloatArray.h>
#include <vtkDataArray.h>
#include <vtkSelection.h>
#include <vtkStringArray.h>
#include "vtkGraphToBoostAdapter.h"
#include "vtkGraph.h"
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/property_map.hpp>
#include <boost/vector_property_map.hpp>
#include <boost/pending/queue.hpp>
using namespace boost;
vtkCxxRevisionMacro(vtkBoostBreadthFirstSearch, "1.2");
vtkStandardNewMacro(vtkBoostBreadthFirstSearch);
// Redefine the bfs visitor, the only visitor we
// are using is the tree_edge visitor.
template <typename DistanceMap>
class my_distance_recorder : public default_bfs_visitor
{
public:
my_distance_recorder() { }
my_distance_recorder(DistanceMap dist, vtkIdType* far)
: d(dist), far_vertex(far), far_dist(-1) { *far_vertex = -1; }
template <typename Vertex, typename Graph>
void discover_vertex(Vertex v, const Graph& g)
{
// If this is the start vertex, initialize far vertex and distance
if (*far_vertex < 0)
{
*far_vertex = v;
far_dist = 0;
}
}
template <typename Edge, typename Graph>
void tree_edge(Edge e, const Graph& g)
{
typename graph_traits<Graph>::vertex_descriptor
u = source(e, g), v = target(e, g);
put(d, v, get(d, u) + 1);
if (get(d, v) > far_dist)
{
*far_vertex = v;
far_dist = get(d, v);
}
}
private:
DistanceMap d;
vtkIdType* far_vertex;
vtkIdType far_dist;
};
// Constructor/Destructor
vtkBoostBreadthFirstSearch::vtkBoostBreadthFirstSearch()
{
// Default values for the origin vertex
this->OriginVertexIndex = 0;
this->InputArrayName = 0;
this->OutputArrayName = 0;
this->OutputSelectionType = 0;
this->SetOutputSelectionType("MAX_DIST_FROM_ROOT");
this->OriginValue = -1;
this->OutputSelection = false;
this->OriginFromSelection = false;
this->SetNumberOfInputPorts(2);
this->SetNumberOfOutputPorts(2);
}
vtkBoostBreadthFirstSearch::~vtkBoostBreadthFirstSearch()
{
this->SetInputArrayName(0);
this->SetOutputArrayName(0);
}
// Description:
// Set the index (into the vertex array) of the
// breadth first search 'origin' vertex.
void vtkBoostBreadthFirstSearch::SetOriginVertex(vtkIdType index)
{
this->OriginVertexIndex = index;
this->InputArrayName = NULL; // Reset any origin set by another method
this->Modified();
}
// Description:
// Set the breadth first search 'origin' vertex.
// This method is basically the same as above
// but allows the application to simply specify
// an array name and value, instead of having to
// know the specific index of the vertex.
void vtkBoostBreadthFirstSearch::SetOriginVertex(
vtkStdString arrayName, vtkVariant value)
{
this->SetInputArrayName(arrayName);
this->OriginValue = value;
this->Modified();
}
vtkIdType vtkBoostBreadthFirstSearch::GetVertexIndex(
vtkAbstractArray *abstract,vtkVariant value)
{
// Okay now what type of array is it
if (abstract->IsNumeric())
{
vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract);
int intValue = value.ToInt();
for(int i=0; i<dataArray->GetNumberOfTuples(); ++i)
{
if (intValue == static_cast<int>(dataArray->GetTuple1(i)))
{
return i;
}
}
}
else
{
vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract);
vtkStdString stringValue(value.ToString());
for(int i=0; i<stringArray->GetNumberOfTuples(); ++i)
{
if (stringValue == stringArray->GetValue(i))
{
return i;
}
}
}
// Failed
vtkErrorMacro("Did not find a valid vertex index...");
return 0;
}
int vtkBoostBreadthFirstSearch::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkGraph *input = vtkGraph::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkGraph *output = vtkGraph::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
// Send the data to output.
output->ShallowCopy(input);
// Sanity check
// The Boost BFS likes to crash on empty datasets
if (input->GetNumberOfVertices() == 0)
{
//vtkWarningMacro("Empty input into " << this->GetClassName());
return 1;
}
if (this->OriginFromSelection)
{
vtkSelection* selection = vtkSelection::GetData(inputVector[1], 0);
if (selection == NULL)
{
vtkErrorMacro("OriginFromSelection set but selection input undefined.");
return 0;
}
if (selection->GetProperties()->Get(vtkSelection::CONTENT_TYPE()) != vtkSelection::GLOBALIDS ||
selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) != vtkSelection::POINT)
{
vtkErrorMacro("Selection must be point ids.");
return 0;
}
vtkAbstractArray* arr = selection->GetSelectionList();
if (arr == NULL)
{
vtkErrorMacro("Selection array is null");
return 0;
}
vtkIdTypeArray* idArr = vtkIdTypeArray::SafeDownCast(arr);
if (idArr == NULL)
{
vtkErrorMacro("Selection array is not a vtkIdTypeArray");
return 0;
}
if (idArr->GetNumberOfTuples() == 0)
{
vtkErrorMacro("Selection array has no elements");
return 0;
}
this->OriginVertexIndex = idArr->GetValue(0);
}
else
{
// Now figure out the origin vertex of the
// breadth first search
if (this->InputArrayName)
{
vtkAbstractArray* abstract = input->GetVertexData()->GetAbstractArray(this->InputArrayName);
// Does the array exist at all?
if (abstract == NULL)
{
vtkErrorMacro("Could not find array named " << this->InputArrayName);
return 0;
}
this->OriginVertexIndex = this->GetVertexIndex(abstract,this->OriginValue);
}
}
// Create the attribute array
vtkIntArray* BFSArray = vtkIntArray::New();
if (this->OutputArrayName)
{
BFSArray->SetName(this->OutputArrayName);
}
else
{
BFSArray->SetName("BFS");
}
BFSArray->SetNumberOfTuples(output->GetNumberOfVertices());
// Initialize the BFS array to all 0's
for(int i=0;i< BFSArray->GetNumberOfTuples(); ++i)
{
BFSArray->SetValue(i,0);
}
// Create a color map (used for marking visited nodes)
vector_property_map<default_color_type> color;
// Create a queue to hand off to the BFS
boost::queue<int> Q;
vtkIdType maxFromRootVertex, Root = 0;
my_distance_recorder<vtkIntArray*> bfsVisitor(BFSArray, &maxFromRootVertex);
// Is the graph directed or undirected
if (output->GetDirected())
{
vtkBoostDirectedGraph g(output);
breadth_first_search(g, this->OriginVertexIndex, Q, bfsVisitor, color);
}
else
{
vtkBoostUndirectedGraph g(output);
breadth_first_search(g, this->OriginVertexIndex, Q, bfsVisitor, color);
}
// Add attribute array to the output
output->GetVertexData()->AddArray(BFSArray);
BFSArray->Delete();
if (this->OutputSelection)
{
vtkSelection* sel = vtkSelection::GetData(outputVector, 1);
vtkIdTypeArray* ids = vtkIdTypeArray::New();
// Set the output based on the output selection type
if (!strcmp(OutputSelectionType,"MAX_DIST_FROM_ROOT"))
{
ids->InsertNextValue(maxFromRootVertex);
}
sel->SetSelectionList(ids);
sel->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), vtkSelection::GLOBALIDS);
sel->GetProperties()->Set(vtkSelection::FIELD_TYPE(), vtkSelection::POINT);
ids->Delete();
}
return 1;
}
void vtkBoostBreadthFirstSearch::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "OriginVertexIndex: " << this->OriginVertexIndex << endl;
os << indent << "InputArrayName: "
<< (this->InputArrayName ? this->InputArrayName : "(none)") << endl;
os << indent << "OutputArrayName: "
<< (this->OutputArrayName ? this->OutputArrayName : "(none)") << endl;
os << indent << "OriginValue: " << this->OriginValue.ToString() << endl;
os << indent << "OutputSelection: "
<< (this->OutputSelection ? "on" : "off") << endl;
os << indent << "OriginFromSelection: "
<< (this->OriginFromSelection ? "on" : "off") << endl;
os << indent << "OutputSelectionType: "
<< (this->OutputSelectionType ? this->OutputSelectionType : "(none)") << endl;
}
//----------------------------------------------------------------------------
int vtkBoostBreadthFirstSearch::FillInputPortInformation(
int port, vtkInformation* info)
{
// now add our info
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph");
}
else if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
}
return 1;
}
//----------------------------------------------------------------------------
int vtkBoostBreadthFirstSearch::FillOutputPortInformation(
int port, vtkInformation* info)
{
// now add our info
if (port == 0)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkGraph");
}
else if (port == 1)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkSelection");
}
return 1;
}
<|endoftext|> |
<commit_before>/***********************************************
* Author: Jun Jiang - [email protected]
* Create: 2017-07-27 14:48
* Last modified : 2017-07-27 14:48
* Filename : MatrixAlgebra.cpp
* Description :
**********************************************/
#include "algebra/MatrixHelper.h"
namespace abcdl{
namespace algebra{
template<class T>
void Matrix<T>::dot(const Matrix<T>& mat){
MatrixHelper<T> mh;
mh.dot(*this, *this, mat);
}
template<class T>
void Matrix<T>::outer(const Matrix<T>& mat){
MatrixHelper<T> mh;
mh.outer(*this, *this, mat);
}
template<class T>
void Matrix<T>::pow(const T& exponent){
MatrixHelper<T> mh;
mh.pow(*this, *this, exponent);
}
template<class T>
void Matrix<T>::log(){
MatrixHelper<T> mh;
mh.log(*this, *this);
}
template<class T>
void Matrix<T>::exp(){
MatrixHelper<T> mh;
mh.exp(*this, *this);
}
template<class T>
void Matrix<T>::sigmoid(){
MatrixHelper<T> mh;
mh.sigmoid(*this, *this);
}
template<class T>
void Matrix<T>::softmax(){
MatrixHelper<T> mh;
mh.softmax(*this, *this);
}
template<class T>
void Matrix<T>::tanh(){
MatrixHelper<T> mh;
mh.tanh(*this, *this);
}
template<class T>
void Matrix<T>::relu(){
MatrixHelper<T> mh;
mh.relu(*this, *this);
}
template<class T>
T Matrix<T>::sum() const{
T sum = 0;
auto lamda = [](T* a, const T& b){if(b != 0){ *a += b;} };
ParallelOperator po;
po.parallel_reduce_mul2one<T>(_data, get_size(), &sum, lamda);
return sum;
}
template<class T>
real Matrix<T>::mean() const{
return ((real)sum)/get_size();
}
void Matrix<T>::transpose(){
}
template class Matrix<int>;
template class Matrix<real>;
}//namespace algebra
}//namespace abcdl
<commit_msg>initialized<commit_after>/***********************************************
* Author: Jun Jiang - [email protected]
* Create: 2017-07-27 14:48
* Last modified : 2017-07-27 14:48
* Filename : MatrixAlgebra.cpp
* Description :
**********************************************/
#include "algebra/MatrixHelper.h"
namespace abcdl{
namespace algebra{
template<class T>
void Matrix<T>::dot(const Matrix<T>& mat){
MatrixHelper<T> mh;
mh.dot(*this, *this, mat);
}
template<class T>
void Matrix<T>::outer(const Matrix<T>& mat){
MatrixHelper<T> mh;
mh.outer(*this, *this, mat);
}
template<class T>
void Matrix<T>::pow(const T& exponent){
MatrixHelper<T> mh;
mh.pow(*this, *this, exponent);
}
template<class T>
void Matrix<T>::log(){
MatrixHelper<T> mh;
mh.log(*this, *this);
}
template<class T>
void Matrix<T>::exp(){
MatrixHelper<T> mh;
mh.exp(*this, *this);
}
template<class T>
void Matrix<T>::sigmoid(){
MatrixHelper<T> mh;
mh.sigmoid(*this, *this);
}
template<class T>
void Matrix<T>::softmax(){
MatrixHelper<T> mh;
mh.softmax(*this, *this);
}
template<class T>
void Matrix<T>::tanh(){
MatrixHelper<T> mh;
mh.tanh(*this, *this);
}
template<class T>
void Matrix<T>::relu(){
MatrixHelper<T> mh;
mh.relu(*this, *this);
}
template<class T>
T Matrix<T>::sum() const{
T sum = 0;
auto lamda = [](T* a, const T& b){if(b != 0){ *a += b;} };
utils::ParallelOperator po;
po.parallel_reduce_mul2one<T>(_data, get_size(), &sum, lamda);
return sum;
}
template<class T>
real Matrix<T>::mean() const{
return ((real)sum())/get_size();
}
template<class T>
void Matrix<T>::transpose(){
}
template class Matrix<int>;
template class Matrix<real>;
}//namespace algebra
}//namespace abcdl
<|endoftext|> |
<commit_before>/// @file
/// @author uentity
/// @date 26.02.2020
/// @brief Qt model helper impl
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/
#include <bs/log.h>
#include <bs/tree/context.h>
#include "tree_impl.h"
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/uuid_hash.hpp>
#include <boost/container_hash/hash.hpp>
#include <unordered_map>
NAMESPACE_BEGIN(blue_sky::tree)
auto to_string(const lids_v& path, bool as_absolute) -> std::string {
auto res = std::vector<std::string>(as_absolute ? path.size() + 1 : path.size());
std::transform(
path.begin(), path.end(),
as_absolute ? std::next(res.begin()) : res.begin(),
[](const auto& Lid) { return to_string(Lid); }
);
return boost::join(res, "/");
}
// convert string path to vector of lids
static auto to_lids_v(const std::string& path) -> lids_v {
[[maybe_unused]] static const auto uuid_from_str = boost::uuids::string_generator{};
auto path_split = std::vector< std::pair<std::string::const_iterator, std::string::const_iterator> >{};
boost::split(path_split, path, boost::is_any_of("/"));
if(path_split.empty()) return {};
auto from = path_split.begin();
const auto skip_first = from->first == from->second;
auto res = skip_first ? lids_v(path_split.size() - 1) : lids_v(path_split.size());
std::transform(
skip_first ? ++from : from, path_split.end(), res.begin(),
[](const auto& Lid) { return uuid_from_str(Lid.first, Lid.second); }
);
return res;
}
// enters data node only if allowed to (don't auto-expand lazy links)
static auto data_node(const link& L) -> sp_node {
if( L.req_status(Req::DataNode) == ReqStatus::OK || !(L.flags(unsafe) & LazyLoad) )
return L.data_node();
return nullptr;
}
// simple `deref_path` impl for vector of lids
template<typename PathIterator>
static auto deref_path(PathIterator from, PathIterator to, const link& root) -> link {
auto res = link{};
auto level = root;
for(; from != to; ++from) {
if(auto N = data_node(level)) {
if(( res = N->find(*from) ))
level = res;
else
break;
}
}
return res;
}
/*-----------------------------------------------------------------------------
* impl
*-----------------------------------------------------------------------------*/
struct BS_HIDDEN_API context::impl {
using path_t = lids_v;
using path_hash_t = boost::hash<path_t>;
using idata_t = std::unordered_map<path_t, link::weak_ptr, path_hash_t>;
idata_t idata_;
sp_node root_;
link root_lnk_;
///////////////////////////////////////////////////////////////////////////////
// ctors
//
impl(link root) :
root_(data_node(root)), root_lnk_(root)
{
verify();
}
impl(sp_node root) :
root_(std::move(root)), root_lnk_(link::make_root<hard_link>("/", root_))
{
verify();
}
auto verify() -> void {
if(!root_) {
if(root_lnk_) root_ = data_node(root_lnk_);
if(!root_) {
root_ = std::make_shared<node>();
root_lnk_.reset();
}
}
if(!root_lnk_)
root_lnk_ = link::make_root<hard_link>("/", root_);
}
auto reset(sp_node root, link root_handle) {
idata_.clear();
root_ = std::move(root);
root_lnk_ = root_handle;
verify();
}
auto push(path_t path, const link& item = {}) -> item_tag& {
auto [pos, is_inserted] = idata_.try_emplace(std::move(path), item);
// update existing tag if valid link passed in
if(!is_inserted && item)
pos->second = item;
// DEBUG
//dump();
return *pos;
}
decltype(auto) push(const path_t& base, lid_type leaf, const link& item = {}) {
auto leaf_path = path_t(base.size() + 1);
std::copy(base.begin(), base.end(), leaf_path.begin());
leaf_path.back() = std::move(leaf);
return push(std::move(leaf_path), item);
}
auto pop(const path_t& path) -> bool {
if(auto pos = idata_.find(path); pos != idata_.end()) {
idata_.erase(pos);
return true;
}
return false;
}
template<typename Item>
auto pop_item(const Item& item) -> std::size_t {
std::size_t cnt = 0;
for(auto pos = idata_.begin(); pos != idata_.end();) {
if(pos->second == item) {
idata_.erase(pos++);
++cnt;
}
else
++pos;
}
return cnt;
}
// searh idata for given link (no midifications are made)
auto find(const link& what) const -> existing_tag {
for(auto pos = idata_.begin(), end = idata_.end(); pos != end; ++pos) {
if(pos->second == what)
return &*pos;
}
return {};
}
auto make(const std::string& path, bool nonexact_match = false) -> item_index {
//bsout() << "*** index_from_path()" << bs_end;
auto level = root_;
auto res = item_index{{}, -1};
auto cur_subpath = std::string{};
auto push_subpath = [&](const std::string& next_lid, const sp_node& cur_level) {
if(auto item = level->find(next_lid, Key::ID)) {
cur_subpath += '/';
cur_subpath += next_lid;
res = { &push(to_lids_v(cur_subpath), item), level->index(item.id()).value_or(-1) };
return item;
}
return link{};
};
// walk down tree
detail::deref_path_impl(path, root_lnk_, root_, false, std::move(push_subpath));
return nonexact_match || path == cur_subpath ? res : item_index{{}, -1};
}
auto make(const link& L, std::string path_hint = "/") -> item_index {
//bsout() << "*** index_from_link()" << bs_end;
// make path hint start relative to current model root
// [NOTE] including leading slash!
auto rootp = abspath(root_lnk_, Key::ID);
// if path_hint.startswith(rootp)
if(path_hint.size() >= rootp.size() && std::equal(rootp.begin(), rootp.end(), path_hint.begin()))
path_hint = path_hint.substr(rootp.size());
// get search starting point & ensure it's cached in idata
auto start_tag = make(path_hint, true).first;
auto start_link = start_tag ? (**start_tag).second.lock() : root_lnk_;
// walk down from start node and do step-by-step search for link
// all intermediate paths are added to `idata`
auto res = item_index{{}, -1};
auto develop_link = [&, Lid = L.id()](link R, std::list<link>& nodes, std::vector<link>& objs)
mutable {
// get current root path
auto R_path = path_t{};
if(auto R_tag = find(R))
R_path = (**R_tag).first;
else {
nodes.clear();
return;
}
// leaf checker
bool found = false;
const auto check_link = [&](auto& item) {
if(item.id() == Lid) {
if(auto Rnode = data_node(R)) {
if(auto row = Rnode->index(Lid)) {
res = { &push(R_path, std::move(Lid), item), *row };
found = true;
}
}
}
return found;
};
// check each leaf (both nodes & links)
for(const auto& N : nodes) { if(check_link(N)) break; }
if(!found) {
for(const auto& O : objs) { if(check_link(O)) break; }
}
// if we found a link, stop further iterations
if(found) nodes.clear();
};
walk(start_link, develop_link);
return res;
}
auto make(std::int64_t row, existing_tag parent) -> existing_tag {
//bsout() << "*** index()" << bs_end;
// extract parent node & path
// [NOTE] empty parent means root
auto parent_node = sp_node{};
if(auto parent_link = (parent ? (**parent).second.lock() : root_lnk_))
parent_node = data_node(parent_link);
if(!parent_node) return {};
// obtain child link
auto child_link = [&] {
if(auto par_sz = (std::int64_t)parent_node->size(); row < par_sz) {
// sometimes we can get negative row, it just means last element
if(row < 0) row = par_sz - 1;
if(row >= 0) return parent_node->find((std::size_t)row);
}
return link{};
}();
if(child_link)
return &push(parent_node != root_ ? (**parent).first : lids_v{}, child_link.id(), child_link);
return {};
}
auto make(const item_tag& child) -> item_index {
// obtain parent
auto parent_node = child.second.lock().owner();
if(!parent_node || parent_node == root_) return {{}, -1};
// child path have to consist at least of two parts
// if it contains one part, then parent is hidden root
const auto& child_path = child.first;
if(child_path.size() < 2) return {};
// extract grandparent, it's ID is child_path[-3]
auto grandpa_node = [&] {
if(child_path.size() < 3)
return root_;
else {
auto grandpa_link = deref_path(child_path.begin(), child_path.end() - 2, root_lnk_);
return grandpa_link ? data_node(grandpa_link) : sp_node{};
}
}();
if(!grandpa_node) return {};
// parent's ID is child_path[-2]
if(auto parent_link = grandpa_node->find(*(child_path.end() - 2)))
return {
&push(lids_v(child_path.begin(), child_path.end() - 1), parent_link),
grandpa_node->index(parent_link.id()).value_or(-1)
};
return {{}, -1};
}
auto make(existing_tag child) -> item_index {
//bsout() << "*** parent()" << bs_end;
return child ? make(**child) : item_index{{}, -1};
}
auto dump() const -> void {
for(const auto& [p, l] : idata_) {
auto L = l.lock();
if(!L) continue;
bsout() << "{} -> [{}, {}]" << to_string(p) << to_string(L.id()) << L.name(unsafe) << bs_end;
}
bsout() << "====" << bs_end;
}
};
/*-----------------------------------------------------------------------------
* context
*-----------------------------------------------------------------------------*/
context::context(sp_node root) :
pimpl_{std::make_unique<impl>(std::move(root))}
{}
context::context(link root) :
pimpl_{std::make_unique<impl>(std::move(root))}
{}
context::~context() = default;
auto context::reset(link root) -> void {
pimpl_->reset(nullptr, root);
}
auto context::reset(sp_node root, link root_handle) -> void {
pimpl_->reset(std::move(root), root_handle);
}
auto context::root() const -> sp_node {
return pimpl_->root_;
}
auto context::root_link() const -> link {
return pimpl_->root_lnk_;
}
auto context::root_path(Key path_unit) const -> std::string {
return abspath(pimpl_->root_lnk_, path_unit);
}
/// make tag for given path
auto context::operator()(const std::string& path, bool nonexact_match) -> item_index {
return pimpl_->make(path, nonexact_match);
}
/// for given link + possible hint
auto context::operator()(const link& L, std::string path_hint) -> item_index {
return pimpl_->make(L, std::move(path_hint));
}
/// helper for abstrct model's `index()`
auto context::operator()(std::int64_t row, existing_tag parent) -> existing_tag {
return pimpl_->make(row, parent);
}
/// for `parent()`
auto context::operator()(existing_tag child) -> item_index {
return pimpl_->make(child);
}
auto context::dump() const -> void {
pimpl_->dump();
}
NAMESPACE_END(blue_sky::tree)
<commit_msg>tree/context: fix tag from link recovery<commit_after>/// @file
/// @author uentity
/// @date 26.02.2020
/// @brief Qt model helper impl
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/
#include <bs/log.h>
#include <bs/tree/context.h>
#include "tree_impl.h"
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/uuid_hash.hpp>
#include <boost/container_hash/hash.hpp>
#include <unordered_map>
NAMESPACE_BEGIN(blue_sky::tree)
auto to_string(const lids_v& path, bool as_absolute) -> std::string {
auto res = std::vector<std::string>(as_absolute ? path.size() + 1 : path.size());
std::transform(
path.begin(), path.end(),
as_absolute ? std::next(res.begin()) : res.begin(),
[](const auto& Lid) { return to_string(Lid); }
);
return boost::join(res, "/");
}
// convert string path to vector of lids
static auto to_lids_v(const std::string& path) -> lids_v {
[[maybe_unused]] static const auto uuid_from_str = boost::uuids::string_generator{};
auto path_split = std::vector< std::pair<std::string::const_iterator, std::string::const_iterator> >{};
boost::split(path_split, path, boost::is_any_of("/"));
if(path_split.empty()) return {};
auto from = path_split.begin();
const auto skip_first = from->first == from->second;
auto res = skip_first ? lids_v(path_split.size() - 1) : lids_v(path_split.size());
std::transform(
skip_first ? ++from : from, path_split.end(), res.begin(),
[](const auto& Lid) { return uuid_from_str(Lid.first, Lid.second); }
);
return res;
}
// enters data node only if allowed to (don't auto-expand lazy links)
static auto data_node(const link& L) -> sp_node {
if( L.req_status(Req::DataNode) == ReqStatus::OK || !(L.flags(unsafe) & LazyLoad) )
return L.data_node();
return nullptr;
}
// simple `deref_path` impl for vector of lids
template<typename PathIterator>
static auto deref_path(PathIterator from, PathIterator to, const link& root) -> link {
auto res = link{};
auto level = root;
for(; from != to; ++from) {
if(auto N = data_node(level)) {
if(( res = N->find(*from) ))
level = res;
else
break;
}
}
return res;
}
/*-----------------------------------------------------------------------------
* impl
*-----------------------------------------------------------------------------*/
struct BS_HIDDEN_API context::impl {
using path_t = lids_v;
using path_hash_t = boost::hash<path_t>;
using idata_t = std::unordered_map<path_t, link::weak_ptr, path_hash_t>;
idata_t idata_;
sp_node root_;
link root_lnk_;
///////////////////////////////////////////////////////////////////////////////
// ctors
//
impl(link root) :
root_(data_node(root)), root_lnk_(root)
{
verify();
}
impl(sp_node root) :
root_(std::move(root)), root_lnk_(link::make_root<hard_link>("/", root_))
{
verify();
}
auto verify() -> void {
if(!root_) {
if(root_lnk_) root_ = data_node(root_lnk_);
if(!root_) {
root_ = std::make_shared<node>();
root_lnk_.reset();
}
}
if(!root_lnk_)
root_lnk_ = link::make_root<hard_link>("/", root_);
}
auto reset(sp_node root, link root_handle) {
idata_.clear();
root_ = std::move(root);
root_lnk_ = root_handle;
verify();
}
auto push(path_t path, const link& item = {}) -> item_tag& {
auto [pos, is_inserted] = idata_.try_emplace(std::move(path), item);
// update existing tag if valid link passed in
if(!is_inserted && item)
pos->second = item;
// DEBUG
//dump();
return *pos;
}
decltype(auto) push(const path_t& base, lid_type leaf, const link& item = {}) {
auto leaf_path = path_t(base.size() + 1);
std::copy(base.begin(), base.end(), leaf_path.begin());
leaf_path.back() = std::move(leaf);
return push(std::move(leaf_path), item);
}
auto pop(const path_t& path) -> bool {
if(auto pos = idata_.find(path); pos != idata_.end()) {
idata_.erase(pos);
return true;
}
return false;
}
template<typename Item>
auto pop_item(const Item& item) -> std::size_t {
std::size_t cnt = 0;
for(auto pos = idata_.begin(); pos != idata_.end();) {
if(pos->second == item) {
idata_.erase(pos++);
++cnt;
}
else
++pos;
}
return cnt;
}
// searh idata for given link (no midifications are made)
auto find(const link& what) const -> existing_tag {
for(auto pos = idata_.begin(), end = idata_.end(); pos != end; ++pos) {
if(pos->second == what)
return &*pos;
}
return {};
}
auto make(const std::string& path, bool nonexact_match = false) -> item_index {
//bsout() << "*** index_from_path()" << bs_end;
auto level = root_;
auto res = item_index{{}, -1};
auto cur_subpath = std::string{};
auto push_subpath = [&](const std::string& next_lid, const sp_node& cur_level) {
if(auto item = level->find(next_lid, Key::ID)) {
cur_subpath += '/';
cur_subpath += next_lid;
res = { &push(to_lids_v(cur_subpath), item), level->index(item.id()).value_or(-1) };
return item;
}
return link{};
};
// walk down tree
detail::deref_path_impl(path, root_lnk_, root_, false, std::move(push_subpath));
return nonexact_match || path == cur_subpath ? res : item_index{{}, -1};
}
auto make(const link& L, std::string path_hint = "/") -> item_index {
//bsout() << "*** index_from_link()" << bs_end;
// make path hint start relative to current model root
// [NOTE] including leading slash!
auto rootp = abspath(root_lnk_, Key::ID);
// if path_hint.startswith(rootp)
if(path_hint.size() >= rootp.size() && std::equal(rootp.begin(), rootp.end(), path_hint.begin()))
path_hint = path_hint.substr(rootp.size());
// get search starting point & ensure it's cached in idata
auto start_tag = make(path_hint, true).first;
auto start_link = start_tag ? (**start_tag).second.lock() : root_lnk_;
// walk down from start node and do step-by-step search for link
// all intermediate paths are added to `idata`
auto res = item_index{{}, -1};
auto develop_link = [&, Lid = L.id()](link R, std::list<link>& nodes, std::vector<link>& objs)
mutable {
// get current root path
auto R_path = path_t{};
if(auto R_tag = find(R))
R_path = (**R_tag).first;
else if(R != root_lnk_) {
nodes.clear();
return;
}
// leaf checker
bool found = false;
const auto check_link = [&](auto& item) {
if(item.id() == Lid) {
if(auto Rnode = data_node(R)) {
if(auto row = Rnode->index(Lid)) {
res = { &push(R_path, std::move(Lid), item), *row };
found = true;
}
}
}
return found;
};
// check each leaf (both nodes & links)
for(const auto& N : nodes) { if(check_link(N)) break; }
if(!found) {
for(const auto& O : objs) { if(check_link(O)) break; }
}
// if we found a link, stop further iterations
if(found) nodes.clear();
};
walk(start_link, develop_link);
return res;
}
auto make(std::int64_t row, existing_tag parent) -> existing_tag {
//bsout() << "*** index()" << bs_end;
// extract parent node & path
// [NOTE] empty parent means root
auto parent_node = sp_node{};
if(auto parent_link = (parent ? (**parent).second.lock() : root_lnk_))
parent_node = data_node(parent_link);
if(!parent_node) return {};
// obtain child link
auto child_link = [&] {
if(auto par_sz = (std::int64_t)parent_node->size(); row < par_sz) {
// sometimes we can get negative row, it just means last element
if(row < 0) row = par_sz - 1;
if(row >= 0) return parent_node->find((std::size_t)row);
}
return link{};
}();
if(child_link)
return &push(parent_node != root_ ? (**parent).first : lids_v{}, child_link.id(), child_link);
return {};
}
auto make(const item_tag& child) -> item_index {
// obtain parent
auto parent_node = child.second.lock().owner();
if(!parent_node || parent_node == root_) return {{}, -1};
// child path have to consist at least of two parts
// if it contains one part, then parent is hidden root
const auto& child_path = child.first;
if(child_path.size() < 2) return {};
// extract grandparent, it's ID is child_path[-3]
auto grandpa_node = [&] {
if(child_path.size() < 3)
return root_;
else {
auto grandpa_link = deref_path(child_path.begin(), child_path.end() - 2, root_lnk_);
return grandpa_link ? data_node(grandpa_link) : sp_node{};
}
}();
if(!grandpa_node) return {};
// parent's ID is child_path[-2]
if(auto parent_link = grandpa_node->find(*(child_path.end() - 2)))
return {
&push(lids_v(child_path.begin(), child_path.end() - 1), parent_link),
grandpa_node->index(parent_link.id()).value_or(-1)
};
return {{}, -1};
}
auto make(existing_tag child) -> item_index {
//bsout() << "*** parent()" << bs_end;
return child ? make(**child) : item_index{{}, -1};
}
auto dump() const -> void {
for(const auto& [p, l] : idata_) {
auto L = l.lock();
if(!L) continue;
bsout() << "{} -> [{}, {}]" << to_string(p) << to_string(L.id()) << L.name(unsafe) << bs_end;
}
bsout() << "====" << bs_end;
}
};
/*-----------------------------------------------------------------------------
* context
*-----------------------------------------------------------------------------*/
context::context(sp_node root) :
pimpl_{std::make_unique<impl>(std::move(root))}
{}
context::context(link root) :
pimpl_{std::make_unique<impl>(std::move(root))}
{}
context::~context() = default;
auto context::reset(link root) -> void {
pimpl_->reset(nullptr, root);
}
auto context::reset(sp_node root, link root_handle) -> void {
pimpl_->reset(std::move(root), root_handle);
}
auto context::root() const -> sp_node {
return pimpl_->root_;
}
auto context::root_link() const -> link {
return pimpl_->root_lnk_;
}
auto context::root_path(Key path_unit) const -> std::string {
return abspath(pimpl_->root_lnk_, path_unit);
}
/// make tag for given path
auto context::operator()(const std::string& path, bool nonexact_match) -> item_index {
return pimpl_->make(path, nonexact_match);
}
/// for given link + possible hint
auto context::operator()(const link& L, std::string path_hint) -> item_index {
return pimpl_->make(L, std::move(path_hint));
}
/// helper for abstrct model's `index()`
auto context::operator()(std::int64_t row, existing_tag parent) -> existing_tag {
return pimpl_->make(row, parent);
}
/// for `parent()`
auto context::operator()(existing_tag child) -> item_index {
return pimpl_->make(child);
}
auto context::dump() const -> void {
pimpl_->dump();
}
NAMESPACE_END(blue_sky::tree)
<|endoftext|> |
<commit_before>//
// Copyright (C) 2013-2016 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "odsimporter.h"
#include "sharedmemory.h"
#include "ods/odsxmlmanifesthandler.h"
#include "ods/odsxmlcontentshandler.h"
#include "filereader.h"
#include <QXmlInputSource>
using namespace std;
using namespace boost;
using namespace ods;
//Data * ODSImporter::_dta = 0;
ODSImporter::ODSImporter(DataSetPackage *packageData)
: Importer(packageData)
{
// Spreadsheet files are never JASP archives.
packageData->isArchive = false;
}
ODSImporter::~ODSImporter()
{
}
/* Redundant, 11-01-2017
void ODSImporter::loadDataSet(
DataSetPackage *packageData,
const string &locator,
boost::function<void (const string &, int)> progress
)
{
packageData->isArchive = false; // Spreadsheet files are never JASP archives.
// Build our data collection object.
try
{
if (_dta != 0)
delete _dta;
_dta = new Data();
// Check mnaifest for the contents file.
progress("Reading ODS manifest.", 0);
readManifest(packageData, locator);
// Read the sheet contents.
progress("Reading ODS contents.", 2);
readContents(locator);
// Process and pass to app.
progress("Reading ODS contents.", 80);
vector<Data::JaspColumn> colMeta = _dta->process();
// Importing
// Init the data set
bool success = false;
packageData->dataSet = SharedMemory::createDataSet();
do
{
try
{
success = true;
packageData->dataSet->setColumnCount(_dta->sheet().numColumns());
packageData->dataSet->setRowCount(_dta->sheet().numRows());
}
catch (boost::interprocess::bad_alloc &e)
{
try {
packageData->dataSet = SharedMemory::enlargeDataSet(packageData->dataSet);
success = false;
}
catch (std::exception &e)
{
throw runtime_error("Out of memory: This data set is too large for your computer's available memory.");
}
}
catch (std::exception &e)
{
cout << "n " << e.what() << "\n";
cout.flush();
}
catch (...)
{
cout << "something else\n ";
cout.flush();
}
}
while (success == false);
// Got enough memory, set up the colums and data.
const Data::Sheet &sheet = _dta->sheet();
for (int columnNumber = 0; columnNumber < sheet.numColumns(); columnNumber++)
{
Column &jaspCol = packageData->dataSet->column(columnNumber);
jaspCol.labels().clear();
jaspCol.setName(colMeta[columnNumber].lable());
jaspCol.setColumnType(colMeta[columnNumber].type());
const Data::SheetColumn &sheetCol = sheet[columnNumber];
switch(colMeta[columnNumber].type())
{
case Column::ColumnTypeNominalText:
// insert all the strings as labels.
for (int i = 0; i < sheetCol.numberLabels(); i++)
jaspCol.labels().add(sheetCol.labelAt(i));
// Drop through!
case Column::ColumnTypeNominal:
case Column::ColumnTypeOrdinal:
{
// Insert integer values, inserting empty where the column has no rows.
Column::Ints::iterator addIter = jaspCol.AsInts.begin();
for (int rowCnt = 1; rowCnt <= sheet.maxRow(); rowCnt++)
{
if ((rowCnt < sheetCol.minRow()) || (rowCnt > sheetCol.maxRow()))
*addIter = Data::SheetCellLong::EmptyInt;
else
*addIter = _dta->sheet()[columnNumber].valueAsInt(rowCnt);\
addIter++;
}
}
break;
case Column::ColumnTypeScale:
{
// Insert double values, inserting empty where the column has no rows.
Column::Doubles::iterator addIter = jaspCol.AsDoubles.begin();
for (int rowCnt = 1; rowCnt <= sheet.maxRow(); rowCnt++)
{
if ((rowCnt < sheetCol.minRow()) || (rowCnt > sheetCol.maxRow()))
*addIter = Data::SheetCellLong::EmptyDouble;
else
*addIter = _dta->sheet()[columnNumber].valueAsDouble(rowCnt);
addIter++;
}
}
case Column::ColumnTypeUnknown:
break;
}
}
}
catch(...)
{
delete _dta;
_dta = 0;
throw;
}
} */
// Implmemtation of Inporter base class.
ImportDataSet* ODSImporter::loadFile(const string &locator, boost::function<void(const string &, int)> progressCallback)
{
// Create new data set.
ODSImportDataSet * result = new ODSImportDataSet();
// Check mnaifest for the contents file.
progressCallback("Reading ODS manifest.", 0);
readManifest(locator, result);
// Read the sheet contents.
progressCallback("Reading ODS contents.", 33);
readContents(locator, result);
// Do post load processing:
progressCallback("Processing.", 60);
result->postLoadProcess();
// Build the dictionary for sync.
result->buildDictionary();
return result;
}
void ODSImporter::fillSharedMemoryColumn(ImportColumn *importColumn, Column &column)
{
const ODSImportColumn &impCol = static_cast<const ODSImportColumn &> (*importColumn);
column.setColumnType( impCol.getJASPColumnType() );
column.labels().clear();
// Pass the message on to the columns, and find the maximum rows/cases.
impCol.fillSharedMemoryColumn(column);
}
void ODSImporter::readManifest(const string &path, ODSImportDataSet *dataset)
{
QXmlInputSource src;
{
// Get the data file proper from the ODS manifest file.
FileReader manifest(path, ODSImportDataSet::manifestPath);
QString tmp;
int errorCode = 0;
if (((tmp = manifest.readAllData(errorCode)).size() == 0) || (errorCode < 0))
throw runtime_error("Error reading manifest in ODS.");
src.setData(tmp);
manifest.close();
}
{
XmlManifestHandler * manHandler = new XmlManifestHandler(dataset);
QXmlSimpleReader reader;
reader.setContentHandler(manHandler);
reader.setErrorHandler(manHandler);
reader.parse(src);
}
}
void ODSImporter::readContents(const string &path, ODSImportDataSet *dataset)
{
FileReader contents(path, dataset->getContentFilename());
QXmlInputSource src;
{
QString tmp;
int errorCode = 0;
if (((tmp = contents.readAllData(errorCode)).size() == 0) || (errorCode < 0))
throw runtime_error("Error reading contents in ODS.");
src.setData(tmp);
}
{
XmlContentsHandler * contentsHandler = new XmlContentsHandler(dataset);
QXmlSimpleReader reader;
reader.setContentHandler(contentsHandler);
reader.setErrorHandler(contentsHandler);
reader.parse(src);
}
contents.close();
}
<commit_msg>removed redundant code<commit_after>//
// Copyright (C) 2013-2016 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "odsimporter.h"
#include "sharedmemory.h"
#include "ods/odsxmlmanifesthandler.h"
#include "ods/odsxmlcontentshandler.h"
#include "filereader.h"
#include <QXmlInputSource>
using namespace std;
using namespace boost;
using namespace ods;
//Data * ODSImporter::_dta = 0;
ODSImporter::ODSImporter(DataSetPackage *packageData)
: Importer(packageData)
{
// Spreadsheet files are never JASP archives.
packageData->isArchive = false;
}
ODSImporter::~ODSImporter()
{
}
// Implmemtation of Inporter base class.
ImportDataSet* ODSImporter::loadFile(const string &locator, boost::function<void(const string &, int)> progressCallback)
{
// Create new data set.
ODSImportDataSet * result = new ODSImportDataSet();
// Check mnaifest for the contents file.
progressCallback("Reading ODS manifest.", 0);
readManifest(locator, result);
// Read the sheet contents.
progressCallback("Reading ODS contents.", 33);
readContents(locator, result);
// Do post load processing:
progressCallback("Processing.", 60);
result->postLoadProcess();
// Build the dictionary for sync.
result->buildDictionary();
return result;
}
void ODSImporter::fillSharedMemoryColumn(ImportColumn *importColumn, Column &column)
{
const ODSImportColumn &impCol = static_cast<const ODSImportColumn &> (*importColumn);
column.setColumnType( impCol.getJASPColumnType() );
column.labels().clear();
// Pass the message on to the columns, and find the maximum rows/cases.
impCol.fillSharedMemoryColumn(column);
}
void ODSImporter::readManifest(const string &path, ODSImportDataSet *dataset)
{
QXmlInputSource src;
{
// Get the data file proper from the ODS manifest file.
FileReader manifest(path, ODSImportDataSet::manifestPath);
QString tmp;
int errorCode = 0;
if (((tmp = manifest.readAllData(errorCode)).size() == 0) || (errorCode < 0))
throw runtime_error("Error reading manifest in ODS.");
src.setData(tmp);
manifest.close();
}
{
XmlManifestHandler * manHandler = new XmlManifestHandler(dataset);
QXmlSimpleReader reader;
reader.setContentHandler(manHandler);
reader.setErrorHandler(manHandler);
reader.parse(src);
}
}
void ODSImporter::readContents(const string &path, ODSImportDataSet *dataset)
{
FileReader contents(path, dataset->getContentFilename());
QXmlInputSource src;
{
QString tmp;
int errorCode = 0;
if (((tmp = contents.readAllData(errorCode)).size() == 0) || (errorCode < 0))
throw runtime_error("Error reading contents in ODS.");
src.setData(tmp);
}
{
XmlContentsHandler * contentsHandler = new XmlContentsHandler(dataset);
QXmlSimpleReader reader;
reader.setContentHandler(contentsHandler);
reader.setErrorHandler(contentsHandler);
reader.parse(src);
}
contents.close();
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include "vesa_console.hpp"
#include "vesa.hpp"
#include "early_memory.hpp"
namespace {
constexpr const size_t MARGIN = 10;
constexpr const size_t PADDING = 5;
constexpr const size_t LEFT = MARGIN + PADDING;
constexpr const size_t TOP = 40;
size_t _lines;
size_t _columns;
uint32_t _color;
size_t buffer_size;
} //end of anonymous namespace
void vesa_console::init(){
auto& block = *reinterpret_cast<vesa::mode_info_block_t*>(early::vesa_mode_info_address);
_columns = (block.width - (MARGIN + PADDING) * 2) / 8;
_lines = (block.height - TOP - MARGIN - PADDING) / 16;
_color = vesa::make_color(0, 255, 0);
buffer_size = block.height * block.bytes_per_scan_line;
vesa::draw_hline(MARGIN, MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, 35, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, block.height - MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_vline(MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
vesa::draw_vline(block.width - MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
auto title_left = (block.width - 4 * 8) / 2;
vesa::draw_char(title_left, PADDING + MARGIN, 'T', _color);
vesa::draw_char(title_left + 8, PADDING + MARGIN, 'H', _color);
vesa::draw_char(title_left + 16, PADDING + MARGIN, 'O', _color);
vesa::draw_char(title_left + 24, PADDING + MARGIN, 'R', _color);
}
size_t vesa_console::lines(){
return _lines;
}
size_t vesa_console::columns(){
return _columns;
}
void vesa_console::clear(){
vesa::draw_rect(LEFT, TOP, _columns * 8, _lines* 16, 0, 0, 0);
}
void vesa_console::scroll_up(){
vesa::move_lines_up(TOP + 16, LEFT, _columns * 8, (_lines - 1) * 16, 16);
vesa::draw_rect(LEFT, TOP + (_lines - 1) * 16, _columns * 8, 16, 0, 0, 0);
}
void vesa_console::print_char(size_t line, size_t column, char c){
vesa::draw_char(LEFT + 8 * column, TOP + 16 * line, c, _color);
}
void* vesa_console::save(void* buffer){
void* buffer32 = static_cast<uint32_t*>(buffer);
if(!buffer32){
buffer32 = new uint32_t[buffer_size];
}
vesa::save(static_cast<char*>(buffer32));
return buffer32;
}
void vesa_console::restore(void* buffer){
vesa::redraw(static_cast<char*>(buffer));
}
<commit_msg>Reformat<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include "vesa_console.hpp"
#include "vesa.hpp"
#include "early_memory.hpp"
namespace {
constexpr const size_t MARGIN = 10;
constexpr const size_t PADDING = 5;
constexpr const size_t LEFT = MARGIN + PADDING;
constexpr const size_t TOP = 40;
// Constants extracted from VESA
size_t _lines;
size_t _columns;
uint32_t _color;
size_t buffer_size;
} //end of anonymous namespace
void vesa_console::init() {
auto& block = *reinterpret_cast<vesa::mode_info_block_t*>(early::vesa_mode_info_address);
_columns = (block.width - (MARGIN + PADDING) * 2) / 8;
_lines = (block.height - TOP - MARGIN - PADDING) / 16;
_color = vesa::make_color(0, 255, 0);
buffer_size = block.height * block.bytes_per_scan_line;
vesa::draw_hline(MARGIN, MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, 35, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, block.height - MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_vline(MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
vesa::draw_vline(block.width - MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
auto title_left = (block.width - 4 * 8) / 2;
vesa::draw_char(title_left, PADDING + MARGIN, 'T', _color);
vesa::draw_char(title_left + 8, PADDING + MARGIN, 'H', _color);
vesa::draw_char(title_left + 16, PADDING + MARGIN, 'O', _color);
vesa::draw_char(title_left + 24, PADDING + MARGIN, 'R', _color);
}
size_t vesa_console::lines() {
return _lines;
}
size_t vesa_console::columns() {
return _columns;
}
void vesa_console::clear() {
vesa::draw_rect(LEFT, TOP, _columns * 8, _lines * 16, 0, 0, 0);
}
void vesa_console::scroll_up() {
vesa::move_lines_up(TOP + 16, LEFT, _columns * 8, (_lines - 1) * 16, 16);
vesa::draw_rect(LEFT, TOP + (_lines - 1) * 16, _columns * 8, 16, 0, 0, 0);
}
void vesa_console::print_char(size_t line, size_t column, char c) {
vesa::draw_char(LEFT + 8 * column, TOP + 16 * line, c, _color);
}
void* vesa_console::save(void* buffer) {
void* buffer32 = static_cast<uint32_t*>(buffer);
if (!buffer32) {
buffer32 = new uint32_t[buffer_size];
}
vesa::save(static_cast<char*>(buffer32));
return buffer32;
}
void vesa_console::restore(void* buffer) {
vesa::redraw(static_cast<char*>(buffer));
}
<|endoftext|> |
<commit_before>//
// Created by Darren Otgaar on 2018/04/15.
//
#ifndef ZAP_RENDER_BATCH_HPP
#define ZAP_RENDER_BATCH_HPP
#include <array>
#include <engine/index_buffer.hpp>
#include <engine/vertex_buffer.hpp>
#include <engine/accessor.hpp>
#include <engine/mesh.hpp>
namespace zap { namespace renderer {
template <typename VertexStreamT, typename IndexBufferT=void, size_t Count=VertexStreamT::count>
class render_batch;
template <typename VertexStreamT>
class render_batch<VertexStreamT, void, 1> {
public:
using stream_t = VertexStreamT;
static constexpr size_t count = 1;
using vbuf_t = typename engine::stream_query<0, stream_t>::type;
using vertex_t = typename vbuf_t::type;
using mesh_t = engine::mesh<VertexStreamT>;
using vbuf_acc_t = engine::accessor<vbuf_t>;
using range = engine::range;
using primitive_type = engine::primitive_type;
struct token {
uint32_t id;
primitive_type type;
range vtx_range;
operator bool() const { return is_valid(); }
bool is_valid() const { return id != INVALID_IDX; }
void clear() { id = INVALID_IDX; }
token() = default;
token(uint32_t id, primitive_type pt, const range& vrange) : id(id), type(pt), vtx_range(vrange) { }
};
static const token invalid_token;
render_batch() = default;
~render_batch() = default;
const token& get_token(uint32_t id) const {
return id < batch_.size() && batch_[id].is_valid() ? batch_[id] : invalid_token;
}
bool initialise(uint32_t vertex_count, engine::buffer_usage usage=engine::buffer_usage::BU_STATIC_DRAW) {
mesh_ = engine::make_mesh<vertex_t>(size_t(vertex_count), usage);
if(!mesh_.is_allocated()) return false;
vbuf_ptr_ = mesh_.vstream.ptr;
vbuf_acc_.initialise(vbuf_ptr_);
return true;
}
token allocate(primitive_type type, uint32_t count) {
auto rng = vbuf_acc_.allocate(count);
if(rng.is_valid()) {
uint32_t id = search_free_ ? find_free() : INVALID_IDX;
if(id == INVALID_IDX) {
id = uint32_t(batch_.size());
batch_.push_back(token(id, type, rng));
} else {
batch_[id] = token(id, type, rng);
}
return batch_[id];
}
return invalid_token;
}
void bind() { mesh_.bind(); }
void release() { mesh_.release(); }
bool map_read() { return vbuf_acc_.map_read(); }
bool map_write() { return vbuf_acc_.map_write(); }
bool map_readwrite() { return vbuf_acc_.map_readwrite(); }
bool map_read(const token& tok) { return vbuf_acc_.map_read(tok.vtx_range); }
bool map_write(const token& tok) { return vbuf_acc_.map_write(tok.vtx_range); }
bool map_readwrite(const token tok) { return vbuf_acc_.map_readwrite(tok.vtx_range); }
bool unmap() { return vbuf_acc_.unmap(); }
void set(const token& tok, uint32_t offset, const vertex_t& v) { vbuf_acc_.set(tok.vtx_range, offset, v); }
void set(const token& tok, uint32_t offset, uint32_t count, const vertex_t* p) { vbuf_acc_.set(tok.vtx_range, count, p); }
void set(const token& tok, uint32_t offset, const std::vector<vertex_t>& v) { vbuf_acc_.set(tok.vtx_range, 0, v); }
void draw(const token& tok) { mesh_.draw(tok.type, tok.vtx_range.start, tok.vtx_range.count); }
protected:
uint32_t find_free() const {
auto it = std::find_if(batch_.begin(), batch_.end(), [](const auto& tk){ return !tk.is_valid(); });
return it != batch_.end() ? uint32_t(it - batch_.begin()) : INVALID_IDX;
}
private:
mesh_t mesh_;
vbuf_t* vbuf_ptr_ = nullptr;
engine::accessor<vbuf_t> vbuf_acc_;
std::vector<token> batch_;
bool search_free_ = false;
};
template <typename VertexStreamT>
const typename render_batch<VertexStreamT, void, 1>::token render_batch<VertexStreamT, void, 1>::invalid_token = {INVALID_IDX, engine::primitive_type::PT_NONE, engine::range()};
}}
#endif //ZAP_RENDER_BATCH_HPP
<commit_msg>- Fixed ptr initialiser for render_batch<commit_after>//
// Created by Darren Otgaar on 2018/04/15.
//
#ifndef ZAP_RENDER_BATCH_HPP
#define ZAP_RENDER_BATCH_HPP
#include <array>
#include <engine/index_buffer.hpp>
#include <engine/vertex_buffer.hpp>
#include <engine/accessor.hpp>
#include <engine/mesh.hpp>
namespace zap { namespace renderer {
template <typename VertexStreamT, typename IndexBufferT=void, size_t Count=VertexStreamT::count>
class render_batch;
template <typename VertexStreamT>
class render_batch<VertexStreamT, void, 1> {
public:
using stream_t = VertexStreamT;
static constexpr size_t count = 1;
using vbuf_t = typename engine::stream_query<0, stream_t>::type;
using vertex_t = typename vbuf_t::type;
using mesh_t = engine::mesh<VertexStreamT>;
using vbuf_acc_t = engine::accessor<vbuf_t>;
using range = engine::range;
using primitive_type = engine::primitive_type;
struct token {
uint32_t id;
primitive_type type;
range vtx_range;
operator bool() const { return is_valid(); }
bool is_valid() const { return id != INVALID_IDX; }
void clear() { id = INVALID_IDX; }
token() = default;
token(uint32_t id, primitive_type pt, const range& vrange) : id(id), type(pt), vtx_range(vrange) { }
};
static const token invalid_token;
render_batch() = default;
~render_batch() = default;
const token& get_token(uint32_t id) const {
return id < batch_.size() && batch_[id].is_valid() ? batch_[id] : invalid_token;
}
bool initialise(uint32_t vertex_count, engine::buffer_usage usage=engine::buffer_usage::BU_STATIC_DRAW) {
mesh_ = engine::make_mesh<vertex_t>(size_t(vertex_count), usage);
if(!mesh_.is_allocated()) return false;
vbuf_ptr_ = mesh_.vstream.ptr;
vbuf_acc_.initialise(vbuf_ptr_);
return true;
}
token allocate(primitive_type type, uint32_t count) {
auto rng = vbuf_acc_.allocate(count);
if(rng.is_valid()) {
uint32_t id = search_free_ ? find_free() : INVALID_IDX;
if(id == INVALID_IDX) {
id = uint32_t(batch_.size());
batch_.push_back(token(id, type, rng));
} else {
batch_[id] = token(id, type, rng);
}
return batch_[id];
}
return invalid_token;
}
void bind() { mesh_.bind(); }
void release() { mesh_.release(); }
bool map_read() { return vbuf_acc_.map_read(); }
bool map_write() { return vbuf_acc_.map_write(); }
bool map_readwrite() { return vbuf_acc_.map_readwrite(); }
bool map_read(const token& tok) { return vbuf_acc_.map_read(tok.vtx_range); }
bool map_write(const token& tok) { return vbuf_acc_.map_write(tok.vtx_range); }
bool map_readwrite(const token tok) { return vbuf_acc_.map_readwrite(tok.vtx_range); }
bool unmap() { return vbuf_acc_.unmap(); }
void set(const token& tok, uint32_t offset, const vertex_t& v) { vbuf_acc_.set(tok.vtx_range, offset, v); }
void set(const token& tok, uint32_t offset, uint32_t count, const vertex_t* p) { vbuf_acc_.set(tok.vtx_range, offset, count, p); }
void set(const token& tok, uint32_t offset, const std::vector<vertex_t>& v) { vbuf_acc_.set(tok.vtx_range, offset, v); }
void draw(const token& tok) { mesh_.draw(tok.type, tok.vtx_range.start, tok.vtx_range.count); }
protected:
uint32_t find_free() const {
auto it = std::find_if(batch_.begin(), batch_.end(), [](const auto& tk){ return !tk.is_valid(); });
return it != batch_.end() ? uint32_t(it - batch_.begin()) : INVALID_IDX;
}
private:
mesh_t mesh_;
vbuf_t* vbuf_ptr_ = nullptr;
engine::accessor<vbuf_t> vbuf_acc_;
std::vector<token> batch_;
bool search_free_ = false;
};
template <typename VertexStreamT>
const typename render_batch<VertexStreamT, void, 1>::token render_batch<VertexStreamT, void, 1>::invalid_token = {INVALID_IDX, engine::primitive_type::PT_NONE, engine::range()};
}}
#endif //ZAP_RENDER_BATCH_HPP
<|endoftext|> |
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 2006 Pierre Phaneuf <[email protected]>
*
* This program 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 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
* 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
*/
#include "update.h"
#include "cfgfile.h"
#include "dict.h"
#include "http_request.h"
#include "stringtable.h"
#include "version.h"
#define UPDATE_HOST "quadra.googlecode.com"
#define UPDATE_PORT 80
#define UPDATE_PATH "/svn/version.txt"
#define UPDATE_VERSION_KEY "stable"
class AutoUpdaterImpl: public AutoUpdater {
Http_request *req;
Buf buf;
public:
AutoUpdaterImpl():
req(NULL) {
}
void init();
void step();
~AutoUpdaterImpl();
};
// Do not update more than once per this many seconds.
static time_t mindelay = 24 * 60 * 60;
static AutoUpdaterImpl* updater;
void AutoUpdater::start() {
msgbox("Attempting to start auto-update...\n");
if(updater) {
msgbox("Auto-updater already started.\n");
return;
}
updater = new AutoUpdaterImpl;
}
void AutoUpdaterImpl::init() {
time_t now(time(NULL));
char st[256];
msgbox("update: init called.\n");
if(now < config.info3.last_update + mindelay) {
now = config.info3.last_update + mindelay;
msgbox("update: updated too recently, not before %s", ctime(&now));
ret();
return;
}
buf.resize(0);
buf.append("GET "UPDATE_PATH" HTTP/1.0\r\n");
buf.append("Host: "UPDATE_HOST"\r\n");
buf.append("Connection: close\r\n");
snprintf(st, sizeof(st), "User-Agent: Quadra/%s\r\n", VERSION_STRING);
buf.append(st);
if(*config.info3.last_modified) {
msgbox("update: setting If-Modified-Since to %s\n",
config.info3.last_modified);
buf.append("If-Modified-Since: ");
buf.append(config.info3.last_modified);
buf.append("\r\n");
} else
msgbox("update: not setting If-Modified-Since\n");
buf.append("\r\n");
req = new Http_request(UPDATE_HOST, UPDATE_PORT, buf.get(), buf.size());
}
void AutoUpdaterImpl::step() {
if(!req) {
ret();
return;
}
if(!req->done())
return;
ret();
if(req->getsize()) {
Stringtable st(req->getbuf(), req->getsize());
char last_mod[64] = "";
enum {
STATUS,
HEADER,
REPLY,
} state = STATUS;
Dict reply;
for(int i = 0; i < st.size(); ++i) {
const char* str = st.get(i);
switch(state) {
case STATUS:
if(strncmp(str, "HTTP/", 5) != 0) {
msgbox("update: Invalid HTTP response\n");
return;
}
while(str && *str != '\0' && *str != ' ' && *str != '\t')
++str;
while(str && *str != '\0' && (*str == ' ' || *str == '\t'))
++str;
if(strncmp(str, "200", 3) == 0)
msgbox("HTTP status is OK\n");
else if(strncmp(str, "304", 3) == 0) {
msgbox("update: version file not modified\n");
config.info3.last_update = time(NULL);
config.write();
return;
} else {
msgbox("update: HTTP status isn't 200 or 304: %s\n", str);
return;
}
state = HEADER;
break;
case HEADER:
if(*str == '\0') {
state = REPLY;
continue;
}
// Take note of the Last-Modified header.
if(strncasecmp(str, "Last-Modified:", 14) == 0) {
while(str && *str != '\0' && *str != ' ' && *str != '\t')
++str;
while(str && *str != '\0' && (*str == ' ' || *str == '\t'))
++str;
snprintf(last_mod, sizeof(last_mod), "%s", str);
msgbox("update: Last-Modified: %s\n", last_mod);
}
break;
case REPLY:
msgbox("update: reply: %s\n", str);
reply.add(str);
break;
};
}
const char* val = reply.find("qserv");
if(val)
snprintf(config.info3.default_game_server_address,
sizeof(config.info3.default_game_server_address),
"%s", val);
if(reply.find_sub("version")) {
val = reply.find_sub("version")->find(UPDATE_VERSION_KEY);
if(val)
{
int s = sizeof(config.info3.latest_version);
strncpy(config.info3.latest_version, val, s);
config.info3.latest_version[s-1] = 0;
}
}
if(*last_mod)
snprintf(config.info3.last_modified, sizeof(config.info3.last_modified),
"%s", last_mod);
config.info3.last_update = time(NULL);
config.write();
msgbox("update: done\n");
} else
msgbox("update: failed\n");
}
AutoUpdaterImpl::~AutoUpdaterImpl() {
updater = NULL;
delete req;
}
<commit_msg>We weren't honoring (the lack of) the ENABLE_VERSION_CHECK define correctly. We'd do the request, then just not display the result. Since some of the people who requested being able to disable this were concerned for their privacy, this clearly wasn't enough.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 2006 Pierre Phaneuf <[email protected]>
*
* This program 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 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
* 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
*/
#include "update.h"
#include "cfgfile.h"
#include "dict.h"
#include "http_request.h"
#include "stringtable.h"
#include "version.h"
#define UPDATE_HOST "quadra.googlecode.com"
#define UPDATE_PORT 80
#define UPDATE_PATH "/svn/version.txt"
#define UPDATE_VERSION_KEY "stable"
class AutoUpdaterImpl: public AutoUpdater {
Http_request *req;
Buf buf;
public:
AutoUpdaterImpl():
req(NULL) {
}
void init();
void step();
~AutoUpdaterImpl();
};
// Do not update more than once per this many seconds.
static time_t mindelay = 24 * 60 * 60;
static AutoUpdaterImpl* updater;
void AutoUpdater::start() {
#ifdef ENABLE_VERSION_CHECK
msgbox("Attempting to start auto-update...\n");
if(updater) {
msgbox("Auto-updater already started.\n");
return;
}
updater = new AutoUpdaterImpl;
#endif
}
void AutoUpdaterImpl::init() {
time_t now(time(NULL));
char st[256];
msgbox("update: init called.\n");
if(now < config.info3.last_update + mindelay) {
now = config.info3.last_update + mindelay;
msgbox("update: updated too recently, not before %s", ctime(&now));
ret();
return;
}
buf.resize(0);
buf.append("GET "UPDATE_PATH" HTTP/1.0\r\n");
buf.append("Host: "UPDATE_HOST"\r\n");
buf.append("Connection: close\r\n");
snprintf(st, sizeof(st), "User-Agent: Quadra/%s\r\n", VERSION_STRING);
buf.append(st);
if(*config.info3.last_modified) {
msgbox("update: setting If-Modified-Since to %s\n",
config.info3.last_modified);
buf.append("If-Modified-Since: ");
buf.append(config.info3.last_modified);
buf.append("\r\n");
} else
msgbox("update: not setting If-Modified-Since\n");
buf.append("\r\n");
req = new Http_request(UPDATE_HOST, UPDATE_PORT, buf.get(), buf.size());
}
void AutoUpdaterImpl::step() {
if(!req) {
ret();
return;
}
if(!req->done())
return;
ret();
if(req->getsize()) {
Stringtable st(req->getbuf(), req->getsize());
char last_mod[64] = "";
enum {
STATUS,
HEADER,
REPLY,
} state = STATUS;
Dict reply;
for(int i = 0; i < st.size(); ++i) {
const char* str = st.get(i);
switch(state) {
case STATUS:
if(strncmp(str, "HTTP/", 5) != 0) {
msgbox("update: Invalid HTTP response\n");
return;
}
while(str && *str != '\0' && *str != ' ' && *str != '\t')
++str;
while(str && *str != '\0' && (*str == ' ' || *str == '\t'))
++str;
if(strncmp(str, "200", 3) == 0)
msgbox("HTTP status is OK\n");
else if(strncmp(str, "304", 3) == 0) {
msgbox("update: version file not modified\n");
config.info3.last_update = time(NULL);
config.write();
return;
} else {
msgbox("update: HTTP status isn't 200 or 304: %s\n", str);
return;
}
state = HEADER;
break;
case HEADER:
if(*str == '\0') {
state = REPLY;
continue;
}
// Take note of the Last-Modified header.
if(strncasecmp(str, "Last-Modified:", 14) == 0) {
while(str && *str != '\0' && *str != ' ' && *str != '\t')
++str;
while(str && *str != '\0' && (*str == ' ' || *str == '\t'))
++str;
snprintf(last_mod, sizeof(last_mod), "%s", str);
msgbox("update: Last-Modified: %s\n", last_mod);
}
break;
case REPLY:
msgbox("update: reply: %s\n", str);
reply.add(str);
break;
};
}
const char* val = reply.find("qserv");
if(val)
snprintf(config.info3.default_game_server_address,
sizeof(config.info3.default_game_server_address),
"%s", val);
if(reply.find_sub("version")) {
val = reply.find_sub("version")->find(UPDATE_VERSION_KEY);
if(val)
{
int s = sizeof(config.info3.latest_version);
strncpy(config.info3.latest_version, val, s);
config.info3.latest_version[s-1] = 0;
}
}
if(*last_mod)
snprintf(config.info3.last_modified, sizeof(config.info3.last_modified),
"%s", last_mod);
config.info3.last_update = time(NULL);
config.write();
msgbox("update: done\n");
} else
msgbox("update: failed\n");
}
AutoUpdaterImpl::~AutoUpdaterImpl() {
updater = NULL;
delete req;
}
<|endoftext|> |
<commit_before>/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-2018 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* 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 <algorithm>
#include <cstdlib>
#include <climits>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
/* ap_config.h checks whether the compiler has support for C99's designated
* initializers, and defines AP_HAVE_DESIGNATED_INITIALIZER if it does. However,
* g++ does not support designated initializers, even when ap_config.h thinks
* it does. Here we undefine the macro to force httpd_config.h to not use
* designated initializers. This should fix compilation problems on some systems.
*/
#include <ap_config.h>
#undef AP_HAVE_DESIGNATED_INITIALIZER
#include <JsonTools/Autocast.h>
#include <SystemTools/UserDatabase.h>
#include <Utils.h>
#include <Constants.h>
// The APR headers must come after the Passenger headers.
// See Hooks.cpp to learn why.
#include <apr_strings.h>
// In Apache < 2.4, this macro was necessary for core_dir_config and other structs
#define CORE_PRIVATE
#include <http_core.h>
#include <http_config.h>
#include <http_log.h>
#include "Config.h"
#include "ConfigGeneral/SetterFuncs.h"
#include "ConfigGeneral/ManifestGeneration.h"
#include "DirConfig/AutoGeneratedCreateFunction.cpp"
#include "DirConfig/AutoGeneratedMergeFunction.cpp"
#include "Utils.h"
extern "C" module AP_MODULE_DECLARE_DATA passenger_module;
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(passenger);
#endif
#ifndef ap_get_core_module_config
#define ap_get_core_module_config(s) ap_get_module_config(s, &core_module)
#endif
#include "ConfigGeneral/AutoGeneratedSetterFuncs.cpp"
namespace Passenger {
namespace Apache2Module {
using namespace std;
typedef const char * (*Take1Func)();
typedef const char * (*Take2Func)();
typedef const char * (*FlagFunc)();
ServerConfig serverConfig;
template<typename T> static apr_status_t
destroyConfigStruct(void *x) {
delete (T *) x;
return APR_SUCCESS;
}
template<typename Collection, typename T> static bool
contains(const Collection &coll, const T &item) {
typename Collection::const_iterator it;
for (it = coll.begin(); it != coll.end(); it++) {
if (*it == item) {
return true;
}
}
return false;
}
static DirConfig *
createDirConfigStruct(apr_pool_t *pool) {
DirConfig *config = new DirConfig();
apr_pool_cleanup_register(pool, config, destroyConfigStruct<DirConfig>, apr_pool_cleanup_null);
return config;
}
void *
createDirConfig(apr_pool_t *p, char *dirspec) {
DirConfig *config = createDirConfigStruct(p);
createDirConfig_autoGenerated(config);
return config;
}
void *
mergeDirConfig(apr_pool_t *p, void *basev, void *addv) {
DirConfig *config = createDirConfigStruct(p);
DirConfig *base = (DirConfig *) basev;
DirConfig *add = (DirConfig *) addv;
mergeDirConfig_autoGenerated(config, base, add);
return config;
}
void
postprocessConfig(server_rec *s, apr_pool_t *pool, apr_pool_t *temp_pool) {
if (serverConfig.defaultGroup.empty()) {
OsUser osUser;
if (!lookupSystemUserByName(serverConfig.defaultUser, osUser)) {
throw ConfigurationException(
"The user that PassengerDefaultUser refers to, '"
+ serverConfig.defaultUser
+ "', does not exist.");
}
OsGroup osGroup;
if (!lookupSystemGroupByGid(osUser.pwd.pw_gid, osGroup)) {
throw ConfigurationException(
"The option PassengerDefaultUser is set to '"
+ serverConfig.defaultUser
+ "', but its primary group doesn't exist. "
"In other words, your system's user account database "
"is broken. Please fix it.");
}
serverConfig.defaultGroup = apr_pstrdup(pool, osGroup.grp.gr_name);
}
serverConfig.manifest = ConfigManifestGenerator(s, temp_pool).execute();
if (!serverConfig.dumpConfigManifest.empty()) {
FILE *f = fopen(serverConfig.dumpConfigManifest.c_str(), "w");
if (f == NULL) {
fprintf(stderr, "Error opening %s for writing\n",
serverConfig.dumpConfigManifest.c_str());
} else {
string dumpContent = serverConfig.manifest.toStyledString();
size_t ret = fwrite(dumpContent.data(), 1, dumpContent.size(), f);
(void) ret; // Ignore compilation warning.
fclose(f);
}
}
}
/*************************************************
* Passenger settings
*************************************************/
static const char *
cmd_passenger_enterprise_only(cmd_parms *cmd, void *pcfg, const char *arg) {
return "this feature is only available in Phusion Passenger Enterprise. "
"You are currently running the open source Phusion Passenger Enterprise. "
"Please learn more about and/or buy Phusion Passenger Enterprise at https://www.phusionpassenger.com/enterprise";
}
static const char *
cmd_passenger_ctl(cmd_parms *cmd, void *dummy, const char *name, const char *value) {
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, cmd->temp_pool,
"WARNING: %s", err);
}
serverConfig.ctlSourceFile = cmd->directive->filename;
serverConfig.ctlSourceLine = cmd->directive->line_num;
serverConfig.ctlExplicitlySet = true;
try {
serverConfig.ctl[name] = autocastValueToJson(value);
return NULL;
} catch (const Json::Reader &) {
return "Error parsing value as JSON";
}
}
static const char *
cmd_passenger_spawn_method(cmd_parms *cmd, void *pcfg, const char *arg) {
const char *err = ap_check_cmd_context(cmd, NOT_IN_FILES);
if (err != NULL) {
return err;
}
DirConfig *config = (DirConfig *) pcfg;
config->mSpawnMethodSourceFile = cmd->directive->filename;
config->mSpawnMethodSourceLine = cmd->directive->line_num;
config->mSpawnMethodExplicitlySet = true;
if (strcmp(arg, "smart") == 0 || strcmp(arg, "smart-lv2") == 0) {
config->mSpawnMethod = "smart";
} else if (strcmp(arg, "conservative") == 0 || strcmp(arg, "direct") == 0) {
config->mSpawnMethod = "direct";
} else {
return "PassengerSpawnMethod may only be 'smart', 'direct'.";
}
return NULL;
}
static const char *
cmd_passenger_base_uri(cmd_parms *cmd, void *pcfg, const char *arg) {
const char *err = ap_check_cmd_context(cmd, NOT_IN_FILES);
if (err != NULL) {
return err;
}
DirConfig *config = (DirConfig *) pcfg;
config->mBaseURIsSourceFile = cmd->directive->filename;
config->mBaseURIsSourceLine = cmd->directive->line_num;
config->mBaseURIsExplicitlySet = true;
if (strlen(arg) == 0) {
return "PassengerBaseURI may not be set to the empty string";
} else if (arg[0] != '/') {
return "PassengerBaseURI must start with a slash (/)";
} else if (strlen(arg) > 1 && arg[strlen(arg) - 1] == '/') {
return "PassengerBaseURI must not end with a slash (/)";
} else {
config->mBaseURIs.insert(arg);
return NULL;
}
}
} // namespace Apache2Module
} // namespace Passenger
#include "ConfigGeneral/AutoGeneratedDefinitions.cpp"
<commit_msg>Fix Apache 2 module compilation on CentOS 6<commit_after>/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-2018 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* 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 <algorithm>
#include <cstdlib>
#include <climits>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
/* ap_config.h checks whether the compiler has support for C99's designated
* initializers, and defines AP_HAVE_DESIGNATED_INITIALIZER if it does. However,
* g++ does not support designated initializers, even when ap_config.h thinks
* it does. Here we undefine the macro to force httpd_config.h to not use
* designated initializers. This should fix compilation problems on some systems.
*/
#include <ap_config.h>
#undef AP_HAVE_DESIGNATED_INITIALIZER
#include <JsonTools/Autocast.h>
#include <SystemTools/UserDatabase.h>
#include <Utils.h>
#include <Constants.h>
// The APR headers must come after the Passenger headers.
// See Hooks.cpp to learn why.
#include <apr_strings.h>
// In Apache < 2.4, this macro was necessary for core_dir_config and other structs
#define CORE_PRIVATE
#include <httpd.h>
#include <http_config.h>
#include <http_log.h>
#include <http_core.h>
#include "Config.h"
#include "ConfigGeneral/SetterFuncs.h"
#include "ConfigGeneral/ManifestGeneration.h"
#include "DirConfig/AutoGeneratedCreateFunction.cpp"
#include "DirConfig/AutoGeneratedMergeFunction.cpp"
#include "Utils.h"
extern "C" module AP_MODULE_DECLARE_DATA passenger_module;
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(passenger);
#endif
#ifndef ap_get_core_module_config
#define ap_get_core_module_config(s) ap_get_module_config(s, &core_module)
#endif
#include "ConfigGeneral/AutoGeneratedSetterFuncs.cpp"
namespace Passenger {
namespace Apache2Module {
using namespace std;
typedef const char * (*Take1Func)();
typedef const char * (*Take2Func)();
typedef const char * (*FlagFunc)();
ServerConfig serverConfig;
template<typename T> static apr_status_t
destroyConfigStruct(void *x) {
delete (T *) x;
return APR_SUCCESS;
}
template<typename Collection, typename T> static bool
contains(const Collection &coll, const T &item) {
typename Collection::const_iterator it;
for (it = coll.begin(); it != coll.end(); it++) {
if (*it == item) {
return true;
}
}
return false;
}
static DirConfig *
createDirConfigStruct(apr_pool_t *pool) {
DirConfig *config = new DirConfig();
apr_pool_cleanup_register(pool, config, destroyConfigStruct<DirConfig>, apr_pool_cleanup_null);
return config;
}
void *
createDirConfig(apr_pool_t *p, char *dirspec) {
DirConfig *config = createDirConfigStruct(p);
createDirConfig_autoGenerated(config);
return config;
}
void *
mergeDirConfig(apr_pool_t *p, void *basev, void *addv) {
DirConfig *config = createDirConfigStruct(p);
DirConfig *base = (DirConfig *) basev;
DirConfig *add = (DirConfig *) addv;
mergeDirConfig_autoGenerated(config, base, add);
return config;
}
void
postprocessConfig(server_rec *s, apr_pool_t *pool, apr_pool_t *temp_pool) {
if (serverConfig.defaultGroup.empty()) {
OsUser osUser;
if (!lookupSystemUserByName(serverConfig.defaultUser, osUser)) {
throw ConfigurationException(
"The user that PassengerDefaultUser refers to, '"
+ serverConfig.defaultUser
+ "', does not exist.");
}
OsGroup osGroup;
if (!lookupSystemGroupByGid(osUser.pwd.pw_gid, osGroup)) {
throw ConfigurationException(
"The option PassengerDefaultUser is set to '"
+ serverConfig.defaultUser
+ "', but its primary group doesn't exist. "
"In other words, your system's user account database "
"is broken. Please fix it.");
}
serverConfig.defaultGroup = apr_pstrdup(pool, osGroup.grp.gr_name);
}
serverConfig.manifest = ConfigManifestGenerator(s, temp_pool).execute();
if (!serverConfig.dumpConfigManifest.empty()) {
FILE *f = fopen(serverConfig.dumpConfigManifest.c_str(), "w");
if (f == NULL) {
fprintf(stderr, "Error opening %s for writing\n",
serverConfig.dumpConfigManifest.c_str());
} else {
string dumpContent = serverConfig.manifest.toStyledString();
size_t ret = fwrite(dumpContent.data(), 1, dumpContent.size(), f);
(void) ret; // Ignore compilation warning.
fclose(f);
}
}
}
/*************************************************
* Passenger settings
*************************************************/
static const char *
cmd_passenger_enterprise_only(cmd_parms *cmd, void *pcfg, const char *arg) {
return "this feature is only available in Phusion Passenger Enterprise. "
"You are currently running the open source Phusion Passenger Enterprise. "
"Please learn more about and/or buy Phusion Passenger Enterprise at https://www.phusionpassenger.com/enterprise";
}
static const char *
cmd_passenger_ctl(cmd_parms *cmd, void *dummy, const char *name, const char *value) {
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, cmd->temp_pool,
"WARNING: %s", err);
}
serverConfig.ctlSourceFile = cmd->directive->filename;
serverConfig.ctlSourceLine = cmd->directive->line_num;
serverConfig.ctlExplicitlySet = true;
try {
serverConfig.ctl[name] = autocastValueToJson(value);
return NULL;
} catch (const Json::Reader &) {
return "Error parsing value as JSON";
}
}
static const char *
cmd_passenger_spawn_method(cmd_parms *cmd, void *pcfg, const char *arg) {
const char *err = ap_check_cmd_context(cmd, NOT_IN_FILES);
if (err != NULL) {
return err;
}
DirConfig *config = (DirConfig *) pcfg;
config->mSpawnMethodSourceFile = cmd->directive->filename;
config->mSpawnMethodSourceLine = cmd->directive->line_num;
config->mSpawnMethodExplicitlySet = true;
if (strcmp(arg, "smart") == 0 || strcmp(arg, "smart-lv2") == 0) {
config->mSpawnMethod = "smart";
} else if (strcmp(arg, "conservative") == 0 || strcmp(arg, "direct") == 0) {
config->mSpawnMethod = "direct";
} else {
return "PassengerSpawnMethod may only be 'smart', 'direct'.";
}
return NULL;
}
static const char *
cmd_passenger_base_uri(cmd_parms *cmd, void *pcfg, const char *arg) {
const char *err = ap_check_cmd_context(cmd, NOT_IN_FILES);
if (err != NULL) {
return err;
}
DirConfig *config = (DirConfig *) pcfg;
config->mBaseURIsSourceFile = cmd->directive->filename;
config->mBaseURIsSourceLine = cmd->directive->line_num;
config->mBaseURIsExplicitlySet = true;
if (strlen(arg) == 0) {
return "PassengerBaseURI may not be set to the empty string";
} else if (arg[0] != '/') {
return "PassengerBaseURI must start with a slash (/)";
} else if (strlen(arg) > 1 && arg[strlen(arg) - 1] == '/') {
return "PassengerBaseURI must not end with a slash (/)";
} else {
config->mBaseURIs.insert(arg);
return NULL;
}
}
} // namespace Apache2Module
} // namespace Passenger
#include "ConfigGeneral/AutoGeneratedDefinitions.cpp"
<|endoftext|> |
<commit_before>// Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "src/clients/c++/perf_client/model_parser.h"
nic::Error
ModelParser::Init(
const ni::ModelMetadataResponse& metadata, const ni::ModelConfig& config,
const std::string& model_version,
const std::unordered_map<std::string, std::vector<int64_t>>& input_shapes,
std::unique_ptr<TritonClientWrapper>& client_wrapper)
{
model_name_ = metadata.name();
model_version_ = model_version;
// Get the scheduler type for the model
if (config.has_ensemble_scheduling()) {
bool is_sequential = false;
RETURN_IF_ERROR(GetEnsembleSchedulerType(
config, model_version, client_wrapper, &is_sequential));
if (is_sequential) {
scheduler_type_ = ENSEMBLE_SEQUENCE;
} else {
scheduler_type_ = ENSEMBLE;
}
} else if (config.has_sequence_batching()) {
scheduler_type_ = SEQUENCE;
} else if (config.has_dynamic_batching()) {
scheduler_type_ = DYNAMIC;
} else {
scheduler_type_ = NONE;
}
max_batch_size_ = config.max_batch_size();
// Get the information about inputs from metadata
for (const auto& input : metadata.inputs()) {
auto it = inputs_->emplace(input.name(), ModelTensor()).first;
it->second.name_ = input.name();
it->second.datatype_ = input.datatype();
bool is_dynamic = false;
// Skip the batch size in the shape
bool skip = (max_batch_size_ > 0);
for (const auto dim : input.shape()) {
if (skip) {
skip = false;
continue;
}
if (dim == -1) {
is_dynamic = true;
}
it->second.shape_.push_back(dim);
}
if (is_dynamic) {
const auto user_shape_it = input_shapes.find(input.name());
if (user_shape_it != input_shapes.end()) {
// Update the default shape to be used.
it->second.shape_.clear();
for (const auto dim : user_shape_it->second) {
it->second.shape_.push_back(dim);
}
}
}
}
// Check whether the tensor is shape tensor or not from config.
for (const auto& input_config : config.input()) {
const auto& itr = inputs_->find(input_config.name());
if (itr == inputs_->end()) {
return nic::Error(
"no metadata found for input tensor " + input_config.name());
}
itr->second.is_shape_tensor_ = input_config.is_shape_tensor();
}
// Get the information about outputs from metadata
for (const auto& output : metadata.outputs()) {
auto it = outputs_->emplace(output.name(), ModelTensor()).first;
it->second.name_ = output.name();
it->second.datatype_ = output.datatype();
// Skip the batch size in the shape
bool skip = (max_batch_size_ > 0);
for (const auto dim : output.shape()) {
if (skip) {
skip = false;
continue;
}
it->second.shape_.push_back(dim);
}
}
// Check whether the tensor is shape tensor or not from config.
for (const auto& output_config : config.output()) {
const auto& itr = outputs_->find(output_config.name());
if (itr == outputs_->end()) {
return nic::Error(
"no metadata found for output tensor " + output_config.name());
}
itr->second.is_shape_tensor_ = output_config.is_shape_tensor();
}
return nic::Error::Success;
}
nic::Error
ModelParser::GetEnsembleSchedulerType(
const ni::ModelConfig& config, const std::string& model_version,
std::unique_ptr<TritonClientWrapper>& client_wrapper, bool* is_sequential)
{
if (config.has_sequence_batching()) {
*is_sequential = true;
}
if (config.platform() == "ensemble") {
for (const auto& step : config.ensemble_scheduling().step()) {
ni::ModelConfigResponse model_config;
std::string step_version;
if (step.model_version() != -1) {
step_version = std::to_string(step.model_version());
}
(*composing_models_map_)[config.name()].emplace(
step.model_name(), step_version);
RETURN_IF_ERROR(client_wrapper->ModelConfig(
&model_config, step.model_name(), step_version));
RETURN_IF_ERROR(GetEnsembleSchedulerType(
model_config.config(), step_version, client_wrapper, is_sequential));
}
}
return nic::Error::Success;
}
nic::Error
ModelParser::Init(
const rapidjson::Document& metadata, const rapidjson::Document& config,
const std::string& model_version,
const std::unordered_map<std::string, std::vector<int64_t>>& input_shapes,
std::unique_ptr<TritonClientWrapper>& client_wrapper)
{
model_name_ = metadata["name"].GetString();
model_version_ = model_version;
// Get the scheduler type for the model
scheduler_type_ = NONE;
const auto& ensemble_itr = config.FindMember("ensemble_scheduling");
if (ensemble_itr != config.MemberEnd()) {
bool is_sequential = false;
RETURN_IF_ERROR(GetEnsembleSchedulerType(
config, model_version, client_wrapper, &is_sequential));
if (is_sequential) {
scheduler_type_ = ENSEMBLE_SEQUENCE;
} else {
scheduler_type_ = ENSEMBLE;
}
} else {
const auto& sequence_itr = config.FindMember("sequence_batching");
if (sequence_itr != config.MemberEnd()) {
scheduler_type_ = SEQUENCE;
} else {
const auto& dynamic_itr = config.FindMember("dynamic_batching");
if (dynamic_itr != config.MemberEnd()) {
scheduler_type_ = DYNAMIC;
}
}
}
max_batch_size_ = 0;
const auto bs_itr = config.FindMember("max_batch_size");
if (bs_itr != config.MemberEnd()) {
max_batch_size_ = bs_itr->value.GetInt();
}
// Get the information about inputs from metadata
const auto inputs_itr = metadata.FindMember("inputs");
if (inputs_itr != metadata.MemberEnd()) {
for (const auto& input : inputs_itr->value.GetArray()) {
auto it =
inputs_->emplace(input["name"].GetString(), ModelTensor()).first;
it->second.name_ = input["name"].GetString();
it->second.datatype_ = input["datatype"].GetString();
bool is_dynamic = false;
bool skip = (max_batch_size_ > 0);
for (const auto& dim : input["shape"].GetArray()) {
if (skip) {
skip = false;
continue;
}
if (dim.GetInt() == -1) {
is_dynamic = true;
}
it->second.shape_.push_back(dim.GetInt());
}
if (is_dynamic) {
const auto user_shape_it = input_shapes.find(it->second.name_);
if (user_shape_it != input_shapes.end()) {
// Update the default shape to be used.
it->second.shape_.clear();
for (const auto dim : user_shape_it->second) {
it->second.shape_.push_back(dim);
}
}
}
}
}
// Check whether the tensor is shape tensor or not from config.
const auto inputs_config_itr = config.FindMember("input");
if (inputs_config_itr != config.MemberEnd()) {
for (const auto& input_config : inputs_config_itr->value.GetArray()) {
const auto name = std::string(
input_config["name"].GetString(),
input_config["name"].GetStringLength());
auto it = inputs_->find(name);
if (it == inputs_->end()) {
return nic::Error("no metadata found for input tensor " + name);
}
const auto& shape_tensor_itr = input_config.FindMember("is_shape_tensor");
if (shape_tensor_itr != input_config.MemberEnd()) {
it->second.is_shape_tensor_ = shape_tensor_itr->value.GetBool();
}
}
}
// Get the information about outputs from metadata
const auto outputs_itr = metadata.FindMember("outputs");
if (outputs_itr != metadata.MemberEnd()) {
for (const auto& output : outputs_itr->value.GetArray()) {
auto it =
outputs_->emplace(output["name"].GetString(), ModelTensor()).first;
it->second.name_ = output["name"].GetString();
it->second.datatype_ = output["datatype"].GetString();
bool skip = (max_batch_size_ > 0);
for (const auto& dim : output["shape"].GetArray()) {
if (skip) {
skip = false;
continue;
}
it->second.shape_.push_back(dim.GetInt());
}
}
}
// Check whether the tensor is shape tensor or not from config.
const auto output_config_itr = config.FindMember("output");
if (output_config_itr != config.MemberEnd()) {
for (const auto& output_config : output_config_itr->value.GetArray()) {
const auto name = std::string(
output_config["name"].GetString(),
output_config["name"].GetStringLength());
auto itr = outputs_->find(name);
if (itr == outputs_->end()) {
return nic::Error("no metadata found for output tensor " + name);
}
const auto& shape_tensor_itr =
output_config.FindMember("is_shape_tensor");
if (shape_tensor_itr != output_config.MemberEnd()) {
itr->second.is_shape_tensor_ = shape_tensor_itr->value.GetBool();
}
}
}
return nic::Error::Success;
}
nic::Error
ModelParser::GetEnsembleSchedulerType(
const rapidjson::Document& config, const std::string& model_version,
std::unique_ptr<TritonClientWrapper>& client_wrapper, bool* is_sequential)
{
const auto& sequence_itr = config.FindMember("sequence_batching");
if (sequence_itr != config.MemberEnd()) {
*is_sequential = true;
}
if (std::string(config["platform"].GetString()).compare("ensemble") == 0) {
const auto step_itr = config["ensemble_scheduling"].FindMember("step");
for (const auto& step : step_itr->value.GetArray()) {
std::string step_model_version(step["model_version"].GetString());
int64_t model_version_int = std::stol(step_model_version);
if (model_version_int == -1) {
step_model_version = "";
}
(*composing_models_map_)[config["name"].GetString()].emplace(
std::string(step["model_name"].GetString()), step_model_version);
rapidjson::Document model_config;
RETURN_IF_ERROR(client_wrapper->ModelConfig(
&model_config, step["model_name"].GetString(), step_model_version));
RETURN_IF_ERROR(GetEnsembleSchedulerType(
model_config, step_model_version, client_wrapper, is_sequential));
}
}
return nic::Error::Success;
}
<commit_msg>Fix json representation of model configuration (#1664)<commit_after>// Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "src/clients/c++/perf_client/model_parser.h"
nic::Error
ModelParser::Init(
const ni::ModelMetadataResponse& metadata, const ni::ModelConfig& config,
const std::string& model_version,
const std::unordered_map<std::string, std::vector<int64_t>>& input_shapes,
std::unique_ptr<TritonClientWrapper>& client_wrapper)
{
model_name_ = metadata.name();
model_version_ = model_version;
// Get the scheduler type for the model
if (config.has_ensemble_scheduling()) {
bool is_sequential = false;
RETURN_IF_ERROR(GetEnsembleSchedulerType(
config, model_version, client_wrapper, &is_sequential));
if (is_sequential) {
scheduler_type_ = ENSEMBLE_SEQUENCE;
} else {
scheduler_type_ = ENSEMBLE;
}
} else if (config.has_sequence_batching()) {
scheduler_type_ = SEQUENCE;
} else if (config.has_dynamic_batching()) {
scheduler_type_ = DYNAMIC;
} else {
scheduler_type_ = NONE;
}
max_batch_size_ = config.max_batch_size();
// Get the information about inputs from metadata
for (const auto& input : metadata.inputs()) {
auto it = inputs_->emplace(input.name(), ModelTensor()).first;
it->second.name_ = input.name();
it->second.datatype_ = input.datatype();
bool is_dynamic = false;
// Skip the batch size in the shape
bool skip = (max_batch_size_ > 0);
for (const auto dim : input.shape()) {
if (skip) {
skip = false;
continue;
}
if (dim == -1) {
is_dynamic = true;
}
it->second.shape_.push_back(dim);
}
if (is_dynamic) {
const auto user_shape_it = input_shapes.find(input.name());
if (user_shape_it != input_shapes.end()) {
// Update the default shape to be used.
it->second.shape_.clear();
for (const auto dim : user_shape_it->second) {
it->second.shape_.push_back(dim);
}
}
}
}
// Check whether the tensor is shape tensor or not from config.
for (const auto& input_config : config.input()) {
const auto& itr = inputs_->find(input_config.name());
if (itr == inputs_->end()) {
return nic::Error(
"no metadata found for input tensor " + input_config.name());
}
itr->second.is_shape_tensor_ = input_config.is_shape_tensor();
}
// Get the information about outputs from metadata
for (const auto& output : metadata.outputs()) {
auto it = outputs_->emplace(output.name(), ModelTensor()).first;
it->second.name_ = output.name();
it->second.datatype_ = output.datatype();
// Skip the batch size in the shape
bool skip = (max_batch_size_ > 0);
for (const auto dim : output.shape()) {
if (skip) {
skip = false;
continue;
}
it->second.shape_.push_back(dim);
}
}
// Check whether the tensor is shape tensor or not from config.
for (const auto& output_config : config.output()) {
const auto& itr = outputs_->find(output_config.name());
if (itr == outputs_->end()) {
return nic::Error(
"no metadata found for output tensor " + output_config.name());
}
itr->second.is_shape_tensor_ = output_config.is_shape_tensor();
}
return nic::Error::Success;
}
nic::Error
ModelParser::GetEnsembleSchedulerType(
const ni::ModelConfig& config, const std::string& model_version,
std::unique_ptr<TritonClientWrapper>& client_wrapper, bool* is_sequential)
{
if (config.has_sequence_batching()) {
*is_sequential = true;
}
if (config.platform() == "ensemble") {
for (const auto& step : config.ensemble_scheduling().step()) {
ni::ModelConfigResponse model_config;
std::string step_version;
if (step.model_version() != -1) {
step_version = std::to_string(step.model_version());
}
(*composing_models_map_)[config.name()].emplace(
step.model_name(), step_version);
RETURN_IF_ERROR(client_wrapper->ModelConfig(
&model_config, step.model_name(), step_version));
RETURN_IF_ERROR(GetEnsembleSchedulerType(
model_config.config(), step_version, client_wrapper, is_sequential));
}
}
return nic::Error::Success;
}
nic::Error
ModelParser::Init(
const rapidjson::Document& metadata, const rapidjson::Document& config,
const std::string& model_version,
const std::unordered_map<std::string, std::vector<int64_t>>& input_shapes,
std::unique_ptr<TritonClientWrapper>& client_wrapper)
{
model_name_ = metadata["name"].GetString();
model_version_ = model_version;
// Get the scheduler type for the model
scheduler_type_ = NONE;
const auto& ensemble_itr = config.FindMember("ensemble_scheduling");
if (ensemble_itr != config.MemberEnd()) {
bool is_sequential = false;
RETURN_IF_ERROR(GetEnsembleSchedulerType(
config, model_version, client_wrapper, &is_sequential));
if (is_sequential) {
scheduler_type_ = ENSEMBLE_SEQUENCE;
} else {
scheduler_type_ = ENSEMBLE;
}
} else {
const auto& sequence_itr = config.FindMember("sequence_batching");
if (sequence_itr != config.MemberEnd()) {
scheduler_type_ = SEQUENCE;
} else {
const auto& dynamic_itr = config.FindMember("dynamic_batching");
if (dynamic_itr != config.MemberEnd()) {
scheduler_type_ = DYNAMIC;
}
}
}
max_batch_size_ = 0;
const auto bs_itr = config.FindMember("max_batch_size");
if (bs_itr != config.MemberEnd()) {
max_batch_size_ = bs_itr->value.GetInt();
}
// Get the information about inputs from metadata
const auto inputs_itr = metadata.FindMember("inputs");
if (inputs_itr != metadata.MemberEnd()) {
for (const auto& input : inputs_itr->value.GetArray()) {
auto it =
inputs_->emplace(input["name"].GetString(), ModelTensor()).first;
it->second.name_ = input["name"].GetString();
it->second.datatype_ = input["datatype"].GetString();
bool is_dynamic = false;
bool skip = (max_batch_size_ > 0);
for (const auto& dim : input["shape"].GetArray()) {
if (skip) {
skip = false;
continue;
}
if (dim.GetInt() == -1) {
is_dynamic = true;
}
it->second.shape_.push_back(dim.GetInt());
}
if (is_dynamic) {
const auto user_shape_it = input_shapes.find(it->second.name_);
if (user_shape_it != input_shapes.end()) {
// Update the default shape to be used.
it->second.shape_.clear();
for (const auto dim : user_shape_it->second) {
it->second.shape_.push_back(dim);
}
}
}
}
}
// Check whether the tensor is shape tensor or not from config.
const auto inputs_config_itr = config.FindMember("input");
if (inputs_config_itr != config.MemberEnd()) {
for (const auto& input_config : inputs_config_itr->value.GetArray()) {
const auto name = std::string(
input_config["name"].GetString(),
input_config["name"].GetStringLength());
auto it = inputs_->find(name);
if (it == inputs_->end()) {
return nic::Error("no metadata found for input tensor " + name);
}
const auto& shape_tensor_itr = input_config.FindMember("is_shape_tensor");
if (shape_tensor_itr != input_config.MemberEnd()) {
it->second.is_shape_tensor_ = shape_tensor_itr->value.GetBool();
}
}
}
// Get the information about outputs from metadata
const auto outputs_itr = metadata.FindMember("outputs");
if (outputs_itr != metadata.MemberEnd()) {
for (const auto& output : outputs_itr->value.GetArray()) {
auto it =
outputs_->emplace(output["name"].GetString(), ModelTensor()).first;
it->second.name_ = output["name"].GetString();
it->second.datatype_ = output["datatype"].GetString();
bool skip = (max_batch_size_ > 0);
for (const auto& dim : output["shape"].GetArray()) {
if (skip) {
skip = false;
continue;
}
it->second.shape_.push_back(dim.GetInt());
}
}
}
// Check whether the tensor is shape tensor or not from config.
const auto output_config_itr = config.FindMember("output");
if (output_config_itr != config.MemberEnd()) {
for (const auto& output_config : output_config_itr->value.GetArray()) {
const auto name = std::string(
output_config["name"].GetString(),
output_config["name"].GetStringLength());
auto itr = outputs_->find(name);
if (itr == outputs_->end()) {
return nic::Error("no metadata found for output tensor " + name);
}
const auto& shape_tensor_itr =
output_config.FindMember("is_shape_tensor");
if (shape_tensor_itr != output_config.MemberEnd()) {
itr->second.is_shape_tensor_ = shape_tensor_itr->value.GetBool();
}
}
}
return nic::Error::Success;
}
nic::Error
ModelParser::GetEnsembleSchedulerType(
const rapidjson::Document& config, const std::string& model_version,
std::unique_ptr<TritonClientWrapper>& client_wrapper, bool* is_sequential)
{
const auto& sequence_itr = config.FindMember("sequence_batching");
if (sequence_itr != config.MemberEnd()) {
*is_sequential = true;
}
if (std::string(config["platform"].GetString()).compare("ensemble") == 0) {
const auto step_itr = config["ensemble_scheduling"].FindMember("step");
for (const auto& step : step_itr->value.GetArray()) {
std::string step_model_version;
const int64_t model_version_int = step["model_version"].GetInt64();
if (model_version_int == -1) {
step_model_version = "";
} else {
step_model_version = std::to_string(model_version_int);
}
(*composing_models_map_)[config["name"].GetString()].emplace(
std::string(step["model_name"].GetString()), step_model_version);
rapidjson::Document model_config;
RETURN_IF_ERROR(client_wrapper->ModelConfig(
&model_config, step["model_name"].GetString(), step_model_version));
RETURN_IF_ERROR(GetEnsembleSchedulerType(
model_config, step_model_version, client_wrapper, is_sequential));
}
}
return nic::Error::Success;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2005 The Apache Software Foundation.
*
* 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.
*/
/*
* XSEC
*
* NSSCryptoX509:= NSS based class for handling X509 (V3) certificates
*
* Author(s): Milan Tomic
*
*/
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xsec/enc/NSS/NSSCryptoProvider.hpp>
#include <xsec/enc/NSS/NSSCryptoX509.hpp>
#include <xsec/enc/NSS/NSSCryptoKeyDSA.hpp>
#include <xsec/enc/NSS/NSSCryptoKeyRSA.hpp>
#include <xsec/enc/XSECCryptoException.hpp>
#include <xsec/enc/XSCrypt/XSCryptCryptoBase64.hpp>
#if defined (HAVE_NSS)
#include <nss/cert.h>
#include <xercesc/util/Janitor.hpp>
XSEC_USING_XERCES(ArrayJanitor);
// --------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------
NSSCryptoX509::NSSCryptoX509() : m_DERX509(""), mp_cert(NULL) {
}
// --------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------
NSSCryptoX509::NSSCryptoX509(CERTCertificate * pCert) {
// Build this from an existing CERTCertificate structure
mp_cert = pCert;
unsigned char * encCert;
unsigned long len = mp_cert->derCert.len * 2;
XSECnew(encCert, unsigned char [len]);
ArrayJanitor<unsigned char> j_encCert(encCert);
// Base64 Encode
XSCryptCryptoBase64 b64;
b64.encodeInit();
unsigned long encCertLen = b64.encode(mp_cert->derCert.data, mp_cert->derCert.len, encCert, len);
encCertLen += b64.encodeFinish(&encCert[encCertLen], len - encCertLen);
// Check the result
if (encCert == NULL) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSSX509:NSSX509 - Error encoding certificate");
}
m_DERX509.sbMemcpyIn(encCert, encCertLen);
m_DERX509[encCertLen] = '\0';
}
// --------------------------------------------------------------------------------
// Destructor
// --------------------------------------------------------------------------------
NSSCryptoX509::~NSSCryptoX509() {
if (mp_cert != 0)
CERT_DestroyCertificate(mp_cert);
}
// --------------------------------------------------------------------------------
// Load X509
// --------------------------------------------------------------------------------
void NSSCryptoX509::loadX509Base64Bin(const char * buf, unsigned int len) {
unsigned char * rawCert;
XSECnew(rawCert, unsigned char [len]);
ArrayJanitor<unsigned char> j_rawCert(rawCert);
// Base64 Decode
XSCryptCryptoBase64 b64;
b64.decodeInit();
unsigned int rawCertLen = b64.decode((unsigned char *) buf, len, rawCert, len);
rawCertLen += b64.decodeFinish(&rawCert[rawCertLen], len - rawCertLen);
// Now load certificate
SECItem i;
i.type = siBuffer;
i.data = rawCert;
i.len = rawCertLen;
mp_cert = __CERT_DecodeDERCertificate(&i, PR_TRUE, NULL);
// Since __CERT_DecodeDERCertificate is a private function we might consider using
// __CERT_NewTempCertificate() or CERT_ImportCerts() instead
if (mp_cert == 0) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSSX509:loadX509Base64Bin - Error decoding certificate");
}
m_DERX509.sbMemcpyIn(buf, len);
m_DERX509[len] = '\0';
}
// --------------------------------------------------------------------------------
// Get NSS provider name
// --------------------------------------------------------------------------------
const XMLCh * NSSCryptoX509::getProviderName() {
return DSIGConstants::s_unicodeStrPROVNSS;
}
// --------------------------------------------------------------------------------
// Get publickey type: RSA or DSA
// --------------------------------------------------------------------------------
XSECCryptoKey::KeyType NSSCryptoX509::getPublicKeyType() {
if (mp_cert == NULL) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSS:X509 - getPublicKeyType called before X509 loaded");
}
XSECCryptoKey::KeyType kt = XSECCryptoKey::KEY_NONE;
SECKEYPublicKey * pubkey = CERT_ExtractPublicKey(mp_cert);
if (pubkey == 0) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSS:X509 - Error extracting public key from X509 certificate");
}
if (pubkey->keyType == dsaKey)
kt = XSECCryptoKey::KEY_DSA_PUBLIC;
if (pubkey->keyType == rsaKey)
kt = XSECCryptoKey::KEY_RSA_PUBLIC;
SECKEY_DestroyPublicKey(pubkey);
return kt;
}
// --------------------------------------------------------------------------------
// Replicate public key
// --------------------------------------------------------------------------------
XSECCryptoKey * NSSCryptoX509::clonePublicKey() {
if (mp_cert == NULL) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSS:X509 - clonePublicKey called before X509 loaded");
}
// Import the key into the provider to get a pointer to the key
if (getPublicKeyType() == XSECCryptoKey::KEY_DSA_PUBLIC) {
SECKEYPublicKey * pubkey = CERT_ExtractPublicKey(mp_cert);
// Now that we have a handle for the DSA key, create a DSA Key object to
// wrap it in
NSSCryptoKeyDSA * ret;
XSECnew(ret, NSSCryptoKeyDSA(pubkey));
return ret;
}
if (getPublicKeyType() == XSECCryptoKey::KEY_RSA_PUBLIC) {
SECKEYPublicKey * pubkey = CERT_ExtractPublicKey(mp_cert);
// Now that we have a handle for the DSA key, create a DSA Key object to
// wrap it in
NSSCryptoKeyRSA * ret;
XSECnew(ret, NSSCryptoKeyRSA(pubkey));
return ret;
}
return NULL; // Unknown key type, but not necessarily an error
}
#endif /* HAVE_NSS */<commit_msg>Instructions for "fixing" compiler error.<commit_after>/*
* Copyright 2005 The Apache Software Foundation.
*
* 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.
*/
/*
* XSEC
*
* NSSCryptoX509:= NSS based class for handling X509 (V3) certificates
*
* Author(s): Milan Tomic
*
*/
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xsec/enc/NSS/NSSCryptoProvider.hpp>
#include <xsec/enc/NSS/NSSCryptoX509.hpp>
#include <xsec/enc/NSS/NSSCryptoKeyDSA.hpp>
#include <xsec/enc/NSS/NSSCryptoKeyRSA.hpp>
#include <xsec/enc/XSECCryptoException.hpp>
#include <xsec/enc/XSCrypt/XSCryptCryptoBase64.hpp>
#if defined (HAVE_NSS)
#include <nss/cert.h>
#include <xercesc/util/Janitor.hpp>
XSEC_USING_XERCES(ArrayJanitor);
// --------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------
NSSCryptoX509::NSSCryptoX509() : m_DERX509(""), mp_cert(NULL) {
}
// --------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------
NSSCryptoX509::NSSCryptoX509(CERTCertificate * pCert) {
// Build this from an existing CERTCertificate structure
mp_cert = pCert;
unsigned char * encCert;
unsigned long len = mp_cert->derCert.len * 2;
XSECnew(encCert, unsigned char [len]);
ArrayJanitor<unsigned char> j_encCert(encCert);
// Base64 Encode
XSCryptCryptoBase64 b64;
b64.encodeInit();
unsigned long encCertLen = b64.encode(mp_cert->derCert.data, mp_cert->derCert.len, encCert, len);
encCertLen += b64.encodeFinish(&encCert[encCertLen], len - encCertLen);
// Check the result
if (encCert == NULL) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSSX509:NSSX509 - Error encoding certificate");
}
m_DERX509.sbMemcpyIn(encCert, encCertLen);
m_DERX509[encCertLen] = '\0';
}
// --------------------------------------------------------------------------------
// Destructor
// --------------------------------------------------------------------------------
NSSCryptoX509::~NSSCryptoX509() {
if (mp_cert != 0)
CERT_DestroyCertificate(mp_cert);
}
// --------------------------------------------------------------------------------
// Load X509
// --------------------------------------------------------------------------------
void NSSCryptoX509::loadX509Base64Bin(const char * buf, unsigned int len) {
unsigned char * rawCert;
XSECnew(rawCert, unsigned char [len]);
ArrayJanitor<unsigned char> j_rawCert(rawCert);
// Base64 Decode
XSCryptCryptoBase64 b64;
b64.decodeInit();
unsigned int rawCertLen = b64.decode((unsigned char *) buf, len, rawCert, len);
rawCertLen += b64.decodeFinish(&rawCert[rawCertLen], len - rawCertLen);
// Now load certificate
SECItem i;
i.type = siBuffer;
i.data = rawCert;
i.len = rawCertLen;
mp_cert = __CERT_DecodeDERCertificate(&i, PR_TRUE, NULL);
// 1. If you got an compiler error here add into "nss/cert.h" delacarion for
// CERT_DecodeDERCertificate() (the same parameters as for __CERT_DecodeDERCertificate())
// 2. Since __CERT_DecodeDERCertificate is a private function we might consider using
// __CERT_NewTempCertificate() or CERT_ImportCerts() instead.
if (mp_cert == 0) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSSX509:loadX509Base64Bin - Error decoding certificate");
}
m_DERX509.sbMemcpyIn(buf, len);
m_DERX509[len] = '\0';
}
// --------------------------------------------------------------------------------
// Get NSS provider name
// --------------------------------------------------------------------------------
const XMLCh * NSSCryptoX509::getProviderName() {
return DSIGConstants::s_unicodeStrPROVNSS;
}
// --------------------------------------------------------------------------------
// Get publickey type: RSA or DSA
// --------------------------------------------------------------------------------
XSECCryptoKey::KeyType NSSCryptoX509::getPublicKeyType() {
if (mp_cert == NULL) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSS:X509 - getPublicKeyType called before X509 loaded");
}
XSECCryptoKey::KeyType kt = XSECCryptoKey::KEY_NONE;
SECKEYPublicKey * pubkey = CERT_ExtractPublicKey(mp_cert);
if (pubkey == 0) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSS:X509 - Error extracting public key from X509 certificate");
}
if (pubkey->keyType == dsaKey)
kt = XSECCryptoKey::KEY_DSA_PUBLIC;
if (pubkey->keyType == rsaKey)
kt = XSECCryptoKey::KEY_RSA_PUBLIC;
SECKEY_DestroyPublicKey(pubkey);
return kt;
}
// --------------------------------------------------------------------------------
// Replicate public key
// --------------------------------------------------------------------------------
XSECCryptoKey * NSSCryptoX509::clonePublicKey() {
if (mp_cert == NULL) {
throw XSECCryptoException(XSECCryptoException::X509Error,
"NSS:X509 - clonePublicKey called before X509 loaded");
}
// Import the key into the provider to get a pointer to the key
if (getPublicKeyType() == XSECCryptoKey::KEY_DSA_PUBLIC) {
SECKEYPublicKey * pubkey = CERT_ExtractPublicKey(mp_cert);
// Now that we have a handle for the DSA key, create a DSA Key object to
// wrap it in
NSSCryptoKeyDSA * ret;
XSECnew(ret, NSSCryptoKeyDSA(pubkey));
return ret;
}
if (getPublicKeyType() == XSECCryptoKey::KEY_RSA_PUBLIC) {
SECKEYPublicKey * pubkey = CERT_ExtractPublicKey(mp_cert);
// Now that we have a handle for the DSA key, create a DSA Key object to
// wrap it in
NSSCryptoKeyRSA * ret;
XSECnew(ret, NSSCryptoKeyRSA(pubkey));
return ret;
}
return NULL; // Unknown key type, but not necessarily an error
}
#endif /* HAVE_NSS */<|endoftext|> |
<commit_before>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.20 2003/09/26 13:15:04 rdm Exp $
// Author: Rene Brun 17/02/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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#include "TError.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(const char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Break("TInterruptHandler::Notify", "keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
return gApplication->HandleTermInput();
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo && !NoLogoOpt())
PrintLogo();
// Everybody expects iostream to be available, so load it...
ProcessLine("#include <iostream>", kTRUE);
// Allow the usage of ClassDef and ClassImp in interpreted macros
ProcessLine("#include <RtypesCint.h>", kTRUE);
// The following libs are also useful to have, make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon),kTRUE);
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
ih->Add();
SetSignalHandler(ih);
// Handle stdin events
fInputHandler = new TTermInputHandler(0);
fInputHandler->Add();
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop, unless the -q
// command line option was specfied in which case the program terminates.
// When retrun is true this method returns even when -q was specified.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt()) {
if (retrn) return;
Terminate(0);
}
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
if (QuitOpt()) {
printf("\n");
if (retrn) return;
Terminate(0);
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *", root_version, root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
if (strstr(gVirtualX->GetName(), "TTF")) {
Int_t major, minor, patch;
//TTF::Version(major, minor, patch);
// avoid dependency on libGraf and hard code, will not change too often
major = 2; minor = 1; patch = 3;
Printf("\nFreeType Engine v%d.%d.%d used to render TrueType fonts.",
major, minor, patch);
}
#ifdef _REENTRANT
else
printf("\n");
Printf("Compiled for %s with thread support.", gSystem->GetBuildArch());
#else
else
printf("\n");
Printf("Compiled for %s.", gSystem->GetBuildArch());
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
static TString op = fDefaultPrompt;
if (newPrompt && strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op.Data();
}
//______________________________________________________________________________
Bool_t TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
Gl_histadd(line);
TString sline = line;
line[0] = 0;
// strip off '\n' and leading and trailing blanks
sline = sline.Chop();
sline = sline.Strip(TString::kBoth);
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++;
// prevent recursive calling of this routine
fInputHandler->Remove();
if (gROOT->Timer()) timer.Start();
ProcessLine(sline);
if (gROOT->Timer()) timer.Print();
// enable again intput handler
fInputHandler->Add();
if (!sline.BeginsWith(".reset"))
gInterpreter->EndOfLineAction();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
return kTRUE;
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<commit_msg>From Philippe: re-enable the input handler after an interrupt.<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.21 2003/10/28 14:09:48 rdm Exp $
// Author: Rene Brun 17/02/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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#include "TError.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(const char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Break("TInterruptHandler::Notify", "keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
return gApplication->HandleTermInput();
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo && !NoLogoOpt())
PrintLogo();
// Everybody expects iostream to be available, so load it...
ProcessLine("#include <iostream>", kTRUE);
// Allow the usage of ClassDef and ClassImp in interpreted macros
ProcessLine("#include <RtypesCint.h>", kTRUE);
// The following libs are also useful to have, make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon),kTRUE);
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
ih->Add();
SetSignalHandler(ih);
// Handle stdin events
fInputHandler = new TTermInputHandler(0);
fInputHandler->Add();
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop, unless the -q
// command line option was specfied in which case the program terminates.
// When retrun is true this method returns even when -q was specified.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt()) {
if (retrn) return;
Terminate(0);
}
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
if (QuitOpt()) {
printf("\n");
if (retrn) return;
Terminate(0);
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *", root_version, root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
if (strstr(gVirtualX->GetName(), "TTF")) {
Int_t major, minor, patch;
//TTF::Version(major, minor, patch);
// avoid dependency on libGraf and hard code, will not change too often
major = 2; minor = 1; patch = 3;
Printf("\nFreeType Engine v%d.%d.%d used to render TrueType fonts.",
major, minor, patch);
}
#ifdef _REENTRANT
else
printf("\n");
Printf("Compiled for %s with thread support.", gSystem->GetBuildArch());
#else
else
printf("\n");
Printf("Compiled for %s.", gSystem->GetBuildArch());
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
static TString op = fDefaultPrompt;
if (newPrompt && strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op.Data();
}
//______________________________________________________________________________
Bool_t TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
Gl_histadd(line);
TString sline = line;
line[0] = 0;
// strip off '\n' and leading and trailing blanks
sline = sline.Chop();
sline = sline.Strip(TString::kBoth);
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++;
// prevent recursive calling of this routine
fInputHandler->Remove();
if (gROOT->Timer()) timer.Start();
Bool_t added = kFALSE;
#ifdef R__EH
try {
#endif
TRY {
ProcessLine(sline);
} CATCH(excode) {
// enable again input handler
fInputHandler->Add();
added = kTRUE;
Throw(excode);
} ENDTRY;
#ifdef R__EH
}
// handle every exception
catch (...) {
// enable again intput handler
if (!added) fInputHandler->Add();
throw;
}
#endif
if (gROOT->Timer()) timer.Print();
// enable again intput handler
fInputHandler->Add();
if (!sline.BeginsWith(".reset"))
gInterpreter->EndOfLineAction();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
return kTRUE;
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2016 ScyllaDB.
*/
#pragma once
#include <ostream>
/// \addtogroup utilities
/// @{
/// \brief Type-safe boolean
///
/// bool_class objects are type-safe boolean values that cannot be implicitly
/// casted to untyped bools, integers or different bool_class types while still
/// provides all relevant logical and comparison operators.
///
/// bool_class template parameter is a tag type that is going to be used to
/// distinguish booleans of different types.
///
/// Usage examples:
/// \code
/// struct foo_tag { };
/// using foo = bool_class<foo_tag>;
///
/// struct bar_tag { };
/// using bar = bool_class<bar_tag>;
///
/// foo v1 = foo::yes; // OK
/// bar v2 = foo::yes; // ERROR, no implicit cast
/// foo v4 = v1 || foo::no; // OK
/// bar v5 = bar::yes && bar(true); // OK
/// bool v6 = v5; // ERROR, no implicit cast
/// \endcode
///
/// \tparam Tag type used as a tag
template<typename Tag>
class bool_class {
bool _value;
public:
static constexpr bool_class yes { true };
static constexpr bool_class no { false };
/// Constructs a bool_class object initialised to \c false.
constexpr bool_class() noexcept : _value(false) { }
/// Constructs a bool_class object initialised to \c v.
constexpr explicit bool_class(bool v) noexcept : _value(v) { }
/// Casts a bool_class object to an untyped \c bool.
explicit operator bool() const noexcept { return _value; }
/// Logical OR.
friend bool_class operator||(bool_class x, bool_class y) noexcept {
return bool_class(x._value || y._value);
}
/// Logical AND.
friend bool_class operator&&(bool_class x, bool_class y) noexcept {
return bool_class(x._value && y._value);
}
/// Logical NOT.
friend bool_class operator!(bool_class x) noexcept {
return bool_class(!x._value);
}
/// Equal-to operator.
friend bool operator==(bool_class x, bool_class y) noexcept {
return x._value == y._value;
}
/// Not-equal-to operator.
friend bool operator!=(bool_class x, bool_class y) noexcept {
return x._value != y._value;
}
/// Prints bool_class value to an output stream.
friend std::ostream& operator<<(std::ostream& os, bool_class v) {
return os << (v._value ? "true" : "false");
}
};
template<typename Tag>
constexpr bool_class<Tag> bool_class<Tag>::yes;
template<typename Tag>
constexpr bool_class<Tag> bool_class<Tag>::no;
/// @}
<commit_msg>bool_class: avoid initializing object of incomplete type<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2016 ScyllaDB.
*/
#pragma once
#include <ostream>
/// \addtogroup utilities
/// @{
/// \brief Type-safe boolean
///
/// bool_class objects are type-safe boolean values that cannot be implicitly
/// casted to untyped bools, integers or different bool_class types while still
/// provides all relevant logical and comparison operators.
///
/// bool_class template parameter is a tag type that is going to be used to
/// distinguish booleans of different types.
///
/// Usage examples:
/// \code
/// struct foo_tag { };
/// using foo = bool_class<foo_tag>;
///
/// struct bar_tag { };
/// using bar = bool_class<bar_tag>;
///
/// foo v1 = foo::yes; // OK
/// bar v2 = foo::yes; // ERROR, no implicit cast
/// foo v4 = v1 || foo::no; // OK
/// bar v5 = bar::yes && bar(true); // OK
/// bool v6 = v5; // ERROR, no implicit cast
/// \endcode
///
/// \tparam Tag type used as a tag
template<typename Tag>
class bool_class {
bool _value;
public:
static const bool_class yes;
static const bool_class no;
/// Constructs a bool_class object initialised to \c false.
constexpr bool_class() noexcept : _value(false) { }
/// Constructs a bool_class object initialised to \c v.
constexpr explicit bool_class(bool v) noexcept : _value(v) { }
/// Casts a bool_class object to an untyped \c bool.
explicit operator bool() const noexcept { return _value; }
/// Logical OR.
friend bool_class operator||(bool_class x, bool_class y) noexcept {
return bool_class(x._value || y._value);
}
/// Logical AND.
friend bool_class operator&&(bool_class x, bool_class y) noexcept {
return bool_class(x._value && y._value);
}
/// Logical NOT.
friend bool_class operator!(bool_class x) noexcept {
return bool_class(!x._value);
}
/// Equal-to operator.
friend bool operator==(bool_class x, bool_class y) noexcept {
return x._value == y._value;
}
/// Not-equal-to operator.
friend bool operator!=(bool_class x, bool_class y) noexcept {
return x._value != y._value;
}
/// Prints bool_class value to an output stream.
friend std::ostream& operator<<(std::ostream& os, bool_class v) {
return os << (v._value ? "true" : "false");
}
};
template<typename Tag>
const bool_class<Tag> bool_class<Tag>::yes { true };
template<typename Tag>
const bool_class<Tag> bool_class<Tag>::no { false };
/// @}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "util/cf_options.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <cassert>
#include <limits>
#include <string>
#include "port/port.h"
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "util/db_options.h"
namespace rocksdb {
ImmutableCFOptions::ImmutableCFOptions(const Options& options)
: ImmutableCFOptions(ImmutableDBOptions(options), options) {}
ImmutableCFOptions::ImmutableCFOptions(const ImmutableDBOptions& db_options,
const ColumnFamilyOptions& cf_options)
: compaction_style(cf_options.compaction_style),
compaction_pri(cf_options.compaction_pri),
compaction_options_universal(cf_options.compaction_options_universal),
compaction_options_fifo(cf_options.compaction_options_fifo),
prefix_extractor(cf_options.prefix_extractor.get()),
comparator(cf_options.comparator),
merge_operator(cf_options.merge_operator.get()),
compaction_filter(cf_options.compaction_filter),
compaction_filter_factory(cf_options.compaction_filter_factory.get()),
min_write_buffer_number_to_merge(
cf_options.min_write_buffer_number_to_merge),
max_write_buffer_number_to_maintain(
cf_options.max_write_buffer_number_to_maintain),
inplace_update_support(cf_options.inplace_update_support),
inplace_callback(cf_options.inplace_callback),
info_log(db_options.info_log.get()),
statistics(db_options.statistics.get()),
env(db_options.env),
delayed_write_rate(db_options.delayed_write_rate),
allow_mmap_reads(db_options.allow_mmap_reads),
allow_mmap_writes(db_options.allow_mmap_writes),
db_paths(db_options.db_paths),
memtable_factory(cf_options.memtable_factory.get()),
table_factory(cf_options.table_factory.get()),
table_properties_collector_factories(
cf_options.table_properties_collector_factories),
advise_random_on_open(db_options.advise_random_on_open),
bloom_locality(cf_options.bloom_locality),
purge_redundant_kvs_while_flush(
cf_options.purge_redundant_kvs_while_flush),
disable_data_sync(db_options.disable_data_sync),
use_fsync(db_options.use_fsync),
compression_per_level(cf_options.compression_per_level),
bottommost_compression(cf_options.bottommost_compression),
compression_opts(cf_options.compression_opts),
level_compaction_dynamic_level_bytes(
cf_options.level_compaction_dynamic_level_bytes),
access_hint_on_compaction_start(
db_options.access_hint_on_compaction_start),
new_table_reader_for_compaction_inputs(
db_options.new_table_reader_for_compaction_inputs),
compaction_readahead_size(db_options.compaction_readahead_size),
num_levels(cf_options.num_levels),
optimize_filters_for_hits(cf_options.optimize_filters_for_hits),
listeners(db_options.listeners),
row_cache(db_options.row_cache),
max_subcompactions(db_options.max_subcompactions) {}
// Multiple two operands. If they overflow, return op1.
uint64_t MultiplyCheckOverflow(uint64_t op1, int op2) {
if (op1 == 0) {
return 0;
}
if (op2 <= 0) {
return op1;
}
uint64_t casted_op2 = (uint64_t) op2;
if (std::numeric_limits<uint64_t>::max() / op1 < casted_op2) {
return op1;
}
return op1 * casted_op2;
}
void MutableCFOptions::RefreshDerivedOptions(int num_levels,
CompactionStyle compaction_style) {
max_file_size.resize(num_levels);
for (int i = 0; i < num_levels; ++i) {
if (i == 0 && compaction_style == kCompactionStyleUniversal) {
max_file_size[i] = ULLONG_MAX;
} else if (i > 1) {
max_file_size[i] = MultiplyCheckOverflow(max_file_size[i - 1],
target_file_size_multiplier);
} else {
max_file_size[i] = target_file_size_base;
}
}
}
uint64_t MutableCFOptions::MaxFileSizeForLevel(int level) const {
assert(level >= 0);
assert(level < (int)max_file_size.size());
return max_file_size[level];
}
void MutableCFOptions::Dump(Logger* log) const {
// Memtable related options
Log(log, " write_buffer_size: %" ROCKSDB_PRIszt,
write_buffer_size);
Log(log, " max_write_buffer_number: %d",
max_write_buffer_number);
Log(log, " arena_block_size: %" ROCKSDB_PRIszt,
arena_block_size);
Log(log, " memtable_prefix_bloom_ratio: %f",
memtable_prefix_bloom_size_ratio);
Log(log, " memtable_huge_page_size: %" ROCKSDB_PRIszt,
memtable_huge_page_size);
Log(log, " max_successive_merges: %" ROCKSDB_PRIszt,
max_successive_merges);
Log(log, " inplace_update_num_locks: %" ROCKSDB_PRIszt,
inplace_update_num_locks);
Log(log, " disable_auto_compactions: %d",
disable_auto_compactions);
Log(log, " soft_pending_compaction_bytes_limit: %" PRIu64,
soft_pending_compaction_bytes_limit);
Log(log, " hard_pending_compaction_bytes_limit: %" PRIu64,
hard_pending_compaction_bytes_limit);
Log(log, " level0_file_num_compaction_trigger: %d",
level0_file_num_compaction_trigger);
Log(log, " level0_slowdown_writes_trigger: %d",
level0_slowdown_writes_trigger);
Log(log, " level0_stop_writes_trigger: %d",
level0_stop_writes_trigger);
Log(log, " max_compaction_bytes: %" PRIu64,
max_compaction_bytes);
Log(log, " target_file_size_base: %" PRIu64,
target_file_size_base);
Log(log, " target_file_size_multiplier: %d",
target_file_size_multiplier);
Log(log, " max_bytes_for_level_base: %" PRIu64,
max_bytes_for_level_base);
Log(log, " max_bytes_for_level_multiplier: %d",
max_bytes_for_level_multiplier);
std::string result;
char buf[10];
for (const auto m : max_bytes_for_level_multiplier_additional) {
snprintf(buf, sizeof(buf), "%d, ", m);
result += buf;
}
result.resize(result.size() - 2);
Log(log, "max_bytes_for_level_multiplier_additional: %s", result.c_str());
Log(log, " verify_checksums_in_compaction: %d",
verify_checksums_in_compaction);
Log(log, " max_sequential_skip_in_iterations: %" PRIu64,
max_sequential_skip_in_iterations);
Log(log, " paranoid_file_checks: %d",
paranoid_file_checks);
Log(log, " report_bg_io_stats: %d", report_bg_io_stats);
Log(log, " compression: %d",
static_cast<int>(compression));
Log(log, " min_partial_merge_operands: %" PRIu32,
min_partial_merge_operands);
}
} // namespace rocksdb
<commit_msg>Fix -ve std::string::resize<commit_after>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "util/cf_options.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <cassert>
#include <limits>
#include <string>
#include "port/port.h"
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "util/db_options.h"
namespace rocksdb {
ImmutableCFOptions::ImmutableCFOptions(const Options& options)
: ImmutableCFOptions(ImmutableDBOptions(options), options) {}
ImmutableCFOptions::ImmutableCFOptions(const ImmutableDBOptions& db_options,
const ColumnFamilyOptions& cf_options)
: compaction_style(cf_options.compaction_style),
compaction_pri(cf_options.compaction_pri),
compaction_options_universal(cf_options.compaction_options_universal),
compaction_options_fifo(cf_options.compaction_options_fifo),
prefix_extractor(cf_options.prefix_extractor.get()),
comparator(cf_options.comparator),
merge_operator(cf_options.merge_operator.get()),
compaction_filter(cf_options.compaction_filter),
compaction_filter_factory(cf_options.compaction_filter_factory.get()),
min_write_buffer_number_to_merge(
cf_options.min_write_buffer_number_to_merge),
max_write_buffer_number_to_maintain(
cf_options.max_write_buffer_number_to_maintain),
inplace_update_support(cf_options.inplace_update_support),
inplace_callback(cf_options.inplace_callback),
info_log(db_options.info_log.get()),
statistics(db_options.statistics.get()),
env(db_options.env),
delayed_write_rate(db_options.delayed_write_rate),
allow_mmap_reads(db_options.allow_mmap_reads),
allow_mmap_writes(db_options.allow_mmap_writes),
db_paths(db_options.db_paths),
memtable_factory(cf_options.memtable_factory.get()),
table_factory(cf_options.table_factory.get()),
table_properties_collector_factories(
cf_options.table_properties_collector_factories),
advise_random_on_open(db_options.advise_random_on_open),
bloom_locality(cf_options.bloom_locality),
purge_redundant_kvs_while_flush(
cf_options.purge_redundant_kvs_while_flush),
disable_data_sync(db_options.disable_data_sync),
use_fsync(db_options.use_fsync),
compression_per_level(cf_options.compression_per_level),
bottommost_compression(cf_options.bottommost_compression),
compression_opts(cf_options.compression_opts),
level_compaction_dynamic_level_bytes(
cf_options.level_compaction_dynamic_level_bytes),
access_hint_on_compaction_start(
db_options.access_hint_on_compaction_start),
new_table_reader_for_compaction_inputs(
db_options.new_table_reader_for_compaction_inputs),
compaction_readahead_size(db_options.compaction_readahead_size),
num_levels(cf_options.num_levels),
optimize_filters_for_hits(cf_options.optimize_filters_for_hits),
listeners(db_options.listeners),
row_cache(db_options.row_cache),
max_subcompactions(db_options.max_subcompactions) {}
// Multiple two operands. If they overflow, return op1.
uint64_t MultiplyCheckOverflow(uint64_t op1, int op2) {
if (op1 == 0) {
return 0;
}
if (op2 <= 0) {
return op1;
}
uint64_t casted_op2 = (uint64_t) op2;
if (std::numeric_limits<uint64_t>::max() / op1 < casted_op2) {
return op1;
}
return op1 * casted_op2;
}
void MutableCFOptions::RefreshDerivedOptions(int num_levels,
CompactionStyle compaction_style) {
max_file_size.resize(num_levels);
for (int i = 0; i < num_levels; ++i) {
if (i == 0 && compaction_style == kCompactionStyleUniversal) {
max_file_size[i] = ULLONG_MAX;
} else if (i > 1) {
max_file_size[i] = MultiplyCheckOverflow(max_file_size[i - 1],
target_file_size_multiplier);
} else {
max_file_size[i] = target_file_size_base;
}
}
}
uint64_t MutableCFOptions::MaxFileSizeForLevel(int level) const {
assert(level >= 0);
assert(level < (int)max_file_size.size());
return max_file_size[level];
}
void MutableCFOptions::Dump(Logger* log) const {
// Memtable related options
Log(log, " write_buffer_size: %" ROCKSDB_PRIszt,
write_buffer_size);
Log(log, " max_write_buffer_number: %d",
max_write_buffer_number);
Log(log, " arena_block_size: %" ROCKSDB_PRIszt,
arena_block_size);
Log(log, " memtable_prefix_bloom_ratio: %f",
memtable_prefix_bloom_size_ratio);
Log(log, " memtable_huge_page_size: %" ROCKSDB_PRIszt,
memtable_huge_page_size);
Log(log, " max_successive_merges: %" ROCKSDB_PRIszt,
max_successive_merges);
Log(log, " inplace_update_num_locks: %" ROCKSDB_PRIszt,
inplace_update_num_locks);
Log(log, " disable_auto_compactions: %d",
disable_auto_compactions);
Log(log, " soft_pending_compaction_bytes_limit: %" PRIu64,
soft_pending_compaction_bytes_limit);
Log(log, " hard_pending_compaction_bytes_limit: %" PRIu64,
hard_pending_compaction_bytes_limit);
Log(log, " level0_file_num_compaction_trigger: %d",
level0_file_num_compaction_trigger);
Log(log, " level0_slowdown_writes_trigger: %d",
level0_slowdown_writes_trigger);
Log(log, " level0_stop_writes_trigger: %d",
level0_stop_writes_trigger);
Log(log, " max_compaction_bytes: %" PRIu64,
max_compaction_bytes);
Log(log, " target_file_size_base: %" PRIu64,
target_file_size_base);
Log(log, " target_file_size_multiplier: %d",
target_file_size_multiplier);
Log(log, " max_bytes_for_level_base: %" PRIu64,
max_bytes_for_level_base);
Log(log, " max_bytes_for_level_multiplier: %d",
max_bytes_for_level_multiplier);
std::string result;
char buf[10];
for (const auto m : max_bytes_for_level_multiplier_additional) {
snprintf(buf, sizeof(buf), "%d, ", m);
result += buf;
}
if (result.size() >= 2) {
result.resize(result.size() - 2);
} else {
result = "";
}
Log(log, "max_bytes_for_level_multiplier_additional: %s", result.c_str());
Log(log, " verify_checksums_in_compaction: %d",
verify_checksums_in_compaction);
Log(log, " max_sequential_skip_in_iterations: %" PRIu64,
max_sequential_skip_in_iterations);
Log(log, " paranoid_file_checks: %d",
paranoid_file_checks);
Log(log, " report_bg_io_stats: %d", report_bg_io_stats);
Log(log, " compression: %d",
static_cast<int>(compression));
Log(log, " min_partial_merge_operands: %" PRIu32,
min_partial_merge_operands);
}
} // namespace rocksdb
<|endoftext|> |
<commit_before>// -*- mode: C++; c-file-style: "gnu" -*-
/**
* folderdiaquotatab.cpp
*
* Copyright (c) 2006 Till Adam <[email protected]>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#include "folderdiaquotatab.h"
#include "kmfolder.h"
#include "kmfoldertype.h"
#include "kmfolderimap.h"
#include "kmfoldercachedimap.h"
#include "kmacctcachedimap.h"
#include "imapaccountbase.h"
#include <qwidgetstack.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qprogressbar.h>
#include <qwhatsthis.h>
#include "folderdiaquotatab_p.h"
#include <assert.h>
using namespace KMail;
KMail::FolderDiaQuotaTab::FolderDiaQuotaTab( KMFolderDialog* dlg, QWidget* parent, const char* name )
: FolderDiaTab( parent, name ),
mImapAccount( 0 ),
mDlg( dlg )
{
QVBoxLayout* topLayout = new QVBoxLayout( this );
// We need a widget stack to show either a label ("no qutoa support", "please wait"...)
// or quota info
mStack = new QWidgetStack( this );
topLayout->addWidget( mStack );
mLabel = new QLabel( mStack );
mLabel->setAlignment( AlignHCenter | AlignVCenter | WordBreak );
mStack->addWidget( mLabel );
mQuotaWidget = new KMail::QuotaWidget( mStack );
}
void KMail::FolderDiaQuotaTab::initializeWithValuesFromFolder( KMFolder* folder )
{
// This can be simplified once KMFolderImap and KMFolderCachedImap have a common base class
mFolderType = folder->folderType();
if ( mFolderType == KMFolderTypeImap ) {
KMFolderImap* folderImap = static_cast<KMFolderImap*>( folder->storage() );
mImapAccount = folderImap->account();
mImapPath = folderImap->imapPath();
}
else if ( mFolderType == KMFolderTypeCachedImap ) {
KMFolderCachedImap* folderImap = static_cast<KMFolderCachedImap*>( folder->storage() );
mImapAccount = folderImap->account();
mQuotaInfo = folderImap->quotaInfo();
}
else
assert( 0 ); // see KMFolderDialog constructor
}
void KMail::FolderDiaQuotaTab::load()
{
if ( mDlg->folder() ) {
// existing folder
initializeWithValuesFromFolder( mDlg->folder() );
} else if ( mDlg->parentFolder() ) {
// new folder
initializeWithValuesFromFolder( mDlg->parentFolder() );
}
if ( mFolderType == KMFolderTypeCachedImap ) {
showQuotaWidget();
return;
}
assert( mFolderType == KMFolderTypeImap );
// Loading, for online IMAP, consists of two steps:
// 1) connect
// 2) get quota info
// First ensure we are connected
mStack->raiseWidget( mLabel );
if ( !mImapAccount ) { // hmmm?
mLabel->setText( i18n( "Error: no IMAP account defined for this folder" ) );
return;
}
KMFolder* folder = mDlg->folder() ? mDlg->folder() : mDlg->parentFolder();
if ( folder && folder->storage() == mImapAccount->rootFolder() )
return; // nothing to be done for the (virtual) account folder
mLabel->setText( i18n( "Connecting to server %1, please wait..." ).arg( mImapAccount->host() ) );
ImapAccountBase::ConnectionState state = mImapAccount->makeConnection();
if ( state == ImapAccountBase::Error ) { // Cancelled by user, or slave can't start
slotConnectionResult( -1, QString::null );
} else if ( state == ImapAccountBase::Connecting ) {
connect( mImapAccount, SIGNAL( connectionResult(int, const QString&) ),
this, SLOT( slotConnectionResult(int, const QString&) ) );
} else { // Connected
slotConnectionResult( 0, QString::null );
}
}
void KMail::FolderDiaQuotaTab::slotConnectionResult( int errorCode, const QString& errorMsg )
{
disconnect( mImapAccount, SIGNAL( connectionResult(int, const QString&) ),
this, SLOT( slotConnectionResult(int, const QString&) ) );
if ( errorCode ) {
if ( errorCode == -1 ) // unspecified error
mLabel->setText( i18n( "Error connecting to server %1" ).arg( mImapAccount->host() ) );
else
// Connection error (error message box already shown by the account)
mLabel->setText( KIO::buildErrorString( errorCode, errorMsg ) );
return;
}
connect( mImapAccount, SIGNAL( receivedStorageQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& ) ),
this, SLOT( slotReceivedQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& ) ) );
KMFolder* folder = mDlg->folder() ? mDlg->folder() : mDlg->parentFolder();
mImapAccount->getStorageQuotaInfo( folder, mImapPath );
}
void KMail::FolderDiaQuotaTab::slotReceivedQuotaInfo( KMFolder* folder,
KIO::Job* job,
const KMail::QuotaInfo& info )
{
if ( folder == mDlg->folder() ? mDlg->folder() : mDlg->parentFolder() ) {
//KMFolderImap* folderImap = static_cast<KMFolderImap*>( folder->storage() );
disconnect( mImapAccount, SIGNAL(receivedStorageQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& )),
this, SLOT(slotReceivedQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& )) );
if ( job && job->error() ) {
if ( job->error() == KIO::ERR_UNSUPPORTED_ACTION )
mLabel->setText( i18n( "This account does not have support for quota information." ) );
else
mLabel->setText( i18n( "Error retrieving quota information from server\n%1" ).arg( job->errorString() ) );
} else {
mQuotaInfo = info;
}
showQuotaWidget();
}
}
void KMail::FolderDiaQuotaTab::showQuotaWidget()
{
if ( !mQuotaInfo.isValid() ) {
if ( !mImapAccount->hasQuotaSupport() ) {
mLabel->setText( i18n( "This account does not have support for quota information." ) );
}
} else {
if ( !mQuotaInfo.isEmpty() ) {
mStack->raiseWidget( mQuotaWidget );
mQuotaWidget->setQuotaInfo( mQuotaInfo );
} else {
mLabel->setText( i18n( "No quota is set for this folder." ) );
}
}
}
KMail::FolderDiaTab::AcceptStatus KMail::FolderDiaQuotaTab::accept()
{
if ( mFolderType == KMFolderTypeCachedImap || mFolderType == KMFolderTypeImap )
return Accepted;
else
assert(0);
}
bool KMail::FolderDiaQuotaTab::save()
{
// nothing to do, we are read-only
return true;
}
bool KMail::FolderDiaQuotaTab::supports( KMFolder* refFolder )
{
ImapAccountBase* imapAccount = 0;
if ( refFolder->folderType() == KMFolderTypeImap )
imapAccount = static_cast<KMFolderImap*>( refFolder->storage() )->account();
else if ( refFolder->folderType() == KMFolderTypeCachedImap )
imapAccount = static_cast<KMFolderCachedImap*>( refFolder->storage() )->account();
return imapAccount && imapAccount->hasQuotaSupport(); // support for Quotas (or not tried connecting yet)
}
#include "folderdiaquotatab.moc"
<commit_msg>Make this code pass our automated testing - otherwise it looks like it returns garbage<commit_after>// -*- mode: C++; c-file-style: "gnu" -*-
/**
* folderdiaquotatab.cpp
*
* Copyright (c) 2006 Till Adam <[email protected]>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#include "folderdiaquotatab.h"
#include "kmfolder.h"
#include "kmfoldertype.h"
#include "kmfolderimap.h"
#include "kmfoldercachedimap.h"
#include "kmacctcachedimap.h"
#include "imapaccountbase.h"
#include <qwidgetstack.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qprogressbar.h>
#include <qwhatsthis.h>
#include "folderdiaquotatab_p.h"
#include <assert.h>
using namespace KMail;
KMail::FolderDiaQuotaTab::FolderDiaQuotaTab( KMFolderDialog* dlg, QWidget* parent, const char* name )
: FolderDiaTab( parent, name ),
mImapAccount( 0 ),
mDlg( dlg )
{
QVBoxLayout* topLayout = new QVBoxLayout( this );
// We need a widget stack to show either a label ("no qutoa support", "please wait"...)
// or quota info
mStack = new QWidgetStack( this );
topLayout->addWidget( mStack );
mLabel = new QLabel( mStack );
mLabel->setAlignment( AlignHCenter | AlignVCenter | WordBreak );
mStack->addWidget( mLabel );
mQuotaWidget = new KMail::QuotaWidget( mStack );
}
void KMail::FolderDiaQuotaTab::initializeWithValuesFromFolder( KMFolder* folder )
{
// This can be simplified once KMFolderImap and KMFolderCachedImap have a common base class
mFolderType = folder->folderType();
if ( mFolderType == KMFolderTypeImap ) {
KMFolderImap* folderImap = static_cast<KMFolderImap*>( folder->storage() );
mImapAccount = folderImap->account();
mImapPath = folderImap->imapPath();
}
else if ( mFolderType == KMFolderTypeCachedImap ) {
KMFolderCachedImap* folderImap = static_cast<KMFolderCachedImap*>( folder->storage() );
mImapAccount = folderImap->account();
mQuotaInfo = folderImap->quotaInfo();
}
else
assert( 0 ); // see KMFolderDialog constructor
}
void KMail::FolderDiaQuotaTab::load()
{
if ( mDlg->folder() ) {
// existing folder
initializeWithValuesFromFolder( mDlg->folder() );
} else if ( mDlg->parentFolder() ) {
// new folder
initializeWithValuesFromFolder( mDlg->parentFolder() );
}
if ( mFolderType == KMFolderTypeCachedImap ) {
showQuotaWidget();
return;
}
assert( mFolderType == KMFolderTypeImap );
// Loading, for online IMAP, consists of two steps:
// 1) connect
// 2) get quota info
// First ensure we are connected
mStack->raiseWidget( mLabel );
if ( !mImapAccount ) { // hmmm?
mLabel->setText( i18n( "Error: no IMAP account defined for this folder" ) );
return;
}
KMFolder* folder = mDlg->folder() ? mDlg->folder() : mDlg->parentFolder();
if ( folder && folder->storage() == mImapAccount->rootFolder() )
return; // nothing to be done for the (virtual) account folder
mLabel->setText( i18n( "Connecting to server %1, please wait..." ).arg( mImapAccount->host() ) );
ImapAccountBase::ConnectionState state = mImapAccount->makeConnection();
if ( state == ImapAccountBase::Error ) { // Cancelled by user, or slave can't start
slotConnectionResult( -1, QString::null );
} else if ( state == ImapAccountBase::Connecting ) {
connect( mImapAccount, SIGNAL( connectionResult(int, const QString&) ),
this, SLOT( slotConnectionResult(int, const QString&) ) );
} else { // Connected
slotConnectionResult( 0, QString::null );
}
}
void KMail::FolderDiaQuotaTab::slotConnectionResult( int errorCode, const QString& errorMsg )
{
disconnect( mImapAccount, SIGNAL( connectionResult(int, const QString&) ),
this, SLOT( slotConnectionResult(int, const QString&) ) );
if ( errorCode ) {
if ( errorCode == -1 ) // unspecified error
mLabel->setText( i18n( "Error connecting to server %1" ).arg( mImapAccount->host() ) );
else
// Connection error (error message box already shown by the account)
mLabel->setText( KIO::buildErrorString( errorCode, errorMsg ) );
return;
}
connect( mImapAccount, SIGNAL( receivedStorageQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& ) ),
this, SLOT( slotReceivedQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& ) ) );
KMFolder* folder = mDlg->folder() ? mDlg->folder() : mDlg->parentFolder();
mImapAccount->getStorageQuotaInfo( folder, mImapPath );
}
void KMail::FolderDiaQuotaTab::slotReceivedQuotaInfo( KMFolder* folder,
KIO::Job* job,
const KMail::QuotaInfo& info )
{
if ( folder == mDlg->folder() ? mDlg->folder() : mDlg->parentFolder() ) {
//KMFolderImap* folderImap = static_cast<KMFolderImap*>( folder->storage() );
disconnect( mImapAccount, SIGNAL(receivedStorageQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& )),
this, SLOT(slotReceivedQuotaInfo( KMFolder*, KIO::Job*, const KMail::QuotaInfo& )) );
if ( job && job->error() ) {
if ( job->error() == KIO::ERR_UNSUPPORTED_ACTION )
mLabel->setText( i18n( "This account does not have support for quota information." ) );
else
mLabel->setText( i18n( "Error retrieving quota information from server\n%1" ).arg( job->errorString() ) );
} else {
mQuotaInfo = info;
}
showQuotaWidget();
}
}
void KMail::FolderDiaQuotaTab::showQuotaWidget()
{
if ( !mQuotaInfo.isValid() ) {
if ( !mImapAccount->hasQuotaSupport() ) {
mLabel->setText( i18n( "This account does not have support for quota information." ) );
}
} else {
if ( !mQuotaInfo.isEmpty() ) {
mStack->raiseWidget( mQuotaWidget );
mQuotaWidget->setQuotaInfo( mQuotaInfo );
} else {
mLabel->setText( i18n( "No quota is set for this folder." ) );
}
}
}
KMail::FolderDiaTab::AcceptStatus KMail::FolderDiaQuotaTab::accept()
{
if ( mFolderType == KMFolderTypeCachedImap || mFolderType == KMFolderTypeImap )
return Accepted;
else
assert(0);
return Accepted; // our code sanity checker doesn't know there is no coming back from assert(0)
}
bool KMail::FolderDiaQuotaTab::save()
{
// nothing to do, we are read-only
return true;
}
bool KMail::FolderDiaQuotaTab::supports( KMFolder* refFolder )
{
ImapAccountBase* imapAccount = 0;
if ( refFolder->folderType() == KMFolderTypeImap )
imapAccount = static_cast<KMFolderImap*>( refFolder->storage() )->account();
else if ( refFolder->folderType() == KMFolderTypeCachedImap )
imapAccount = static_cast<KMFolderCachedImap*>( refFolder->storage() )->account();
return imapAccount && imapAccount->hasQuotaSupport(); // support for Quotas (or not tried connecting yet)
}
#include "folderdiaquotatab.moc"
<|endoftext|> |
<commit_before>/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cartographer/io/proto_stream.h"
namespace cartographer {
namespace io {
namespace {
// First eight bytes to identify our proto stream format.
const uint64 kMagic = 0x7b1d1f7b5bf501db;
void WriteSizeAsLittleEndian(uint64 size, std::ostream* out) {
for (int i = 0; i != 8; ++i) {
out->put(size & 0xff);
size >>= 8;
}
}
bool ReadSizeAsLittleEndian(std::istream* in, uint64* size) {
*size = 0;
for (int i = 0; i != 8; ++i) {
*size >>= 8;
*size += static_cast<uint64>(in->get()) << 56;
}
return !in->fail();
}
} // namespace
ProtoStreamWriter::ProtoStreamWriter(const std::string& filename)
: out_(filename, std::ios::out | std::ios::binary) {
WriteSizeAsLittleEndian(kMagic, &out_);
}
void ProtoStreamWriter::Write(const std::string& uncompressed_data) {
std::string compressed_data;
common::FastGzipString(uncompressed_data, &compressed_data);
WriteSizeAsLittleEndian(compressed_data.size(), &out_);
out_.write(compressed_data.data(), compressed_data.size());
}
void ProtoStreamWriter::WriteProto(const google::protobuf::Message& proto) {
std::string uncompressed_data;
proto.SerializeToString(&uncompressed_data);
Write(uncompressed_data);
}
bool ProtoStreamWriter::Close() {
out_.close();
return !out_.fail();
}
ProtoStreamReader::ProtoStreamReader(const std::string& filename)
: in_(filename, std::ios::in | std::ios::binary) {
uint64 magic;
if (!ReadSizeAsLittleEndian(&in_, &magic) || magic != kMagic) {
in_.setstate(std::ios::failbit);
}
}
bool ProtoStreamReader::Read(std::string* decompressed_data) {
uint64 compressed_size;
if (!ReadSizeAsLittleEndian(&in_, &compressed_size)) {
return false;
}
std::string compressed_data(compressed_size, '\0');
if (!in_.read(&compressed_data.front(), compressed_size)) {
return false;
}
common::FastGunzipString(compressed_data, decompressed_data);
return true;
}
bool ProtoStreamReader::ReadProto(google::protobuf::Message* proto) {
std::string decompressed_data;
return Read(&decompressed_data) && proto->ParseFromString(decompressed_data);
}
bool ProtoStreamReader::eof() const { return in_.eof(); }
} // namespace io
} // namespace cartographer
<commit_msg>Check ifstream::good() in proto_stream.cc (#929)<commit_after>/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cartographer/io/proto_stream.h"
#include "glog/logging.h"
namespace cartographer {
namespace io {
namespace {
// First eight bytes to identify our proto stream format.
const uint64 kMagic = 0x7b1d1f7b5bf501db;
void WriteSizeAsLittleEndian(uint64 size, std::ostream* out) {
for (int i = 0; i != 8; ++i) {
out->put(size & 0xff);
size >>= 8;
}
}
bool ReadSizeAsLittleEndian(std::istream* in, uint64* size) {
*size = 0;
for (int i = 0; i != 8; ++i) {
*size >>= 8;
*size += static_cast<uint64>(in->get()) << 56;
}
return !in->fail();
}
} // namespace
ProtoStreamWriter::ProtoStreamWriter(const std::string& filename)
: out_(filename, std::ios::out | std::ios::binary) {
WriteSizeAsLittleEndian(kMagic, &out_);
}
void ProtoStreamWriter::Write(const std::string& uncompressed_data) {
std::string compressed_data;
common::FastGzipString(uncompressed_data, &compressed_data);
WriteSizeAsLittleEndian(compressed_data.size(), &out_);
out_.write(compressed_data.data(), compressed_data.size());
}
void ProtoStreamWriter::WriteProto(const google::protobuf::Message& proto) {
std::string uncompressed_data;
proto.SerializeToString(&uncompressed_data);
Write(uncompressed_data);
}
bool ProtoStreamWriter::Close() {
out_.close();
return !out_.fail();
}
ProtoStreamReader::ProtoStreamReader(const std::string& filename)
: in_(filename, std::ios::in | std::ios::binary) {
uint64 magic;
if (!ReadSizeAsLittleEndian(&in_, &magic) || magic != kMagic) {
in_.setstate(std::ios::failbit);
}
CHECK(in_.good()) << "Failed to open proto stream '" << filename << "'.";
}
bool ProtoStreamReader::Read(std::string* decompressed_data) {
uint64 compressed_size;
if (!ReadSizeAsLittleEndian(&in_, &compressed_size)) {
return false;
}
std::string compressed_data(compressed_size, '\0');
if (!in_.read(&compressed_data.front(), compressed_size)) {
return false;
}
common::FastGunzipString(compressed_data, decompressed_data);
return true;
}
bool ProtoStreamReader::ReadProto(google::protobuf::Message* proto) {
std::string decompressed_data;
return Read(&decompressed_data) && proto->ParseFromString(decompressed_data);
}
bool ProtoStreamReader::eof() const { return in_.eof(); }
} // namespace io
} // namespace cartographer
<|endoftext|> |
<commit_before>AliAnalysisTaskSEHFQA* AddTaskHFQA(AliAnalysisTaskSEHFQA::DecChannel ch,TString filecutsname="",Bool_t readMC=kFALSE, Bool_t simplemode=kFALSE, Int_t system=1 /*0=pp, 1=PbPb*/, TString finDirname=""){
//
// Test macro for the AliAnalysisTaskSE for HF mesons quality assurance
//Author: C.Bianchin [email protected]
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskHFQA", "No analysis manager to connect to.");
return NULL;
}
Bool_t stdcuts=kFALSE;
TFile* filecuts;
if( filecutsname.EqualTo("") ) {
stdcuts=kTRUE;
} else {
filecuts=TFile::Open(filecutsname.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
AliFatal("Input file not found : check your cut object");
}
}
Bool_t onoff[5]={kTRUE,kTRUE,kTRUE,kTRUE,kTRUE}; //tracks (0), PID (1), centrality (2), event selection(3), flow observables(4)
if(system==0) onoff[2]=kFALSE;
AliRDHFCuts *analysiscuts=0x0;
TString filename="",out1name="nEntriesQA",out2name="outputPid",out3name="outputTrack",out4name="cuts",out5name="countersCentrality",out6name="outputCentrCheck",out7name="outputEvSel",out8name="outputFlowObs",inname="input",suffix="",cutsobjname="",centr="";
filename = AliAnalysisManager::GetCommonFileName();
filename += ":PWG3_D2H_QA";
filename += finDirname.Data();
switch (ch){
case 0:
cutsobjname="AnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDplustoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(cutsobjname);
suffix="Dplus";
break;
case 1:
cutsobjname="D0toKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(cutsobjname);
suffix="D0";
break;
case 2:
cutsobjname="DStartoKpipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDStartoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDstartoKpipi*)filecuts->Get(cutsobjname);
suffix="Dstar";
break;
case 3:
cutsobjname="DstoKKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDstoKKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2010();
}
else analysiscuts = (AliRDHFCutsDstoKKpi*)filecuts->Get(cutsobjname);
suffix="Ds";
break;
case 4:
cutsobjname="D0toKpipipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpipipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2010();
}
else analysiscuts = (AliRDHFCutsD0toKpipipi*)filecuts->Get(cutsobjname);
suffix="D04";
break;
case 5:
cutsobjname="LctopKpiAnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsLctopKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2010();
}
else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get(cutsobjname);
suffix="Lc";
break;
}
inname+=suffix;
out1name+=suffix;
out2name+=suffix;
out3name+=suffix;
out4name=cutsobjname;
out5name+=suffix;
out6name+=suffix;
out7name+=suffix;
out8name+=suffix;
if(!analysiscuts && filecutsname!="none"){
cout<<"Specific AliRDHFCuts not found"<<endl;
return;
}
centr=Form("%.0f%.0f",analysiscuts->GetMinCentrality(),analysiscuts->GetMaxCentrality());
inname+=centr;
out1name+=centr;
out2name+=centr;
out3name+=centr;
out4name+=centr;
out5name+=centr;
out6name+=centr;
out7name+=centr;
out8name+=centr;
inname+= finDirname.Data();
out1name+= finDirname.Data();
out2name+= finDirname.Data();
out3name+= finDirname.Data();
out4name+= finDirname.Data();
out5name+= finDirname.Data();
out6name+= finDirname.Data();
out7name+= finDirname.Data();
out8name+= finDirname.Data();
AliAnalysisTaskSEHFQA* taskQA=new AliAnalysisTaskSEHFQA(Form("QA%s",suffix.Data()),ch,analysiscuts);
taskQA->SetReadMC(readMC);
taskQA->SetSimpleMode(simplemode); // set to kTRUE to go faster in PbPb
taskQA->SetTrackOn(onoff[0]);
taskQA->SetPIDOn(onoff[1]);
taskQA->SetCentralityOn(onoff[2]);
taskQA->SetEvSelectionOn(onoff[3]);
taskQA->SetFlowObsOn(onoff[4]);
mgr->AddTask(taskQA);
//
// Create containers for input/output
AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer);
mgr->ConnectInput(taskQA,0,mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(out1name,TH1F::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //events analysed
mgr->ConnectOutput(taskQA,1,coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(out2name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //PID
if(onoff[1]) mgr->ConnectOutput(taskQA,2,coutput2);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of tracks
if(onoff[0]) mgr->ConnectOutput(taskQA,3,coutput3);
AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(out4name,AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
mgr->ConnectOutput(taskQA,4,coutput4);
AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(out5name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(onoff[2]) mgr->ConnectOutput(taskQA,5,coutput5);
AliAnalysisDataContainer *coutput6 = mgr->CreateContainer(out6name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(onoff[2]) mgr->ConnectOutput(taskQA,6,coutput6);
AliAnalysisDataContainer *coutput7 = mgr->CreateContainer(out7name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //event selection
if(onoff[3]) mgr->ConnectOutput(taskQA,7,coutput7);
AliAnalysisDataContainer *coutput8 = mgr->CreateContainer(out8name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //flow observables
if(onoff[4]) mgr->ConnectOutput(taskQA,8,coutput8);
return taskQA;
}
<commit_msg>Update to allow to swicth off one by one different parts of the QA task (ChiaraB)<commit_after>AliAnalysisTaskSEHFQA* AddTaskHFQA(AliAnalysisTaskSEHFQA::DecChannel ch,TString filecutsname="",Bool_t readMC=kFALSE, Bool_t simplemode=kFALSE, Int_t system=1 /*0=pp, 1=PbPb*/, TString finDirname="",Bool_t trackon=kTRUE,Bool_t pidon=kTRUE,Bool_t centralityon=kTRUE, Bool_t eventselon=kTRUE, Bool_t flowobson=kFALSE){
//
// Test macro for the AliAnalysisTaskSE for HF mesons quality assurance
//Author: C.Bianchin [email protected]
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskHFQA", "No analysis manager to connect to.");
return NULL;
}
Bool_t stdcuts=kFALSE;
TFile* filecuts;
if( filecutsname.EqualTo("") ) {
stdcuts=kTRUE;
} else {
filecuts=TFile::Open(filecutsname.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
AliFatal("Input file not found : check your cut object");
}
}
if(system==0) centralityon=kFALSE;
AliRDHFCuts *analysiscuts=0x0;
TString filename="",out1name="nEntriesQA",out2name="outputPid",out3name="outputTrack",out4name="cuts",out5name="countersCentrality",out6name="outputCentrCheck",out7name="outputEvSel",out8name="outputFlowObs",inname="input",suffix="",cutsobjname="",centr="";
filename = AliAnalysisManager::GetCommonFileName();
filename += ":PWG3_D2H_QA";
filename += finDirname.Data();
switch (ch){
case 0:
cutsobjname="AnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDplustoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(cutsobjname);
suffix="Dplus";
break;
case 1:
cutsobjname="D0toKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(cutsobjname);
suffix="D0";
break;
case 2:
cutsobjname="DStartoKpipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDStartoKpipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2011();
}
else analysiscuts = (AliRDHFCutsDstartoKpipi*)filecuts->Get(cutsobjname);
suffix="Dstar";
break;
case 3:
cutsobjname="DstoKKpiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsDstoKKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2010();
}
else analysiscuts = (AliRDHFCutsDstoKKpi*)filecuts->Get(cutsobjname);
suffix="Ds";
break;
case 4:
cutsobjname="D0toKpipipiCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsD0toKpipipi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2010();
}
else analysiscuts = (AliRDHFCutsD0toKpipipi*)filecuts->Get(cutsobjname);
suffix="D04";
break;
case 5:
cutsobjname="LctopKpiAnalysisCuts";
if(stdcuts) {
analysiscuts = new AliRDHFCutsLctopKpi();
if (system == 0) analysiscuts->SetStandardCutsPP2010();
else analysiscuts->SetStandardCutsPbPb2010();
}
else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get(cutsobjname);
suffix="Lc";
break;
}
inname+=suffix;
out1name+=suffix;
out2name+=suffix;
out3name+=suffix;
out4name=cutsobjname;
out5name+=suffix;
out6name+=suffix;
out7name+=suffix;
out8name+=suffix;
if(!analysiscuts && filecutsname!="none"){
cout<<"Specific AliRDHFCuts not found"<<endl;
return;
}
centr=Form("%.0f%.0f",analysiscuts->GetMinCentrality(),analysiscuts->GetMaxCentrality());
inname+=centr;
out1name+=centr;
out2name+=centr;
out3name+=centr;
out4name+=centr;
out5name+=centr;
out6name+=centr;
out7name+=centr;
out8name+=centr;
inname+= finDirname.Data();
out1name+= finDirname.Data();
out2name+= finDirname.Data();
out3name+= finDirname.Data();
out4name+= finDirname.Data();
out5name+= finDirname.Data();
out6name+= finDirname.Data();
out7name+= finDirname.Data();
out8name+= finDirname.Data();
AliAnalysisTaskSEHFQA* taskQA=new AliAnalysisTaskSEHFQA(Form("QA%s",suffix.Data()),ch,analysiscuts);
taskQA->SetReadMC(readMC);
taskQA->SetSimpleMode(simplemode); // set to kTRUE to go faster in PbPb
taskQA->SetTrackOn(trackon);
taskQA->SetPIDOn(pidon);
taskQA->SetCentralityOn(centralityon);
taskQA->SetEvSelectionOn(eventselon);
taskQA->SetFlowObsOn(flowobson);
mgr->AddTask(taskQA);
//
// Create containers for input/output
AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer);
mgr->ConnectInput(taskQA,0,mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(out1name,TH1F::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //events analysed
mgr->ConnectOutput(taskQA,1,coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(out2name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //PID
if(pidon) mgr->ConnectOutput(taskQA,2,coutput2);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of tracks
if(trackon) mgr->ConnectOutput(taskQA,3,coutput3);
AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(out4name,AliRDHFCuts::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
mgr->ConnectOutput(taskQA,4,coutput4);
AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(out5name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(centralityon) mgr->ConnectOutput(taskQA,5,coutput5);
AliAnalysisDataContainer *coutput6 = mgr->CreateContainer(out6name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //quality of centrality
if(centralityon) mgr->ConnectOutput(taskQA,6,coutput6);
AliAnalysisDataContainer *coutput7 = mgr->CreateContainer(out7name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //event selection
if(eventselon) mgr->ConnectOutput(taskQA,7,coutput7);
AliAnalysisDataContainer *coutput8 = mgr->CreateContainer(out8name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //flow observables
if(flowobson) mgr->ConnectOutput(taskQA,8,coutput8);
return taskQA;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* @file red_black_tree_no_parent.h
* @author Alan.W
* @date 12 July 2014
* @remark Implementation of CLRS algorithms, using C++ templates.
***************************************************************************/
//!
//! Problem 13-2 Join operation on red-black trees
//!
//! a. Given a red-black tree T , let us store its black-height as the new attribute T:bh.
//! Argue that RB-INSERT and RB-DELETE can maintain the bh attribute with-
//! out requiring extra storage in the nodes of the tree and without increasing the
//! asymptotic running times. Show that while descending through T , we can de-
//! termine the black-height of each node we visit in O(1) time per node visited.
//!
// Insert : as shown by running the testing code below, black hight only increments
// when the root changes to red. This property can also be proven through
// its symmetry.
// So black height can be maintained like so.
//!
#ifndef RED_BLACK_TREE_WITH_BH_HPP
#define RED_BLACK_TREE_WITH_BH_HPP
#include "redblacktree.hpp"
namespace ch13
{
/**
* @brief The RedBlackTreeWithBh class
*
* for problem 13-2.a
*/
template<typename K, typename D>
class RedBlackTreeWithBh : public RedBlackTree<K,D>
{
public:
using Base = RedBlackTree<K,D>;
using sPointer = typename Base::sPointer;
using KeyType = typename Base::KeyType;
using DataType = typename Base::DataType;
using NodeType = typename Base::NodeType;
using SizeType = std::size_t;
/**
* @brief default Ctor
*/
RedBlackTreeWithBh():
Base(),black_height(0)
{}
/**
* @brief print
*/
virtual void print() const
{
RedBlackTree<K,D>::print();
std::cout << debug::yellow("black Height = ")
<< black_height
<< std::endl;
std::cout << "\n" << std::endl;
}
/**
* @brief insert
* @param key
* @param data
*/
virtual void insert(const KeyType &key, const DataType& data)
{
sPointer added = std::make_shared<NodeType>(key,data);
insert(added);
}
/**
* @brief insert
* @param key
*/
virtual void insert(const KeyType& key)
{
sPointer added = std::make_shared<NodeType>(key);
insert(added);
}
virtual void remove(sPointer target)
{
sPointer x,y;
Color y_original_color;
if(target->left == this->nil)
{
y = target;
y_original_color = y->color;
x = y->right;
Base::transplant(target,x);
}
else if(target->right == this->nil)
{
y = target;
y_original_color = y->color;
x = y->left;
Base::transplant(target,x);
}
else
{
y = Base::minimum(target->right);
y_original_color = y->color;
x = y->right;
if(y->parent.lock() == target)
x->parent = y;
else
{
Base::transplant(y,x);
y->right = target->right;
y->right->parent = y;
}
Base::transplant(target, y);
y->left = target->left;
y->left->parent = y;
y->color = target->color;
}
if(y_original_color == Color::BLACK)
remove_fixup(x);
}
virtual ~RedBlackTreeWithBh(){ }
protected:
SizeType black_height;
/**
* @brief insert
* @param added
*
* @complx O(h)
*/
virtual void insert(sPointer added)
{
sPointer tracker = Base::nil;
sPointer curr = Base::root;
while(curr != Base::nil)
{
tracker = curr;
curr = curr->key > added->key? curr->left : curr->right;
}
added->parent = tracker;
if(tracker == Base::nil)
Base::root = added;
else
(added->key < tracker->key? tracker->left : tracker->right)
= added;
added->left = added->right = Base::nil;
added->color= Color::RED;
insert_fixup(added);
}
/**
* @brief insert_fixup
* @param added
*
* @complx O(h)
*/
virtual void insert_fixup(sPointer added)
{
while(Base::ascend(added,1)->color == Color::RED)
{
if(Base::ascend(added,1)->is_left())
{
sPointer uncle = Base::ascend(added,2)->right;
if(uncle->color == Color::RED)
{
uncle->color = Color::BLACK;
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
added = Base::ascend(added,2);
}
else
{
if(added->is_right())
{
added = Base::ascend(added,1);
Base::left_rotate(added);
}
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
Base::right_rotate(Base::ascend(added,2));
}
}
else
{
sPointer uncle = Base::ascend(added,2)->left;
if(uncle->color == Color::RED)
{
uncle->color = Color::BLACK;
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
added = Base::ascend(added,2);
}
else
{
if(added->is_left())
{
added = Base::ascend(added,1);
Base::right_rotate(added);
}
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
Base::left_rotate(Base::ascend(added,2));
}
}
}
//! @attention:
//! maintain the black height data member
//! as required in problem 13-1.a
if(Base::root->color == Color::RED
&&
(Base::root->left != Base::nil
||
Base::root->right != Base::nil))
++black_height;
Base::root->color = Color::BLACK;
}
/**
* @brief remove_fixup
* @param x
*
* @complx O(lg n)
* @todo find a way to maintain bh when deleting
*/
virtual void remove_fixup(sPointer x)
{
while(x != Base::root && x->color == Color::BLACK)
{
if(x->is_left())
{
sPointer sister = Base::sibling(x);
//! case 1
if(sister->color == Color::RED)
{
sister->color = Color::BLACK;
Base::ascend(x,1)->color = Color::RED;
Base::left_rotate(Base::ascend(x,1));
sister = Base::ascend(x,1)->right;
}
//! case 2
if(sister->left->color == Color::BLACK
&&
sister->right->color == Color::BLACK)
{
sister->color = Color::RED;
x = Base::ascend(x,1);
}
else
{
//! case 3
if(sister->right->color == Color::BLACK)
{
sister->left->color = Color::BLACK;
sister->color = Color::BLACK;
Base::right_rotate(sister);
sister = Base::sibling(x);
}
//! case 4
sister->color = Base::ascend(x,1)->color;
Base::ascend(x,1)->color= Color::BLACK;
sister->right->color = Color::BLACK;
Base::left_rotate(Base::ascend(x,1));
x = Base::root;
}
}
else
{
sPointer sister = Base::sibling(x);
//! case 1
if(sister->color == Color::RED)
{
sister->color = Color::BLACK;
Base::ascend(x,1)->color = Color::RED;
Base::right_rotate(Base::ascend(x,1));
sister = Base::ascend(x,1)->left;
}
//! case 2
if(sister->left->color == Color::BLACK
&&
sister->right->color == Color::BLACK)
{
sister->color = Color::RED;
x = Base::ascend(x,1);
}
else
{
//! case 3
if(sister->left->color == Color::BLACK)
{
sister->right->color = Color::BLACK;
sister->color = Color::BLACK;
Base::left_rotate(sister);
sister = Base::sibling(x);
}
//! case 4
sister->color = Base::ascend(x,1)->color;
Base::ascend(x,1)->color = Color::BLACK;
sister->left->color = Color::BLACK;
Base::right_rotate(Base::ascend(x,1));
x = Base::root;
}
}
}
x->color = Color::BLACK;
}
};
}//namespace
#endif // RED_BLACK_TREE_WITH_BH_HPP
//! code for testing problem 13-2.a insert part
//#include <iostream>
//#include <vector>
//#include "red_black_tree_with_bh.hpp"
//int main()
//{
// ch13::RedBlackTreeWithBh<int, std::string> tree;
// std::vector<int> v = {41,38,31,12,19,8,7,5,2,0};
// for(auto i : v)
// tree.insert(i);
// tree.print();
// return 0;
//}
<commit_msg>update On branch ch13 modified: ch13/red_black_tree_with_bh.hpp<commit_after>/***************************************************************************
* @file red_black_tree_no_parent.h
* @author Alan.W
* @date 12 July 2014
* @remark Implementation of CLRS algorithms, using C++ templates.
***************************************************************************/
//!
//! Problem 13-2 Join operation on red-black trees
//!
//! a. Given a red-black tree T , let us store its black-height as the new attribute T:bh.
//! Argue that RB-INSERT and RB-DELETE can maintain the bh attribute with-
//! out requiring extra storage in the nodes of the tree and without increasing the
//! asymptotic running times. Show that while descending through T , we can de-
//! termine the black-height of each node we visit in O(1) time per node visited.
//!
// Insert : as shown by running the testing code below, black hight only increments
// when the root changes to red. This property can also be proven through
// its symmetry.
// So black height can be maintained like so.
//
// Deletion: to be done.
//
// deterining the node's bh in O(1) time:
// as get_bh() shows
//
//!
#ifndef RED_BLACK_TREE_WITH_BH_HPP
#define RED_BLACK_TREE_WITH_BH_HPP
#include "redblacktree.hpp"
namespace ch13
{
/**
* @brief The RedBlackTreeWithBh class
*
* for problem 13-2.a
*/
template<typename K, typename D>
class RedBlackTreeWithBh : public RedBlackTree<K,D>
{
public:
using Base = RedBlackTree<K,D>;
using sPointer = typename Base::sPointer;
using KeyType = typename Base::KeyType;
using DataType = typename Base::DataType;
using NodeType = typename Base::NodeType;
using SizeType = std::size_t;
/**
* @brief default Ctor
*/
RedBlackTreeWithBh():
Base(),black_height(0)
{}
/**
* @brief print
*/
virtual void print() const
{
RedBlackTree<K,D>::print();
std::cout << debug::yellow("black Height = ")
<< black_height
<< std::endl;
std::cout << "\n" << std::endl;
}
/**
* @brief insert
* @param key
* @param data
*/
virtual void insert(const KeyType &key, const DataType& data)
{
sPointer added = std::make_shared<NodeType>(key,data);
insert(added);
}
/**
* @brief insert
* @param key
*/
virtual void insert(const KeyType& key)
{
sPointer added = std::make_shared<NodeType>(key);
insert(added);
}
virtual void remove(sPointer target)
{
sPointer x,y;
Color y_original_color;
if(target->left == this->nil)
{
y = target;
y_original_color = y->color;
x = y->right;
Base::transplant(target,x);
}
else if(target->right == this->nil)
{
y = target;
y_original_color = y->color;
x = y->left;
Base::transplant(target,x);
}
else
{
y = Base::minimum(target->right);
y_original_color = y->color;
x = y->right;
if(y->parent.lock() == target)
x->parent = y;
else
{
Base::transplant(y,x);
y->right = target->right;
y->right->parent = y;
}
Base::transplant(target, y);
y->left = target->left;
y->left->parent = y;
y->color = target->color;
}
if(y_original_color == Color::BLACK)
remove_fixup(x);
}
virtual ~RedBlackTreeWithBh(){ }
protected:
SizeType black_height;
/**
* @brief insert
* @param added
*
* @complx O(h)
*/
virtual void insert(sPointer added)
{
sPointer tracker = Base::nil;
sPointer curr = Base::root;
while(curr != Base::nil)
{
tracker = curr;
curr = curr->key > added->key? curr->left : curr->right;
}
added->parent = tracker;
if(tracker == Base::nil)
Base::root = added;
else
(added->key < tracker->key? tracker->left : tracker->right)
= added;
added->left = added->right = Base::nil;
added->color= Color::RED;
insert_fixup(added);
}
/**
* @brief insert_fixup
* @param added
*
* @complx O(h)
*/
virtual void insert_fixup(sPointer added)
{
while(Base::ascend(added,1)->color == Color::RED)
{
if(Base::ascend(added,1)->is_left())
{
sPointer uncle = Base::ascend(added,2)->right;
if(uncle->color == Color::RED)
{
uncle->color = Color::BLACK;
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
added = Base::ascend(added,2);
}
else
{
if(added->is_right())
{
added = Base::ascend(added,1);
Base::left_rotate(added);
}
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
Base::right_rotate(Base::ascend(added,2));
}
}
else
{
sPointer uncle = Base::ascend(added,2)->left;
if(uncle->color == Color::RED)
{
uncle->color = Color::BLACK;
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
added = Base::ascend(added,2);
}
else
{
if(added->is_left())
{
added = Base::ascend(added,1);
Base::right_rotate(added);
}
Base::ascend(added,1)->color = Color::BLACK;
Base::ascend(added,2)->color = Color::RED;
Base::left_rotate(Base::ascend(added,2));
}
}
}
//! @attention:
//! maintain the black height data member
//! as required in problem 13-1.a
if(Base::root->color == Color::RED
&&
(Base::root->left != Base::nil
||
Base::root->right != Base::nil))
++black_height;
Base::root->color = Color::BLACK;
}
/**
* @brief remove_fixup
* @param x
*
* @complx O(lg n)
* @todo find a way to maintain bh when deleting
*/
virtual void remove_fixup(sPointer x)
{
while(x != Base::root && x->color == Color::BLACK)
{
if(x->is_left())
{
sPointer sister = Base::sibling(x);
//! case 1
if(sister->color == Color::RED)
{
sister->color = Color::BLACK;
Base::ascend(x,1)->color = Color::RED;
Base::left_rotate(Base::ascend(x,1));
sister = Base::ascend(x,1)->right;
}
//! case 2
if(sister->left->color == Color::BLACK
&&
sister->right->color == Color::BLACK)
{
sister->color = Color::RED;
x = Base::ascend(x,1);
}
else
{
//! case 3
if(sister->right->color == Color::BLACK)
{
sister->left->color = Color::BLACK;
sister->color = Color::BLACK;
Base::right_rotate(sister);
sister = Base::sibling(x);
}
//! case 4
sister->color = Base::ascend(x,1)->color;
Base::ascend(x,1)->color= Color::BLACK;
sister->right->color = Color::BLACK;
Base::left_rotate(Base::ascend(x,1));
x = Base::root;
}
}
else
{
sPointer sister = Base::sibling(x);
//! case 1
if(sister->color == Color::RED)
{
sister->color = Color::BLACK;
Base::ascend(x,1)->color = Color::RED;
Base::right_rotate(Base::ascend(x,1));
sister = Base::ascend(x,1)->left;
}
//! case 2
if(sister->left->color == Color::BLACK
&&
sister->right->color == Color::BLACK)
{
sister->color = Color::RED;
x = Base::ascend(x,1);
}
else
{
//! case 3
if(sister->left->color == Color::BLACK)
{
sister->right->color = Color::BLACK;
sister->color = Color::BLACK;
Base::left_rotate(sister);
sister = Base::sibling(x);
}
//! case 4
sister->color = Base::ascend(x,1)->color;
Base::ascend(x,1)->color = Color::BLACK;
sister->left->color = Color::BLACK;
Base::right_rotate(Base::ascend(x,1));
x = Base::root;
}
}
}
x->color = Color::BLACK;
}
};
}//namespace
#endif // RED_BLACK_TREE_WITH_BH_HPP
//! code for testing problem 13-2.a insert part
//#include <iostream>
//#include <vector>
//#include "red_black_tree_with_bh.hpp"
//int main()
//{
// ch13::RedBlackTreeWithBh<int, std::string> tree;
// std::vector<int> v = {41,38,31,12,19,8,7,5,2,0};
// for(auto i : v)
// tree.insert(i);
// tree.print();
// return 0;
//}
<|endoftext|> |
<commit_before><commit_msg>Autofill filling on HTML form fills all entries except the entry clicked<commit_after><|endoftext|> |
<commit_before>//===---- ClangQuery.cpp - clang-query tool -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool is for interactive exploration of the Clang AST using AST matchers.
// It currently allows the user to enter a matcher at an interactive prompt and
// view the resulting bindings as diagnostics, AST pretty prints or AST dumps.
// Example session:
//
// $ cat foo.c
// void foo(void) {}
// $ clang-query foo.c --
// clang-query> match functionDecl()
//
// Match #1:
//
// foo.c:1:1: note: "root" binds here
// void foo(void) {}
// ^~~~~~~~~~~~~~~~~
// 1 match.
//
//===----------------------------------------------------------------------===//
#include "Query.h"
#include "QueryParser.h"
#include "QuerySession.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include <fstream>
#include <string>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::dynamic;
using namespace clang::query;
using namespace clang::tooling;
using namespace llvm;
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::OptionCategory ClangQueryCategory("clang-query options");
static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
cl::value_desc("command"),
cl::cat(ClangQueryCategory));
static cl::list<std::string> CommandFiles("f",
cl::desc("Read commands from file"),
cl::value_desc("file"),
cl::cat(ClangQueryCategory));
static cl::opt<std::string> PreloadFile(
"preload",
cl::desc("Preload commands from file and start interactive mode"),
cl::value_desc("file"), cl::cat(ClangQueryCategory));
bool runCommandsInFile(const char *ExeName, std::string const &FileName,
QuerySession &QS) {
std::ifstream Input(FileName.c_str());
if (!Input.is_open()) {
llvm::errs() << ExeName << ": cannot open " << FileName << "\n";
return 1;
}
while (Input.good()) {
std::string Line;
std::getline(Input, Line);
QueryRef Q = QueryParser::parse(Line, QS);
if (!Q->run(llvm::outs(), QS))
return true;
}
return false;
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
if (!Commands.empty() && !CommandFiles.empty()) {
llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
return 1;
}
if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) {
llvm::errs() << argv[0]
<< ": cannot specify both -c or -f with --preload\n";
return 1;
}
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
std::vector<std::unique_ptr<ASTUnit>> ASTs;
if (Tool.buildASTs(ASTs) != 0)
return 1;
QuerySession QS(ASTs);
if (!Commands.empty()) {
for (auto I = Commands.begin(), E = Commands.end(); I != E; ++I) {
QueryRef Q = QueryParser::parse(*I, QS);
if (!Q->run(llvm::outs(), QS))
return 1;
}
} else if (!CommandFiles.empty()) {
for (auto I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) {
if (runCommandsInFile(argv[0], *I, QS))
return 1;
}
} else {
if (!PreloadFile.empty()) {
if (runCommandsInFile(argv[0], PreloadFile, QS))
return 1;
}
LineEditor LE("clang-query");
LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
return QueryParser::complete(Line, Pos, QS);
});
while (llvm::Optional<std::string> Line = LE.readLine()) {
QueryRef Q = QueryParser::parse(*Line, QS);
Q->run(llvm::outs(), QS);
llvm::outs().flush();
if (QS.Terminate)
break;
}
}
return 0;
}
<commit_msg>[clang-query] Continue if compilation command not found for some files<commit_after>//===---- ClangQuery.cpp - clang-query tool -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool is for interactive exploration of the Clang AST using AST matchers.
// It currently allows the user to enter a matcher at an interactive prompt and
// view the resulting bindings as diagnostics, AST pretty prints or AST dumps.
// Example session:
//
// $ cat foo.c
// void foo(void) {}
// $ clang-query foo.c --
// clang-query> match functionDecl()
//
// Match #1:
//
// foo.c:1:1: note: "root" binds here
// void foo(void) {}
// ^~~~~~~~~~~~~~~~~
// 1 match.
//
//===----------------------------------------------------------------------===//
#include "Query.h"
#include "QueryParser.h"
#include "QuerySession.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include <fstream>
#include <string>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::dynamic;
using namespace clang::query;
using namespace clang::tooling;
using namespace llvm;
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::OptionCategory ClangQueryCategory("clang-query options");
static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
cl::value_desc("command"),
cl::cat(ClangQueryCategory));
static cl::list<std::string> CommandFiles("f",
cl::desc("Read commands from file"),
cl::value_desc("file"),
cl::cat(ClangQueryCategory));
static cl::opt<std::string> PreloadFile(
"preload",
cl::desc("Preload commands from file and start interactive mode"),
cl::value_desc("file"), cl::cat(ClangQueryCategory));
bool runCommandsInFile(const char *ExeName, std::string const &FileName,
QuerySession &QS) {
std::ifstream Input(FileName.c_str());
if (!Input.is_open()) {
llvm::errs() << ExeName << ": cannot open " << FileName << "\n";
return 1;
}
while (Input.good()) {
std::string Line;
std::getline(Input, Line);
QueryRef Q = QueryParser::parse(Line, QS);
if (!Q->run(llvm::outs(), QS))
return true;
}
return false;
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
if (!Commands.empty() && !CommandFiles.empty()) {
llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
return 1;
}
if ((!Commands.empty() || !CommandFiles.empty()) && !PreloadFile.empty()) {
llvm::errs() << argv[0]
<< ": cannot specify both -c or -f with --preload\n";
return 1;
}
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
std::vector<std::unique_ptr<ASTUnit>> ASTs;
int Status = Tool.buildASTs(ASTs);
int ASTStatus = 0;
if (Status == 1) {
// Building ASTs failed.
return 1;
} else if (Status == 2) {
ASTStatus |= 1;
llvm::errs() << "Failed to build AST for some of the files, "
<< "results may be incomplete."
<< "\n";
} else {
assert(Status == 0 && "Unexpected status returned");
}
QuerySession QS(ASTs);
if (!Commands.empty()) {
for (auto I = Commands.begin(), E = Commands.end(); I != E; ++I) {
QueryRef Q = QueryParser::parse(*I, QS);
if (!Q->run(llvm::outs(), QS))
return 1;
}
} else if (!CommandFiles.empty()) {
for (auto I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) {
if (runCommandsInFile(argv[0], *I, QS))
return 1;
}
} else {
if (!PreloadFile.empty()) {
if (runCommandsInFile(argv[0], PreloadFile, QS))
return 1;
}
LineEditor LE("clang-query");
LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
return QueryParser::complete(Line, Pos, QS);
});
while (llvm::Optional<std::string> Line = LE.readLine()) {
QueryRef Q = QueryParser::parse(*Line, QS);
Q->run(llvm::outs(), QS);
llvm::outs().flush();
if (QS.Terminate)
break;
}
}
return ASTStatus;
}
<|endoftext|> |
<commit_before>#include "representer.h"
#include "debug.h"
#include "geometryutils.h"
#include "manager.h"
#include "resulteditor.h"
#include "resultwidget.h"
#include "settings.h"
#include "task.h"
#include "trayicon.h"
#include <QApplication>
#include <QClipboard>
#include <QMouseEvent>
#include <QScreen>
Representer::Representer(Manager &manager, TrayIcon &tray,
const Settings &settings, const CommonModels &models)
: manager_(manager)
, tray_(tray)
, settings_(settings)
, models_(models)
{
}
Representer::~Representer() = default;
void Representer::showLast()
{
if (settings_.resultShowType == ResultMode::Tooltip) {
SOFT_ASSERT(lastTooltipTask_, return );
showTooltip(lastTooltipTask_);
return;
}
SOFT_ASSERT(!widgets_.empty(), return );
for (auto &widget : widgets_) {
SOFT_ASSERT(widget->task(), continue);
if (widget->task()->generation != generation_)
continue;
widget->show();
widget->activateWindow();
}
}
void Representer::clipboardLast()
{
if (settings_.resultShowType == ResultMode::Tooltip) {
SOFT_ASSERT(lastTooltipTask_, return );
clipboardText(lastTooltipTask_);
return;
}
SOFT_ASSERT(!widgets_.empty(), return );
SOFT_ASSERT(widgets_.front()->task(), return );
clipboardText(widgets_.front()->task());
tray_.showInformation(
QObject::tr("The last result was copied to the clipboard."));
}
void Representer::represent(const TaskPtr &task)
{
if (settings_.resultShowType == ResultMode::Tooltip)
showTooltip(task);
else
showWidget(task);
}
bool Representer::isVisible() const
{
if (widgets_.empty())
return false;
return std::any_of(widgets_.cbegin(), widgets_.cend(),
[](const auto &w) { return w->isVisible(); });
}
void Representer::hide()
{
if (widgets_.empty())
return;
for (auto &w : widgets_) w->hide();
}
void Representer::updateSettings()
{
lastTooltipTask_.reset();
if (widgets_.empty())
return;
for (auto &w : widgets_) w->updateSettings();
}
void Representer::clipboardText(const TaskPtr &task)
{
if (!task)
return;
QClipboard *clipboard = QApplication::clipboard();
auto text = task->recognized;
if (!task->translated.isEmpty())
text += QLatin1String(" - ") + task->translated;
clipboard->setText(text);
}
void Representer::clipboardImage(const TaskPtr &task)
{
if (!task)
return;
QClipboard *clipboard = QApplication::clipboard();
clipboard->setPixmap(task->captured);
}
void Representer::edit(const TaskPtr &task)
{
if (!editor_)
editor_ = std::make_unique<ResultEditor>(manager_, models_, settings_);
editor_->show(task);
const auto cursor = QCursor::pos();
const auto screen = QApplication::screenAt(cursor);
SOFT_ASSERT(screen, return );
editor_->move(service::geometry::cornerAtPoint(cursor, editor_->size(),
screen->geometry()));
}
bool Representer::eventFilter(QObject * /*watched*/, QEvent *event)
{
if (event->type() == QEvent::WindowDeactivate) {
for (const auto &w : widgets_) {
if (w->isActiveWindow())
return false;
}
hide();
} else if (event->type() == QEvent::MouseButtonPress) {
const auto casted = static_cast<QMouseEvent *>(event);
if (casted->button() == Qt::LeftButton)
hide();
}
return false;
}
void Representer::showTooltip(const TaskPtr &task)
{
SOFT_ASSERT(task, return );
lastTooltipTask_ = task;
auto message = task->recognized + " - " + task->translated;
tray_.showInformation(message);
}
void Representer::showWidget(const TaskPtr &task)
{
SOFT_ASSERT(task, return );
generation_ = task->generation;
auto index = 0u;
const auto count = widgets_.size();
for (; index < count; ++index) {
auto &widget = widgets_[index];
SOFT_ASSERT(widget->task(), continue);
if (widget->task()->generation != generation_)
break;
}
if (index == count) {
widgets_.emplace_back(
std::make_unique<ResultWidget>(manager_, *this, settings_));
widgets_.back()->installEventFilter(this);
}
auto &widget = widgets_[index];
widget->show(task);
}
<commit_msg>Do not show translation via tray if not requested<commit_after>#include "representer.h"
#include "debug.h"
#include "geometryutils.h"
#include "manager.h"
#include "resulteditor.h"
#include "resultwidget.h"
#include "settings.h"
#include "task.h"
#include "trayicon.h"
#include <QApplication>
#include <QClipboard>
#include <QMouseEvent>
#include <QScreen>
Representer::Representer(Manager &manager, TrayIcon &tray,
const Settings &settings, const CommonModels &models)
: manager_(manager)
, tray_(tray)
, settings_(settings)
, models_(models)
{
}
Representer::~Representer() = default;
void Representer::showLast()
{
if (settings_.resultShowType == ResultMode::Tooltip) {
SOFT_ASSERT(lastTooltipTask_, return );
showTooltip(lastTooltipTask_);
return;
}
SOFT_ASSERT(!widgets_.empty(), return );
for (auto &widget : widgets_) {
SOFT_ASSERT(widget->task(), continue);
if (widget->task()->generation != generation_)
continue;
widget->show();
widget->activateWindow();
}
}
void Representer::clipboardLast()
{
if (settings_.resultShowType == ResultMode::Tooltip) {
SOFT_ASSERT(lastTooltipTask_, return );
clipboardText(lastTooltipTask_);
return;
}
SOFT_ASSERT(!widgets_.empty(), return );
SOFT_ASSERT(widgets_.front()->task(), return );
clipboardText(widgets_.front()->task());
tray_.showInformation(
QObject::tr("The last result was copied to the clipboard."));
}
void Representer::represent(const TaskPtr &task)
{
if (settings_.resultShowType == ResultMode::Tooltip)
showTooltip(task);
else
showWidget(task);
}
bool Representer::isVisible() const
{
if (widgets_.empty())
return false;
return std::any_of(widgets_.cbegin(), widgets_.cend(),
[](const auto &w) { return w->isVisible(); });
}
void Representer::hide()
{
if (widgets_.empty())
return;
for (auto &w : widgets_) w->hide();
}
void Representer::updateSettings()
{
lastTooltipTask_.reset();
if (widgets_.empty())
return;
for (auto &w : widgets_) w->updateSettings();
}
void Representer::clipboardText(const TaskPtr &task)
{
if (!task)
return;
QClipboard *clipboard = QApplication::clipboard();
auto text = task->recognized;
if (!task->translated.isEmpty())
text += QLatin1String(" - ") + task->translated;
clipboard->setText(text);
}
void Representer::clipboardImage(const TaskPtr &task)
{
if (!task)
return;
QClipboard *clipboard = QApplication::clipboard();
clipboard->setPixmap(task->captured);
}
void Representer::edit(const TaskPtr &task)
{
if (!editor_)
editor_ = std::make_unique<ResultEditor>(manager_, models_, settings_);
editor_->show(task);
const auto cursor = QCursor::pos();
const auto screen = QApplication::screenAt(cursor);
SOFT_ASSERT(screen, return );
editor_->move(service::geometry::cornerAtPoint(cursor, editor_->size(),
screen->geometry()));
}
bool Representer::eventFilter(QObject * /*watched*/, QEvent *event)
{
if (event->type() == QEvent::WindowDeactivate) {
for (const auto &w : widgets_) {
if (w->isActiveWindow())
return false;
}
hide();
} else if (event->type() == QEvent::MouseButtonPress) {
const auto casted = static_cast<QMouseEvent *>(event);
if (casted->button() == Qt::LeftButton)
hide();
}
return false;
}
void Representer::showTooltip(const TaskPtr &task)
{
SOFT_ASSERT(task, return );
lastTooltipTask_ = task;
auto message = task->recognized;
if (!task->translated.isEmpty())
message += QLatin1String(" - ") + task->translated;
tray_.showInformation(message);
}
void Representer::showWidget(const TaskPtr &task)
{
SOFT_ASSERT(task, return );
generation_ = task->generation;
auto index = 0u;
const auto count = widgets_.size();
for (; index < count; ++index) {
auto &widget = widgets_[index];
SOFT_ASSERT(widget->task(), continue);
if (widget->task()->generation != generation_)
break;
}
if (index == count) {
widgets_.emplace_back(
std::make_unique<ResultWidget>(manager_, *this, settings_));
widgets_.back()->installEventFilter(this);
}
auto &widget = widgets_[index];
widget->show(task);
}
<|endoftext|> |
<commit_before>// Copyright 2019 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 <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <tuple>
#include <vector>
#include "absl/base/optimization.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/backward_writer.h"
#include "riegeli/bytes/chain_backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/null_backward_writer.h"
#include "riegeli/bytes/reader.h"
#include "riegeli/bytes/std_io.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/chunk_encoding/chunk.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_decoder.h"
#include "riegeli/messages/message_parse.h"
#include "riegeli/messages/message_serialize.h"
#include "riegeli/messages/text_print.h"
#include "riegeli/records/chunk_reader.h"
#include "riegeli/records/records_metadata.pb.h"
#include "riegeli/records/skipped_region.h"
#include "riegeli/records/tools/riegeli_summary.pb.h"
#include "riegeli/varint/varint_reading.h"
ABSL_FLAG(bool, show_records_metadata, true,
"If true, show parsed file metadata.");
ABSL_FLAG(bool, show_record_sizes, false,
"If true, show the list of record sizes in each chunk.");
ABSL_FLAG(bool, show_records, false,
"If true, show contents of records in each chunk.");
namespace riegeli {
namespace tools {
namespace {
absl::Status DescribeFileMetadataChunk(const Chunk& chunk,
RecordsMetadata& records_metadata) {
// Based on `RecordReaderBase::ParseMetadata()`.
if (ABSL_PREDICT_FALSE(chunk.header.num_records() != 0)) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid file metadata chunk: number of records is not zero: ",
chunk.header.num_records()));
}
ChainReader<> data_reader(&chunk.data);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> serialized_metadata_writer(
ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
std::vector<size_t> limits;
const bool decode_ok = transpose_decoder.Decode(
1, chunk.header.decoded_data_size(), FieldProjection::All(), data_reader,
serialized_metadata_writer, limits);
if (ABSL_PREDICT_FALSE(!serialized_metadata_writer.Close())) {
return serialized_metadata_writer.status();
}
if (ABSL_PREDICT_FALSE(!decode_ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!data_reader.VerifyEndAndClose())) {
return data_reader.status();
}
const Chain& serialized_metadata = serialized_metadata_writer.dest();
RIEGELI_ASSERT_EQ(limits.size(), 1u)
<< "Metadata chunk has unexpected record limits";
RIEGELI_ASSERT_EQ(limits.back(), serialized_metadata.size())
<< "Metadata chunk has unexpected record limits";
return ParseFromChain(serialized_metadata, records_metadata);
}
absl::Status ReadRecords(
Reader& src, const std::vector<size_t>& limits,
google::protobuf::RepeatedPtrField<std::string>& dest) {
// Based on `ChunkDecoder::ReadRecord()`.
const Position initial_pos = src.pos();
for (const size_t limit : limits) {
const size_t start = IntCast<size_t>(src.pos() - initial_pos);
RIEGELI_ASSERT_LE(start, limit) << "Record end positions not sorted";
if (ABSL_PREDICT_FALSE(!src.Read(limit - start, *dest.Add()))) {
return src.StatusOrAnnotate(
absl::InvalidArgumentError("Reading record failed"));
}
}
return absl::OkStatus();
}
absl::Status DescribeSimpleChunk(const Chunk& chunk,
summary::SimpleChunk& simple_chunk) {
ChainReader<> src(&chunk.data);
const bool show_record_sizes = absl::GetFlag(FLAGS_show_record_sizes);
const bool show_records = absl::GetFlag(FLAGS_show_records);
// Based on `SimpleDecoder::Decode()`.
uint8_t compression_type_byte;
if (ABSL_PREDICT_FALSE(!src.ReadByte(compression_type_byte))) {
return absl::InvalidArgumentError("Reading compression type failed");
}
const CompressionType compression_type =
static_cast<CompressionType>(compression_type_byte);
simple_chunk.set_compression_type(
static_cast<summary::CompressionType>(compression_type));
if (show_record_sizes || show_records) {
uint64_t sizes_size;
if (ABSL_PREDICT_FALSE(!ReadVarint64(src, sizes_size))) {
return absl::InvalidArgumentError("Reading size of sizes failed");
}
chunk_encoding_internal::Decompressor<LimitingReader<>> sizes_decompressor(
std::forward_as_tuple(
&src, LimitingReaderBase::Options().set_exact_length(sizes_size)),
compression_type);
if (ABSL_PREDICT_FALSE(!sizes_decompressor.ok())) {
return sizes_decompressor.status();
}
if (show_record_sizes) {
if (ABSL_PREDICT_FALSE(chunk.header.num_records() >
unsigned{std::numeric_limits<int>::max()})) {
return absl::ResourceExhaustedError("Too many records");
}
simple_chunk.mutable_record_sizes()->Reserve(
IntCast<int>(chunk.header.num_records()));
}
std::vector<size_t> limits;
if (show_records) {
if (ABSL_PREDICT_FALSE(chunk.header.num_records() > limits.max_size())) {
return absl::ResourceExhaustedError("Too many records");
}
limits.reserve(IntCast<size_t>(chunk.header.num_records()));
}
size_t limit = 0;
for (uint64_t i = 0; i < chunk.header.num_records(); ++i) {
uint64_t size;
if (ABSL_PREDICT_FALSE(
!ReadVarint64(sizes_decompressor.reader(), size))) {
return sizes_decompressor.reader().StatusOrAnnotate(
absl::InvalidArgumentError("Reading record size failed"));
}
if (ABSL_PREDICT_FALSE(size > chunk.header.decoded_data_size() - limit)) {
return absl::InvalidArgumentError(
"Decoded data size larger than expected");
}
limit += IntCast<size_t>(size);
if (show_record_sizes) simple_chunk.add_record_sizes(size);
if (show_records) limits.push_back(limit);
}
if (ABSL_PREDICT_FALSE(!sizes_decompressor.VerifyEndAndClose())) {
return sizes_decompressor.status();
}
if (ABSL_PREDICT_FALSE(limit != chunk.header.decoded_data_size())) {
return absl::InvalidArgumentError(
"Decoded data size smaller than expected");
}
if (show_records) {
chunk_encoding_internal::Decompressor<> records_decompressor(
&src, compression_type);
if (ABSL_PREDICT_FALSE(!records_decompressor.ok())) {
return records_decompressor.status();
}
{
absl::Status status = ReadRecords(records_decompressor.reader(), limits,
*simple_chunk.mutable_records());
if (!status.ok()) {
return status;
}
}
if (ABSL_PREDICT_FALSE(!records_decompressor.VerifyEndAndClose())) {
return records_decompressor.status();
}
if (ABSL_PREDICT_FALSE(!src.VerifyEndAndClose())) return src.status();
}
}
return absl::OkStatus();
}
absl::Status DescribeTransposedChunk(
const Chunk& chunk, summary::TransposedChunk& transposed_chunk) {
ChainReader<> src(&chunk.data);
const bool show_record_sizes = absl::GetFlag(FLAGS_show_record_sizes);
const bool show_records = absl::GetFlag(FLAGS_show_records);
// Based on `TransposeDecoder::Decode()`.
uint8_t compression_type_byte;
if (ABSL_PREDICT_FALSE(!src.ReadByte(compression_type_byte))) {
return absl::InvalidArgumentError("Reading compression type failed");
}
transposed_chunk.set_compression_type(
static_cast<summary::CompressionType>(compression_type_byte));
if (show_record_sizes || show_records) {
// Based on `ChunkDecoder::Parse()`.
src.Seek(0);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> chain_dest_writer(kClosed);
NullBackwardWriter null_dest_writer(kClosed);
BackwardWriter* dest_writer;
if (show_records) {
chain_dest_writer.Reset(ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
dest_writer = &chain_dest_writer;
} else {
null_dest_writer.Reset();
dest_writer = &null_dest_writer;
}
std::vector<size_t> limits;
const bool decode_ok = transpose_decoder.Decode(
chunk.header.num_records(), chunk.header.decoded_data_size(),
FieldProjection::All(), src, *dest_writer, limits);
if (ABSL_PREDICT_FALSE(!dest_writer->Close())) return dest_writer->status();
if (ABSL_PREDICT_FALSE(!decode_ok)) return transpose_decoder.status();
if (show_record_sizes) {
if (ABSL_PREDICT_FALSE(limits.size() >
unsigned{std::numeric_limits<int>::max()})) {
return absl::ResourceExhaustedError("Too many records");
}
transposed_chunk.mutable_record_sizes()->Reserve(
IntCast<int>(limits.size()));
size_t prev_limit = 0;
for (const size_t next_limit : limits) {
RIEGELI_ASSERT_LE(prev_limit, next_limit)
<< "Failed postcondition of TransposeDecoder: "
"record end positions not sorted";
transposed_chunk.add_record_sizes(next_limit - prev_limit);
prev_limit = next_limit;
}
}
if (show_records) {
ChainReader<> records_reader(&chain_dest_writer.dest());
{
absl::Status status = ReadRecords(records_reader, limits,
*transposed_chunk.mutable_records());
if (!status.ok()) {
return status;
}
}
if (ABSL_PREDICT_FALSE(!records_reader.VerifyEndAndClose())) {
return records_reader.status();
}
}
if (ABSL_PREDICT_FALSE(!src.VerifyEndAndClose())) return src.status();
}
return absl::OkStatus();
}
void DescribeFile(absl::string_view filename, Writer& report, Writer& errors) {
absl::Format(&report,
"file {\n"
" filename: \"%s\"\n",
absl::Utf8SafeCEscape(filename));
DefaultChunkReader<FdReader<>> chunk_reader(std::forward_as_tuple(filename));
if (chunk_reader.SupportsRandomAccess()) {
const absl::optional<Position> size = chunk_reader.Size();
if (size != absl::nullopt) {
absl::Format(&report, " file_size: %u\n", *size);
}
}
TextPrintOptions print_options;
print_options.printer().SetInitialIndentLevel(2);
print_options.printer().SetUseShortRepeatedPrimitives(true);
print_options.printer().SetUseUtf8StringEscaping(true);
for (;;) {
report.Flush();
const Position chunk_begin = chunk_reader.pos();
Chunk chunk;
if (ABSL_PREDICT_FALSE(!chunk_reader.ReadChunk(chunk))) {
SkippedRegion skipped_region;
if (chunk_reader.Recover(&skipped_region)) {
absl::Format(&errors, "%s\n", skipped_region.message());
continue;
}
break;
}
summary::Chunk chunk_summary;
chunk_summary.set_chunk_begin(chunk_begin);
chunk_summary.set_chunk_type(
static_cast<summary::ChunkType>(chunk.header.chunk_type()));
chunk_summary.set_data_size(chunk.header.data_size());
chunk_summary.set_num_records(chunk.header.num_records());
chunk_summary.set_decoded_data_size(chunk.header.decoded_data_size());
{
absl::Status status;
switch (chunk.header.chunk_type()) {
case ChunkType::kFileMetadata:
if (absl::GetFlag(FLAGS_show_records_metadata)) {
status = DescribeFileMetadataChunk(
chunk, *chunk_summary.mutable_file_metadata_chunk());
}
break;
case ChunkType::kSimple:
status =
DescribeSimpleChunk(chunk, *chunk_summary.mutable_simple_chunk());
break;
case ChunkType::kTransposed:
status = DescribeTransposedChunk(
chunk, *chunk_summary.mutable_transposed_chunk());
break;
default:
break;
}
if (ABSL_PREDICT_FALSE(!status.ok())) {
absl::Format(&errors, "%s\n", status.message());
}
}
absl::Format(&report, " chunk {\n");
TextPrintToWriter(chunk_summary, report, print_options).IgnoreError();
absl::Format(&report, " }\n");
}
absl::Format(&report, "}\n");
report.Flush();
if (!chunk_reader.Close()) {
absl::Format(&errors, "%s\n", chunk_reader.status().message());
}
}
const char kUsage[] =
"Usage: describe_riegeli_file (OPTION|FILE)...\n"
"\n"
"Shows summary of Riegeli/records file contents.\n";
} // namespace
} // namespace tools
} // namespace riegeli
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(riegeli::tools::kUsage);
const std::vector<char*> args = absl::ParseCommandLine(argc, argv);
riegeli::StdOut std_out;
riegeli::StdErr std_err;
for (size_t i = 1; i < args.size(); ++i) {
riegeli::tools::DescribeFile(args[i], std_out, std_err);
}
std_out.Close();
std_err.Close();
}
<commit_msg>Use `AnyDependency` instead of two variables holding the possibilities and the third one holding a pointer to the selected one.<commit_after>// Copyright 2019 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 <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <tuple>
#include <vector>
#include "absl/base/optimization.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "riegeli/base/any_dependency.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/backward_writer.h"
#include "riegeli/bytes/chain_backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/null_backward_writer.h"
#include "riegeli/bytes/reader.h"
#include "riegeli/bytes/std_io.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/chunk_encoding/chunk.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_decoder.h"
#include "riegeli/messages/message_parse.h"
#include "riegeli/messages/message_serialize.h"
#include "riegeli/messages/text_print.h"
#include "riegeli/records/chunk_reader.h"
#include "riegeli/records/records_metadata.pb.h"
#include "riegeli/records/skipped_region.h"
#include "riegeli/records/tools/riegeli_summary.pb.h"
#include "riegeli/varint/varint_reading.h"
ABSL_FLAG(bool, show_records_metadata, true,
"If true, show parsed file metadata.");
ABSL_FLAG(bool, show_record_sizes, false,
"If true, show the list of record sizes in each chunk.");
ABSL_FLAG(bool, show_records, false,
"If true, show contents of records in each chunk.");
namespace riegeli {
namespace tools {
namespace {
absl::Status DescribeFileMetadataChunk(const Chunk& chunk,
RecordsMetadata& records_metadata) {
// Based on `RecordReaderBase::ParseMetadata()`.
if (ABSL_PREDICT_FALSE(chunk.header.num_records() != 0)) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid file metadata chunk: number of records is not zero: ",
chunk.header.num_records()));
}
ChainReader<> data_reader(&chunk.data);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> serialized_metadata_writer(
ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
std::vector<size_t> limits;
const bool decode_ok = transpose_decoder.Decode(
1, chunk.header.decoded_data_size(), FieldProjection::All(), data_reader,
serialized_metadata_writer, limits);
if (ABSL_PREDICT_FALSE(!serialized_metadata_writer.Close())) {
return serialized_metadata_writer.status();
}
if (ABSL_PREDICT_FALSE(!decode_ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!data_reader.VerifyEndAndClose())) {
return data_reader.status();
}
const Chain& serialized_metadata = serialized_metadata_writer.dest();
RIEGELI_ASSERT_EQ(limits.size(), 1u)
<< "Metadata chunk has unexpected record limits";
RIEGELI_ASSERT_EQ(limits.back(), serialized_metadata.size())
<< "Metadata chunk has unexpected record limits";
return ParseFromChain(serialized_metadata, records_metadata);
}
absl::Status ReadRecords(
Reader& src, const std::vector<size_t>& limits,
google::protobuf::RepeatedPtrField<std::string>& dest) {
// Based on `ChunkDecoder::ReadRecord()`.
const Position initial_pos = src.pos();
for (const size_t limit : limits) {
const size_t start = IntCast<size_t>(src.pos() - initial_pos);
RIEGELI_ASSERT_LE(start, limit) << "Record end positions not sorted";
if (ABSL_PREDICT_FALSE(!src.Read(limit - start, *dest.Add()))) {
return src.StatusOrAnnotate(
absl::InvalidArgumentError("Reading record failed"));
}
}
return absl::OkStatus();
}
absl::Status DescribeSimpleChunk(const Chunk& chunk,
summary::SimpleChunk& simple_chunk) {
ChainReader<> src(&chunk.data);
const bool show_record_sizes = absl::GetFlag(FLAGS_show_record_sizes);
const bool show_records = absl::GetFlag(FLAGS_show_records);
// Based on `SimpleDecoder::Decode()`.
uint8_t compression_type_byte;
if (ABSL_PREDICT_FALSE(!src.ReadByte(compression_type_byte))) {
return absl::InvalidArgumentError("Reading compression type failed");
}
const CompressionType compression_type =
static_cast<CompressionType>(compression_type_byte);
simple_chunk.set_compression_type(
static_cast<summary::CompressionType>(compression_type));
if (show_record_sizes || show_records) {
uint64_t sizes_size;
if (ABSL_PREDICT_FALSE(!ReadVarint64(src, sizes_size))) {
return absl::InvalidArgumentError("Reading size of sizes failed");
}
chunk_encoding_internal::Decompressor<LimitingReader<>> sizes_decompressor(
std::forward_as_tuple(
&src, LimitingReaderBase::Options().set_exact_length(sizes_size)),
compression_type);
if (ABSL_PREDICT_FALSE(!sizes_decompressor.ok())) {
return sizes_decompressor.status();
}
if (show_record_sizes) {
if (ABSL_PREDICT_FALSE(chunk.header.num_records() >
unsigned{std::numeric_limits<int>::max()})) {
return absl::ResourceExhaustedError("Too many records");
}
simple_chunk.mutable_record_sizes()->Reserve(
IntCast<int>(chunk.header.num_records()));
}
std::vector<size_t> limits;
if (show_records) {
if (ABSL_PREDICT_FALSE(chunk.header.num_records() > limits.max_size())) {
return absl::ResourceExhaustedError("Too many records");
}
limits.reserve(IntCast<size_t>(chunk.header.num_records()));
}
size_t limit = 0;
for (uint64_t i = 0; i < chunk.header.num_records(); ++i) {
uint64_t size;
if (ABSL_PREDICT_FALSE(
!ReadVarint64(sizes_decompressor.reader(), size))) {
return sizes_decompressor.reader().StatusOrAnnotate(
absl::InvalidArgumentError("Reading record size failed"));
}
if (ABSL_PREDICT_FALSE(size > chunk.header.decoded_data_size() - limit)) {
return absl::InvalidArgumentError(
"Decoded data size larger than expected");
}
limit += IntCast<size_t>(size);
if (show_record_sizes) simple_chunk.add_record_sizes(size);
if (show_records) limits.push_back(limit);
}
if (ABSL_PREDICT_FALSE(!sizes_decompressor.VerifyEndAndClose())) {
return sizes_decompressor.status();
}
if (ABSL_PREDICT_FALSE(limit != chunk.header.decoded_data_size())) {
return absl::InvalidArgumentError(
"Decoded data size smaller than expected");
}
if (show_records) {
chunk_encoding_internal::Decompressor<> records_decompressor(
&src, compression_type);
if (ABSL_PREDICT_FALSE(!records_decompressor.ok())) {
return records_decompressor.status();
}
{
absl::Status status = ReadRecords(records_decompressor.reader(), limits,
*simple_chunk.mutable_records());
if (!status.ok()) {
return status;
}
}
if (ABSL_PREDICT_FALSE(!records_decompressor.VerifyEndAndClose())) {
return records_decompressor.status();
}
if (ABSL_PREDICT_FALSE(!src.VerifyEndAndClose())) return src.status();
}
}
return absl::OkStatus();
}
absl::Status DescribeTransposedChunk(
const Chunk& chunk, summary::TransposedChunk& transposed_chunk) {
ChainReader<> src(&chunk.data);
const bool show_record_sizes = absl::GetFlag(FLAGS_show_record_sizes);
const bool show_records = absl::GetFlag(FLAGS_show_records);
// Based on `TransposeDecoder::Decode()`.
uint8_t compression_type_byte;
if (ABSL_PREDICT_FALSE(!src.ReadByte(compression_type_byte))) {
return absl::InvalidArgumentError("Reading compression type failed");
}
transposed_chunk.set_compression_type(
static_cast<summary::CompressionType>(compression_type_byte));
if (show_record_sizes || show_records) {
// Based on `ChunkDecoder::Parse()`.
src.Seek(0);
TransposeDecoder transpose_decoder;
Chain dest;
AnyDependency<BackwardWriter*, ChainBackwardWriter<>, NullBackwardWriter>
dest_writer;
if (show_records) {
dest_writer.Emplace<ChainBackwardWriter<>>(
&dest, ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
} else {
dest_writer.Emplace<NullBackwardWriter>();
}
std::vector<size_t> limits;
const bool decode_ok = transpose_decoder.Decode(
chunk.header.num_records(), chunk.header.decoded_data_size(),
FieldProjection::All(), src, *dest_writer, limits);
if (ABSL_PREDICT_FALSE(!dest_writer->Close())) return dest_writer->status();
if (ABSL_PREDICT_FALSE(!decode_ok)) return transpose_decoder.status();
if (show_record_sizes) {
if (ABSL_PREDICT_FALSE(limits.size() >
unsigned{std::numeric_limits<int>::max()})) {
return absl::ResourceExhaustedError("Too many records");
}
transposed_chunk.mutable_record_sizes()->Reserve(
IntCast<int>(limits.size()));
size_t prev_limit = 0;
for (const size_t next_limit : limits) {
RIEGELI_ASSERT_LE(prev_limit, next_limit)
<< "Failed postcondition of TransposeDecoder: "
"record end positions not sorted";
transposed_chunk.add_record_sizes(next_limit - prev_limit);
prev_limit = next_limit;
}
}
if (show_records) {
ChainReader<> records_reader(&dest);
{
absl::Status status = ReadRecords(records_reader, limits,
*transposed_chunk.mutable_records());
if (!status.ok()) {
return status;
}
}
if (ABSL_PREDICT_FALSE(!records_reader.VerifyEndAndClose())) {
return records_reader.status();
}
}
if (ABSL_PREDICT_FALSE(!src.VerifyEndAndClose())) return src.status();
}
return absl::OkStatus();
}
void DescribeFile(absl::string_view filename, Writer& report, Writer& errors) {
absl::Format(&report,
"file {\n"
" filename: \"%s\"\n",
absl::Utf8SafeCEscape(filename));
DefaultChunkReader<FdReader<>> chunk_reader(std::forward_as_tuple(filename));
if (chunk_reader.SupportsRandomAccess()) {
const absl::optional<Position> size = chunk_reader.Size();
if (size != absl::nullopt) {
absl::Format(&report, " file_size: %u\n", *size);
}
}
TextPrintOptions print_options;
print_options.printer().SetInitialIndentLevel(2);
print_options.printer().SetUseShortRepeatedPrimitives(true);
print_options.printer().SetUseUtf8StringEscaping(true);
for (;;) {
report.Flush();
const Position chunk_begin = chunk_reader.pos();
Chunk chunk;
if (ABSL_PREDICT_FALSE(!chunk_reader.ReadChunk(chunk))) {
SkippedRegion skipped_region;
if (chunk_reader.Recover(&skipped_region)) {
absl::Format(&errors, "%s\n", skipped_region.message());
continue;
}
break;
}
summary::Chunk chunk_summary;
chunk_summary.set_chunk_begin(chunk_begin);
chunk_summary.set_chunk_type(
static_cast<summary::ChunkType>(chunk.header.chunk_type()));
chunk_summary.set_data_size(chunk.header.data_size());
chunk_summary.set_num_records(chunk.header.num_records());
chunk_summary.set_decoded_data_size(chunk.header.decoded_data_size());
{
absl::Status status;
switch (chunk.header.chunk_type()) {
case ChunkType::kFileMetadata:
if (absl::GetFlag(FLAGS_show_records_metadata)) {
status = DescribeFileMetadataChunk(
chunk, *chunk_summary.mutable_file_metadata_chunk());
}
break;
case ChunkType::kSimple:
status =
DescribeSimpleChunk(chunk, *chunk_summary.mutable_simple_chunk());
break;
case ChunkType::kTransposed:
status = DescribeTransposedChunk(
chunk, *chunk_summary.mutable_transposed_chunk());
break;
default:
break;
}
if (ABSL_PREDICT_FALSE(!status.ok())) {
absl::Format(&errors, "%s\n", status.message());
}
}
absl::Format(&report, " chunk {\n");
TextPrintToWriter(chunk_summary, report, print_options).IgnoreError();
absl::Format(&report, " }\n");
}
absl::Format(&report, "}\n");
report.Flush();
if (!chunk_reader.Close()) {
absl::Format(&errors, "%s\n", chunk_reader.status().message());
}
}
const char kUsage[] =
"Usage: describe_riegeli_file (OPTION|FILE)...\n"
"\n"
"Shows summary of Riegeli/records file contents.\n";
} // namespace
} // namespace tools
} // namespace riegeli
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(riegeli::tools::kUsage);
const std::vector<char*> args = absl::ParseCommandLine(argc, argv);
riegeli::StdOut std_out;
riegeli::StdErr std_err;
for (size_t i = 1; i < args.size(); ++i) {
riegeli::tools::DescribeFile(args[i], std_out, std_err);
}
std_out.Close();
std_err.Close();
}
<|endoftext|> |
<commit_before>//===- InputFiles.cpp -----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Chunks.h"
#include "Error.h"
#include "InputFiles.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/LTO/LTOModule.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm::object;
using namespace llvm::support::endian;
using llvm::COFF::ImportHeader;
using llvm::RoundUpToAlignment;
using llvm::sys::fs::identify_magic;
using llvm::sys::fs::file_magic;
namespace lld {
namespace coff {
// Returns the last element of a path, which is supposed to be a filename.
static StringRef getBasename(StringRef Path) {
size_t Pos = Path.rfind('\\');
if (Pos == StringRef::npos)
return Path;
return Path.substr(Pos + 1);
}
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
std::string InputFile::getShortName() {
if (ParentName == "")
return getName().lower();
std::string Res = (getBasename(ParentName) + "(" +
getBasename(getName()) + ")").str();
return StringRef(Res).lower();
}
std::error_code ArchiveFile::parse() {
// Parse a MemoryBufferRef as an archive file.
auto ArchiveOrErr = Archive::create(MB);
if (auto EC = ArchiveOrErr.getError())
return EC;
File = std::move(ArchiveOrErr.get());
// Allocate a buffer for Lazy objects.
size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy);
Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
// Read the symbol table to construct Lazy objects.
uint32_t I = 0;
for (const Archive::Symbol &Sym : File->symbols()) {
// Skip special symbol exists in import library files.
if (Sym.getName() == "__NULL_IMPORT_DESCRIPTOR")
continue;
SymbolBodies.push_back(new (&Buf[I++]) Lazy(this, Sym));
}
return std::error_code();
}
// Returns a buffer pointing to a member file containing a given symbol.
ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
auto ItOrErr = Sym->getMember();
if (auto EC = ItOrErr.getError())
return EC;
Archive::child_iterator It = ItOrErr.get();
// Return an empty buffer if we have already returned the same buffer.
const char *StartAddr = It->getBuffer().data();
auto Pair = Seen.insert(StartAddr);
if (!Pair.second)
return MemoryBufferRef();
return It->getMemoryBufferRef();
}
std::error_code ObjectFile::parse() {
// Parse a memory buffer as a COFF file.
auto BinOrErr = createBinary(MB);
if (auto EC = BinOrErr.getError())
return EC;
std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
Bin.release();
COFFObj.reset(Obj);
} else {
llvm::errs() << getName() << " is not a COFF file.\n";
return make_error_code(LLDError::InvalidFile);
}
// Read section and symbol tables.
if (auto EC = initializeChunks())
return EC;
return initializeSymbols();
}
SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) {
return SparseSymbolBodies[SymbolIndex]->getReplacement();
}
std::error_code ObjectFile::initializeChunks() {
uint32_t NumSections = COFFObj->getNumberOfSections();
Chunks.reserve(NumSections);
SparseChunks.resize(NumSections + 1);
for (uint32_t I = 1; I < NumSections + 1; ++I) {
const coff_section *Sec;
StringRef Name;
if (auto EC = COFFObj->getSection(I, Sec)) {
llvm::errs() << "getSection failed: " << Name << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
if (auto EC = COFFObj->getSectionName(Sec, Name)) {
llvm::errs() << "getSectionName failed: " << Name << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
if (Name == ".drectve") {
ArrayRef<uint8_t> Data;
COFFObj->getSectionContents(Sec, Data);
Directives = StringRef((const char *)Data.data(), Data.size()).trim();
continue;
}
if (Name.startswith(".debug"))
continue;
if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
continue;
auto *C = new (Alloc) SectionChunk(this, Sec, I);
Chunks.push_back(C);
SparseChunks[I] = C;
}
return std::error_code();
}
std::error_code ObjectFile::initializeSymbols() {
uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
SymbolBodies.reserve(NumSymbols);
SparseSymbolBodies.resize(NumSymbols);
int32_t LastSectionNumber = 0;
for (uint32_t I = 0; I < NumSymbols; ++I) {
// Get a COFFSymbolRef object.
auto SymOrErr = COFFObj->getSymbol(I);
if (auto EC = SymOrErr.getError()) {
llvm::errs() << "broken object file: " << getName() << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
COFFSymbolRef Sym = SymOrErr.get();
// Get a symbol name.
StringRef SymbolName;
if (auto EC = COFFObj->getSymbolName(Sym, SymbolName)) {
llvm::errs() << "broken object file: " << getName() << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
// Skip special symbols.
if (SymbolName == "@comp.id" || SymbolName == "@feat.00")
continue;
const void *AuxP = nullptr;
if (Sym.getNumberOfAuxSymbols())
AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
SymbolBody *Body = createSymbolBody(SymbolName, Sym, AuxP, IsFirst);
if (Body) {
SymbolBodies.push_back(Body);
SparseSymbolBodies[I] = Body;
}
I += Sym.getNumberOfAuxSymbols();
LastSectionNumber = Sym.getSectionNumber();
}
return std::error_code();
}
SymbolBody *ObjectFile::createSymbolBody(StringRef Name, COFFSymbolRef Sym,
const void *AuxP, bool IsFirst) {
if (Sym.isUndefined())
return new Undefined(Name);
if (Sym.isCommon()) {
Chunk *C = new (Alloc) CommonChunk(Sym);
Chunks.push_back(C);
return new (Alloc) DefinedRegular(Name, Sym, C);
}
if (Sym.isAbsolute())
return new (Alloc) DefinedAbsolute(Name, Sym.getValue());
// TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS
if (Sym.isWeakExternal()) {
auto *Aux = (const coff_aux_weak_external *)AuxP;
return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
}
if (IsFirst && AuxP) {
if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) {
auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
auto *Parent =
(SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]);
if (Parent)
Parent->addAssociative((SectionChunk *)C);
}
}
if (Chunk *C = SparseChunks[Sym.getSectionNumber()])
return new (Alloc) DefinedRegular(Name, Sym, C);
return nullptr;
}
std::error_code ImportFile::parse() {
const char *Buf = MB.getBufferStart();
const char *End = MB.getBufferEnd();
const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
// Check if the total size is valid.
if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
llvm::errs() << "broken import library\n";
return make_error_code(LLDError::BrokenFile);
}
// Read names and create an __imp_ symbol.
StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
StringRef ExternalName = Name;
if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
ExternalName = "";
auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
Hdr);
SymbolBodies.push_back(ImpSym);
// If type is function, we need to create a thunk which jump to an
// address pointed by the __imp_ symbol. (This allows you to call
// DLL functions just like regular non-DLL functions.)
if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
return std::error_code();
}
std::error_code BitcodeFile::parse() {
std::string Err;
M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
MB.getBufferSize(),
llvm::TargetOptions(), Err));
if (!Err.empty()) {
llvm::errs() << Err << '\n';
return make_error_code(LLDError::BrokenFile);
}
for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
StringRef SymName = M->getSymbolName(I);
if ((M->getSymbolAttributes(I) & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_UNDEFINED) {
SymbolBodies.push_back(new (Alloc) Undefined(SymName));
} else {
SymbolBodies.push_back(new (Alloc) DefinedBitcode(SymName));
}
}
// Extract any linker directives from the bitcode file, which are represented
// as module flags with the key "Linker Options".
llvm::SmallVector<llvm::Module::ModuleFlagEntry, 8> Flags;
M->getModule().getModuleFlagsMetadata(Flags);
for (auto &&Flag : Flags) {
if (Flag.Key->getString() != "Linker Options")
continue;
for (llvm::Metadata *Op : cast<llvm::MDNode>(Flag.Val)->operands()) {
for (llvm::Metadata *InnerOp : cast<llvm::MDNode>(Op)->operands()) {
Directives += " ";
Directives += cast<llvm::MDString>(InnerOp)->getString();
}
}
}
return std::error_code();
}
} // namespace coff
} // namespace lld
<commit_msg>COFF: Fix memory leak.<commit_after>//===- InputFiles.cpp -----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Chunks.h"
#include "Error.h"
#include "InputFiles.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/LTO/LTOModule.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm::object;
using namespace llvm::support::endian;
using llvm::COFF::ImportHeader;
using llvm::RoundUpToAlignment;
using llvm::sys::fs::identify_magic;
using llvm::sys::fs::file_magic;
namespace lld {
namespace coff {
// Returns the last element of a path, which is supposed to be a filename.
static StringRef getBasename(StringRef Path) {
size_t Pos = Path.rfind('\\');
if (Pos == StringRef::npos)
return Path;
return Path.substr(Pos + 1);
}
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
std::string InputFile::getShortName() {
if (ParentName == "")
return getName().lower();
std::string Res = (getBasename(ParentName) + "(" +
getBasename(getName()) + ")").str();
return StringRef(Res).lower();
}
std::error_code ArchiveFile::parse() {
// Parse a MemoryBufferRef as an archive file.
auto ArchiveOrErr = Archive::create(MB);
if (auto EC = ArchiveOrErr.getError())
return EC;
File = std::move(ArchiveOrErr.get());
// Allocate a buffer for Lazy objects.
size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy);
Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
// Read the symbol table to construct Lazy objects.
uint32_t I = 0;
for (const Archive::Symbol &Sym : File->symbols()) {
// Skip special symbol exists in import library files.
if (Sym.getName() == "__NULL_IMPORT_DESCRIPTOR")
continue;
SymbolBodies.push_back(new (&Buf[I++]) Lazy(this, Sym));
}
return std::error_code();
}
// Returns a buffer pointing to a member file containing a given symbol.
ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
auto ItOrErr = Sym->getMember();
if (auto EC = ItOrErr.getError())
return EC;
Archive::child_iterator It = ItOrErr.get();
// Return an empty buffer if we have already returned the same buffer.
const char *StartAddr = It->getBuffer().data();
auto Pair = Seen.insert(StartAddr);
if (!Pair.second)
return MemoryBufferRef();
return It->getMemoryBufferRef();
}
std::error_code ObjectFile::parse() {
// Parse a memory buffer as a COFF file.
auto BinOrErr = createBinary(MB);
if (auto EC = BinOrErr.getError())
return EC;
std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
Bin.release();
COFFObj.reset(Obj);
} else {
llvm::errs() << getName() << " is not a COFF file.\n";
return make_error_code(LLDError::InvalidFile);
}
// Read section and symbol tables.
if (auto EC = initializeChunks())
return EC;
return initializeSymbols();
}
SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) {
return SparseSymbolBodies[SymbolIndex]->getReplacement();
}
std::error_code ObjectFile::initializeChunks() {
uint32_t NumSections = COFFObj->getNumberOfSections();
Chunks.reserve(NumSections);
SparseChunks.resize(NumSections + 1);
for (uint32_t I = 1; I < NumSections + 1; ++I) {
const coff_section *Sec;
StringRef Name;
if (auto EC = COFFObj->getSection(I, Sec)) {
llvm::errs() << "getSection failed: " << Name << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
if (auto EC = COFFObj->getSectionName(Sec, Name)) {
llvm::errs() << "getSectionName failed: " << Name << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
if (Name == ".drectve") {
ArrayRef<uint8_t> Data;
COFFObj->getSectionContents(Sec, Data);
Directives = StringRef((const char *)Data.data(), Data.size()).trim();
continue;
}
if (Name.startswith(".debug"))
continue;
if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
continue;
auto *C = new (Alloc) SectionChunk(this, Sec, I);
Chunks.push_back(C);
SparseChunks[I] = C;
}
return std::error_code();
}
std::error_code ObjectFile::initializeSymbols() {
uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
SymbolBodies.reserve(NumSymbols);
SparseSymbolBodies.resize(NumSymbols);
int32_t LastSectionNumber = 0;
for (uint32_t I = 0; I < NumSymbols; ++I) {
// Get a COFFSymbolRef object.
auto SymOrErr = COFFObj->getSymbol(I);
if (auto EC = SymOrErr.getError()) {
llvm::errs() << "broken object file: " << getName() << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
COFFSymbolRef Sym = SymOrErr.get();
// Get a symbol name.
StringRef SymbolName;
if (auto EC = COFFObj->getSymbolName(Sym, SymbolName)) {
llvm::errs() << "broken object file: " << getName() << ": "
<< EC.message() << "\n";
return make_error_code(LLDError::BrokenFile);
}
// Skip special symbols.
if (SymbolName == "@comp.id" || SymbolName == "@feat.00")
continue;
const void *AuxP = nullptr;
if (Sym.getNumberOfAuxSymbols())
AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
SymbolBody *Body = createSymbolBody(SymbolName, Sym, AuxP, IsFirst);
if (Body) {
SymbolBodies.push_back(Body);
SparseSymbolBodies[I] = Body;
}
I += Sym.getNumberOfAuxSymbols();
LastSectionNumber = Sym.getSectionNumber();
}
return std::error_code();
}
SymbolBody *ObjectFile::createSymbolBody(StringRef Name, COFFSymbolRef Sym,
const void *AuxP, bool IsFirst) {
if (Sym.isUndefined())
return new (Alloc) Undefined(Name);
if (Sym.isCommon()) {
Chunk *C = new (Alloc) CommonChunk(Sym);
Chunks.push_back(C);
return new (Alloc) DefinedRegular(Name, Sym, C);
}
if (Sym.isAbsolute())
return new (Alloc) DefinedAbsolute(Name, Sym.getValue());
// TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS
if (Sym.isWeakExternal()) {
auto *Aux = (const coff_aux_weak_external *)AuxP;
return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
}
if (IsFirst && AuxP) {
if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) {
auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
auto *Parent =
(SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]);
if (Parent)
Parent->addAssociative((SectionChunk *)C);
}
}
if (Chunk *C = SparseChunks[Sym.getSectionNumber()])
return new (Alloc) DefinedRegular(Name, Sym, C);
return nullptr;
}
std::error_code ImportFile::parse() {
const char *Buf = MB.getBufferStart();
const char *End = MB.getBufferEnd();
const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
// Check if the total size is valid.
if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
llvm::errs() << "broken import library\n";
return make_error_code(LLDError::BrokenFile);
}
// Read names and create an __imp_ symbol.
StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
StringRef ExternalName = Name;
if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
ExternalName = "";
auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
Hdr);
SymbolBodies.push_back(ImpSym);
// If type is function, we need to create a thunk which jump to an
// address pointed by the __imp_ symbol. (This allows you to call
// DLL functions just like regular non-DLL functions.)
if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
return std::error_code();
}
std::error_code BitcodeFile::parse() {
std::string Err;
M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
MB.getBufferSize(),
llvm::TargetOptions(), Err));
if (!Err.empty()) {
llvm::errs() << Err << '\n';
return make_error_code(LLDError::BrokenFile);
}
for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
StringRef SymName = M->getSymbolName(I);
if ((M->getSymbolAttributes(I) & LTO_SYMBOL_DEFINITION_MASK) ==
LTO_SYMBOL_DEFINITION_UNDEFINED) {
SymbolBodies.push_back(new (Alloc) Undefined(SymName));
} else {
SymbolBodies.push_back(new (Alloc) DefinedBitcode(SymName));
}
}
// Extract any linker directives from the bitcode file, which are represented
// as module flags with the key "Linker Options".
llvm::SmallVector<llvm::Module::ModuleFlagEntry, 8> Flags;
M->getModule().getModuleFlagsMetadata(Flags);
for (auto &&Flag : Flags) {
if (Flag.Key->getString() != "Linker Options")
continue;
for (llvm::Metadata *Op : cast<llvm::MDNode>(Flag.Val)->operands()) {
for (llvm::Metadata *InnerOp : cast<llvm::MDNode>(Op)->operands()) {
Directives += " ";
Directives += cast<llvm::MDString>(InnerOp)->getString();
}
}
}
return std::error_code();
}
} // namespace coff
} // namespace lld
<|endoftext|> |
<commit_before>#pragma once
#include "../stringify/jss_object.hpp"
#include "../parse/jsd_core.hpp"
#include <string>
#include <iostream>
#include <stdexcept>
#include <vector>
/**
* Provides a wrapper called Base64Binary for use in classes instead of std::vector <char> etc.
* It is meant to compress binary data down.
*
* And it is only meant for that, it does not produce correct output if shoved into stringify itself.
*/
namespace JSON
{
template <typename CharType = char, template <typename...> class ContainerT = std::vector>
void encodeBase64(std::ostream& stream, ContainerT <CharType> const& bytes);
template <typename CharType = char, template <typename...> class ContainerT = std::vector>
void decodeBase64(std::string const& input, ContainerT <CharType>& bytes);
template <typename CharType = char, template <typename...> class ContainerT = std::vector>
struct Base64Binary
{
private:
ContainerT <CharType> binary_;
public:
using value_type = CharType;
using allocator_type = std::allocator <CharType>;
using reference = CharType&;
using const_reference = CharType const&;
using pointer = typename std::allocator_traits <allocator_type>::pointer;
using const_pointer = typename std::allocator_traits <allocator_type>::const_pointer;
using iterator = typename ContainerT <CharType>::iterator;
using const_iterator = typename ContainerT <CharType>::const_iterator;
using reverse_iterator = typename ContainerT <CharType>::reverse_iterator;
using const_reverse_iterator = typename ContainerT <CharType>::const_reverse_iterator;
using difference_type = typename ContainerT <CharType>::difference_type;
using size_type = std::size_t;
ContainerT <CharType>& get() { return binary_; }
Base64Binary ()
{ }
explicit Base64Binary (ContainerT <CharType> container)
: binary_(std::move(container))
{ }
/**
* This constructor does stop on the null terminator '\0' (exclusive).
*/
Base64Binary (const CharType* init)
: binary_()
{
for (auto const* c = init; *c != '\0'; ++c)
binary_.push_back(*c);
}
/**
* Inserts the container contents into a string.
*
* @return A string from the binary data.
*/
std::basic_string <CharType> toString() const
{
return {std::begin(binary_), std::end(binary_)};
}
Base64Binary& operator= (ContainerT <CharType> const& container)
{
binary_ = container;
return *this;
}
Base64Binary& operator= (const CharType* str)
{
binary_.clear();
for (auto const* c = str; *c != '\0'; ++c)
binary_.push_back(*c);
return *this;
}
operator ContainerT <CharType>& () { return binary_; }
iterator begin() { return binary_.begin(); }
iterator end() { return binary_.end(); }
const_iterator cbegin() const { return binary_.cbegin(); }
const_iterator cend() const { return binary_.cend(); }
const_iterator begin() const { return binary_.begin(); }
const_iterator end() const { return binary_.end(); }
reference front() { return binary_.front(); }
const_reference front() const { return binary_.front(); }
reference back() { return binary_.back(); }
const_reference back() const { return binary_.back(); }
reference operator[] (size_type n) { return binary_[n]; }
const_reference operator[] (size_type n) const { return binary_[n]; }
reference at (size_type n) { return binary_.at(n); }
const_reference at (size_type n) const { return binary_.at(n); }
value_type* data() noexcept { return binary_.data(); }
const value_type* data() const noexcept { return binary_.data(); }
size_type size() const { return binary_.size(); }
size_type max_size() const noexcept { return binary_.max_size(); }
bool empty() const { return binary_.empty(); }
void push_back(value_type const& v) { binary_.push_back(v); }
void pop_back() { binary_.pop_back(); }
void clear() noexcept { binary_.clear(); }
void resize (size_type n) { binary_.resize(n); }
void resize (size_type n, const value_type& val) { binary_.resize(n, val); }
std::ostream& stringify(std::ostream& stream, StringificationOptions const& = DEFAULT_OPTIONS) const
{
stream << "\"";
encodeBase64(stream, binary_);
stream << "\"";
return stream;
}
void parse(std::string const& name, PropertyTree const& tree, ParsingOptions const& = DEFAULT_PARSER_OPTIONS)
{
std::string str = tree.tree.get<std::string>(name);
decodeBase64(str, binary_);
}
};
}
namespace JSON
{
template <typename CharType, template <typename...> class ContainerT>
void encodeBase64(std::ostream& stream, ContainerT <CharType> const& bytes)
{
static CharType const table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
std::size_t b;
for (std::size_t i = 0; i < bytes.size(); i += 3)
{
b = (bytes[i] & 0xFC) >> 2;
stream << table [b];
b = (bytes[i] & 0x03) << 4;
if (i + 1 < bytes.size())
{
b |= (bytes[i + 1] & 0xF0) >> 4;
stream << table [b];
b = (bytes[i + 1] & 0x0F) << 2;
if (i + 2 < bytes.size())
{
b |= (bytes[i + 2] & 0xC0) >> 6;
stream << table [b];
b = bytes[i + 2] & 0x3F;
stream << table [b];
}
else
{
stream << table [b];
stream << '=';
}
}
else
{
stream << table [b];
stream << "==";
}
}
}
template <typename CharType, template <typename...> class ContainerT>
void decodeBase64(std::string const& input, ContainerT <CharType>& bytes)
{
// static CharType const table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
bytes.clear();
if (input.empty())
return;
if (input.length() % 4 != 0) {
throw std::invalid_argument ("input does not have correct size for base64");
}
std::size_t size = (input.length() * 3) / 4;
if (*input.rbegin() == '=')
size--;
if (*(input.rbegin() + 1) == '=')
size--;
bytes.resize(size);
auto backwardsTable = [](int c) -> int {
if (c >= (int)'A' && c <= (int)'Z')
return c - 'A';
if (c >= (int)'a' && c <= (int)'z')
return c - 'a' + 26;
if (c >= (int)'0' && c <= (int)'9')
return c - '0' + 52;
if (c == '+')
return 62;
if (c == '/')
return 63;
if (c == '=')
return 64;
else
throw std::invalid_argument ("input contains characters that are not base64");
return 0;
};
int j = 0;
int b[4];
for (std::size_t i = 0; i < input.length(); i += 4)
{
b[0] = backwardsTable(input[i]);
b[1] = backwardsTable(input[i + 1]);
b[2] = backwardsTable(input[i + 2]);
b[3] = backwardsTable(input[i + 3]);
bytes[j++] = (CharType) ((b[0] << 2) | (b[1] >> 4));
if (b[2] < 64)
{
bytes[j++] = (CharType) ((b[1] << 4) | (b[2] >> 2));
if (b[3] < 64)
{
bytes[j++] = (CharType) ((b[2] << 6) | b[3]);
}
}
}
}
}
<commit_msg>encodeBase64 now also takes strings and more special containers.<commit_after>#pragma once
#include "../stringify/jss_object.hpp"
#include "../parse/jsd_core.hpp"
#include <string>
#include <iostream>
#include <stdexcept>
#include <vector>
/**
* Provides a wrapper called Base64Binary for use in classes instead of std::vector <char> etc.
* It is meant to compress binary data down.
*
* And it is only meant for that, it does not produce correct output if shoved into stringify itself.
*/
namespace JSON
{
template <typename CharType = char, template <typename...> class ContainerT = std::vector, typename... Dummys>
void encodeBase64(std::ostream& stream, ContainerT <CharType, Dummys...> const& bytes);
template <typename CharType = char, template <typename...> class ContainerT = std::vector, typename... Dummys>
void decodeBase64(std::string const& input, ContainerT <CharType, Dummys...>& bytes);
template <typename CharType = char, template <typename...> class ContainerT = std::vector>
struct Base64Binary
{
private:
ContainerT <CharType> binary_;
public:
using value_type = CharType;
using allocator_type = std::allocator <CharType>;
using reference = CharType&;
using const_reference = CharType const&;
using pointer = typename std::allocator_traits <allocator_type>::pointer;
using const_pointer = typename std::allocator_traits <allocator_type>::const_pointer;
using iterator = typename ContainerT <CharType>::iterator;
using const_iterator = typename ContainerT <CharType>::const_iterator;
using reverse_iterator = typename ContainerT <CharType>::reverse_iterator;
using const_reverse_iterator = typename ContainerT <CharType>::const_reverse_iterator;
using difference_type = typename ContainerT <CharType>::difference_type;
using size_type = std::size_t;
ContainerT <CharType>& get() { return binary_; }
Base64Binary ()
{ }
explicit Base64Binary (ContainerT <CharType> container)
: binary_(std::move(container))
{ }
/**
* This constructor does stop on the null terminator '\0' (exclusive).
*/
Base64Binary (const CharType* init)
: binary_()
{
for (auto const* c = init; *c != '\0'; ++c)
binary_.push_back(*c);
}
/**
* Inserts the container contents into a string.
*
* @return A string from the binary data.
*/
std::basic_string <CharType> toString() const
{
return {std::begin(binary_), std::end(binary_)};
}
Base64Binary& operator= (ContainerT <CharType> const& container)
{
binary_ = container;
return *this;
}
Base64Binary& operator= (const CharType* str)
{
binary_.clear();
for (auto const* c = str; *c != '\0'; ++c)
binary_.push_back(*c);
return *this;
}
operator ContainerT <CharType>& () { return binary_; }
iterator begin() { return binary_.begin(); }
iterator end() { return binary_.end(); }
const_iterator cbegin() const { return binary_.cbegin(); }
const_iterator cend() const { return binary_.cend(); }
const_iterator begin() const { return binary_.begin(); }
const_iterator end() const { return binary_.end(); }
reference front() { return binary_.front(); }
const_reference front() const { return binary_.front(); }
reference back() { return binary_.back(); }
const_reference back() const { return binary_.back(); }
reference operator[] (size_type n) { return binary_[n]; }
const_reference operator[] (size_type n) const { return binary_[n]; }
reference at (size_type n) { return binary_.at(n); }
const_reference at (size_type n) const { return binary_.at(n); }
value_type* data() noexcept { return binary_.data(); }
const value_type* data() const noexcept { return binary_.data(); }
size_type size() const { return binary_.size(); }
size_type max_size() const noexcept { return binary_.max_size(); }
bool empty() const { return binary_.empty(); }
void push_back(value_type const& v) { binary_.push_back(v); }
void pop_back() { binary_.pop_back(); }
void clear() noexcept { binary_.clear(); }
void resize (size_type n) { binary_.resize(n); }
void resize (size_type n, const value_type& val) { binary_.resize(n, val); }
std::ostream& stringify(std::ostream& stream, StringificationOptions const& = DEFAULT_OPTIONS) const
{
stream << "\"";
encodeBase64(stream, binary_);
stream << "\"";
return stream;
}
void parse(std::string const& name, PropertyTree const& tree, ParsingOptions const& = DEFAULT_PARSER_OPTIONS)
{
std::string str = tree.tree.get<std::string>(name);
decodeBase64(str, binary_);
}
};
}
namespace JSON
{
template <typename CharType, template <typename...> class ContainerT, typename... Dummys>
void encodeBase64(std::ostream& stream, ContainerT <CharType, Dummys...> const& bytes)
{
static CharType const table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
std::size_t b;
for (std::size_t i = 0; i < bytes.size(); i += 3)
{
b = (bytes[i] & 0xFC) >> 2;
stream << table [b];
b = (bytes[i] & 0x03) << 4;
if (i + 1 < bytes.size())
{
b |= (bytes[i + 1] & 0xF0) >> 4;
stream << table [b];
b = (bytes[i + 1] & 0x0F) << 2;
if (i + 2 < bytes.size())
{
b |= (bytes[i + 2] & 0xC0) >> 6;
stream << table [b];
b = bytes[i + 2] & 0x3F;
stream << table [b];
}
else
{
stream << table [b];
stream << '=';
}
}
else
{
stream << table [b];
stream << "==";
}
}
}
template <typename CharType, template <typename...> class ContainerT, typename... Dummys>
void decodeBase64(std::string const& input, ContainerT <CharType, Dummys...>& bytes)
{
// static CharType const table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
bytes.clear();
if (input.empty())
return;
if (input.length() % 4 != 0) {
throw std::invalid_argument ("input does not have correct size for base64");
}
std::size_t size = (input.length() * 3) / 4;
if (*input.rbegin() == '=')
size--;
if (*(input.rbegin() + 1) == '=')
size--;
bytes.resize(size);
auto backwardsTable = [](int c) -> int {
if (c >= (int)'A' && c <= (int)'Z')
return c - 'A';
if (c >= (int)'a' && c <= (int)'z')
return c - 'a' + 26;
if (c >= (int)'0' && c <= (int)'9')
return c - '0' + 52;
if (c == '+')
return 62;
if (c == '/')
return 63;
if (c == '=')
return 64;
else
throw std::invalid_argument ("input contains characters that are not base64");
return 0;
};
int j = 0;
int b[4];
for (std::size_t i = 0; i < input.length(); i += 4)
{
b[0] = backwardsTable(input[i]);
b[1] = backwardsTable(input[i + 1]);
b[2] = backwardsTable(input[i + 2]);
b[3] = backwardsTable(input[i + 3]);
bytes[j++] = (CharType) ((b[0] << 2) | (b[1] >> 4));
if (b[2] < 64)
{
bytes[j++] = (CharType) ((b[1] << 4) | (b[2] >> 2));
if (b[3] < 64)
{
bytes[j++] = (CharType) ((b[2] << 6) | b[3]);
}
}
}
}
}
<|endoftext|> |
<commit_before>// read two strings and report whether the strings have the same length
// If not, report which is longer
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string str1, str2;
while (cin >> str1 >> str2)
{
if (str1.size() == str2.size())
cout << "The two strings have the same length." << endl;
else
cout << "The longer string is " << ((str1.size() > str2.size()) ? str1 : str2);
}
return 0;
}
<commit_msg>Update ex3_4b.cpp<commit_after>// read two strings and report whether the strings have the same length
// If not, report which is longer
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
for (string str1, str2; cin >> str1 >> str2;/* */)
{
if (str1.size() == str2.size())
cout << "The two strings have the same length." << endl;
else
cout << "The longer string is " << ((str1.size() > str2.size()) ? str1 : str2) << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>//
// ex9_19.cpp
// Exercise 9.19
//
// Created by pezy on 12/3/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Rewrite the program from the previous exercise to use a list.
// List the changes you needed to make.
// @See ex9_18.cpp
#include <iostream>
#include <string>
#include <list>
using std::string;
using std::list;
using std::cout;
using std::cin;
using std::endl;
int main()
{
list<string> input;
for (string str; cin >> str; input.push_back(str))
;
for (auto iter = input.cbegin(); iter != input.cend(); ++iter)
cout << *iter << endl;
return 0;
}
<commit_msg>Update ex9_19.cpp<commit_after>//
// ex9_19.cpp
// Exercise 9.19
//
// Created by pezy on 12/3/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Rewrite the program from the previous exercise to use a list.
// List the changes you needed to make.
// @See ex9_18.cpp
#include <iostream>
#include <list>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::list;
using std::string;
int main()
{
list<string> input;
for(string str; cin>>str; input.push_back(str))
;
for(auto iter=input.cbegin(); iter!=input.cend(); ++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
}
<|endoftext|> |
<commit_before>//!
//! @author @huangjuncmj @Alan
//! @date 19.11.2014
//!
//! Exercise 9.26:
//! Using the following definition of ia, copy ia into a vector and into a list.
//! Use the single-iterator form of erase to remove the elements with odd values from your
//! list and the even values from your vector.
//!
#include <iostream>
#include <vector>
#include <list>
using std::vector; using std::list; using std::cout; using std::endl; using std::end;
int main()
{
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
//! init
vector<int> vec(ia, end(ia));
list<int> lst(vec.begin(), vec.end());
//! remove odd value
for(auto it = lst.begin(); it != lst.end(); )
if(*it & 0x1) it = lst.erase(it);
else ++it;
//! remove even value
for(auto it = vec.begin(); it != vec.end(); )
if(! *it & 0x1) it = vec.erase(it);
else ++it;
//! print
cout << "list : ";
for(auto i : lst) cout << i << " ";
cout << "\nvector : ";
for(auto i : vec) cout << i << " ";
cout << std::endl;
return 0;
}
<commit_msg>Update ex9_26.cpp<commit_after>//!
//! @author @huangjuncmj @Alan
//! @date 19.11.2014
//!
//! Exercise 9.26:
//! Using the following definition of ia, copy ia into a vector and into a list.
//! Use the single-iterator form of erase to remove the elements with odd values from your
//! list and the even values from your vector.
//!
#include <iostream>
#include <vector>
#include <list>
using std::vector; using std::list; using std::cout; using std::endl; using std::end;
int main()
{
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
//! init
vector<int> vec(ia, end(ia));
list<int> lst(vec.begin(), vec.end());
//! remove odd value
for(auto it = lst.begin(); it != lst.end(); )
if(*it & 0x1) it = lst.erase(it);
else ++it;
//! remove even value
for(auto it = vec.begin(); it != vec.end(); )
if(! (*it & 0x1)) it = vec.erase(it);
else ++it;
//! print
cout << "list : ";
for(auto i : lst) cout << i << " ";
cout << "\nvector : ";
for(auto i : vec) cout << i << " ";
cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>//! @Soyn
//!
//! Exercise 9.51:
//! Write a class that has three unsigned members representing year,
//! month, and day. Write a constructor that takes a string representing
//! a date. Your constructor should handle a variety of date formats,
//! such as January 1, 1900, 1/1/1900, Jan 1, 1900, and so on.
//!
#include <iostream>
#include <string>
#include <vector>
/*@Soyn
*Ex 9.51
*Date: 2015.6.12
*/
using namespace std;
class My_date{
private:
unsigned year, month, day;
public:
My_date(const string &s){
unsigned tag;
unsigned format;
format = tag = 0;
//! 1/1/1900
if(s.find_first_of("/")!= string :: npos)
{
format = 0x01;
}
//! January 1,1900 or Jan 1, 1900
if((s.find_first_of(',') >= 4) && s.find_first_of(',')!= string :: npos){
format = 0x10;
}
else{ //! Jan 1 1900
if(s.find_first_of(' ') >= 3
&& s.find_first_of(' ')!= string :: npos){
format = 0x10;
tag = 1;
}
}
switch(format){
case 0x01:
day = stoi(s.substr(0,s.find_first_of("/")));
month = stoi(s.substr(s.find_first_of("/") + 1, s.find_last_of("/")- s.find_first_of("/")));
year = stoi(s.substr(s.find_last_of("/") + 1, 4));
break;
case 0x10:
if( s.find("Jan") < s.size() ) month = 1;
if( s.find("Feb") < s.size() ) month = 2;
if( s.find("Mar") < s.size() ) month = 3;
if( s.find("Apr") < s.size() ) month = 4;
if( s.find("May") < s.size() ) month = 5;
if( s.find("Jun") < s.size() ) month = 6;
if( s.find("Jul") < s.size() ) month = 7;
if( s.find("Aug") < s.size() ) month = 8;
if( s.find("Sep") < s.size() ) month = 9;
if( s.find("Oct") < s.size() ) month =10;
if( s.find("Nov") < s.size() ) month =11;
if( s.find("Dec") < s.size() ) month =12;
char chr = ',';
if(tag == 1){
chr = ' ';
cout << "shit";
}
day = stoi(s.substr(s.find_first_of("123456789"), s.find_first_of(chr) - s.find_first_of("123456789")));
year = stoi(s.substr(s.find_last_of(' ') + 1, 4));
break;
}
}
void print(){
cout << "day" << day << " " << "month: " << month << " " << "year: " << year;
}
};
int main()
{
My_date d("Jan 1 1900");
d.print();
return 0;
}
<commit_msg>Update ex9_51.cpp<commit_after>//! @Soyn
//!
//! Exercise 9.51:
//! Write a class that has three unsigned members representing year,
//! month, and day. Write a constructor that takes a string representing
//! a date. Your constructor should handle a variety of date formats,
//! such as January 1, 1900, 1/1/1900, Jan 1, 1900, and so on.
//!
#include <iostream>
#include <string>
#include <vector>
/*@Soyn
*Ex 9.51
*Date: 2015.6.12
*/
using namespace std;
class My_date{
private:
unsigned year, month, day;
public:
My_date(const string &s){
unsigned tag;
unsigned format;
format = tag = 0;
//! 1/1/1900
if(s.find_first_of("/")!= string :: npos)
{
format = 0x01;
}
//! January 1,1900 or Jan 1, 1900
if((s.find_first_of(',') >= 4) && s.find_first_of(',')!= string :: npos){
format = 0x10;
}
else{ //! Jan 1 1900
if(s.find_first_of(' ') >= 3
&& s.find_first_of(' ')!= string :: npos){
format = 0x10;
tag = 1;
}
}
switch(format){
case 0x01:
day = stoi(s.substr(0,s.find_first_of("/")));
month = stoi(s.substr(s.find_first_of("/") + 1, s.find_last_of("/")- s.find_first_of("/")));
year = stoi(s.substr(s.find_last_of("/") + 1, 4));
break;
case 0x10:
if( s.find("Jan") < s.size() ) month = 1;
if( s.find("Feb") < s.size() ) month = 2;
if( s.find("Mar") < s.size() ) month = 3;
if( s.find("Apr") < s.size() ) month = 4;
if( s.find("May") < s.size() ) month = 5;
if( s.find("Jun") < s.size() ) month = 6;
if( s.find("Jul") < s.size() ) month = 7;
if( s.find("Aug") < s.size() ) month = 8;
if( s.find("Sep") < s.size() ) month = 9;
if( s.find("Oct") < s.size() ) month =10;
if( s.find("Nov") < s.size() ) month =11;
if( s.find("Dec") < s.size() ) month =12;
char chr = ',';
if(tag == 1){
chr = ' ';
}
day = stoi(s.substr(s.find_first_of("123456789"), s.find_first_of(chr) - s.find_first_of("123456789")));
year = stoi(s.substr(s.find_last_of(' ') + 1, 4));
break;
}
}
void print(){
cout << "day£º" << day << " " << "month: " << month << " " << "year: " << year;
}
};
int main()
{
My_date d("Jan 1 1900");
d.print();
return 0;
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <unordered_map>
#include "core/future.hh"
#include "net/api.hh"
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/shared_ptr.hh"
namespace rpc {
using id_type = int64_t;
struct SerializerConcept {
template<typename T>
future<> operator()(output_stream<char>& out, T&& v);
template<typename T>
future<> operator()(input_stream<char>& in, T& v);
// id_type and sstring are needed for compilation to succeed
future<> operator()(output_stream<char>& out, id_type& v);
future<> operator()(input_stream<char>& in, id_type& v);
future<> operator()(output_stream<char>& out, sstring& v);
future<> operator()(input_stream<char>& in, sstring& v);
};
struct client_info {
socket_address addr;
};
// MsgType is a type that holds type of a message. The type should be hashable
// and serializable. It is preferable to use enum for message types, but
// do not forget to provide hash function for it
template<typename Serializer, typename MsgType = uint32_t>
class protocol {
class connection {
protected:
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
future<> _output_ready = make_ready_future<>();
bool _error = false;
protocol& _proto;
public:
connection(connected_socket&& fd, protocol& proto) : _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf(_fd.output()), _proto(proto) {}
connection(protocol& proto) : _proto(proto) {}
// functions below are public because they are used by external heavily templated functions
// and I am not smart enough to know how to define them as friends
auto& in() { return _read_buf; }
auto& out() { return _write_buf; }
auto& out_ready() { return _output_ready; }
bool error() { return _error; }
auto& serializer() { return _proto._serializer; }
auto& get_protocol() { return _proto; }
};
friend connection;
public:
class server {
private:
protocol& _proto;
public:
class connection : public protocol::connection, public enable_lw_shared_from_this<connection> {
server& _server;
MsgType _type;
client_info _info;
public:
connection(server& s, connected_socket&& fd, socket_address&& addr, protocol& proto);
future<> process();
auto& info() { return _info; }
};
server(protocol& proto, ipv4_addr addr);
void accept(server_socket&& ss);
friend connection;
};
class client : public protocol::connection {
promise<> _connected;
id_type _message_id = 1;
id_type _rcv_msg_id = 0;
struct reply_handler_base {
virtual future<> operator()(client&, id_type) = 0;
virtual ~reply_handler_base() {};
};
public:
struct stats {
using counter_type = uint64_t;
counter_type replied = 0;
counter_type pending = 0;
counter_type exception_received = 0;
counter_type sent_messages = 0;
counter_type wait_reply = 0;
};
template<typename Reply, typename Func>
struct reply_handler final : reply_handler_base {
Func func;
Reply reply;
reply_handler(Func&& f) : func(std::move(f)) {}
virtual future<> operator()(client& client, id_type msg_id) override {
return func(reply, client, msg_id);
}
virtual ~reply_handler() {}
};
private:
std::unordered_map<id_type, std::unique_ptr<reply_handler_base>> _outstanding;
stats _stats;
public:
client(protocol& proto, ipv4_addr addr, ipv4_addr local = ipv4_addr());
stats get_stats() const {
stats res = _stats;
res.wait_reply = _outstanding.size();
return _stats;
}
stats& get_stats_internal() {
return _stats;
}
auto next_message_id() { return _message_id++; }
void wait_for_reply(id_type id, std::unique_ptr<reply_handler_base>&& h) {
_outstanding.emplace(id, std::move(h));
}
};
friend server;
private:
using rpc_handler = std::function<future<>(lw_shared_ptr<typename server::connection>)>;
std::unordered_map<MsgType, rpc_handler> _handlers;
Serializer _serializer;
std::function<void(const sstring&)> _logger;
public:
protocol(Serializer&& serializer) : _serializer(std::forward<Serializer>(serializer)) {}
template<typename Func>
auto make_client(MsgType t);
// returns a function which type depends on Func
// if Func == Ret(Args...) then return function is
// future<Ret>(protocol::client&, Args...)
template<typename Func>
auto register_handler(MsgType t, Func&& func);
void set_logger(std::function<void(const sstring&)> logger) {
_logger = logger;
}
void log(const sstring& str) {
if (_logger) {
_logger(str);
_logger("\n");
}
}
void log(const client_info& info, id_type msg_id, const sstring& str) {
log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + " msg_id " + to_sstring(msg_id) + ": " + str);
}
private:
void register_receiver(MsgType t, rpc_handler&& handler) {
_handlers.emplace(t, std::move(handler));
}
};
class error : public std::runtime_error {
public:
error(const std::string& msg) : std::runtime_error(msg) {}
};
class closed_error : public error {
public:
closed_error() : error("connection is closed") {}
};
struct no_wait_type {};
// return this from a callback if client does not want to waiting for a reply
extern no_wait_type no_wait;
}
#include "rpc_impl.hh"
<commit_msg>rpc: fix get_stats not returning the updated stats structure<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <unordered_map>
#include "core/future.hh"
#include "net/api.hh"
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/shared_ptr.hh"
namespace rpc {
using id_type = int64_t;
struct SerializerConcept {
template<typename T>
future<> operator()(output_stream<char>& out, T&& v);
template<typename T>
future<> operator()(input_stream<char>& in, T& v);
// id_type and sstring are needed for compilation to succeed
future<> operator()(output_stream<char>& out, id_type& v);
future<> operator()(input_stream<char>& in, id_type& v);
future<> operator()(output_stream<char>& out, sstring& v);
future<> operator()(input_stream<char>& in, sstring& v);
};
struct client_info {
socket_address addr;
};
// MsgType is a type that holds type of a message. The type should be hashable
// and serializable. It is preferable to use enum for message types, but
// do not forget to provide hash function for it
template<typename Serializer, typename MsgType = uint32_t>
class protocol {
class connection {
protected:
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
future<> _output_ready = make_ready_future<>();
bool _error = false;
protocol& _proto;
public:
connection(connected_socket&& fd, protocol& proto) : _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf(_fd.output()), _proto(proto) {}
connection(protocol& proto) : _proto(proto) {}
// functions below are public because they are used by external heavily templated functions
// and I am not smart enough to know how to define them as friends
auto& in() { return _read_buf; }
auto& out() { return _write_buf; }
auto& out_ready() { return _output_ready; }
bool error() { return _error; }
auto& serializer() { return _proto._serializer; }
auto& get_protocol() { return _proto; }
};
friend connection;
public:
class server {
private:
protocol& _proto;
public:
class connection : public protocol::connection, public enable_lw_shared_from_this<connection> {
server& _server;
MsgType _type;
client_info _info;
public:
connection(server& s, connected_socket&& fd, socket_address&& addr, protocol& proto);
future<> process();
auto& info() { return _info; }
};
server(protocol& proto, ipv4_addr addr);
void accept(server_socket&& ss);
friend connection;
};
class client : public protocol::connection {
promise<> _connected;
id_type _message_id = 1;
id_type _rcv_msg_id = 0;
struct reply_handler_base {
virtual future<> operator()(client&, id_type) = 0;
virtual ~reply_handler_base() {};
};
public:
struct stats {
using counter_type = uint64_t;
counter_type replied = 0;
counter_type pending = 0;
counter_type exception_received = 0;
counter_type sent_messages = 0;
counter_type wait_reply = 0;
};
template<typename Reply, typename Func>
struct reply_handler final : reply_handler_base {
Func func;
Reply reply;
reply_handler(Func&& f) : func(std::move(f)) {}
virtual future<> operator()(client& client, id_type msg_id) override {
return func(reply, client, msg_id);
}
virtual ~reply_handler() {}
};
private:
std::unordered_map<id_type, std::unique_ptr<reply_handler_base>> _outstanding;
stats _stats;
public:
client(protocol& proto, ipv4_addr addr, ipv4_addr local = ipv4_addr());
stats get_stats() const {
stats res = _stats;
res.wait_reply = _outstanding.size();
return res;
}
stats& get_stats_internal() {
return _stats;
}
auto next_message_id() { return _message_id++; }
void wait_for_reply(id_type id, std::unique_ptr<reply_handler_base>&& h) {
_outstanding.emplace(id, std::move(h));
}
};
friend server;
private:
using rpc_handler = std::function<future<>(lw_shared_ptr<typename server::connection>)>;
std::unordered_map<MsgType, rpc_handler> _handlers;
Serializer _serializer;
std::function<void(const sstring&)> _logger;
public:
protocol(Serializer&& serializer) : _serializer(std::forward<Serializer>(serializer)) {}
template<typename Func>
auto make_client(MsgType t);
// returns a function which type depends on Func
// if Func == Ret(Args...) then return function is
// future<Ret>(protocol::client&, Args...)
template<typename Func>
auto register_handler(MsgType t, Func&& func);
void set_logger(std::function<void(const sstring&)> logger) {
_logger = logger;
}
void log(const sstring& str) {
if (_logger) {
_logger(str);
_logger("\n");
}
}
void log(const client_info& info, id_type msg_id, const sstring& str) {
log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + " msg_id " + to_sstring(msg_id) + ": " + str);
}
private:
void register_receiver(MsgType t, rpc_handler&& handler) {
_handlers.emplace(t, std::move(handler));
}
};
class error : public std::runtime_error {
public:
error(const std::string& msg) : std::runtime_error(msg) {}
};
class closed_error : public error {
public:
closed_error() : error("connection is closed") {}
};
struct no_wait_type {};
// return this from a callback if client does not want to waiting for a reply
extern no_wait_type no_wait;
}
#include "rpc_impl.hh"
<|endoftext|> |
<commit_before><commit_msg>Revert r369927 - [DAGCombiner] Remove a bunch of redundant AddToWorklist calls.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_SOURCES_RX_ITERATE_HPP)
#define RXCPP_SOURCES_RX_ITERATE_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace sources {
namespace detail {
template<class Collection>
struct is_iterable
{
typedef typename std::decay<Collection>::type collection_type;
struct not_void {};
template<class CC>
static auto check(int) -> decltype(std::begin(*(CC*)nullptr));
template<class CC>
static not_void check(...);
static const bool value = !std::is_same<decltype(check<collection_type>(0)), not_void>::value;
};
template<class Collection>
struct iterate_traits
{
typedef typename std::decay<Collection>::type collection_type;
typedef decltype(std::begin(*(collection_type*)nullptr)) iterator_type;
typedef typename std::iterator_traits<iterator_type>::value_type value_type;
};
template<class Collection, class Coordination>
struct iterate : public source_base<typename iterate_traits<Collection>::value_type>
{
typedef iterate<Collection, Coordination> this_type;
typedef iterate_traits<Collection> traits;
typedef typename std::decay<Coordination>::type coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
typedef typename traits::collection_type collection_type;
typedef typename traits::iterator_type iterator_type;
struct iterate_initial_type
{
iterate_initial_type(collection_type c, coordination_type cn)
: collection(std::move(c))
, coordination(std::move(cn))
{
}
collection_type collection;
coordination_type coordination;
};
iterate_initial_type initial;
iterate(collection_type c, coordination_type cn)
: initial(std::move(c), std::move(cn))
{
}
template<class Subscriber>
void on_subscribe(Subscriber o) const {
static_assert(is_subscriber<Subscriber>::value, "subscribe must be passed a subscriber");
typedef typename coordinator_type::template get<Subscriber>::type output_type;
struct iterate_state_type
: public iterate_initial_type
{
iterate_state_type(const iterate_initial_type& i, output_type o)
: iterate_initial_type(i)
, cursor(std::begin(iterate_initial_type::collection))
, end(std::end(iterate_initial_type::collection))
, out(std::move(o))
{
}
iterate_state_type(const iterate_state_type& o)
: iterate_initial_type(o)
, cursor(std::begin(iterate_initial_type::collection))
, end(std::end(iterate_initial_type::collection))
, out(std::move(o.out)) // since lambda capture does not yet support move
{
}
mutable iterator_type cursor;
iterator_type end;
mutable output_type out;
};
// creates a worker whose lifetime is the same as this subscription
auto coordinator = initial.coordination.create_coordinator(o.get_subscription());
iterate_state_type state(initial, o);
auto controller = coordinator.get_worker();
auto producer = [state](const rxsc::schedulable& self){
if (!state.out.is_subscribed()) {
// terminate loop
return;
}
if (state.cursor != state.end) {
// send next value
state.out.on_next(*state.cursor);
++state.cursor;
}
if (state.cursor == state.end) {
state.out.on_completed();
// o is unsubscribed
return;
}
// tail recurse this same action to continue loop
self();
};
auto selectedProducer = on_exception(
[&](){return coordinator.act(producer);},
o);
if (selectedProducer.empty()) {
return;
}
controller.schedule(selectedProducer.get());
}
};
}
template<class Collection>
auto iterate(Collection c)
-> observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, identity_one_worker>> {
return observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, identity_one_worker>>(
detail::iterate<Collection, identity_one_worker>(std::move(c), identity_immediate()));
}
template<class Collection, class Coordination>
auto iterate(Collection c, Coordination cn)
-> observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, Coordination>> {
return observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, Coordination>>(
detail::iterate<Collection, Coordination>(std::move(c), std::move(cn)));
}
template<class T>
auto from()
-> decltype(iterate(std::array<T, 0>(), identity_immediate())) {
return iterate(std::array<T, 0>(), identity_immediate());
}
template<class T, class Coordination>
auto from(Coordination cn)
-> typename std::enable_if<is_coordination<Coordination>::value,
decltype( iterate(std::array<T, 0>(), std::move(cn)))>::type {
return iterate(std::array<T, 0>(), std::move(cn));
}
template<class Value0, class... ValueN>
auto from(Value0 v0, ValueN... vn)
-> typename std::enable_if<!is_coordination<Value0>::value,
decltype(iterate(std::array<Value0, sizeof...(ValueN) + 1>{v0, vn...}, identity_immediate()))>::type {
std::array<Value0, sizeof...(ValueN) + 1> c = {v0, vn...};
return iterate(std::move(c), identity_immediate());
}
template<class Coordination, class Value0, class... ValueN>
auto from(Coordination cn, Value0 v0, ValueN... vn)
-> typename std::enable_if<is_coordination<Coordination>::value,
decltype(iterate(std::array<Value0, sizeof...(ValueN) + 1>{v0, vn...}, std::move(cn)))>::type {
std::array<Value0, sizeof...(ValueN) + 1> c = {v0, vn...};
return iterate(std::move(c), std::move(cn));
}
}
}
#endif
<commit_msg>try to find a solution that works on all compilers<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_SOURCES_RX_ITERATE_HPP)
#define RXCPP_SOURCES_RX_ITERATE_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace sources {
namespace detail {
template<class Collection>
struct is_iterable
{
typedef typename std::decay<Collection>::type collection_type;
struct not_void {};
template<class CC>
static auto check(int) -> decltype(std::begin(*(CC*)nullptr));
template<class CC>
static not_void check(...);
static const bool value = !std::is_same<decltype(check<collection_type>(0)), not_void>::value;
};
template<class Collection>
struct iterate_traits
{
typedef typename std::decay<Collection>::type collection_type;
typedef decltype(std::begin(*(collection_type*)nullptr)) iterator_type;
typedef typename std::iterator_traits<iterator_type>::value_type value_type;
};
template<class Collection, class Coordination>
struct iterate : public source_base<typename iterate_traits<Collection>::value_type>
{
typedef iterate<Collection, Coordination> this_type;
typedef iterate_traits<Collection> traits;
typedef typename std::decay<Coordination>::type coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
typedef typename traits::collection_type collection_type;
typedef typename traits::iterator_type iterator_type;
struct iterate_initial_type
{
iterate_initial_type(collection_type c, coordination_type cn)
: collection(std::move(c))
, coordination(std::move(cn))
{
}
collection_type collection;
coordination_type coordination;
};
iterate_initial_type initial;
iterate(collection_type c, coordination_type cn)
: initial(std::move(c), std::move(cn))
{
}
template<class Subscriber>
void on_subscribe(Subscriber o) const {
static_assert(is_subscriber<Subscriber>::value, "subscribe must be passed a subscriber");
typedef typename coordinator_type::template get<Subscriber>::type output_type;
struct iterate_state_type
: public iterate_initial_type
{
iterate_state_type(const iterate_initial_type& i, output_type o)
: iterate_initial_type(i)
, cursor(std::begin(iterate_initial_type::collection))
, end(std::end(iterate_initial_type::collection))
, out(std::move(o))
{
}
iterate_state_type(const iterate_state_type& o)
: iterate_initial_type(o)
, cursor(std::begin(iterate_initial_type::collection))
, end(std::end(iterate_initial_type::collection))
, out(std::move(o.out)) // since lambda capture does not yet support move
{
}
mutable iterator_type cursor;
iterator_type end;
mutable output_type out;
};
// creates a worker whose lifetime is the same as this subscription
auto coordinator = initial.coordination.create_coordinator(o.get_subscription());
iterate_state_type state(initial, o);
auto controller = coordinator.get_worker();
auto producer = [state](const rxsc::schedulable& self){
if (!state.out.is_subscribed()) {
// terminate loop
return;
}
if (state.cursor != state.end) {
// send next value
state.out.on_next(*state.cursor);
++state.cursor;
}
if (state.cursor == state.end) {
state.out.on_completed();
// o is unsubscribed
return;
}
// tail recurse this same action to continue loop
self();
};
auto selectedProducer = on_exception(
[&](){return coordinator.act(producer);},
o);
if (selectedProducer.empty()) {
return;
}
controller.schedule(selectedProducer.get());
}
};
}
template<class Collection>
auto iterate(Collection c)
-> observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, identity_one_worker>> {
return observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, identity_one_worker>>(
detail::iterate<Collection, identity_one_worker>(std::move(c), identity_immediate()));
}
template<class Collection, class Coordination>
auto iterate(Collection c, Coordination cn)
-> observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, Coordination>> {
return observable<typename detail::iterate_traits<Collection>::value_type, detail::iterate<Collection, Coordination>>(
detail::iterate<Collection, Coordination>(std::move(c), std::move(cn)));
}
template<class T>
auto from()
-> decltype(iterate(std::array<T, 0>(), identity_immediate())) {
return iterate(std::array<T, 0>(), identity_immediate());
}
template<class T, class Coordination>
auto from(Coordination cn)
-> typename std::enable_if<is_coordination<Coordination>::value,
decltype( iterate(std::array<T, 0>(), std::move(cn)))>::type {
return iterate(std::array<T, 0>(), std::move(cn));
}
template<class Value0, class... ValueN>
auto from(Value0 v0, ValueN... vn)
-> typename std::enable_if<!is_coordination<Value0>::value,
decltype(iterate(*(std::array<Value0, sizeof...(ValueN) + 1>*)nullptr, identity_immediate()))>::type {
std::array<Value0, sizeof...(ValueN) + 1> c = {v0, vn...};
return iterate(std::move(c), identity_immediate());
}
template<class Coordination, class Value0, class... ValueN>
auto from(Coordination cn, Value0 v0, ValueN... vn)
-> typename std::enable_if<is_coordination<Coordination>::value,
decltype(iterate(*(std::array<Value0, sizeof...(ValueN) + 1>*)nullptr, std::move(cn)))>::type {
std::array<Value0, sizeof...(ValueN) + 1> c = {v0, vn...};
return iterate(std::move(c), std::move(cn));
}
}
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* 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. *
******************************************************************************/
#include "caf/attachable.hpp"
namespace caf {
attachable::~attachable() {
// nop
}
attachable::token::token(size_t typenr, const void* vptr)
: subtype(typenr), ptr(vptr) {
// nop
}
void attachable::actor_exited(const error&, execution_unit*) {
// nop
}
bool attachable::matches(const token&) {
return false;
}
} // namespace caf
<commit_msg>Fix possible stack overflow in ~attachable<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* 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. *
******************************************************************************/
#include "caf/attachable.hpp"
namespace caf {
attachable::~attachable() {
// Avoid recursive cleanup of next pointers because this can cause a stack
// overflow for long linked lists.
using std::swap;
while (next != nullptr) {
attachable_ptr tmp;
swap(next->next, tmp);
swap(next, tmp);
}
}
attachable::token::token(size_t typenr, const void* vptr)
: subtype(typenr), ptr(vptr) {
// nop
}
void attachable::actor_exited(const error&, execution_unit*) {
// nop
}
bool attachable::matches(const token&) {
return false;
}
} // namespace caf
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkSource.h"
#include "vtkDataObject.h"
#ifndef NULL
#define NULL 0
#endif
//----------------------------------------------------------------------------
vtkSource::vtkSource()
{
this->NumberOfOutputs = 0;
this->Outputs = NULL;
this->Updating = 0;
}
//----------------------------------------------------------------------------
vtkSource::~vtkSource()
{
int idx;
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->SetSource(NULL);
this->Outputs[idx]->UnRegister(this);
this->Outputs[idx] = NULL;
}
}
if (this->Outputs)
{
delete [] this->Outputs;
this->Outputs = NULL;
this->NumberOfOutputs = 0;
}
}
//----------------------------------------------------------------------------
vtkDataObject *vtkSource::GetOutput(int i)
{
if (this->NumberOfOutputs < i+1)
{
return NULL;
}
return this->Outputs[i];
}
//----------------------------------------------------------------------------
int vtkSource::GetReleaseDataFlag()
{
if (this->GetOutput(0))
{
return this->GetOutput(0)->GetReleaseDataFlag();
}
vtkWarningMacro(<<"Output doesn't exist!");
return 1;
}
//----------------------------------------------------------------------------
void vtkSource::SetReleaseDataFlag(int i)
{
int idx;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->SetReleaseDataFlag(i);
}
}
}
//----------------------------------------------------------------------------
void vtkSource::Update()
{
if (this->GetOutput(0))
{
this->GetOutput(0)->Update();
}
}
typedef vtkDataObject *vtkDataObjectPointer;
//----------------------------------------------------------------------------
// Called by constructor to set up output array.
void vtkSource::SetNumberOfOutputs(int num)
{
int idx;
vtkDataObjectPointer *outputs;
// in case nothing has changed.
if (num == this->NumberOfOutputs)
{
return;
}
// Allocate new arrays.
outputs = new vtkDataObjectPointer[num];
// Initialize with NULLs.
for (idx = 0; idx < num; ++idx)
{
outputs[idx] = NULL;
}
// Copy old outputs
for (idx = 0; idx < num && idx < this->NumberOfOutputs; ++idx)
{
outputs[idx] = this->Outputs[idx];
}
// delete the previous arrays
if (this->Outputs)
{
delete [] this->Outputs;
this->Outputs = NULL;
this->NumberOfOutputs = 0;
}
// Set the new arrays
this->Outputs = outputs;
this->NumberOfOutputs = num;
this->Modified();
}
//----------------------------------------------------------------------------
// Adds an output to the first null position in the output list.
// Expands the list memory if necessary
void vtkSource::AddOutput(vtkDataObject *output)
{
int idx;
if (output)
{
output->SetSource(this);
output->Register(this);
}
this->Modified();
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx] == NULL)
{
this->Outputs[idx] = output;
return;
}
}
this->SetNumberOfOutputs(this->NumberOfOutputs + 1);
this->Outputs[this->NumberOfOutputs - 1] = output;
}
//----------------------------------------------------------------------------
// Adds an output to the first null position in the output list.
// Expands the list memory if necessary
void vtkSource::RemoveOutput(vtkDataObject *output)
{
int idx, loc;
if (!output)
{
return;
}
// find the output in the list of outputs
loc = -1;
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx] == output)
{
loc = idx;
}
}
if (loc == -1)
{
vtkDebugMacro("tried to remove an output that was not in the list");
return;
}
this->Outputs[loc]->SetSource(NULL);
this->Outputs[loc]->UnRegister(this);
this->Outputs[loc] = NULL;
// if that was the last output, then shrink the list
if (loc == this->NumberOfOutputs - 1)
{
this->SetNumberOfOutputs(this->NumberOfOutputs - 1);
}
this->Modified();
}
//----------------------------------------------------------------------------
// Set an Output of this filter.
void vtkSource::SetOutput(int idx, vtkDataObject *output)
{
if (idx < 0)
{
vtkErrorMacro(<< "SetOutput: " << idx << ", cannot set output. ");
return;
}
// Expand array if necessary.
if (idx >= this->NumberOfOutputs)
{
this->SetNumberOfOutputs(idx + 1);
}
// does this change anything?
if (output == this->Outputs[idx])
{
return;
}
if (this->Outputs[idx])
{
this->Outputs[idx]->SetSource(NULL);
this->Outputs[idx]->UnRegister(this);
this->Outputs[idx] = NULL;
}
if (output)
{
output->SetSource(this);
output->Register(this);
}
this->Outputs[idx] = output;
this->Modified();
}
//----------------------------------------------------------------------------
// Update input to this filter and the filter itself.
// This is a streaming version of the update method.
void vtkSource::InternalUpdate(vtkDataObject *output)
{
int idx;
int numDivisions, division;
// prevent chasing our tail
if (this->Updating)
{
return;
}
// Let the source initialize the data for streaming.
// output->Initialize and CopyStructure ...
this->StreamExecuteStart();
// Determine how many pieces we are going to process.
numDivisions = this->GetNumberOfStreamDivisions();
for (division = 0; division < numDivisions; ++division)
{
// Compute the update extent for all of the inputs.
if (this->ComputeDivisionExtents(output, division, numDivisions))
{
// Update the inputs
this->Updating = 1;
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
this->Inputs[idx]->InternalUpdate();
}
}
this->Updating = 0;
// Execute
if ( this->StartMethod )
{
(*this->StartMethod)(this->StartMethodArg);
}
// reset Abort flag
this->AbortExecute = 0;
this->Progress = 0.0;
this->Execute();
if ( !this->AbortExecute )
{
this->UpdateProgress(1.0);
}
if ( this->EndMethod )
{
(*this->EndMethod)(this->EndMethodArg);
}
}
}
// Let the source clean up after streaming.
this->StreamExecuteEnd();
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
if ( this->Inputs[idx]->ShouldIReleaseData() )
{
this->Inputs[idx]->ReleaseData();
}
}
}
}
//----------------------------------------------------------------------------
// To facilitate a single Update method, we are putting data initialization
// in this method.
void vtkSource::StreamExecuteStart()
{
int idx;
// clear output (why isn't this ReleaseData. Does it allocate data too?)
// Should it be done if StreamExecuteStart?
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->Initialize();
}
}
}
//----------------------------------------------------------------------------
int vtkSource::ComputeDivisionExtents(vtkDataObject *output,
int idx, int numDivisions)
{
if (idx == 0 && numDivisions == 1)
{
return this->ComputeInputUpdateExtents(output);
}
if (this->NumberOfInputs > 0)
{
vtkErrorMacro("Source did not implement ComputeDivisionExtents");
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
int vtkSource::ComputeInputUpdateExtents(vtkDataObject *output)
{
if (this->NumberOfInputs > 0)
{
vtkErrorMacro("Subclass did not implement ComputeInputUpdateExtents");
}
return 1;
}
// This will have to be merged with the streaming update.
#if 0
//----------------------------------------------------------------------------
// This Update supports the MPI and SharedMemoryPorts,
void vtkSource::InternalUpdate()
{
vtkDataObject *pd;
int idx;
// prevent chasing our tail
if (this->Updating)
{
return;
}
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx] != NULL)
{
this->Outputs[idx]->Initialize(); //clear output
}
}
// The UpdateInformation has already started the non-blocking update.
// Here we should probably sort by locality, but
// dividing into two groups should do for now.
// UpdateInformation has started non blocking updates on the
// non local inputs, so update the local inputs next.
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
pd = this->Inputs[idx];
if (pd->GetLocality() != 0)
{
this->Updating = 1;
pd->InternalUpdate();
this->Updating = 0;
}
}
}
// Now ask the non-local inputs (ports) to send there data.
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
pd = this->Inputs[idx];
if (pd->GetLocality() == 0)
{
this->Updating = 1;
pd->InternalUpdate();
this->Updating = 0;
}
}
}
// execute
if ( this->StartMethod )
{
(*this->StartMethod)(this->StartMethodArg);
}
// reset Abort flag
this->AbortExecute = 0;
this->Progress = 0.0;
this->Execute();
if ( !this->AbortExecute )
{
this->UpdateProgress(1.0);
}
if ( this->EndMethod )
{
(*this->EndMethod)(this->EndMethodArg);
}
// clean up
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
pd = this->Inputs[idx];
if ( pd->ShouldIReleaseData() )
{
pd->ReleaseData();
}
}
}
}
#endif
//----------------------------------------------------------------------------
void vtkSource::UpdateInformation()
{
unsigned long t1, t2, size;
int locality, l2, idx;
vtkDataObject *pd;
if (this->Outputs[0] == NULL)
{
return;
}
// Update information on the input and
// compute information that is general to vtkDataObject.
t1 = this->GetMTime();
size = 0;
locality = 0;
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
pd = this->Inputs[idx];
this->Updating = 1;
pd->UpdateInformation();
this->Updating = 0;
// for MPI port stuff
l2 = pd->GetLocality();
if (l2 > locality)
{
locality = l2;
}
// Pipeline MTime stuff
t2 = pd->GetPipelineMTime();
if (t2 > t1)
{
t1 = t2;
}
// Pipeline MTime does not include the MTime of the data object itself.
// Factor these mtimes into the next PipelineMTime
t2 = pd->GetMTime();
if (t2 > t1)
{
t1 = t2;
}
// Default estimated size is just the sum of the sizes of the inputs.
size += pd->GetEstimatedMemorySize();
}
}
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->GetOutput(idx))
{
this->GetOutput(idx)->SetLocality(locality + 1);
this->GetOutput(idx)->SetEstimatedMemorySize(size);
this->GetOutput(idx)->SetPipelineMTime(t1);
}
}
// Call ExecuteInformation for subclass specific information.
// Some sources (readers) have an expensive ExecuteInformation method.
if (t1 > this->InformationTime.GetMTime())
{
this->ExecuteInformation();
this->InformationTime.Modified();
}
}
//----------------------------------------------------------------------------
void vtkSource::Execute()
{
vtkErrorMacro(<< "Definition of Execute() method should be in subclass");
}
//----------------------------------------------------------------------------
void vtkSource::ExecuteInformation()
{
//vtkErrorMacro(<< "Subclass did not implement ExecuteInformation");
}
//----------------------------------------------------------------------------
void vtkSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkProcessObject::PrintSelf(os,indent);
if ( this->NumberOfOutputs)
{
int idx;
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
os << indent << "Output " << idx << ": (" << this->Outputs[idx] << ")\n";
}
}
else
{
os << indent <<"No Outputs\n";
}
}
int vtkSource::InRegisterLoop(vtkObject *o)
{
int idx;
int num = 0;
int cnum = 0;
int match = 0;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
if (this->Outputs[idx] == o)
{
match = 1;
}
if (this->Outputs[idx]->GetSource() == this)
{
num++;
cnum += this->Outputs[idx]->GetNetReferenceCount();
}
}
}
// if no one outside is using us
// and our data objects are down to one net reference
// and we are being asked by one of our data objects
if (this->ReferenceCount == num && cnum == (num + 1) && match)
{
return 1;
}
return 0;
}
void vtkSource::UnRegister(vtkObject *o)
{
int idx;
int done = 0;
// detect the circular loop source <-> data
// If we have two references and one of them is my data
// and I am not being unregistered by my data, break the loop.
if (this->ReferenceCount == (this->NumberOfOutputs+1))
{
done = 1;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
if (this->Outputs[idx] == o)
{
done = 0;
}
if (this->Outputs[idx]->GetNetReferenceCount() != 1)
{
done = 0;
}
}
}
}
if (this->ReferenceCount == this->NumberOfOutputs)
{
int match = 0;
int total = 0;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
if (this->Outputs[idx] == o)
{
match = 1;
}
total += this->Outputs[idx]->GetNetReferenceCount();
}
}
if (total == 6 && match)
{
done = 1;
}
}
if (done)
{
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->SetSource(NULL);
}
}
}
this->vtkObject::UnRegister(o);
}
<commit_msg>LoopShrk.cxx bug<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkSource.h"
#include "vtkDataObject.h"
#ifndef NULL
#define NULL 0
#endif
//----------------------------------------------------------------------------
vtkSource::vtkSource()
{
this->NumberOfOutputs = 0;
this->Outputs = NULL;
this->Updating = 0;
}
//----------------------------------------------------------------------------
vtkSource::~vtkSource()
{
int idx;
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->SetSource(NULL);
this->Outputs[idx]->UnRegister(this);
this->Outputs[idx] = NULL;
}
}
if (this->Outputs)
{
delete [] this->Outputs;
this->Outputs = NULL;
this->NumberOfOutputs = 0;
}
}
//----------------------------------------------------------------------------
vtkDataObject *vtkSource::GetOutput(int i)
{
if (this->NumberOfOutputs < i+1)
{
return NULL;
}
return this->Outputs[i];
}
//----------------------------------------------------------------------------
int vtkSource::GetReleaseDataFlag()
{
if (this->GetOutput(0))
{
return this->GetOutput(0)->GetReleaseDataFlag();
}
vtkWarningMacro(<<"Output doesn't exist!");
return 1;
}
//----------------------------------------------------------------------------
void vtkSource::SetReleaseDataFlag(int i)
{
int idx;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->SetReleaseDataFlag(i);
}
}
}
//----------------------------------------------------------------------------
void vtkSource::Update()
{
if (this->GetOutput(0))
{
this->GetOutput(0)->Update();
}
}
typedef vtkDataObject *vtkDataObjectPointer;
//----------------------------------------------------------------------------
// Called by constructor to set up output array.
void vtkSource::SetNumberOfOutputs(int num)
{
int idx;
vtkDataObjectPointer *outputs;
// in case nothing has changed.
if (num == this->NumberOfOutputs)
{
return;
}
// Allocate new arrays.
outputs = new vtkDataObjectPointer[num];
// Initialize with NULLs.
for (idx = 0; idx < num; ++idx)
{
outputs[idx] = NULL;
}
// Copy old outputs
for (idx = 0; idx < num && idx < this->NumberOfOutputs; ++idx)
{
outputs[idx] = this->Outputs[idx];
}
// delete the previous arrays
if (this->Outputs)
{
delete [] this->Outputs;
this->Outputs = NULL;
this->NumberOfOutputs = 0;
}
// Set the new arrays
this->Outputs = outputs;
this->NumberOfOutputs = num;
this->Modified();
}
//----------------------------------------------------------------------------
// Adds an output to the first null position in the output list.
// Expands the list memory if necessary
void vtkSource::AddOutput(vtkDataObject *output)
{
int idx;
if (output)
{
output->SetSource(this);
output->Register(this);
}
this->Modified();
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx] == NULL)
{
this->Outputs[idx] = output;
return;
}
}
this->SetNumberOfOutputs(this->NumberOfOutputs + 1);
this->Outputs[this->NumberOfOutputs - 1] = output;
}
//----------------------------------------------------------------------------
// Adds an output to the first null position in the output list.
// Expands the list memory if necessary
void vtkSource::RemoveOutput(vtkDataObject *output)
{
int idx, loc;
if (!output)
{
return;
}
// find the output in the list of outputs
loc = -1;
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->Outputs[idx] == output)
{
loc = idx;
}
}
if (loc == -1)
{
vtkDebugMacro("tried to remove an output that was not in the list");
return;
}
this->Outputs[loc]->SetSource(NULL);
this->Outputs[loc]->UnRegister(this);
this->Outputs[loc] = NULL;
// if that was the last output, then shrink the list
if (loc == this->NumberOfOutputs - 1)
{
this->SetNumberOfOutputs(this->NumberOfOutputs - 1);
}
this->Modified();
}
//----------------------------------------------------------------------------
// Set an Output of this filter.
void vtkSource::SetOutput(int idx, vtkDataObject *output)
{
if (idx < 0)
{
vtkErrorMacro(<< "SetOutput: " << idx << ", cannot set output. ");
return;
}
// Expand array if necessary.
if (idx >= this->NumberOfOutputs)
{
this->SetNumberOfOutputs(idx + 1);
}
// does this change anything?
if (output == this->Outputs[idx])
{
return;
}
if (this->Outputs[idx])
{
this->Outputs[idx]->SetSource(NULL);
this->Outputs[idx]->UnRegister(this);
this->Outputs[idx] = NULL;
}
if (output)
{
output->SetSource(this);
output->Register(this);
}
this->Outputs[idx] = output;
this->Modified();
}
//----------------------------------------------------------------------------
// Update input to this filter and the filter itself.
// This is a streaming version of the update method.
void vtkSource::InternalUpdate(vtkDataObject *output)
{
int idx;
int numDivisions, division;
// prevent chasing our tail
if (this->Updating)
{
return;
}
// Let the source initialize the data for streaming.
// output->Initialize and CopyStructure ...
this->StreamExecuteStart();
// Determine how many pieces we are going to process.
numDivisions = this->GetNumberOfStreamDivisions();
for (division = 0; division < numDivisions; ++division)
{
// Compute the update extent for all of the inputs.
if (this->ComputeDivisionExtents(output, division, numDivisions))
{
// Update the inputs
this->Updating = 1;
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
this->Inputs[idx]->InternalUpdate();
}
}
this->Updating = 0;
// Execute
if ( this->StartMethod )
{
(*this->StartMethod)(this->StartMethodArg);
}
// reset Abort flag
this->AbortExecute = 0;
this->Progress = 0.0;
this->Execute();
if ( !this->AbortExecute )
{
this->UpdateProgress(1.0);
}
if ( this->EndMethod )
{
(*this->EndMethod)(this->EndMethodArg);
}
}
}
// Let the source clean up after streaming.
this->StreamExecuteEnd();
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
if ( this->Inputs[idx]->ShouldIReleaseData() )
{
this->Inputs[idx]->ReleaseData();
}
}
}
}
//----------------------------------------------------------------------------
// To facilitate a single Update method, we are putting data initialization
// in this method.
void vtkSource::StreamExecuteStart()
{
int idx;
// clear output (why isn't this ReleaseData. Does it allocate data too?)
// Should it be done if StreamExecuteStart?
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->Initialize();
}
}
}
//----------------------------------------------------------------------------
int vtkSource::ComputeDivisionExtents(vtkDataObject *output,
int idx, int numDivisions)
{
if (idx == 0 && numDivisions == 1)
{
return this->ComputeInputUpdateExtents(output);
}
if (this->NumberOfInputs > 0)
{
vtkErrorMacro("Source did not implement ComputeDivisionExtents");
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
int vtkSource::ComputeInputUpdateExtents(vtkDataObject *output)
{
if (this->NumberOfInputs > 0)
{
vtkErrorMacro("Subclass did not implement ComputeInputUpdateExtents");
}
return 1;
}
//----------------------------------------------------------------------------
void vtkSource::UpdateInformation()
{
unsigned long t1, t2, size;
int locality, l2, idx;
vtkDataObject *pd;
if (this->Outputs[0] == NULL)
{
return;
}
if (this->Updating)
{
// We are in a pipeline loop.
// Force an update
this->GetOutput(0)->Modified();
return;
}
// Update information on the input and
// compute information that is general to vtkDataObject.
t1 = this->GetMTime();
size = 0;
locality = 0;
for (idx = 0; idx < this->NumberOfInputs; ++idx)
{
if (this->Inputs[idx] != NULL)
{
pd = this->Inputs[idx];
this->Updating = 1;
pd->UpdateInformation();
this->Updating = 0;
// for MPI port stuff
l2 = pd->GetLocality();
if (l2 > locality)
{
locality = l2;
}
// Pipeline MTime stuff
t2 = pd->GetPipelineMTime();
if (t2 > t1)
{
t1 = t2;
}
// Pipeline MTime does not include the MTime of the data object itself.
// Factor these mtimes into the next PipelineMTime
t2 = pd->GetMTime();
if (t2 > t1)
{
t1 = t2;
}
// Default estimated size is just the sum of the sizes of the inputs.
size += pd->GetEstimatedMemorySize();
}
}
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
if (this->GetOutput(idx))
{
this->GetOutput(idx)->SetLocality(locality + 1);
this->GetOutput(idx)->SetEstimatedMemorySize(size);
this->GetOutput(idx)->SetPipelineMTime(t1);
}
}
// Call ExecuteInformation for subclass specific information.
// Some sources (readers) have an expensive ExecuteInformation method.
if (t1 > this->InformationTime.GetMTime())
{
this->ExecuteInformation();
this->InformationTime.Modified();
}
}
//----------------------------------------------------------------------------
void vtkSource::Execute()
{
vtkErrorMacro(<< "Definition of Execute() method should be in subclass");
}
//----------------------------------------------------------------------------
void vtkSource::ExecuteInformation()
{
//vtkErrorMacro(<< "Subclass did not implement ExecuteInformation");
}
//----------------------------------------------------------------------------
void vtkSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkProcessObject::PrintSelf(os,indent);
if ( this->NumberOfOutputs)
{
int idx;
for (idx = 0; idx < this->NumberOfOutputs; ++idx)
{
os << indent << "Output " << idx << ": (" << this->Outputs[idx] << ")\n";
}
}
else
{
os << indent <<"No Outputs\n";
}
}
int vtkSource::InRegisterLoop(vtkObject *o)
{
int idx;
int num = 0;
int cnum = 0;
int match = 0;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
if (this->Outputs[idx] == o)
{
match = 1;
}
if (this->Outputs[idx]->GetSource() == this)
{
num++;
cnum += this->Outputs[idx]->GetNetReferenceCount();
}
}
}
// if no one outside is using us
// and our data objects are down to one net reference
// and we are being asked by one of our data objects
if (this->ReferenceCount == num && cnum == (num + 1) && match)
{
return 1;
}
return 0;
}
void vtkSource::UnRegister(vtkObject *o)
{
int idx;
int done = 0;
// detect the circular loop source <-> data
// If we have two references and one of them is my data
// and I am not being unregistered by my data, break the loop.
if (this->ReferenceCount == (this->NumberOfOutputs+1))
{
done = 1;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
if (this->Outputs[idx] == o)
{
done = 0;
}
if (this->Outputs[idx]->GetNetReferenceCount() != 1)
{
done = 0;
}
}
}
}
if (this->ReferenceCount == this->NumberOfOutputs)
{
int match = 0;
int total = 0;
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
if (this->Outputs[idx] == o)
{
match = 1;
}
total += this->Outputs[idx]->GetNetReferenceCount();
}
}
if (total == 6 && match)
{
done = 1;
}
}
if (done)
{
for (idx = 0; idx < this->NumberOfOutputs; idx++)
{
if (this->Outputs[idx])
{
this->Outputs[idx]->SetSource(NULL);
}
}
}
this->vtkObject::UnRegister(o);
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
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. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3307
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3307 to 3308<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
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. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3308
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before><commit_msg>Don't try to draw if there's no canvas or surface<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
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. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3291
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3291 to 3292<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
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. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3292
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
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. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3360
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3360 to 3361<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
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. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3361
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before><commit_msg>add global pair distance interaction<commit_after><|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TheBestName {
vector <string> sort(vector <string> names) {
auto sum = [](string const & s) {
int t = 0;
ei(a, s) t += a - 'A';
return t;
};
std::sort(all(names), [sum](const string & a, const string & b) {
if (a == "JOHN") return true;
if (b == "JOHN") return false;
int d = sum(b) - sum(a);
if (d > 0) return false;
if (d< 0) return true;
return a > b;
});
return names;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TheBestName *obj;
vector <string> answer;
obj = new TheBestName();
clock_t startTime = clock();
answer = obj->sort(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p1[i] << "\"";
}
cout << "}" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(answer.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << answer[i] << "\"";
}
cout << "}" << endl;
if (hasAnswer) {
if (answer.size() != p1.size()) {
res = false;
} else {
for (int i = 0; int(answer.size()) > i; ++i) {
if (answer[i] != p1[i]) {
res = false;
}
}
}
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
vector <string> p1;
// ----- test 0 -----
disabled = false;
p0 = {"JOHN","PETR","ACRUSH"};
p1 = {"JOHN","ACRUSH","PETR"};
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"GLUK","MARGARITKA"};
p1 = {"MARGARITKA","GLUK"};
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"};
p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"};
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"};
p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"};
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>TheBestName<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TheBestName {
vector <string> sort(vector <string> names) {
auto sum = [](string const & s) {
int t = 0;
ei(a, s) t += a - 'A' + 1;
return t;
};
std::sort(all(names), [sum](const string & a, const string & b) {
if (a == "JOHN") return true;
if (b == "JOHN") return false;
int d = sum(b) - sum(a);
if (d > 0) return false;
if (d < 0) return true;
return a > b;
});
return names;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TheBestName *obj;
vector <string> answer;
obj = new TheBestName();
clock_t startTime = clock();
answer = obj->sort(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p1[i] << "\"";
}
cout << "}" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(answer.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << answer[i] << "\"";
}
cout << "}" << endl;
if (hasAnswer) {
if (answer.size() != p1.size()) {
res = false;
} else {
for (int i = 0; int(answer.size()) > i; ++i) {
if (answer[i] != p1[i]) {
res = false;
}
}
}
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
vector <string> p1;
// ----- test 0 -----
disabled = false;
p0 = {"JOHN","PETR","ACRUSH"};
p1 = {"JOHN","ACRUSH","PETR"};
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"GLUK","MARGARITKA"};
p1 = {"MARGARITKA","GLUK"};
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"};
p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"};
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"};
p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"};
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|> |
<commit_before>#include "WPILib.h"
/**
* This is a quick sample program to show how to use the new Talon SRX over CAN.
* As of the time of this writing (11/20/14), the only mode supported on the SRX is the
* straight-up throttle (status info, such as current and temperature should work).
*
*/
class Robot : public SampleRobot {
CANTalon m_motor;
// update every 0.005 seconds/5 milliseconds.
double kUpdatePeriod = 0.005;
public:
Robot()
: m_motor(1) // Initialize the Talon as device 1. Use the roboRIO web
// interface to change the device number on the talons.
{}
/**
* Runs the motor from the output of a Joystick.
*/
void OperatorControl() {
talon.EnableControl();
while (IsOperatorControl() && IsEnabled()) {
// Takes a number from -1.0 (full reverse) to +1.0 (full forwards).
m_motor.Set(0.5);
Wait(kUpdatePeriod); // Wait 5ms for the next update.
}
m_motor.Set(0.0);
}
};
START_ROBOT_CLASS(Robot);
<commit_msg>Fixed a typo in the SRX sample project to correct a variable name error<commit_after>#include "WPILib.h"
/**
* This is a quick sample program to show how to use the new Talon SRX over CAN.
* As of the time of this writing (11/20/14), the only mode supported on the SRX is the
* straight-up throttle (status info, such as current and temperature should work).
*
*/
class Robot : public SampleRobot {
CANTalon m_motor;
// update every 0.005 seconds/5 milliseconds.
double kUpdatePeriod = 0.005;
public:
Robot()
: m_motor(1) // Initialize the Talon as device 1. Use the roboRIO web
// interface to change the device number on the talons.
{}
/**
* Runs the motor from the output of a Joystick.
*/
void OperatorControl() {
m_motor.EnableControl();
while (IsOperatorControl() && IsEnabled()) {
// Takes a number from -1.0 (full reverse) to +1.0 (full forwards).
m_motor.Set(0.5);
Wait(kUpdatePeriod); // Wait 5ms for the next update.
}
m_motor.Set(0.0);
}
};
START_ROBOT_CLASS(Robot);
<|endoftext|> |
<commit_before>#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>
#include "config.h"
#include <boost/shared_ptr.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "sentence_metadata.h"
#include "scorer.h"
#include "verbose.h"
#include "viterbi.h"
#include "hg.h"
#include "prob.h"
#include "kbest.h"
#include "ff_register.h"
#include "decoder.h"
#include "filelib.h"
#include "fdict.h"
#include "weights.h"
#include "sparse_vector.h"
using namespace std;
using boost::shared_ptr;
namespace po = boost::program_options;
bool invert_score;
void SanityCheck(const vector<double>& w) {
for (int i = 0; i < w.size(); ++i) {
assert(!isnan(w[i]));
assert(!isinf(w[i]));
}
}
struct FComp {
const vector<double>& w_;
FComp(const vector<double>& w) : w_(w) {}
bool operator()(int a, int b) const {
return fabs(w_[a]) > fabs(w_[b]);
}
};
void ShowLargestFeatures(const vector<double>& w) {
vector<int> fnums(w.size());
for (int i = 0; i < w.size(); ++i)
fnums[i] = i;
vector<int>::iterator mid = fnums.begin();
mid += (w.size() > 10 ? 10 : w.size());
partial_sort(fnums.begin(), mid, fnums.end(), FComp(w));
cerr << "TOP FEATURES:";
--mid;
for (vector<int>::iterator i = fnums.begin(); i != mid; ++i) {
cerr << ' ' << FD::Convert(*i) << '=' << w[*i];
}
cerr << endl;
}
bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("input_weights,w",po::value<string>(),"Input feature weights file")
("source,i",po::value<string>(),"Source file for development set")
("passes,p", po::value<int>()->default_value(15), "Number of passes through the training data")
("reference,r",po::value<vector<string> >(), "[REQD] Reference translation(s) (tokenized text file)")
("mt_metric,m",po::value<string>()->default_value("ibm_bleu"), "Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)")
("max_step_size,C", po::value<double>()->default_value(0.01), "regularization strength (C)")
("mt_metric_scale,s", po::value<double>()->default_value(1.0), "Amount to scale MT loss function by")
("k_best_size,k", po::value<int>()->default_value(250), "Size of hypothesis list to search for oracles")
("decoder_config,c",po::value<string>(),"Decoder configuration file");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || !conf->count("input_weights") || !conf->count("source") || !conf->count("decoder_config") || !conf->count("reference")) {
cerr << dcmdline_options << endl;
return false;
}
return true;
}
static const double kMINUS_EPSILON = -1e-6;
struct HypothesisInfo {
SparseVector<double> features;
double mt_metric;
};
struct GoodBadOracle {
shared_ptr<HypothesisInfo> good;
shared_ptr<HypothesisInfo> bad;
};
struct TrainingObserver : public DecoderObserver {
TrainingObserver(const int k, const DocScorer& d, vector<GoodBadOracle>* o) : ds(d), oracles(*o), kbest_size(k) {}
const DocScorer& ds;
vector<GoodBadOracle>& oracles;
shared_ptr<HypothesisInfo> cur_best;
const int kbest_size;
const HypothesisInfo& GetCurrentBestHypothesis() const {
return *cur_best;
}
virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) {
UpdateOracles(smeta.GetSentenceID(), *hg);
}
shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) {
shared_ptr<HypothesisInfo> h(new HypothesisInfo);
h->features = feats;
h->mt_metric = score;
return h;
}
void UpdateOracles(int sent_id, const Hypergraph& forest) {
shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good;
shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad;
cur_bad.reset(); // TODO get rid of??
KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size);
for (int i = 0; i < kbest_size; ++i) {
const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =
kbest.LazyKthBest(forest.nodes_.size() - 1, i);
if (!d) break;
float sentscore = ds[sent_id]->ScoreCandidate(d->yield)->ComputeScore();
if (invert_score) sentscore *= -1.0;
// cerr << TD::GetString(d->yield) << " ||| " << d->score << " ||| " << sentscore << endl;
if (i == 0)
cur_best = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_good || sentscore > cur_good->mt_metric)
cur_good = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_bad || sentscore < cur_bad->mt_metric)
cur_bad = MakeHypothesisInfo(d->feature_values, sentscore);
}
//cerr << "GOOD: " << cur_good->mt_metric << endl;
//cerr << " CUR: " << cur_best->mt_metric << endl;
//cerr << " BAD: " << cur_bad->mt_metric << endl;
}
};
void ReadTrainingCorpus(const string& fname, vector<string>* c) {
ReadFile rf(fname);
istream& in = *rf.stream();
string line;
while(in) {
getline(in, line);
if (!in) break;
c->push_back(line);
}
}
bool ApproxEqual(double a, double b) {
if (a == b) return true;
return (fabs(a-b)/fabs(b)) < 0.000001;
}
int main(int argc, char** argv) {
register_feature_functions();
SetSilent(true); // turn off verbose decoder output
po::variables_map conf;
if (!InitCommandLine(argc, argv, &conf)) return 1;
vector<string> corpus;
ReadTrainingCorpus(conf["source"].as<string>(), &corpus);
const string metric_name = conf["mt_metric"].as<string>();
ScoreType type = ScoreTypeFromString(metric_name);
if (type == TER) {
invert_score = true;
} else {
invert_score = false;
}
DocScorer ds(type, conf["reference"].as<vector<string> >(), "");
cerr << "Loaded " << ds.size() << " references for scoring with " << metric_name << endl;
if (ds.size() != corpus.size()) {
cerr << "Mismatched number of references (" << ds.size() << ") and sources (" << corpus.size() << ")\n";
return 1;
}
// load initial weights
Weights weights;
weights.InitFromFile(conf["input_weights"].as<string>());
SparseVector<double> lambdas;
weights.InitSparseVector(&lambdas);
ReadFile ini_rf(conf["decoder_config"].as<string>());
Decoder decoder(ini_rf.stream());
const double max_step_size = conf["max_step_size"].as<double>();
const double mt_metric_scale = conf["mt_metric_scale"].as<double>();
assert(corpus.size() > 0);
vector<GoodBadOracle> oracles(corpus.size());
TrainingObserver observer(conf["k_best_size"].as<int>(), ds, &oracles);
int cur_sent = 0;
int lcount = 0;
int normalizer = 0;
double tot_loss = 0;
int dots = 0;
int cur_pass = 0;
vector<double> dense_weights;
SparseVector<double> tot;
tot += lambdas; // initial weights
normalizer++; // count for initial weights
int max_iteration = conf["passes"].as<int>() * corpus.size();
string msg = "# MIRA tuned weights";
string msga = "# MIRA tuned weights AVERAGED";
while (lcount <= max_iteration) {
dense_weights.clear();
weights.InitFromVector(lambdas);
weights.InitVector(&dense_weights);
decoder.SetWeights(dense_weights);
if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; }
if (corpus.size() == cur_sent) {
cerr << " [AVG METRIC LAST PASS=" << (tot_loss / corpus.size()) << "]\n";
ShowLargestFeatures(dense_weights);
cur_sent = 0;
tot_loss = 0;
dots = 0;
ostringstream os;
os << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << ".gz";
weights.WriteToFile(os.str(), true, &msg);
SparseVector<double> x = tot;
x /= normalizer;
ostringstream sa;
sa << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << "-avg.gz";
Weights ww;
ww.InitFromVector(x);
ww.WriteToFile(sa.str(), true, &msga);
++cur_pass;
} else if (cur_sent == 0) {
cerr << "PASS " << (lcount / corpus.size() + 1) << endl;
}
decoder.SetId(cur_sent);
decoder.Decode(corpus[cur_sent], &observer); // update oracles
const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis();
const HypothesisInfo& cur_good = *oracles[cur_sent].good;
const HypothesisInfo& cur_bad = *oracles[cur_sent].bad;
tot_loss += cur_hyp.mt_metric;
if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) {
const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) +
mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric);
//cerr << "LOSS: " << loss << endl;
if (loss > 0.0) {
SparseVector<double> diff = cur_good.features;
diff -= cur_bad.features;
double step_size = loss / diff.l2norm_sq();
//cerr << loss << " " << step_size << " " << diff << endl;
if (step_size > max_step_size) step_size = max_step_size;
lambdas += (cur_good.features * step_size);
lambdas -= (cur_bad.features * step_size);
//cerr << "L: " << lambdas << endl;
}
}
tot += lambdas;
++normalizer;
++lcount;
++cur_sent;
}
cerr << endl;
weights.WriteToFile("weights.mira-final.gz", true, &msg);
tot /= normalizer;
weights.InitFromVector(tot);
msg = "# MIRA tuned weights (averaged vector)";
weights.WriteToFile("weights.mira-final-avg.gz", true, &msg);
cerr << "Optimization complete.\nAVERAGED WEIGHTS: weights.mira-final-avg.gz\n";
return 0;
}
<commit_msg>randomize order of samples in mira<commit_after>#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>
#include "config.h"
#include <boost/shared_ptr.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "sentence_metadata.h"
#include "scorer.h"
#include "verbose.h"
#include "viterbi.h"
#include "hg.h"
#include "prob.h"
#include "kbest.h"
#include "ff_register.h"
#include "decoder.h"
#include "filelib.h"
#include "fdict.h"
#include "weights.h"
#include "sparse_vector.h"
#include "sampler.h"
using namespace std;
using boost::shared_ptr;
namespace po = boost::program_options;
bool invert_score;
boost::shared_ptr<MT19937> rng;
void SanityCheck(const vector<double>& w) {
for (int i = 0; i < w.size(); ++i) {
assert(!isnan(w[i]));
assert(!isinf(w[i]));
}
}
struct FComp {
const vector<double>& w_;
FComp(const vector<double>& w) : w_(w) {}
bool operator()(int a, int b) const {
return fabs(w_[a]) > fabs(w_[b]);
}
};
void RandomPermutation(int len, vector<int>* p_ids) {
vector<int>& ids = *p_ids;
ids.resize(len);
for (int i = 0; i < len; ++i) ids[i] = i;
for (int i = len; i > 0; --i) {
int j = rng->next() * i;
if (j == i) i--;
swap(ids[i-1], ids[j]);
}
}
void ShowLargestFeatures(const vector<double>& w) {
vector<int> fnums(w.size());
for (int i = 0; i < w.size(); ++i)
fnums[i] = i;
vector<int>::iterator mid = fnums.begin();
mid += (w.size() > 10 ? 10 : w.size());
partial_sort(fnums.begin(), mid, fnums.end(), FComp(w));
cerr << "TOP FEATURES:";
--mid;
for (vector<int>::iterator i = fnums.begin(); i != mid; ++i) {
cerr << ' ' << FD::Convert(*i) << '=' << w[*i];
}
cerr << endl;
}
bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("input_weights,w",po::value<string>(),"Input feature weights file")
("source,i",po::value<string>(),"Source file for development set")
("passes,p", po::value<int>()->default_value(15), "Number of passes through the training data")
("reference,r",po::value<vector<string> >(), "[REQD] Reference translation(s) (tokenized text file)")
("mt_metric,m",po::value<string>()->default_value("ibm_bleu"), "Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)")
("max_step_size,C", po::value<double>()->default_value(0.01), "regularization strength (C)")
("mt_metric_scale,s", po::value<double>()->default_value(1.0), "Amount to scale MT loss function by")
("k_best_size,k", po::value<int>()->default_value(250), "Size of hypothesis list to search for oracles")
("random_seed,S", po::value<uint32_t>(), "Random seed (if not specified, /dev/random will be used)")
("decoder_config,c",po::value<string>(),"Decoder configuration file");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || !conf->count("input_weights") || !conf->count("source") || !conf->count("decoder_config") || !conf->count("reference")) {
cerr << dcmdline_options << endl;
return false;
}
return true;
}
static const double kMINUS_EPSILON = -1e-6;
struct HypothesisInfo {
SparseVector<double> features;
double mt_metric;
};
struct GoodBadOracle {
shared_ptr<HypothesisInfo> good;
shared_ptr<HypothesisInfo> bad;
};
struct TrainingObserver : public DecoderObserver {
TrainingObserver(const int k, const DocScorer& d, vector<GoodBadOracle>* o) : ds(d), oracles(*o), kbest_size(k) {}
const DocScorer& ds;
vector<GoodBadOracle>& oracles;
shared_ptr<HypothesisInfo> cur_best;
const int kbest_size;
const HypothesisInfo& GetCurrentBestHypothesis() const {
return *cur_best;
}
virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) {
UpdateOracles(smeta.GetSentenceID(), *hg);
}
shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) {
shared_ptr<HypothesisInfo> h(new HypothesisInfo);
h->features = feats;
h->mt_metric = score;
return h;
}
void UpdateOracles(int sent_id, const Hypergraph& forest) {
shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good;
shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad;
cur_bad.reset(); // TODO get rid of??
KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size);
for (int i = 0; i < kbest_size; ++i) {
const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =
kbest.LazyKthBest(forest.nodes_.size() - 1, i);
if (!d) break;
float sentscore = ds[sent_id]->ScoreCandidate(d->yield)->ComputeScore();
if (invert_score) sentscore *= -1.0;
// cerr << TD::GetString(d->yield) << " ||| " << d->score << " ||| " << sentscore << endl;
if (i == 0)
cur_best = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_good || sentscore > cur_good->mt_metric)
cur_good = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_bad || sentscore < cur_bad->mt_metric)
cur_bad = MakeHypothesisInfo(d->feature_values, sentscore);
}
//cerr << "GOOD: " << cur_good->mt_metric << endl;
//cerr << " CUR: " << cur_best->mt_metric << endl;
//cerr << " BAD: " << cur_bad->mt_metric << endl;
}
};
void ReadTrainingCorpus(const string& fname, vector<string>* c) {
ReadFile rf(fname);
istream& in = *rf.stream();
string line;
while(in) {
getline(in, line);
if (!in) break;
c->push_back(line);
}
}
bool ApproxEqual(double a, double b) {
if (a == b) return true;
return (fabs(a-b)/fabs(b)) < 0.000001;
}
int main(int argc, char** argv) {
register_feature_functions();
SetSilent(true); // turn off verbose decoder output
po::variables_map conf;
if (!InitCommandLine(argc, argv, &conf)) return 1;
if (conf.count("random_seed"))
rng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
else
rng.reset(new MT19937);
vector<string> corpus;
ReadTrainingCorpus(conf["source"].as<string>(), &corpus);
const string metric_name = conf["mt_metric"].as<string>();
ScoreType type = ScoreTypeFromString(metric_name);
if (type == TER) {
invert_score = true;
} else {
invert_score = false;
}
DocScorer ds(type, conf["reference"].as<vector<string> >(), "");
cerr << "Loaded " << ds.size() << " references for scoring with " << metric_name << endl;
if (ds.size() != corpus.size()) {
cerr << "Mismatched number of references (" << ds.size() << ") and sources (" << corpus.size() << ")\n";
return 1;
}
// load initial weights
Weights weights;
weights.InitFromFile(conf["input_weights"].as<string>());
SparseVector<double> lambdas;
weights.InitSparseVector(&lambdas);
ReadFile ini_rf(conf["decoder_config"].as<string>());
Decoder decoder(ini_rf.stream());
const double max_step_size = conf["max_step_size"].as<double>();
const double mt_metric_scale = conf["mt_metric_scale"].as<double>();
assert(corpus.size() > 0);
vector<GoodBadOracle> oracles(corpus.size());
TrainingObserver observer(conf["k_best_size"].as<int>(), ds, &oracles);
int cur_sent = 0;
int lcount = 0;
int normalizer = 0;
double tot_loss = 0;
int dots = 0;
int cur_pass = 0;
vector<double> dense_weights;
SparseVector<double> tot;
tot += lambdas; // initial weights
normalizer++; // count for initial weights
int max_iteration = conf["passes"].as<int>() * corpus.size();
string msg = "# MIRA tuned weights";
string msga = "# MIRA tuned weights AVERAGED";
vector<int> order;
RandomPermutation(corpus.size(), &order);
while (lcount <= max_iteration) {
dense_weights.clear();
weights.InitFromVector(lambdas);
weights.InitVector(&dense_weights);
decoder.SetWeights(dense_weights);
if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; }
if (corpus.size() == cur_sent) {
cerr << " [AVG METRIC LAST PASS=" << (tot_loss / corpus.size()) << "]\n";
ShowLargestFeatures(dense_weights);
cur_sent = 0;
tot_loss = 0;
dots = 0;
ostringstream os;
os << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << ".gz";
weights.WriteToFile(os.str(), true, &msg);
SparseVector<double> x = tot;
x /= normalizer;
ostringstream sa;
sa << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << "-avg.gz";
Weights ww;
ww.InitFromVector(x);
ww.WriteToFile(sa.str(), true, &msga);
++cur_pass;
RandomPermutation(corpus.size(), &order);
}
if (cur_sent == 0) {
cerr << "PASS " << (lcount / corpus.size() + 1) << endl;
}
decoder.SetId(order[cur_sent]);
decoder.Decode(corpus[order[cur_sent]], &observer); // update oracles
const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis();
const HypothesisInfo& cur_good = *oracles[order[cur_sent]].good;
const HypothesisInfo& cur_bad = *oracles[order[cur_sent]].bad;
tot_loss += cur_hyp.mt_metric;
if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) {
const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) +
mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric);
//cerr << "LOSS: " << loss << endl;
if (loss > 0.0) {
SparseVector<double> diff = cur_good.features;
diff -= cur_bad.features;
double step_size = loss / diff.l2norm_sq();
//cerr << loss << " " << step_size << " " << diff << endl;
if (step_size > max_step_size) step_size = max_step_size;
lambdas += (cur_good.features * step_size);
lambdas -= (cur_bad.features * step_size);
//cerr << "L: " << lambdas << endl;
}
}
tot += lambdas;
++normalizer;
++lcount;
++cur_sent;
}
cerr << endl;
weights.WriteToFile("weights.mira-final.gz", true, &msg);
tot /= normalizer;
weights.InitFromVector(tot);
msg = "# MIRA tuned weights (averaged vector)";
weights.WriteToFile("weights.mira-final-avg.gz", true, &msg);
cerr << "Optimization complete.\nAVERAGED WEIGHTS: weights.mira-final-avg.gz\n";
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.