text stringlengths 54 60.6k |
|---|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include "node_connection.h"
#include "node_request.h"
#include <iostream>
#include <memory>
namespace arangodb { namespace fuerte { namespace js {
///////////////////////////////////////////////////////////////////////////////
// NConnectionBuilder /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnectionBuilder::New) {
if (info.IsConstructCall()) {
NConnectionBuilder* obj = new NConnectionBuilder();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> builder = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(builder).ToLocalChecked());
}
}
NAN_METHOD(NConnectionBuilder::connect){
v8::Local<v8::Function> connFunction = Nan::New(NConnection::constructor());
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {info.This()};
auto connInstance = Nan::NewInstance(connFunction, argc, argv).ToLocalChecked();
info.GetReturnValue().Set(connInstance);
}
NAN_METHOD(NConnectionBuilder::host){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.host(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::async){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.async(to<bool>(info[0]));
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::user){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.user(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::password){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.password(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
}
///////////////////////////////////////////////////////////////////////////////
// NConnection ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnection::New) {
if (info.IsConstructCall()) {
NConnection* obj = new NConnection();
if(info[0]->IsObject()){ // NConnectionBuilderObject -- exact type check?
obj->_cppClass = unwrap<NConnectionBuilder>(info[0])->_cppClass.connect();
}
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
}
}
NAN_METHOD(NConnection::sendRequest) {
if (info.Length() != 3 ) {
Nan::ThrowTypeError("Not 3 Arguments");
}
// get isolate - has node only one context??!?!? how do they work
// context is probably a lighter version of isolate but does not allow threads
v8::Isolate* iso = v8::Isolate::GetCurrent();
auto jsOnErr = v8::Local<v8::Function>::Cast(info[1]);
v8::Persistent<v8::Function> persOnErr;
persOnErr.Reset(iso, jsOnErr);
auto jsOnSucc = v8::Local<v8::Function>::Cast(info[2]);
v8::Persistent<v8::Function> persOnSucc;
persOnSucc.Reset(iso, jsOnSucc);
fu::OnErrorCallback err = [iso,&persOnErr](unsigned err
,std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
v8::HandleScope scope(iso);
v8::Local<v8::Function> jsOnErr = v8::Local<v8::Function>::New(iso,persOnErr);
// wrap request
v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor());
auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked();
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = Nan::New(NConnection::constructor());
auto resObj = Nan::NewInstance(requestProto).ToLocalChecked();
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 3;
v8::Local<v8::Value> argv[argc] = { Nan::New<v8::Integer>(err), reqObj, resObj };
// call and dispose
jsOnErr->Call(v8::Null(iso), argc, argv);
persOnErr.Reset(); // dispose of persistent
};
fu::OnSuccessCallback succ = [iso,&persOnSucc](std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
v8::HandleScope scope(iso);
std::cout << std::endl << "req/res " << creq.get() << "/" << cres.get() << std::endl;
// wrap request
//v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor()); // with Nan
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
//auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked(); // with Nan
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 2;
v8::Local<v8::Value> argv[argc] = { reqObj, resObj };
// call and dispose
std::cout << std::endl << "running js callback success, with iso: " << iso << std::endl;
v8::Local<v8::Function> jsOnSucc = v8::Local<v8::Function>::New(iso,persOnSucc);
//jsOnSucc->Call(v8::Null(iso), argc, argv);
jsOnSucc->Call(iso->GetCurrentContext(), iso->GetCurrentContext()->Global(), argc, argv);
persOnSucc.Reset(); // dispose of persistent
//persOnSucc.Reset(iso,v8::Local<v8::Function>()); // dispose of persistent
};
//finally invoke the c++ callback
auto req = std::unique_ptr<fu::Request>(new fu::Request(*(unwrap<NRequest>(info[0])->_cppClass))); //copy request so the old object stays valid
unwrapSelf<NConnection>(info)->_cppClass->sendRequest(std::move(req), err, succ);
}
}}}
<commit_msg>successfully send first request via JavaScript<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include "node_connection.h"
#include "node_request.h"
#include <iostream>
#include <memory>
#include <mutex>
#include <atomic>
namespace arangodb { namespace fuerte { namespace js {
///////////////////////////////////////////////////////////////////////////////
// NConnectionBuilder /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnectionBuilder::New) {
if (info.IsConstructCall()) {
NConnectionBuilder* obj = new NConnectionBuilder();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> builder = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(builder).ToLocalChecked());
}
}
NAN_METHOD(NConnectionBuilder::connect){
v8::Local<v8::Function> connFunction = Nan::New(NConnection::constructor());
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {info.This()};
auto connInstance = Nan::NewInstance(connFunction, argc, argv).ToLocalChecked();
info.GetReturnValue().Set(connInstance);
}
NAN_METHOD(NConnectionBuilder::host){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.host(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::async){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.async(to<bool>(info[0]));
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::user){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.user(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::password){
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.password(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
}
///////////////////////////////////////////////////////////////////////////////
// NConnection ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnection::New) {
if (info.IsConstructCall()) {
NConnection* obj = new NConnection();
if(info[0]->IsObject()){ // NConnectionBuilderObject -- exact type check?
obj->_cppClass = unwrap<NConnectionBuilder>(info[0])->_cppClass.connect();
}
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
}
}
///////////////////////////////////////////////////////////////////////////////
// SendRequest ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// When we switch to c++14 we should use UniquePersistent and move it into
// the generalized lambda caputre avoiding the locking alltogehter
static std::map<fu::MessageID
,std::pair<v8::Persistent<v8::Function> // error
,v8::Persistent<v8::Function> // success
>
> callbackMap;
static std::mutex maplock;
static std::atomic<uint64_t> jsMessageID(0);
NAN_METHOD(NConnection::sendRequest) {
if (info.Length() != 3 ) {
Nan::ThrowTypeError("Not 3 Arguments");
}
if (!info[1]->IsFunction() || !info[2]->IsFunction()){
Nan::ThrowTypeError("Callback is not a Function");
}
// get isolate - has node only one context??!?!? how do they work
// context is probably a lighter version of isolate but does not allow threads
v8::Isolate* iso = v8::Isolate::GetCurrent();
uint64_t id =0;
{
std::lock_guard<std::mutex> lock(maplock);
auto& callbackPair = callbackMap[++id]; //create map element
auto jsOnErr = v8::Local<v8::Function>::Cast(info[1]);
callbackPair.first.Reset(iso, jsOnErr);
auto jsOnSucc = v8::Local<v8::Function>::Cast(info[2]);
callbackPair.second.Reset(iso, jsOnSucc);
}
fu::OnErrorCallback err = [iso,id](unsigned err
,std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
v8::HandleScope scope(iso);
auto jsOnErr = v8::Local<v8::Function>();
{ //create local function and dispose persistent
std::lock_guard<std::mutex> lock(maplock);
auto& mapElement = callbackMap[id];
jsOnErr = v8::Local<v8::Function>::New(iso,mapElement.first);
mapElement.first.Reset();
mapElement.second.Reset();
callbackMap.erase(id);
}
// wrap request
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 3;
v8::Local<v8::Value> argv[argc] = { Nan::New<v8::Integer>(err), reqObj, resObj };
// call
jsOnErr->Call(iso->GetCurrentContext(), jsOnErr, argc, argv);
};
fu::OnSuccessCallback succ = [iso,id](std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
v8::HandleScope scope(iso);
auto jsOnSucc = v8::Local<v8::Function>();
{ // create locacl function and dispose persistent
std::lock_guard<std::mutex> lock(maplock);
auto& mapElement = callbackMap[id];
//create local function
jsOnSucc = v8::Local<v8::Function>::New(iso,callbackMap[id].second);
//dispose map element
mapElement.first.Reset(); // do not depend on kResetInDestructorFlag of Persistent
mapElement.second.Reset();
callbackMap.erase(id);
}
// wrap request
//v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor()); // with Nan
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
//auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked(); // with Nan
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 2;
v8::Local<v8::Value> argv[argc] = { reqObj, resObj };
// call
//jsOnSucc->Call(v8::Null(iso), argc, argv);
jsOnSucc->Call(iso->GetCurrentContext(), jsOnSucc, argc, argv);
//jsOnSucc->Call(iso->GetCurrentContext(), iso->GetCurrentContext()->Global(), argc, argv);
};
//finally invoke the c++ callback
auto req = std::unique_ptr<fu::Request>(new fu::Request(*(unwrap<NRequest>(info[0])->_cppClass))); //copy request so the old object stays valid
unwrapSelf<NConnection>(info)->_cppClass->sendRequest(std::move(req), err, succ);
}
}}}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "test_string_aogo.h"
void test_case_conv()
{
std::string sText = "123WSxx";
std::string sT2 = boost::to_lower_copy(sText);
assert(sText == "123WSxx");
assert(sT2 == "123wsxx");
boost::to_lower(sText);
assert(sText == "123wsxx");
boost::to_upper(sText);
assert(sText == "123WSXX");
}
struct string_pred
{
bool operator()(char p)
{
if (p>'0'&&p<'9' || p>'a'&&p<'z')
{
return true;
}
return false;
}
};
struct string_pred2
{
bool operator()(char p)
{
if (p>'0'&&p<'9')
{
return true;
}
return false;
}
};
void test_predicates()
{
std::string sText = "123WSxx";
assert(boost::starts_with(sText, "123"));
assert(boost::istarts_with(sText, "123wsXX"));
assert(boost::ends_with(sText, "123") == false);
assert(boost::contains(sText, "x"));
std::string sText2 = "123sss";
assert(boost::all(sText2, string_pred()));
assert(boost::all(sText2, string_pred2()) == false);
}
void test_classification()
{
std::string sText = "123a";
std::string sText2 = "123";
std::string sText3 = "ass";
assert(all(sText, boost::is_digit()) == false);
assert(all(sText2, boost::is_digit()));
assert(all(sText3, boost::is_lower()));
}
void test_trim()
{
string str1 = " hello world! ";
string str2 = boost::trim_left_copy(str1);
assert(str2 == "hello world! ");
string str3 = boost::trim_right_copy(str1);
assert(str3 == " hello world!");
boost::trim(str1);
assert(str1 == "hello world!");
string phone = "00423333444";
boost::trim_if(phone, boost::is_any_of("04"));
assert(phone == "23333");
}
void test_find()
{
char text[] = "hello dolly!";
boost::iterator_range<char*> result = boost::find_last(text, "ll");
std::transform( result.begin(), result.end(), result.begin(), std::bind2nd(std::plus<char>(), 1));
assert(boost::equal(text, "hello dommy!"));
boost::to_upper(result);
assert(boost::equal(text, "hello doMMy!"));
boost::iterator_range<char*> result2 = boost::find_first(text, "doMMy");
assert(result2.size() == 5);
}
void test_replace()
{
}
void test_find_iterator()
{
}
void test_split()
{
}
void test_string_aogo()
{
test_case_conv();
test_predicates();
test_classification();
test_trim();
test_find();
test_replace();
test_find_iterator();
test_split();
}
<commit_msg>* boost.str_aogo.split<commit_after>#include "stdafx.h"
#include "test_string_aogo.h"
void test_case_conv()
{
std::string sText = "123WSxx";
std::string sT2 = boost::to_lower_copy(sText);
assert(sText == "123WSxx");
assert(sT2 == "123wsxx");
boost::to_lower(sText);
assert(sText == "123wsxx");
boost::to_upper(sText);
assert(sText == "123WSXX");
}
struct string_pred
{
bool operator()(char p)
{
if (p>'0'&&p<'9' || p>'a'&&p<'z')
{
return true;
}
return false;
}
};
struct string_pred2
{
bool operator()(char p)
{
if (p>'0'&&p<'9')
{
return true;
}
return false;
}
};
void test_predicates()
{
std::string sText = "123WSxx";
assert(boost::starts_with(sText, "123"));
assert(boost::istarts_with(sText, "123wsXX"));
assert(boost::ends_with(sText, "123") == false);
assert(boost::contains(sText, "x"));
std::string sText2 = "123sss";
assert(boost::all(sText2, string_pred()));
assert(boost::all(sText2, string_pred2()) == false);
}
void test_classification()
{
std::string sText = "123a";
std::string sText2 = "123";
std::string sText3 = "ass";
assert(all(sText, boost::is_digit()) == false);
assert(all(sText2, boost::is_digit()));
assert(all(sText3, boost::is_lower()));
}
void test_trim()
{
string str1 = " hello world! ";
string str2 = boost::trim_left_copy(str1);
assert(str2 == "hello world! ");
string str3 = boost::trim_right_copy(str1);
assert(str3 == " hello world!");
boost::trim(str1);
assert(str1 == "hello world!");
string phone = "00423333444";
boost::trim_if(phone, boost::is_any_of("04"));
assert(phone == "23333");
}
void test_find()
{
char text[] = "hello dolly!";
boost::iterator_range<char*> result = boost::find_last(text, "ll");
std::transform( result.begin(), result.end(), result.begin(), std::bind2nd(std::plus<char>(), 1));
assert(boost::equal(text, "hello dommy!"));
boost::to_upper(result);
assert(boost::equal(text, "hello doMMy!"));
boost::iterator_range<char*> result2 = boost::find_first(text, "doMMy");
assert(result2.size() == 5);
}
void test_replace()
{
}
void test_find_iterator()
{
}
void test_split()
{
string str1("hello abc-*-ABC-*-aBc goodbye");
std::vector<string> SplitVec;
boost::split(SplitVec, str1, boost::is_any_of("-*"), boost::token_compress_on);
// SplitVec == { "hello abc","ABC","aBc goodbye" }
for each (auto var in SplitVec)
{
cout<<var<<endl;
}
}
void test_string_aogo()
{
test_case_conv();
test_predicates();
test_classification();
test_trim();
test_find();
test_replace();
test_find_iterator();
test_split();
}
<|endoftext|> |
<commit_before>/**
* The MIT License (MIT)
*
* Copyright © 2018 Ruben Van Boxem
*
* 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.
**/
/*
* css::rule_set
* In memory representation of CSS.
*/
#ifndef SKUI_CSS_RULE_SET_H
#define SKUI_CSS_RULE_SET_H
#include <css/property.h++>
#include "css/declaration_block.h++"
#include <core/string.h++>
#include <any>
#include <unordered_map>
namespace skui::css
{
using rule_set = std::unordered_map<core::string, std::unordered_map<property, std::any>>;
}
#endif
<commit_msg>Adapt rule_set to better reflect intent of the class.<commit_after>/**
* The MIT License (MIT)
*
* Copyright © 2018 Ruben Van Boxem
*
* 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.
**/
/*
* css::rule_set
* In memory representation of CSS.
*/
#ifndef SKUI_CSS_RULE_SET_H
#define SKUI_CSS_RULE_SET_H
#include "css/declaration_block.h++"
#include "css/selector.h++"
#include <core/string.h++>
#include <utility>
#include <vector>
namespace skui::css
{
class rule_set
{
std::vector<std::pair<selector, declaration_block>> declaration_blocks;
};
}
#endif
<|endoftext|> |
<commit_before>#include <r2d2.hpp>
#include <sstream>
#include <boost/format.hpp>
#include <iostream>
#include <iomanip>
Message::Message(bool isDirect, bool requiresResponse) {
this->isDirect_ = isDirect;
this->requiresResponse_ = requiresResponse;
}
bool Message::requiresResponse() const {
return this->requiresResponse_;
}
bool Message::isDirect() const {
return this->isDirect_;
}
void Message::add_u8(uint8_t v) {
this->sstream_ << v;
}
void Message::add_s8(int8_t v) {
this->sstream_ << v;
}
void Message::add_string(size_t n_bytes, const std::string& v) {
this->sstream_ << std::setfill(static_cast<char>(0x00)) << std::left << std::setw(n_bytes) << v;
}
std::string Message::get_value() {
return this->sstream_.str();
}
Motor::Motor(NXT *nxt, uint8_t port) {
this->nxt_ = nxt;
this->port_ = port;
}
void Motor::setForward(uint8_t power) {
Message msg(true, false);
msg.add_u8(Message::START_MOTOR);
msg.add_u8(this->port_);
msg.add_s8(power);
msg.add_u8(0x01 | 0x04); // UNKNOWN
msg.add_u8(0x01); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x20); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
std::string out = msg.get_value();
this->nxt_->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
}
void Motor::setReverse(uint8_t power) {
Message msg(true, false);
msg.add_u8(Message::START_MOTOR);
msg.add_u8(this->port_);
msg.add_s8(-power);
msg.add_u8(0x01 | 0x04); // UNKNOWN
msg.add_u8(0x01); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x20); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
std::string out = msg.get_value();
this->nxt_->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
}
void Motor::stop(bool brake) {
Message msg(true, false);
msg.add_u8(Message::STOP_MOTOR);
msg.add_u8(this->port_);
msg.add_s8(0); // power 0?
if (brake) {
msg.add_u8(0x01 | 0x02 | 0x04); // UNKNOWN
msg.add_u8(0x01); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x20); // UNKNOWN
} else {
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
}
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
msg.add_u8(0x00); // UNKNOWN
std::string out = msg.get_value();
this->nxt_->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
}
Sensor::Sensor(NXT *nxt, uint8_t port) {
this->nxt_ = nxt;
this->port_ = port;
}
int Sensor::getValue() {
Message msg(true, true);
msg.add_u8(Message::GET_VALUE);
msg.add_u8(this->port_);
std::string out = msg.get_value();
uint8_t responseBuffer[16];
memset(responseBuffer, 1, sizeof(responseBuffer));
this->nxt_->sendDirectCommand(true, (int8_t *)out.c_str(), out.size(), responseBuffer, sizeof(responseBuffer));
return responseBuffer[13] * 256 + responseBuffer[12];
}
SonarSensor::SonarSensor(NXT *nxt, uint8_t port) : Sensor(nxt, port) {
this->nxt_ = nxt;
this->port_ = port;
}
int SonarSensor::lsGetStatus(uint8_t *outbuf) {
Message msg(true, true);
msg.add_u8(Message::LS_GET_STATUS);
msg.add_u8(this->port_);
std::string out = msg.get_value();
uint8_t responseBuffer[4];
memset(responseBuffer, 1, sizeof(responseBuffer));
this->nxt_->sendDirectCommand(true, (int8_t *)out.c_str(), out.size(), responseBuffer, sizeof(responseBuffer));
std::copy(responseBuffer, responseBuffer + sizeof(responseBuffer), outbuf);
return static_cast<int>(responseBuffer[3]);
}
void SonarSensor::lsRead(uint8_t *outbuf) {
Message msg(true, true);
msg.add_u8(Message::LS_READ);
msg.add_u8(this->port_);
std::string out = msg.get_value();
uint8_t responseBuffer[20];
memset(responseBuffer, 1, sizeof(responseBuffer));
this->nxt_->sendDirectCommand(true, (int8_t *)out.c_str(), out.size(), responseBuffer, sizeof(responseBuffer));
std::copy(responseBuffer, responseBuffer + sizeof(responseBuffer), outbuf);
}
void SonarSensor::lsWrite(const std::string& indata, uint8_t *outBuf, size_t outSize) {
Message msg(true, true);
msg.add_u8(Message::LS_WRITE);
msg.add_u8(this->port_);
msg.add_u8(indata.size());
msg.add_u8(outSize);
msg.add_string(indata.size(), indata);
std::string tosend = msg.get_value();
uint8_t responseBuffer[3];
memset(responseBuffer, 1, sizeof(responseBuffer));
this->nxt_->sendDirectCommand(true, (int8_t *)(tosend.c_str()), tosend.size(), responseBuffer, sizeof(responseBuffer));
std::memcpy(outBuf, responseBuffer, outSize * sizeof(uint8_t));
}
int SonarSensor::getSonarValue() {
Message msg(true, true);
msg.add_u8(0x02); // I2C_DEV
msg.add_u8(0x41); // COMMAND
msg.add_u8(0x02); // CONTINUOUS
std::string out = msg.get_value();
uint8_t outbuf2[66];
memset(outbuf2, 1, sizeof(outbuf2));
this->lsWrite(out, outbuf2, 0x00);
while (1) {
Message msg(true, true);
msg.add_u8(0x02); // I2C_DEV
msg.add_u8(0x42); // READ VALUE FROM I2C
std::string out2 = msg.get_value();
uint8_t outbuf3[66];
memset(outbuf3, 1, sizeof(outbuf3));
this->lsWrite(out2, outbuf3, 1);
uint8_t outbuf4[4];
memset(outbuf4, 1, sizeof(outbuf4));
this->lsGetStatus(outbuf4);
if (outbuf4[3] >= 1) { // 1 bytes
break;
}
}
uint8_t outbuf5[20];
memset(outbuf5, 1, sizeof(outbuf5));
this->lsRead(outbuf5);
if (outbuf5[2] == 0) {
return outbuf5[4];
} else {
return -1;
}
}
BTComm::BTComm(struct sockaddr_rc addr) {
this->addr_ = addr;
}
bool BTComm::open() {
this->sock_ = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
int status = connect(this->sock_, (struct sockaddr *)&(this->addr_), sizeof(this->addr_));
return (status == 0);
}
void BTComm::devWrite(uint8_t * buf, int buf_size) {
uint8_t bf = buf_size;
uint8_t header[] = {bf, 0x00};
uint8_t outBuf[2 + buf_size];
memcpy(outBuf, header, sizeof(header));
memcpy(outBuf + 2, buf, buf_size);
write(this->sock_, outBuf, sizeof(outBuf));
}
void BTComm::devRead(uint8_t * buf, int buf_size) {
char reply[64];
memset(reply, 0, sizeof(reply));
// read data from the client
int bytes_read = read(this->sock_, reply, 2);
if ( bytes_read > 0 ) {
int replylength = reply[0] + (reply[1] * 256);
bytes_read = read(this->sock_, reply, replylength);
if (bytes_read == replylength) {
memcpy(buf, reply, buf_size);
}
}
}
bool USBComm::open() {
int nEp = 0;
if (this->usb_dev_ == 0) {
std::cerr << "Device not found!" << std::endl;
return false;
}
int r = libusb_open(this->usb_dev_, &(this->pUSBHandle_));
if (r != 0) {
std::cerr << "Not able to claim the USB device" << std::endl;
return false;
} else {
libusb_config_descriptor *config;
libusb_get_config_descriptor(this->usb_dev_, 0, &config);
if (config->interface) {
if (config->interface->altsetting) {
r = libusb_claim_interface(this->pUSBHandle_, config->interface->altsetting->bInterfaceNumber);
if ((nEp = config->interface->altsetting->bNumEndpoints)) {
if (config->interface->altsetting->endpoint) {
this->ucEpIn_ = (config->interface->altsetting->endpoint[0].bEndpointAddress);
if (nEp > 1) {
this->ucEpOut_ = (config->interface->altsetting->endpoint[1].bEndpointAddress);
}
}
}
}
}
}
return true;
}
void USBComm::devWrite(uint8_t * buf, int buf_size) {
boost::mutex::scoped_lock lock(this->io_mutex);
if (this->pUSBHandle_) {
int actual_length;
int r = libusb_bulk_transfer(this->pUSBHandle_, this->ucEpIn_, buf, buf_size, &actual_length, TIMEOUT);
if (r == 0 && actual_length == buf_size) {
} else {
std::cerr << "ERROR WRITING" << std::endl;
std::cerr << "READ: " << actual_length << std::endl;
std::cerr << "BUF LEN: " << buf_size << std::endl;
std::cerr << "RES: " << r << std::endl;
}
}
}
void USBComm::devRead(uint8_t * buf, int buf_size) {
boost::mutex::scoped_lock lock(this->io_mutex);
if (this->pUSBHandle_) {
int actual_length;
int r = libusb_bulk_transfer(this->pUSBHandle_, this->ucEpOut_, buf, buf_size, &actual_length, TIMEOUT);
if (r == 0 && actual_length <= buf_size) {
} else {
std::cerr << "ERROR READING" << std::endl;
std::cerr << "READ: " << actual_length << std::endl;
std::cerr << "BUF LEN: " << buf_size << std::endl;
std::cerr << "RES: " << r << std::endl;
}
}
}
USBComm::USBComm(libusb_context *ctx, libusb_device *usb_dev) {
this->ctx_ = ctx;
this->usb_dev_ = usb_dev;
}
USBComm::~USBComm() {
libusb_unref_device(this->usb_dev_);
libusb_close(this->pUSBHandle_);
}
Sensor* NXT::makeTouch(uint8_t port) {
Message msg(true, false);
msg.add_u8(Message::SET_INPUT_MODE);
msg.add_u8(port);
msg.add_u8(Message::TOUCH);
msg.add_u8(Mode::BOOLEAN);
std::string out = msg.get_value();
this->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
return new Sensor(this, port);
}
SonarSensor* NXT::makeSonar(uint8_t port) {
// 0x05 -> setInputMode
// 0x0B -> LOWSPEED_9V
// 0x00 -> RAW
Message msg(true, false);
msg.add_u8(Message::SET_INPUT_MODE);
msg.add_u8(port);
msg.add_u8(Message::LOWSPEED_9V);
msg.add_u8(Mode::RAW);
std::string out = msg.get_value();
this->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
return new SonarSensor(this, port);
}
Motor* NXT::makeMotor(uint8_t port) {
return new Motor(this, port);
}
bool NXT::open() {
return this->comm_->open();
}
bool NXT::isHalted() const {
return this->halted;
}
void NXT::halt() {
for (uint8_t port = 0; port < 3; ++port) {
this->makeMotor(port)->stop(false);
}
this->halted = true;
}
double NXT::getFirmwareVersion() {
uint8_t outBuf[7];
const int min = 4, maj = 5;
Message msg(false, true);
msg.add_u8(0x88);
std::string data = msg.get_value();
// Send the system command to the NXT.
this->sendSystemCommand(true, (int8_t *)data.c_str(), data.size(), outBuf, sizeof(outBuf));
double version = outBuf[min];
while (version >= 1)
version /= 10;
version += outBuf[maj];
return version;
}
void NXT::getDeviceInfo(uint8_t * outBuf, size_t size) {
//uint8_t inBuf[] = { 0x01, 0x9B };
int8_t inBuf[] = { static_cast<int8_t>(0x9B) };
// Send the system command to the NXT.
this->sendSystemCommand(true, inBuf, sizeof(inBuf), outBuf, size);
}
std::string NXT::getName() {
uint8_t outBuf[33];
char name[15];
name[0] = '\0';
this->getDeviceInfo(outBuf, sizeof(outBuf));
std::memcpy(name, outBuf + 2, 15 * sizeof(uint8_t));
name[15] = '\0';
return std::string(name);
}
NXT::NXT(Comm *comm) {
this->comm_ = comm;
this->halted = false;
}
void NXT::sendSystemCommand(bool response, int8_t * dc_buf,
size_t dc_buf_size, uint8_t * re_buf, size_t re_buf_size) {
uint8_t buf[dc_buf_size + 1];
std::copy(dc_buf, dc_buf + dc_buf_size, buf + 1);
buf[0] = response ? 0x01 : 0x81;
this->comm_->devWrite(buf, dc_buf_size + 1);
if (response) {
uint8_t tempreadbuf[re_buf_size];
this->comm_->devRead(tempreadbuf, re_buf_size);
std::copy(tempreadbuf + 1, tempreadbuf + re_buf_size, re_buf);
}
}
void NXT::submitDirectCommand(Command *command) {
}
void NXT::sendDirectCommand(bool response, int8_t * dc_buf,
size_t dc_buf_size, uint8_t * re_buf, size_t re_buf_size) {
uint8_t buf[dc_buf_size + 1];
std::copy(dc_buf, dc_buf + dc_buf_size, buf + 1);
buf[0] = response ? 0x00 : 0x80;
this->comm_->devWrite(buf, dc_buf_size + 1);
if (response) {
this->comm_->devRead(re_buf, re_buf_size);
}
}
std::vector<NXT *>* USBNXTManager::list() {
// List all the NXT devices
std::vector<NXT*>* v = new std::vector<NXT*>();
libusb_device **devs;
libusb_context *ctx = NULL;
libusb_device *dev;
int r;
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx);
if (r < 0) {
std::cout<<"Init Error "<<r<<std::endl; //there was an error
return v;
}
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if (cnt < 0) {
std::cout<<"Get Device Error"<<std::endl; //there was an error
return v;
}
std::cout<<cnt<<" Devices in list."<<std::endl; //print total number of usb devices
ssize_t i; //for iterating through the list
for (i = 0; i < cnt; i++) {
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(devs[i], &desc);
if (r < 0) {
std::cout<<"failed to get device descriptor"<<std::endl;
continue;
}
if (desc.idVendor == NXT_VENDOR_ID && desc.idProduct == NXT_PRODUCT_ID) {
libusb_device_handle *devh = NULL;
libusb_open(devs[i], &devh);
libusb_reset_device(devh);
libusb_close(devh);
}
}
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if (cnt < 0) {
std::cout<<"Get Device Error"<<std::endl; //there was an error
return v;
}
std::cout<<cnt<<" Devices in list."<<std::endl; //print total number of usb devices
for (i = 0; i < cnt; i++) {
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(devs[i], &desc);
if (r < 0) {
std::cout<<"failed to get device descriptor"<<std::endl;
continue;
}
if (desc.idVendor == NXT_VENDOR_ID && desc.idProduct == NXT_PRODUCT_ID) {
dev = libusb_ref_device(devs[i]);
USBComm *comm = new USBComm(ctx, dev);
NXT *nxt = new NXT(comm);
v->push_back(nxt);
}
}
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
// libusb_exit(ctx); //close the session
return v;
}
std::vector<NXT *>* BTNXTManager::list() {
// List all the NXT devices
std::vector<NXT*>* v = new std::vector<NXT*>();
inquiry_info *ii = NULL;
int max_rsp, num_rsp;
int dev_id, sock, len, flags;
int i;
dev_id = hci_get_route(NULL);
sock = hci_open_dev( dev_id );
if (dev_id < 0 || sock < 0) {
perror("opening socket");
exit(1);
}
len = 8;
max_rsp = 255;
flags = IREQ_CACHE_FLUSH;
ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));
num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
if ( num_rsp < 0 ) perror("hci_inquiry");
for (i = 0; i < num_rsp; i++) {
bdaddr_t *ba = &(ii+i)->bdaddr;
if (ba->b[5] == 0x00 && ba->b[4] == 0x16 && ba->b[3] == 0x53) {
struct sockaddr_rc addr;
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
memcpy(&(addr.rc_bdaddr), ba, sizeof(bdaddr_t));
BTComm *comm = new BTComm(addr);
NXT *nxt = new NXT(comm);
v->push_back(nxt);
}
}
free( ii );
close( sock );
return v;
}
<commit_msg>removed unused comm.cpp file<commit_after><|endoftext|> |
<commit_before>class OSingleton
{
public:
static OSingleton * GetSingleton();
virtual ~OSingleton(){}
protected :
OSingleton(){}
static OSingleton * m_pSingleton;
};
OSingleton * OSingleton::m_pSingleton = NULL;
OSingleton * OSingleton::GetSingleton()
{
if(m_pSingleton == NULL )
{
m_pSingleton = new OSingleton;
}
return m_pSingleton;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.1.126); FILE MERGED 2006/09/01 17:53:49 kaib 1.1.126.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: singleton.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:47:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
class OSingleton
{
public:
static OSingleton * GetSingleton();
virtual ~OSingleton(){}
protected :
OSingleton(){}
static OSingleton * m_pSingleton;
};
OSingleton * OSingleton::m_pSingleton = NULL;
OSingleton * OSingleton::GetSingleton()
{
if(m_pSingleton == NULL )
{
m_pSingleton = new OSingleton;
}
return m_pSingleton;
}
<|endoftext|> |
<commit_before>/***************************************************************************
yahooaddcontact.cpp - description
-------------------
begin : Fri Apr 26 2002
copyright : (C) 2002 by Gav Wood
email : gav@kde.org
Based on code from : (C) 2002 by Duncan Mac-Vicar Prett
email : duncan@kde.org
***************************************************************************/
/***************************************************************************
* *
* 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 <qcheckbox.h>
// KDE Includes
#include <kdebug.h>
#include <kmessagebox.h>
// Kopete Includes
#include <addcontactpage.h>
// Local Includes
#include "yahooaccount.h"
#include "yahoocontact.h"
#include "yahooeditaccount.h"
// Yahoo Add Contact page
YahooEditAccount::YahooEditAccount(YahooProtocol *protocol, KopeteAccount *theAccount, QWidget *parent, const char *name): YahooEditAccountBase(parent), EditAccountWidget(theAccount)
{
kdDebug(14180) << "YahooEditAccount::YahooEditAccount(<protocol>, <theAccount>, <parent>, " << name << ")";
theProtocol = protocol;
if(m_account)
{ mScreenName->setText(m_account->accountId());
if(m_account->rememberPassword())
mPassword->setText(m_account->getPassword());
mAutoConnect->setChecked(m_account->autoLogin());
mRememberPassword->setChecked(true);
}
show();
}
bool YahooEditAccount::validateData()
{
kdDebug(14180) << "YahooEditAccount::validateData()";
if(mScreenName->text() == "")
{ KMessageBox::sorry(this, i18n("<qt>You must enter a valid screen name</qt>"), i18n("Yahoo"));
return false;
}
if(mPassword->text() == "")
{ KMessageBox::sorry(this, i18n("<qt>You must enter a valid password</qt>"), i18n("Yahoo"));
return false;
}
return true;
}
KopeteAccount *YahooEditAccount::apply()
{
kdDebug(14180) << "YahooEditAccount::apply()";
if(!m_account)
m_account = new YahooAccount(theProtocol, mScreenName->text());
else
m_account->setAccountId(mScreenName->text());
m_account->setAutoLogin(mAutoConnect->isChecked());
if(mRememberPassword->isChecked())
m_account->setPassword(mPassword->text());
return m_account;
}
#include "yahooeditaccount.moc"
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg><commit_after>/***************************************************************************
yahooaddcontact.cpp - description
-------------------
begin : Fri Apr 26 2002
copyright : (C) 2002 by Gav Wood
email : gav@kde.org
Based on code from : (C) 2002 by Duncan Mac-Vicar Prett
email : duncan@kde.org
***************************************************************************/
/***************************************************************************
* *
* 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 <qcheckbox.h>
#include <qlineedit.h>
// KDE Includes
#include <kdebug.h>
#include <kmessagebox.h>
// Kopete Includes
#include <addcontactpage.h>
// Local Includes
#include "yahooaccount.h"
#include "yahoocontact.h"
#include "yahooeditaccount.h"
// Yahoo Add Contact page
YahooEditAccount::YahooEditAccount(YahooProtocol *protocol, KopeteAccount *theAccount, QWidget *parent, const char *name): YahooEditAccountBase(parent), EditAccountWidget(theAccount)
{
kdDebug(14180) << "YahooEditAccount::YahooEditAccount(<protocol>, <theAccount>, <parent>, " << name << ")";
theProtocol = protocol;
if(m_account)
{ mScreenName->setText(m_account->accountId());
if(m_account->rememberPassword())
mPassword->setText(m_account->getPassword());
mAutoConnect->setChecked(m_account->autoLogin());
mRememberPassword->setChecked(true);
}
show();
}
bool YahooEditAccount::validateData()
{
kdDebug(14180) << "YahooEditAccount::validateData()";
if(mScreenName->text() == "")
{ KMessageBox::sorry(this, i18n("<qt>You must enter a valid screen name</qt>"), i18n("Yahoo"));
return false;
}
if(mPassword->text() == "")
{ KMessageBox::sorry(this, i18n("<qt>You must enter a valid password</qt>"), i18n("Yahoo"));
return false;
}
return true;
}
KopeteAccount *YahooEditAccount::apply()
{
kdDebug(14180) << "YahooEditAccount::apply()";
if(!m_account)
m_account = new YahooAccount(theProtocol, mScreenName->text());
else
m_account->setAccountId(mScreenName->text());
m_account->setAutoLogin(mAutoConnect->isChecked());
if(mRememberPassword->isChecked())
m_account->setPassword(mPassword->text());
return m_account;
}
#include "yahooeditaccount.moc"
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*
** Copyright 2014-2016 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#include "com/centreon/broker/bam/bool_binary_operator.hh"
using namespace com::centreon::broker::bam;
/**
* Default constructor.
*/
bool_binary_operator::bool_binary_operator()
: _left_hard(0.0),
_left_soft(0.0),
_right_hard(0.0),
_right_soft(0.0),
_state_known(false),
_in_downtime(false) {}
/**
* Copy constructor.
*
* @param[in] right Object to copy.
*/
bool_binary_operator::bool_binary_operator(
bool_binary_operator const& right)
: bool_value(right) {
_internal_copy(right);
}
/**
* Destructor.
*/
bool_binary_operator::~bool_binary_operator() {}
/**
* Assignment operator.
*
* @param[in] right Object to copy.
*
* @return This object.
*/
bool_binary_operator& bool_binary_operator::operator=(
bool_binary_operator const& right) {
if (this != &right) {
bool_value::operator=(right);
_internal_copy(right);
}
return (*this);
}
/**
* Notification of child update.
*
* @param[in] child Child that got updated.
* @param[out] visitor Visitor.
*
* @return True if the values of this object were modified.
*/
bool bool_binary_operator::child_has_update(
computable* child,
io::stream* visitor) {
(void)visitor;
bool retval(true);
// Check operation members values.
if (child) {
if (child == _left.data()) {
double value_hard(_left->value_hard());
double value_soft(_left->value_soft());
if ((_left_hard != value_hard) || (_left_soft != value_soft)) {
_left_hard = value_hard;
_left_soft = value_soft;
retval = true;
}
}
else if (child == _right.data()) {
double value_hard(_right->value_hard());
double value_soft(_right->value_soft());
if ((_right_hard != value_hard) || (_right_soft == value_soft)) {
_right_hard = value_hard;
_right_soft = value_soft;
retval = true;
}
}
}
// Check known flag.
bool known(state_known());
if (_state_known != known) {
_state_known = known;
retval = true;
}
// Check downtime flag.
bool in_dt(in_downtime());
if (_in_downtime != in_dt) {
_in_downtime = in_dt;
retval = true;
}
return (retval);
}
/**
* Set left member.
*
* @param[in] left Left member of the boolean operator.
*/
void bool_binary_operator::set_left(
misc::shared_ptr<bool_value> const& left) {
_left = left;
return ;
}
/**
* Set right member.
*
* @param[in] right Right member of the boolean operator.
*/
void bool_binary_operator::set_right(
misc::shared_ptr<bool_value> const& right) {
_right = right;
return ;
}
/**
* Copy internal data members.
*
* @param[in] right Object to copy.
*/
void bool_binary_operator::_internal_copy(
bool_binary_operator const& right) {
_left = right._left;
_left_hard = right._left_hard;
_left_soft = right._left_soft;
_right = right._right;
_right_hard = right._right_hard;
_right_soft = right._right_soft;
_state_known = right._state_known;
_in_downtime = right._in_downtime;
return ;
}
/**
* Get if the state is known, i.e has been computed at least once.
*
* @return True if the state is known.
*/
bool bool_binary_operator::state_known() const {
return (!_left.isNull()
&& !_right.isNull()
&& _left->state_known()
&& _right->state_known());
}
/**
* Is this expression in downtime?
*
* @return True if this expression is in downtime.
*/
bool bool_binary_operator::in_downtime() const {
return ((!_left.isNull() && _left->in_downtime())
|| (!_right.isNull() && _right->in_downtime()));
}
<commit_msg>BAM: properly initialize cache of bool_binary_operator.<commit_after>/*
** Copyright 2014-2016 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#include "com/centreon/broker/bam/bool_binary_operator.hh"
using namespace com::centreon::broker::bam;
/**
* Default constructor.
*/
bool_binary_operator::bool_binary_operator()
: _left_hard(0.0),
_left_soft(0.0),
_right_hard(0.0),
_right_soft(0.0),
_state_known(false),
_in_downtime(false) {}
/**
* Copy constructor.
*
* @param[in] right Object to copy.
*/
bool_binary_operator::bool_binary_operator(
bool_binary_operator const& right)
: bool_value(right) {
_internal_copy(right);
}
/**
* Destructor.
*/
bool_binary_operator::~bool_binary_operator() {}
/**
* Assignment operator.
*
* @param[in] right Object to copy.
*
* @return This object.
*/
bool_binary_operator& bool_binary_operator::operator=(
bool_binary_operator const& right) {
if (this != &right) {
bool_value::operator=(right);
_internal_copy(right);
}
return (*this);
}
/**
* Notification of child update.
*
* @param[in] child Child that got updated.
* @param[out] visitor Visitor.
*
* @return True if the values of this object were modified.
*/
bool bool_binary_operator::child_has_update(
computable* child,
io::stream* visitor) {
(void)visitor;
bool retval(true);
// Check operation members values.
if (child) {
if (child == _left.data()) {
double value_hard(_left->value_hard());
double value_soft(_left->value_soft());
if ((_left_hard != value_hard) || (_left_soft != value_soft)) {
_left_hard = value_hard;
_left_soft = value_soft;
retval = true;
}
}
else if (child == _right.data()) {
double value_hard(_right->value_hard());
double value_soft(_right->value_soft());
if ((_right_hard != value_hard) || (_right_soft == value_soft)) {
_right_hard = value_hard;
_right_soft = value_soft;
retval = true;
}
}
}
// Check known flag.
bool known(state_known());
if (_state_known != known) {
_state_known = known;
retval = true;
}
// Check downtime flag.
bool in_dt(in_downtime());
if (_in_downtime != in_dt) {
_in_downtime = in_dt;
retval = true;
}
return (retval);
}
/**
* Set left member.
*
* @param[in] left Left member of the boolean operator.
*/
void bool_binary_operator::set_left(
misc::shared_ptr<bool_value> const& left) {
_left = left;
_left_hard = _left->value_hard();
_left_soft = _left->value_soft();
_state_known = state_known();
_in_downtime = in_downtime();
return ;
}
/**
* Set right member.
*
* @param[in] right Right member of the boolean operator.
*/
void bool_binary_operator::set_right(
misc::shared_ptr<bool_value> const& right) {
_right = right;
_right_hard = _right->value_hard();
_right_soft = _right->value_soft();
_state_known = state_known();
_in_downtime = in_downtime();
return ;
}
/**
* Copy internal data members.
*
* @param[in] right Object to copy.
*/
void bool_binary_operator::_internal_copy(
bool_binary_operator const& right) {
_left = right._left;
_left_hard = right._left_hard;
_left_soft = right._left_soft;
_right = right._right;
_right_hard = right._right_hard;
_right_soft = right._right_soft;
_state_known = right._state_known;
_in_downtime = right._in_downtime;
return ;
}
/**
* Get if the state is known, i.e has been computed at least once.
*
* @return True if the state is known.
*/
bool bool_binary_operator::state_known() const {
return (!_left.isNull()
&& !_right.isNull()
&& _left->state_known()
&& _right->state_known());
}
/**
* Is this expression in downtime?
*
* @return True if this expression is in downtime.
*/
bool bool_binary_operator::in_downtime() const {
return ((!_left.isNull() && _left->in_downtime())
|| (!_right.isNull() && _right->in_downtime()));
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
*/
#include "HelpOperationFactory.hpp"
#include "RpcOperationFactory_p.hpp"
// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"
#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "TelegramServerUser.hpp"
#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"
#include "MTProto/StreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"
#include <QLoggingCategory>
namespace Telegram {
namespace Server {
// Generated process methods
bool HelpRpcOperation::processGetAppChangelog(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetAppChangelog);
context.inputStream() >> m_getAppChangelog;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetAppUpdate(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetAppUpdate);
context.inputStream() >> m_getAppUpdate;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetCdnConfig(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetCdnConfig);
context.inputStream() >> m_getCdnConfig;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetConfig(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetConfig);
context.inputStream() >> m_getConfig;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetInviteText(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetInviteText);
context.inputStream() >> m_getInviteText;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetNearestDc(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetNearestDc);
context.inputStream() >> m_getNearestDc;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetRecentMeUrls(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetRecentMeUrls);
context.inputStream() >> m_getRecentMeUrls;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetSupport(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetSupport);
context.inputStream() >> m_getSupport;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetTermsOfService(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetTermsOfService);
context.inputStream() >> m_getTermsOfService;
return !context.inputStream().error();
}
bool HelpRpcOperation::processSaveAppLog(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runSaveAppLog);
context.inputStream() >> m_saveAppLog;
return !context.inputStream().error();
}
bool HelpRpcOperation::processSetBotUpdatesStatus(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runSetBotUpdatesStatus);
context.inputStream() >> m_setBotUpdatesStatus;
return !context.inputStream().error();
}
// End of generated process methods
// Generated run methods
void HelpRpcOperation::runGetAppChangelog()
{
// TLFunctions::TLHelpGetAppChangelog &arguments = m_getAppChangelog;
if (processNotImplementedMethod(TLValue::HelpGetAppChangelog)) {
return;
}
TLUpdates result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetAppUpdate()
{
if (processNotImplementedMethod(TLValue::HelpGetAppUpdate)) {
return;
}
TLHelpAppUpdate result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetCdnConfig()
{
if (processNotImplementedMethod(TLValue::HelpGetCdnConfig)) {
return;
}
TLCdnConfig result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetConfig()
{
const DcConfiguration dcConfig = api()->serverConfiguration();
TLConfig result;
result.flags = TLConfig::PhonecallsEnabled;
result.testMode = true;
result.thisDc = api()->dcId();
// TODO: fill other fields of result
// manually copy fields from all DcOption's to TLDcOption's
for (const DcOption &dcOption : dcConfig.dcOptions) {
TLDcOption tlDcOption;
tlDcOption.id = dcOption.id;
tlDcOption.ipAddress = dcOption.address;
tlDcOption.port = dcOption.port;
tlDcOption.flags = dcOption.flags;
result.dcOptions.append(std::move(tlDcOption));
}
sendRpcReply(result);
}
void HelpRpcOperation::runGetInviteText()
{
if (processNotImplementedMethod(TLValue::HelpGetInviteText)) {
return;
}
TLHelpInviteText result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetNearestDc()
{
TLNearestDc result;
result.thisDc = api()->dcId();
result.nearestDc = 1;
// ISO 3166-1 alpha-2
result.country = QStringLiteral("AQ");
sendRpcReply(result);
}
void HelpRpcOperation::runGetRecentMeUrls()
{
// TLFunctions::TLHelpGetRecentMeUrls &arguments = m_getRecentMeUrls;
if (processNotImplementedMethod(TLValue::HelpGetRecentMeUrls)) {
return;
}
TLHelpRecentMeUrls result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetSupport()
{
if (processNotImplementedMethod(TLValue::HelpGetSupport)) {
return;
}
TLHelpSupport result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetTermsOfService()
{
if (processNotImplementedMethod(TLValue::HelpGetTermsOfService)) {
return;
}
TLHelpTermsOfService result;
sendRpcReply(result);
}
void HelpRpcOperation::runSaveAppLog()
{
// TLFunctions::TLHelpSaveAppLog &arguments = m_saveAppLog;
if (processNotImplementedMethod(TLValue::HelpSaveAppLog)) {
return;
}
bool result;
sendRpcReply(result);
}
void HelpRpcOperation::runSetBotUpdatesStatus()
{
// TLFunctions::TLHelpSetBotUpdatesStatus &arguments = m_setBotUpdatesStatus;
if (processNotImplementedMethod(TLValue::HelpSetBotUpdatesStatus)) {
return;
}
bool result;
sendRpcReply(result);
}
// End of generated run methods
void HelpRpcOperation::setRunMethod(HelpRpcOperation::RunMethod method)
{
m_runMethod = method;
}
HelpRpcOperation::ProcessingMethod HelpRpcOperation::getMethodForRpcFunction(TLValue function)
{
switch (function) {
// Generated methodForRpcFunction cases
case TLValue::HelpGetAppChangelog:
return &HelpRpcOperation::processGetAppChangelog;
case TLValue::HelpGetAppUpdate:
return &HelpRpcOperation::processGetAppUpdate;
case TLValue::HelpGetCdnConfig:
return &HelpRpcOperation::processGetCdnConfig;
case TLValue::HelpGetConfig:
return &HelpRpcOperation::processGetConfig;
case TLValue::HelpGetInviteText:
return &HelpRpcOperation::processGetInviteText;
case TLValue::HelpGetNearestDc:
return &HelpRpcOperation::processGetNearestDc;
case TLValue::HelpGetRecentMeUrls:
return &HelpRpcOperation::processGetRecentMeUrls;
case TLValue::HelpGetSupport:
return &HelpRpcOperation::processGetSupport;
case TLValue::HelpGetTermsOfService:
return &HelpRpcOperation::processGetTermsOfService;
case TLValue::HelpSaveAppLog:
return &HelpRpcOperation::processSaveAppLog;
case TLValue::HelpSetBotUpdatesStatus:
return &HelpRpcOperation::processSetBotUpdatesStatus;
// End of generated methodForRpcFunction cases
default:
return nullptr;
}
}
RpcOperation *HelpOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
return processRpcCallImpl<HelpRpcOperation>(layer, context);
}
} // Server namespace
} // Telegram namespace
<commit_msg>Server: Add 'date' to help.getConfig result<commit_after>/*
Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
*/
#include "HelpOperationFactory.hpp"
#include "RpcOperationFactory_p.hpp"
// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"
#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "TelegramServerUser.hpp"
#include "ApiUtils.hpp"
#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"
#include "MTProto/StreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"
#include <QLoggingCategory>
namespace Telegram {
namespace Server {
// Generated process methods
bool HelpRpcOperation::processGetAppChangelog(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetAppChangelog);
context.inputStream() >> m_getAppChangelog;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetAppUpdate(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetAppUpdate);
context.inputStream() >> m_getAppUpdate;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetCdnConfig(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetCdnConfig);
context.inputStream() >> m_getCdnConfig;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetConfig(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetConfig);
context.inputStream() >> m_getConfig;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetInviteText(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetInviteText);
context.inputStream() >> m_getInviteText;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetNearestDc(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetNearestDc);
context.inputStream() >> m_getNearestDc;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetRecentMeUrls(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetRecentMeUrls);
context.inputStream() >> m_getRecentMeUrls;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetSupport(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetSupport);
context.inputStream() >> m_getSupport;
return !context.inputStream().error();
}
bool HelpRpcOperation::processGetTermsOfService(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runGetTermsOfService);
context.inputStream() >> m_getTermsOfService;
return !context.inputStream().error();
}
bool HelpRpcOperation::processSaveAppLog(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runSaveAppLog);
context.inputStream() >> m_saveAppLog;
return !context.inputStream().error();
}
bool HelpRpcOperation::processSetBotUpdatesStatus(RpcProcessingContext &context)
{
setRunMethod(&HelpRpcOperation::runSetBotUpdatesStatus);
context.inputStream() >> m_setBotUpdatesStatus;
return !context.inputStream().error();
}
// End of generated process methods
// Generated run methods
void HelpRpcOperation::runGetAppChangelog()
{
// TLFunctions::TLHelpGetAppChangelog &arguments = m_getAppChangelog;
if (processNotImplementedMethod(TLValue::HelpGetAppChangelog)) {
return;
}
TLUpdates result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetAppUpdate()
{
if (processNotImplementedMethod(TLValue::HelpGetAppUpdate)) {
return;
}
TLHelpAppUpdate result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetCdnConfig()
{
if (processNotImplementedMethod(TLValue::HelpGetCdnConfig)) {
return;
}
TLCdnConfig result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetConfig()
{
const DcConfiguration dcConfig = api()->serverConfiguration();
TLConfig result;
result.flags = TLConfig::PhonecallsEnabled;
result.date = Telegram::Utils::getCurrentTime();
result.testMode = true;
result.thisDc = api()->dcId();
// TODO: fill other fields of result
// manually copy fields from all DcOption's to TLDcOption's
for (const DcOption &dcOption : dcConfig.dcOptions) {
TLDcOption tlDcOption;
tlDcOption.id = dcOption.id;
tlDcOption.ipAddress = dcOption.address;
tlDcOption.port = dcOption.port;
tlDcOption.flags = dcOption.flags;
result.dcOptions.append(std::move(tlDcOption));
}
sendRpcReply(result);
}
void HelpRpcOperation::runGetInviteText()
{
if (processNotImplementedMethod(TLValue::HelpGetInviteText)) {
return;
}
TLHelpInviteText result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetNearestDc()
{
TLNearestDc result;
result.thisDc = api()->dcId();
result.nearestDc = 1;
// ISO 3166-1 alpha-2
result.country = QStringLiteral("AQ");
sendRpcReply(result);
}
void HelpRpcOperation::runGetRecentMeUrls()
{
// TLFunctions::TLHelpGetRecentMeUrls &arguments = m_getRecentMeUrls;
if (processNotImplementedMethod(TLValue::HelpGetRecentMeUrls)) {
return;
}
TLHelpRecentMeUrls result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetSupport()
{
if (processNotImplementedMethod(TLValue::HelpGetSupport)) {
return;
}
TLHelpSupport result;
sendRpcReply(result);
}
void HelpRpcOperation::runGetTermsOfService()
{
if (processNotImplementedMethod(TLValue::HelpGetTermsOfService)) {
return;
}
TLHelpTermsOfService result;
sendRpcReply(result);
}
void HelpRpcOperation::runSaveAppLog()
{
// TLFunctions::TLHelpSaveAppLog &arguments = m_saveAppLog;
if (processNotImplementedMethod(TLValue::HelpSaveAppLog)) {
return;
}
bool result;
sendRpcReply(result);
}
void HelpRpcOperation::runSetBotUpdatesStatus()
{
// TLFunctions::TLHelpSetBotUpdatesStatus &arguments = m_setBotUpdatesStatus;
if (processNotImplementedMethod(TLValue::HelpSetBotUpdatesStatus)) {
return;
}
bool result;
sendRpcReply(result);
}
// End of generated run methods
void HelpRpcOperation::setRunMethod(HelpRpcOperation::RunMethod method)
{
m_runMethod = method;
}
HelpRpcOperation::ProcessingMethod HelpRpcOperation::getMethodForRpcFunction(TLValue function)
{
switch (function) {
// Generated methodForRpcFunction cases
case TLValue::HelpGetAppChangelog:
return &HelpRpcOperation::processGetAppChangelog;
case TLValue::HelpGetAppUpdate:
return &HelpRpcOperation::processGetAppUpdate;
case TLValue::HelpGetCdnConfig:
return &HelpRpcOperation::processGetCdnConfig;
case TLValue::HelpGetConfig:
return &HelpRpcOperation::processGetConfig;
case TLValue::HelpGetInviteText:
return &HelpRpcOperation::processGetInviteText;
case TLValue::HelpGetNearestDc:
return &HelpRpcOperation::processGetNearestDc;
case TLValue::HelpGetRecentMeUrls:
return &HelpRpcOperation::processGetRecentMeUrls;
case TLValue::HelpGetSupport:
return &HelpRpcOperation::processGetSupport;
case TLValue::HelpGetTermsOfService:
return &HelpRpcOperation::processGetTermsOfService;
case TLValue::HelpSaveAppLog:
return &HelpRpcOperation::processSaveAppLog;
case TLValue::HelpSetBotUpdatesStatus:
return &HelpRpcOperation::processSetBotUpdatesStatus;
// End of generated methodForRpcFunction cases
default:
return nullptr;
}
}
RpcOperation *HelpOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
return processRpcCallImpl<HelpRpcOperation>(layer, context);
}
} // Server namespace
} // Telegram namespace
<|endoftext|> |
<commit_before>#include "MyModel.h"
#include "DNest4/code/DNest4.h"
#include "Data.h"
#include <cmath>
using namespace std;
using namespace DNest4;
MyModel::MyModel()
:objects(3, 10, false, MyConditionalPrior(-10., 10., 1E-3, 1E3))
,mu(Data::get_instance().get_t().size())
{
}
void MyModel::from_prior(RNG& rng)
{
objects.from_prior(rng);
objects.consolidate_diff();
sigma = exp(log(1E-3) + log(1E6)*rng.rand());
calculate_mu();
}
void MyModel::calculate_mu()
{
// Get the times from the data
const vector<double>& t = Data::get_instance().get_t();
// Update or from scratch?
bool update = false;//(objects.get_added().size() < objects.get_components().size());
// Get the components
const vector< vector<double> >& components = (update)?(objects.get_added()):
(objects.get_components());
// Zero the signal
if(!update)
mu.assign(mu.size(), 0.);
double T, A, phi;
for(size_t j=0; j<components.size(); j++)
{
T = exp(components[j][0]);
A = components[j][1];
phi = components[j][2];
for(size_t i=0; i<t.size(); i++)
mu[i] += A*sin(2.*M_PI*t[i]/T + phi);
}
}
double MyModel::perturb(RNG& rng)
{
double logH = 0.;
if(rng.rand() <= 0.75)
{
logH += objects.perturb(rng);
objects.consolidate_diff();
calculate_mu();
}
else
{
sigma = log(sigma);
sigma += log(1E6)*rng.randh();
sigma = mod(sigma - log(1E-3), log(1E6)) + log(1E-3);
sigma = exp(sigma);
}
return logH;
}
double MyModel::log_likelihood() const
{
// Get the data
const vector<double>& y = Data::get_instance().get_y();
double logL = 0.;
double var = sigma*sigma;
for(size_t i=0; i<y.size(); i++)
logL += -0.5*log(2.*M_PI*var) - 0.5*pow(y[i] - mu[i], 2)/var;
return logL;
}
void MyModel::print(std::ostream& out) const
{
for(size_t i=0; i<mu.size(); i++)
out<<mu[i]<<' ';
out<<sigma<<' ';
objects.print(out); out<<' ';
}
string MyModel::description() const
{
return string("objects, sigma");
}
<commit_msg>Faster by using partial updates<commit_after>#include "MyModel.h"
#include "DNest4/code/DNest4.h"
#include "Data.h"
#include <cmath>
using namespace std;
using namespace DNest4;
MyModel::MyModel()
:objects(3, 10, false, MyConditionalPrior(-10., 10., 1E-3, 1E3))
,mu(Data::get_instance().get_t().size())
{
}
void MyModel::from_prior(RNG& rng)
{
objects.from_prior(rng);
sigma = exp(log(1E-3) + log(1E6)*rng.rand());
calculate_mu();
}
void MyModel::calculate_mu()
{
// Get the times from the data
const vector<double>& t = Data::get_instance().get_t();
// Update or from scratch?
bool update = (objects.get_removed().size() == 0);
// Get the components
const vector< vector<double> >& components = (update)?(objects.get_added()):
(objects.get_components());
// Zero the signal
if(!update)
mu.assign(mu.size(), 0.0);
double T, A, phi;
for(size_t j=0; j<components.size(); j++)
{
T = exp(components[j][0]);
A = components[j][1];
phi = components[j][2];
for(size_t i=0; i<t.size(); i++)
mu[i] += A*sin(2.*M_PI*t[i]/T + phi);
}
}
double MyModel::perturb(RNG& rng)
{
double logH = 0.;
if(rng.rand() <= 0.75)
{
logH += objects.perturb(rng);
calculate_mu();
}
else
{
sigma = log(sigma);
sigma += log(1E6)*rng.randh();
sigma = mod(sigma - log(1E-3), log(1E6)) + log(1E-3);
sigma = exp(sigma);
}
return logH;
}
double MyModel::log_likelihood() const
{
// Get the data
const vector<double>& y = Data::get_instance().get_y();
double logL = 0.;
double var = sigma*sigma;
for(size_t i=0; i<y.size(); i++)
logL += -0.5*log(2.*M_PI*var) - 0.5*pow(y[i] - mu[i], 2)/var;
return logL;
}
void MyModel::print(std::ostream& out) const
{
for(size_t i=0; i<mu.size(); i++)
out<<mu[i]<<' ';
out<<sigma<<' ';
objects.print(out); out<<' ';
}
string MyModel::description() const
{
return string("objects, sigma");
}
<|endoftext|> |
<commit_before>#include "throttle.hpp"
#include <unistd.h>
#include <fcntl.h>
/**
* Read a configuration file.
*
* This function is guaranteed to read in all syntactically correct files, but
* might also accept others.
*/
Conf::Conf(const char *config_fn) {
// open the file
std::ifstream conf_file(config_fn);
if (!conf_file)
throw std::runtime_error(std::string("Couldn't open config file '") + config_fn + '\'');
// read every line and put it in the map
char line[LINE_LENGTH];
std::string name;
// parse: first comes the name of the command
while (conf_file >> name) {
// if line starts with '#', ignore it
if (name[0] == '#') {
conf_file.ignore(LINE_LENGTH, '\n');
continue;
}
conf_file.ignore(LINE_LENGTH, '=');
conf_file.ignore(LINE_LENGTH, ' ');
conf_file.getline(line, LINE_LENGTH);
DEBUG_PRINT("[Conf] " << name << " = " << line);
// write into map
attributes[name] = std::string(line);
}
}
/**
* Translation table for a command queue.
*/
const std::map<std::string, CommQueue::Command> CommQueue::translate = {
{"max", CommQueue::SET_MAX},
{"min", CommQueue::SET_MIN},
{"freq", CommQueue::SET_FREQ},
{"reset", CommQueue::RESET}
};
/**
* Construct a command queue.
*
* We want to know the parent, where we can write changes to,
* and which pipe to listen on.
*/
CommQueue::CommQueue(Throttle *parent, const char *pipe_fn) : Throt(parent)
{
// Open the command pipe
if ((comm_file = open(pipe_fn, O_RDONLY | O_NONBLOCK)) < 0)
throw std::runtime_error(std::string("Couldn't open command pipe '") + pipe_fn + '\'');
}
/**
* Destruct the command queue.
*
* We have to close the file manually here.
*/
CommQueue::~CommQueue()
{
close(comm_file);
}
/**
* Look for updates from the command pipe and process them.
*/
void CommQueue::update()
{
char buf[LINE_LENGTH];
ssize_t ret;
do {
ret = read(comm_file, buf, LINE_LENGTH-1);
if (ret > 0)
processCommand(std::string(buf, ret));
} while (ret > 0);
// This should be because there's nothing more to read
if (ret != 0 && errno != EAGAIN)
throw std::runtime_error("Read error while checking command pipe");
}
/**
* Process a command coming through the pipe.
*/
void CommQueue::processCommand(const std::string &comm)
{
std::istringstream stream(comm);
std::string command;
stream >> command;
int value;
switch (translate.find(command)->second) {
case DEFAULT: // we land here if "command" is not found
DEBUG_PRINT("[CommQueue] Ignored unknown command: " << command);
break;
case SET_MIN:
stream >> value;
Throt->setMinTemp(value);
DEBUG_PRINT("[CommQueue] Set minimum temperature to " << value);
break;
case SET_MAX:
stream >> value;
Throt->setMaxTemp(value);
DEBUG_PRINT("[CommQueue] Set maximum temperature to " << value);
break;
case SET_FREQ:
stream >> value;
Throt->setOverrideFreq(value);
DEBUG_PRINT("[CommQueue] Set frequency to " << value);
break;
case RESET:
Throt->setOverrideFreq(0);
DEBUG_PRINT("[CommQueue] Reset mechanism");
break;
}
}
<commit_msg>Simplification in constructor<commit_after>#include "throttle.hpp"
#include <unistd.h>
#include <fcntl.h>
/**
* Read a configuration file.
*
* This function is guaranteed to read in all syntactically correct files, but
* might also accept others.
*/
Conf::Conf(const char *config_fn) {
// open the file
std::ifstream conf_file(config_fn);
if (!conf_file)
throw std::runtime_error(std::string("Couldn't open config file '") + config_fn + '\'');
// read every line and put it in the map
char line[LINE_LENGTH];
std::string name;
// parse: first comes the name of the command
while (conf_file >> name) {
// if line starts with '#', ignore it
if (name[0] == '#') {
conf_file.ignore(LINE_LENGTH, '\n');
continue;
}
conf_file.ignore(LINE_LENGTH, '=');
conf_file.ignore(LINE_LENGTH, ' ');
conf_file.getline(line, LINE_LENGTH);
DEBUG_PRINT("[Conf] " << name << " = " << line);
// write into map
attributes[name] = std::string(line);
}
}
/**
* Translation table for a command queue.
*/
const std::map<std::string, CommQueue::Command> CommQueue::translate = {
{"max", CommQueue::SET_MAX},
{"min", CommQueue::SET_MIN},
{"freq", CommQueue::SET_FREQ},
{"reset", CommQueue::RESET}
};
/**
* Construct a command queue.
*
* We want to know the parent, where we can write changes to,
* and which pipe to listen on.
*/
CommQueue::CommQueue(Throttle *parent, const char *pipe_fn) : Throt(parent)
{
// Open the command pipe
comm_file = open(pipe_fn, O_RDONLY | O_NONBLOCK);
if (comm_file < 0)
throw std::runtime_error(std::string("Couldn't open command pipe '") + pipe_fn + '\'');
}
/**
* Destruct the command queue.
*
* We have to close the file manually here.
*/
CommQueue::~CommQueue()
{
close(comm_file);
}
/**
* Look for updates from the command pipe and process them.
*/
void CommQueue::update()
{
char buf[LINE_LENGTH];
ssize_t ret;
do {
ret = read(comm_file, buf, LINE_LENGTH-1);
if (ret > 0)
processCommand(std::string(buf, ret));
} while (ret > 0);
// This should be because there's nothing more to read
if (ret != 0 && errno != EAGAIN)
throw std::runtime_error("Read error while checking command pipe");
}
/**
* Process a command coming through the pipe.
*/
void CommQueue::processCommand(const std::string &comm)
{
std::istringstream stream(comm);
std::string command;
stream >> command;
int value;
switch (translate.find(command)->second) {
case DEFAULT: // we land here if "command" is not found
DEBUG_PRINT("[CommQueue] Ignored unknown command: " << command);
break;
case SET_MIN:
stream >> value;
Throt->setMinTemp(value);
DEBUG_PRINT("[CommQueue] Set minimum temperature to " << value);
break;
case SET_MAX:
stream >> value;
Throt->setMaxTemp(value);
DEBUG_PRINT("[CommQueue] Set maximum temperature to " << value);
break;
case SET_FREQ:
stream >> value;
Throt->setOverrideFreq(value);
DEBUG_PRINT("[CommQueue] Set frequency to " << value);
break;
case RESET:
Throt->setOverrideFreq(0);
DEBUG_PRINT("[CommQueue] Reset mechanism");
break;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include "sal/precppunit.hxx"
// autogenerated file with codegen.pl
#include "cppunit/TestAssert.h"
#include "cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>
#include <basegfx/curve/b2dbeziertools.hxx>
#include <basegfx/range/b2dpolyrange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygoncutter.hxx>
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <boost/bind.hpp>
using namespace ::basegfx;
namespace basegfx2d
{
class genericclipper : public CppUnit::TestFixture
{
private:
B2DPolygon aSelfIntersecting;
B2DPolygon aShiftedRectangle;
public:
// initialise your test code values here.
void setUp()
{
aSelfIntersecting.append(B2DPoint(0, 0));
aSelfIntersecting.append(B2DPoint(0, 100));
aSelfIntersecting.append(B2DPoint(75, 100));
aSelfIntersecting.append(B2DPoint(75, 50));
aSelfIntersecting.append(B2DPoint(25, 50));
aSelfIntersecting.append(B2DPoint(25, 150));
aSelfIntersecting.append(B2DPoint(100,150));
aSelfIntersecting.append(B2DPoint(100,0));
aSelfIntersecting.setClosed(true);
aShiftedRectangle = tools::createPolygonFromRect(
B2DRange(0,90,20,150));
}
void tearDown()
{}
void validate(const char* pName,
const char* pValidSvgD,
B2DPolyPolygon (*pFunc)(const B2DPolyPolygon&, const B2DPolyPolygon&))
{
const B2DPolyPolygon aSelfIntersect(
tools::prepareForPolygonOperation(aSelfIntersecting));
const B2DPolyPolygon aRect(
tools::prepareForPolygonOperation(aShiftedRectangle));
#if OSL_DEBUG_LEVEL > 2
fprintf(stderr, "%s input LHS - svg:d=\"%s\"\n",
pName, rtl::OUStringToOString(
basegfx::tools::exportToSvgD(
aSelfIntersect),
RTL_TEXTENCODING_UTF8).getStr() );
fprintf(stderr, "%s input RHS - svg:d=\"%s\"\n",
pName, rtl::OUStringToOString(
basegfx::tools::exportToSvgD(
aRect),
RTL_TEXTENCODING_UTF8).getStr() );
#endif
const B2DPolyPolygon aRes=
pFunc(aSelfIntersect, aRect);
#if OSL_DEBUG_LEVEL > 2
fprintf(stderr, "%s - svg:d=\"%s\"\n",
pName, rtl::OUStringToOString(
basegfx::tools::exportToSvgD(aRes),
RTL_TEXTENCODING_UTF8).getStr() );
#endif
rtl::OUString aValid=rtl::OUString::createFromAscii(pValidSvgD);
CPPUNIT_ASSERT_MESSAGE(pName,
basegfx::tools::exportToSvgD(aRes) == aValid);
}
void validateOr()
{
const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm75 100v-50h-50v50z";
validate("validateOr", pValid, &tools::solvePolygonOperationOr);
}
void validateXor()
{
const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm0 100h20v-10h-20zm75 0v-50h-50v50z";
validate("validateXor", pValid, &tools::solvePolygonOperationXor);
}
void validateAnd()
{
const char* pValid="m0 100v-10h20v10z";
validate("validateAnd", pValid, &tools::solvePolygonOperationAnd);
}
void validateDiff()
{
const char* pValid="m0 90v-90h100v150h-75v-50h-5v-10zm75 10v-50h-50v50z";
validate("validateDiff", pValid, &tools::solvePolygonOperationDiff);
}
void checkCrossoverSolver()
{
B2DPolyPolygon aPoly;
tools::importFromSvgD(
aPoly,
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"m0 0 v 5 h 3 h 1 h 1 h 1 v -2 v -3 z"
"m3 7 v -2 h 1 h 1 h 1 v -2 h 1 v 3 z")));
tools::solveCrossovers(aPoly);
}
// Change the following lines only, if you add, remove or rename
// member functions of the current class,
// because these macros are need by auto register mechanism.
CPPUNIT_TEST_SUITE(genericclipper);
CPPUNIT_TEST(validateOr);
CPPUNIT_TEST(validateXor);
CPPUNIT_TEST(validateAnd);
CPPUNIT_TEST(validateDiff);
CPPUNIT_TEST(checkCrossoverSolver);
CPPUNIT_TEST_SUITE_END();
};
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION(basegfx2d::genericclipper);
} // namespace basegfx2d
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Add more unit test coverage for generic clipper<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include "sal/precppunit.hxx"
// autogenerated file with codegen.pl
#include "cppunit/TestAssert.h"
#include "cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>
#include <basegfx/curve/b2dbeziertools.hxx>
#include <basegfx/range/b2dpolyrange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygoncutter.hxx>
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <boost/bind.hpp>
using namespace ::basegfx;
namespace basegfx2d
{
class genericclipper : public CppUnit::TestFixture
{
private:
B2DPolygon aSelfIntersecting;
B2DPolygon aShiftedRectangle;
public:
// initialise your test code values here.
void setUp()
{
aSelfIntersecting.append(B2DPoint(0, 0));
aSelfIntersecting.append(B2DPoint(0, 100));
aSelfIntersecting.append(B2DPoint(75, 100));
aSelfIntersecting.append(B2DPoint(75, 50));
aSelfIntersecting.append(B2DPoint(25, 50));
aSelfIntersecting.append(B2DPoint(25, 150));
aSelfIntersecting.append(B2DPoint(100,150));
aSelfIntersecting.append(B2DPoint(100,0));
aSelfIntersecting.setClosed(true);
aShiftedRectangle = tools::createPolygonFromRect(
B2DRange(0,90,20,150));
}
void tearDown()
{}
void validate(const char* pName,
const char* pValidSvgD,
B2DPolyPolygon (*pFunc)(const B2DPolyPolygon&, const B2DPolyPolygon&))
{
const B2DPolyPolygon aSelfIntersect(
tools::prepareForPolygonOperation(aSelfIntersecting));
const B2DPolyPolygon aRect(
tools::prepareForPolygonOperation(aShiftedRectangle));
#if OSL_DEBUG_LEVEL > 2
fprintf(stderr, "%s input LHS - svg:d=\"%s\"\n",
pName, rtl::OUStringToOString(
basegfx::tools::exportToSvgD(
aSelfIntersect),
RTL_TEXTENCODING_UTF8).getStr() );
fprintf(stderr, "%s input RHS - svg:d=\"%s\"\n",
pName, rtl::OUStringToOString(
basegfx::tools::exportToSvgD(
aRect),
RTL_TEXTENCODING_UTF8).getStr() );
#endif
const B2DPolyPolygon aRes=
pFunc(aSelfIntersect, aRect);
#if OSL_DEBUG_LEVEL > 2
fprintf(stderr, "%s - svg:d=\"%s\"\n",
pName, rtl::OUStringToOString(
basegfx::tools::exportToSvgD(aRes),
RTL_TEXTENCODING_UTF8).getStr() );
#endif
rtl::OUString aValid=rtl::OUString::createFromAscii(pValidSvgD);
CPPUNIT_ASSERT_MESSAGE(pName,
basegfx::tools::exportToSvgD(aRes) == aValid);
}
void validateOr()
{
const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm75 100v-50h-50v50z";
validate("validateOr", pValid, &tools::solvePolygonOperationOr);
}
void validateXor()
{
const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm0 100h20v-10h-20zm75 0v-50h-50v50z";
validate("validateXor", pValid, &tools::solvePolygonOperationXor);
}
void validateAnd()
{
const char* pValid="m0 100v-10h20v10z";
validate("validateAnd", pValid, &tools::solvePolygonOperationAnd);
}
void validateDiff()
{
const char* pValid="m0 90v-90h100v150h-75v-50h-5v-10zm75 10v-50h-50v50z";
validate("validateDiff", pValid, &tools::solvePolygonOperationDiff);
}
void validateCrossover(const char* pName,
const char* pInputSvgD,
const char* pValidSvgD)
{
rtl::OUString aInput=rtl::OUString::createFromAscii(pInputSvgD);
rtl::OUString aValid=rtl::OUString::createFromAscii(pValidSvgD);
B2DPolyPolygon aInputPoly, aValidPoly;
tools::importFromSvgD(aInputPoly, aInput);
tools::importFromSvgD(aValidPoly, aValid);
CPPUNIT_ASSERT_MESSAGE(
pName,
basegfx::tools::exportToSvgD(
tools::solveCrossovers(aInputPoly)) == aValid);
}
void checkCrossoverSolver()
{
// partially intersecting polygons, with a common subsection
validateCrossover(
"partially intersecting",
"m0 0 v 5 h 3 h 1 h 1 h 1 v -2 v -3 z"
"m3 7 v -2 h 1 h 1 h 1 v -2 h 1 v 3 z",
"m0 0v5h3 1 1 1v-2-3zm3 7v-2h1 1 1v-2h1v3z");
// first polygon is identical to subset of second polygon
validateCrossover(
"full subset",
"m0 0 v 5 h 3 h 1 h 1 v -5 z"
"m3 10 v -5 h 1 h 1 v -5 h -5 v 5 h 3 z",
"m0 0v5h3 1 1v-5zm3 10v-5zm1-5h1v-5h-5v5h3z");
// first polygon is identical to subset of second polygon, but
// oriented in the opposite direction
validateCrossover(
"full subset, opposite direction",
"m0 0 v 5 h 3 h 1 h 1 v -5 z"
"m3 10 v -5 h -1 h -1 h -1 v -5 h 5 v 5 h 2 z",
"m0 0v5h1 1 1-1-1-1v-5h5v5-5zm4 5h1 2l-4 5v-5z");
// first polygon is identical to subset of second polygon, and
// has a curve segment (triggers different code path)
validateCrossover(
"full subset, plus curves",
"m0 0 v 5 h 3 h 1 h 1 c 2 0 2 0 0 -5 z"
"m3 10 v -5 h 1 h 1 c 2 0 2 0 0 -5 h -5 v 5 h 3 z",
"m0 0v5h3 1 1c2 0 2 0 0-5zm3 10v-5zm1-5h1c2 0 2 0 0-5h-5v5h3z");
}
// Change the following lines only, if you add, remove or rename
// member functions of the current class,
// because these macros are need by auto register mechanism.
CPPUNIT_TEST_SUITE(genericclipper);
CPPUNIT_TEST(validateOr);
CPPUNIT_TEST(validateXor);
CPPUNIT_TEST(validateAnd);
CPPUNIT_TEST(validateDiff);
CPPUNIT_TEST(checkCrossoverSolver);
CPPUNIT_TEST_SUITE_END();
};
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION(basegfx2d::genericclipper);
} // namespace basegfx2d
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ximpgrp.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:10:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XIMPGROUP_HXX
#define _XIMPGROUP_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif
//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)
class SdXMLGroupShapeContext : public SdXMLShapeContext
{
// the shape group this group is working on
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxChilds;
protected:
void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
{ mxShapes = rNew; }
public:
TYPEINFO();
SdXMLGroupShapeContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLGroupShapeContext();
virtual SvXMLImportContext *CreateChildContext(
USHORT nPrefix, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
virtual void EndElement();
const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
{ return mxShapes; }
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
{ return mxShapes; }
};
#endif // _XIMPGROUP_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.162); FILE MERGED 2008/04/01 16:09:43 thb 1.7.162.3: #i85898# Stripping all external header guards 2008/04/01 13:04:46 thb 1.7.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:08 rt 1.7.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ximpgrp.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XIMPGROUP_HXX
#define _XIMPGROUP_HXX
#include <xmloff/xmlictxt.hxx>
#include "sdxmlimp_impl.hxx"
#include <xmloff/nmspmap.hxx>
#include <com/sun/star/drawing/XShapes.hpp>
#include <tools/rtti.hxx>
#include "ximpshap.hxx"
//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)
class SdXMLGroupShapeContext : public SdXMLShapeContext
{
// the shape group this group is working on
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxChilds;
protected:
void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
{ mxShapes = rNew; }
public:
TYPEINFO();
SdXMLGroupShapeContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLGroupShapeContext();
virtual SvXMLImportContext *CreateChildContext(
USHORT nPrefix, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
virtual void EndElement();
const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
{ return mxShapes; }
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
{ return mxShapes; }
};
#endif // _XIMPGROUP_HXX
<|endoftext|> |
<commit_before>#ifndef slic3r_Semver_hpp_
#define slic3r_Semver_hpp_
#include <string>
#include <cstring>
#include <ostream>
#include <boost/optional.hpp>
#include <boost/format.hpp>
#include "semver/semver.h"
namespace Slic3r {
class Semver
{
public:
struct Major { const int i; Major(int i) : i(i) {} };
struct Minor { const int i; Minor(int i) : i(i) {} };
struct Patch { const int i; Patch(int i) : i(i) {} };
Semver() : ver(semver_zero()) {}
Semver(int major, int minor, int patch,
boost::optional<std::string> metadata = boost::none,
boost::optional<std::string> prerelease = boost::none)
{
ver.major = major;
ver.minor = minor;
ver.patch = patch;
ver.metadata = metadata ? std::strcpy(ver.metadata, metadata->c_str()) : nullptr;
ver.prerelease = prerelease ? std::strcpy(ver.prerelease, prerelease->c_str()) : nullptr;
}
static boost::optional<Semver> parse(const std::string &str)
{
semver_t ver = semver_zero();
if (::semver_parse(str.c_str(), &ver) == 0) {
return Semver(ver);
} else {
return boost::none;
}
}
static const Semver zero() { return Semver(semver_zero()); }
static const Semver inf()
{
static semver_t ver = { std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), nullptr, nullptr };
return Semver(ver);
}
static const Semver invalid()
{
static semver_t ver = { -1, 0, 0, nullptr, nullptr };
return Semver(ver);
}
Semver(Semver &&other) : ver(other.ver) { other.ver = semver_zero(); }
Semver(const Semver &other) : ver(::semver_copy(&other.ver)) {}
Semver &operator=(Semver &&other)
{
::semver_free(&ver);
ver = other.ver;
other.ver = semver_zero();
return *this;
}
Semver &operator=(const Semver &other)
{
::semver_free(&ver);
ver = ::semver_copy(&other.ver);
return *this;
}
~Semver() { ::semver_free(&ver); }
// const accessors
int major() const { return ver.major; }
int minor() const { return ver.minor; }
int patch() const { return ver.patch; }
const char* prerelease() const { return ver.prerelease; }
const char* metadata() const { return ver.metadata; }
// Comparison
bool operator<(const Semver &b) const { return ::semver_compare(ver, b.ver) == -1; }
bool operator<=(const Semver &b) const { return ::semver_compare(ver, b.ver) <= 0; }
bool operator==(const Semver &b) const { return ::semver_compare(ver, b.ver) == 0; }
bool operator!=(const Semver &b) const { return ::semver_compare(ver, b.ver) != 0; }
bool operator>=(const Semver &b) const { return ::semver_compare(ver, b.ver) >= 0; }
bool operator>(const Semver &b) const { return ::semver_compare(ver, b.ver) == 1; }
// We're using '&' instead of the '~' operator here as '~' is unary-only:
// Satisfies patch if Major and minor are equal.
bool operator&(const Semver &b) const { return ::semver_satisfies_patch(ver, b.ver); }
bool operator^(const Semver &b) const { return ::semver_satisfies_caret(ver, b.ver); }
bool in_range(const Semver &low, const Semver &high) const { return low <= *this && *this <= high; }
// Conversion
std::string to_string() const {
auto res = (boost::format("%1%.%2%.%3%") % ver.major % ver.minor % ver.patch).str();
if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; }
if (ver.metadata != nullptr) { res += '+'; res += ver.metadata; }
return res;
}
// Arithmetics
Semver& operator+=(const Major &b) { ver.major += b.i; return *this; }
Semver& operator+=(const Minor &b) { ver.minor += b.i; return *this; }
Semver& operator+=(const Patch &b) { ver.patch += b.i; return *this; }
Semver& operator-=(const Major &b) { ver.major -= b.i; return *this; }
Semver& operator-=(const Minor &b) { ver.minor -= b.i; return *this; }
Semver& operator-=(const Patch &b) { ver.patch -= b.i; return *this; }
Semver operator+(const Major &b) const { Semver res(*this); return res += b; }
Semver operator+(const Minor &b) const { Semver res(*this); return res += b; }
Semver operator+(const Patch &b) const { Semver res(*this); return res += b; }
Semver operator-(const Major &b) const { Semver res(*this); return res -= b; }
Semver operator-(const Minor &b) const { Semver res(*this); return res -= b; }
Semver operator-(const Patch &b) const { Semver res(*this); return res -= b; }
private:
semver_t ver;
Semver(semver_t ver) : ver(ver) {}
static semver_t semver_zero() { return { 0, 0, 0, nullptr, nullptr }; }
};
}
#endif
<commit_msg>Fix: Avoid the infamous `major` & `minor` macros on GCC<commit_after>#ifndef slic3r_Semver_hpp_
#define slic3r_Semver_hpp_
#include <string>
#include <cstring>
#include <ostream>
#include <boost/optional.hpp>
#include <boost/format.hpp>
#include "semver/semver.h"
namespace Slic3r {
class Semver
{
public:
struct Major { const int i; Major(int i) : i(i) {} };
struct Minor { const int i; Minor(int i) : i(i) {} };
struct Patch { const int i; Patch(int i) : i(i) {} };
Semver() : ver(semver_zero()) {}
Semver(int major, int minor, int patch,
boost::optional<std::string> metadata = boost::none,
boost::optional<std::string> prerelease = boost::none)
{
ver.major = major;
ver.minor = minor;
ver.patch = patch;
ver.metadata = metadata ? std::strcpy(ver.metadata, metadata->c_str()) : nullptr;
ver.prerelease = prerelease ? std::strcpy(ver.prerelease, prerelease->c_str()) : nullptr;
}
static boost::optional<Semver> parse(const std::string &str)
{
semver_t ver = semver_zero();
if (::semver_parse(str.c_str(), &ver) == 0) {
return Semver(ver);
} else {
return boost::none;
}
}
static const Semver zero() { return Semver(semver_zero()); }
static const Semver inf()
{
static semver_t ver = { std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), nullptr, nullptr };
return Semver(ver);
}
static const Semver invalid()
{
static semver_t ver = { -1, 0, 0, nullptr, nullptr };
return Semver(ver);
}
Semver(Semver &&other) : ver(other.ver) { other.ver = semver_zero(); }
Semver(const Semver &other) : ver(::semver_copy(&other.ver)) {}
Semver &operator=(Semver &&other)
{
::semver_free(&ver);
ver = other.ver;
other.ver = semver_zero();
return *this;
}
Semver &operator=(const Semver &other)
{
::semver_free(&ver);
ver = ::semver_copy(&other.ver);
return *this;
}
~Semver() { ::semver_free(&ver); }
// const accessors
int maj() const { return ver.major; }
int min() const { return ver.minor; }
int patch() const { return ver.patch; }
const char* prerelease() const { return ver.prerelease; }
const char* metadata() const { return ver.metadata; }
// Comparison
bool operator<(const Semver &b) const { return ::semver_compare(ver, b.ver) == -1; }
bool operator<=(const Semver &b) const { return ::semver_compare(ver, b.ver) <= 0; }
bool operator==(const Semver &b) const { return ::semver_compare(ver, b.ver) == 0; }
bool operator!=(const Semver &b) const { return ::semver_compare(ver, b.ver) != 0; }
bool operator>=(const Semver &b) const { return ::semver_compare(ver, b.ver) >= 0; }
bool operator>(const Semver &b) const { return ::semver_compare(ver, b.ver) == 1; }
// We're using '&' instead of the '~' operator here as '~' is unary-only:
// Satisfies patch if Major and minor are equal.
bool operator&(const Semver &b) const { return ::semver_satisfies_patch(ver, b.ver); }
bool operator^(const Semver &b) const { return ::semver_satisfies_caret(ver, b.ver); }
bool in_range(const Semver &low, const Semver &high) const { return low <= *this && *this <= high; }
// Conversion
std::string to_string() const {
auto res = (boost::format("%1%.%2%.%3%") % ver.major % ver.minor % ver.patch).str();
if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; }
if (ver.metadata != nullptr) { res += '+'; res += ver.metadata; }
return res;
}
// Arithmetics
Semver& operator+=(const Major &b) { ver.major += b.i; return *this; }
Semver& operator+=(const Minor &b) { ver.minor += b.i; return *this; }
Semver& operator+=(const Patch &b) { ver.patch += b.i; return *this; }
Semver& operator-=(const Major &b) { ver.major -= b.i; return *this; }
Semver& operator-=(const Minor &b) { ver.minor -= b.i; return *this; }
Semver& operator-=(const Patch &b) { ver.patch -= b.i; return *this; }
Semver operator+(const Major &b) const { Semver res(*this); return res += b; }
Semver operator+(const Minor &b) const { Semver res(*this); return res += b; }
Semver operator+(const Patch &b) const { Semver res(*this); return res += b; }
Semver operator-(const Major &b) const { Semver res(*this); return res -= b; }
Semver operator-(const Minor &b) const { Semver res(*this); return res -= b; }
Semver operator-(const Patch &b) const { Semver res(*this); return res -= b; }
private:
semver_t ver;
Semver(semver_t ver) : ver(ver) {}
static semver_t semver_zero() { return { 0, 0, 0, nullptr, nullptr }; }
};
}
#endif
<|endoftext|> |
<commit_before>// 2-SAT - O(V+E)
int n, vis[2*N], ord[2*N], ordn, cnt, cmp[2*N], val[N];
vector<int> adj[2*N], adjt[2*N];
// for a variable u with idx i
// u is 2*i and !u is 2*i+1
// (a v b) == !a -> b ^ !b -> a
int v(int x) { return 2*x; }
int nv(int x) { return 2*x+1; }
// add clause (a v b)
void add(int a, int b){
adj[a^1].push_back(b);
adj[b^1].push_back(a);
adjt[b].push_back(a^1);
adjt[a].push_back(b^1);
}
void dfs(int x){
vis[x] = 1;
for(auto v : adj[x]) if(!vis[v]) dfs(v);
ord[ordn++] = x;
}
void dfst(int x){
cmp[x] = cnt, vis[x] = 0;
for(auto v : adj[x]) if(vis[v]) dfst(v);
}
bool run2sat(){
for(int i = 1; i <= n; i++) {
if(!vis[v(i)]) dfs(v(i));
if(!vis[nv(i)]) dfs(nv(i));
}
for(int i = ordn-1; i >= 0; i--)
if(vis[ord[i]]) cnt++, dfst(ord[i]);
for(int i = 1; i <= n; i ++){
if(cmp[v(i)] == cmp[nv(i)]) return false;
val[i] = cmp[v(i)] > cmp[nv(i)];
}
return true;
}
<commit_msg>Update 2-sat-navarro.cpp<commit_after>// 2-SAT - O(V+E)
int n, vis[2*N], ord[2*N], ordn, cnt, cmp[2*N], val[N];
vector<int> adj[2*N], adjt[2*N];
// for a variable u with idx i
// u is 2*i and !u is 2*i+1
// (a v b) == !a -> b ^ !b -> a
int v(int x) { return 2*x; }
int nv(int x) { return 2*x+1; }
// add clause (a v b)
void add(int a, int b){
adj[a^1].push_back(b);
adj[b^1].push_back(a);
adjt[b].push_back(a^1);
adjt[a].push_back(b^1);
}
void dfs(int x){
vis[x] = 1;
for(auto v : adj[x]) if(!vis[v]) dfs(v);
ord[ordn++] = x;
}
void dfst(int x){
cmp[x] = cnt, vis[x] = 0;
for(auto v : adjt[x]) if(vis[v]) dfst(v);
}
bool run2sat(){
for(int i = 1; i <= n; i++) {
if(!vis[v(i)]) dfs(v(i));
if(!vis[nv(i)]) dfs(nv(i));
}
for(int i = ordn-1; i >= 0; i--)
if(vis[ord[i]]) cnt++, dfst(ord[i]);
for(int i = 1; i <= n; i ++){
if(cmp[v(i)] == cmp[nv(i)]) return false;
val[i] = cmp[v(i)] > cmp[nv(i)];
}
return true;
}
<|endoftext|> |
<commit_before>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#include "ascii_grid_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string> // std::string, std::stoi
#include <vector> // std::vector
namespace loaders
{
bool load_ascii_grid(
std::string ascii_grid_file_name,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals,
std::string triangulation_type)
{
// Beginning of `L4133D.asc`.
//
// ncols 3000
// nrows 3000
// xllcorner 386000.000000000000
// yllcorner 6672000.000000000000
// cellsize 2.000000000000
// NODATA_value -9999.000
// 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832
std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n";
// Open the file
const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str();
std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb");
if (!file)
{
std::cerr << ascii_grid_file_name << " could not be opened.\n";
return false;
}
// Find out file size.
if (std::fseek(file, 0, SEEK_END) != 0)
{
std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
std::fclose(file);
return false;
}
uint64_t file_size = std::ftell(file);
// Move file pointer to the beginning of file.
if (fseek(file, 0, SEEK_SET) != 0)
{
std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
std::fclose(file);
return false;
}
// Reserve enough memory.
char* point_data = new char[file_size];
if (point_data == nullptr)
{
std::cerr << "Reserving memory for point data failed.\n";
std::fclose(file);
return false;
}
char* point_data_pointer = point_data;
// Read the point data from the file into the buffer.
std::fread(point_data, 1, file_size, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
// All possible block identifier strings.
std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
int32_t image_width = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "ncols");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
int32_t image_height = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "nrows");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float xllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "xllcorner");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float yllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "yllcorner");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float cellsize = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "cellsize");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value");
uint32_t image_width_in_use = 3000; // should be 3000.
uint32_t image_height_in_use = 2000;
float* vertex_data;
vertex_data = new float[image_width_in_use * image_height_in_use];
if (vertex_data == nullptr)
{
std::cerr << "Reserving memory for vertex data failed.\n";
delete point_data;
return false;
}
float* vertex_pointer;
vertex_pointer = vertex_data;
// start processing image_data.
for (uint32_t z = 0; z < image_height_in_use; z++)
{
for (uint32_t x = 0; x < image_width_in_use; x++)
{
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
*vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr);
}
}
delete point_data;
std::cout << "Triangulating ascii grid data.\n";
TriangulateQuadsStruct triangulate_quads_struct;
// triangulate_quads_struct.image_width = image_width;
triangulate_quads_struct.image_width = image_width_in_use;
triangulate_quads_struct.image_height = image_height_in_use;
triangulate_quads_struct.triangulation_type = triangulation_type;
triangulate_quads_struct.sphere_radius = NAN;
triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.
bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
delete vertex_data;
return true;
}
}
<commit_msg>Bugfix: Read `cellsize` correctly.<commit_after>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#include "ascii_grid_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string> // std::string, std::stoi
#include <vector> // std::vector
namespace loaders
{
bool load_ascii_grid(
std::string ascii_grid_file_name,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals,
std::string triangulation_type)
{
// Beginning of `L4133D.asc`.
//
// ncols 3000
// nrows 3000
// xllcorner 386000.000000000000
// yllcorner 6672000.000000000000
// cellsize 2.000000000000
// NODATA_value -9999.000
// 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832
std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n";
// Open the file
const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str();
std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb");
if (!file)
{
std::cerr << ascii_grid_file_name << " could not be opened.\n";
return false;
}
// Find out file size.
if (std::fseek(file, 0, SEEK_END) != 0)
{
std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
std::fclose(file);
return false;
}
uint64_t file_size = std::ftell(file);
// Move file pointer to the beginning of file.
if (fseek(file, 0, SEEK_SET) != 0)
{
std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
std::fclose(file);
return false;
}
// Reserve enough memory.
char* point_data = new char[file_size];
if (point_data == nullptr)
{
std::cerr << "Reserving memory for point data failed.\n";
std::fclose(file);
return false;
}
char* point_data_pointer = point_data;
// Read the point data from the file into the buffer.
std::fread(point_data, 1, file_size, file);
// Everything is in memory now, the file can be closed
std::fclose(file);
// All possible block identifier strings.
std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
int32_t image_width = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "ncols");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
int32_t image_height = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "nrows");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float xllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "xllcorner");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float yllcorner = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "yllcorner");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float cellsize = string::extract_float_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "cellsize");
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value");
uint32_t image_width_in_use = 3000; // should be 3000.
uint32_t image_height_in_use = 2000;
float* vertex_data;
vertex_data = new float[image_width_in_use * image_height_in_use];
if (vertex_data == nullptr)
{
std::cerr << "Reserving memory for vertex data failed.\n";
delete point_data;
return false;
}
float* vertex_pointer;
vertex_pointer = vertex_data;
// start processing image_data.
for (uint32_t z = 0; z < image_height_in_use; z++)
{
for (uint32_t x = 0; x < image_width_in_use; x++)
{
while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
{
point_data_pointer++;
}
*vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr);
}
}
delete point_data;
std::cout << "Triangulating ascii grid data.\n";
TriangulateQuadsStruct triangulate_quads_struct;
// triangulate_quads_struct.image_width = image_width;
triangulate_quads_struct.image_width = image_width_in_use;
triangulate_quads_struct.image_height = image_height_in_use;
triangulate_quads_struct.triangulation_type = triangulation_type;
triangulate_quads_struct.sphere_radius = NAN;
triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.
bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
delete vertex_data;
return true;
}
}
<|endoftext|> |
<commit_before><commit_msg>Replaced `#include` line with a forward declaration.<commit_after><|endoftext|> |
<commit_before>#include "DynamixelConsole.h"
const DynamixelCommand DynamixelConsole::sCommand[] =
{{"ping", &DynamixelConsole::ping},
{"read", &DynamixelConsole::read},
{"write", &DynamixelConsole::write},
{"reset", &DynamixelConsole::reset}};
DynamixelConsole::DynamixelConsole(DynamixelInterface &aInterface, Stream &aConsole):
mInterface(aInterface), mConsole(aConsole)
{
mLinePtr=&(mLineBuffer[0]);
mLineBuffer[sLineBufferSize]=0;
}
void DynamixelConsole::loop()
{
//empty input buffer
while(mConsole.available())
mConsole.read();
//write new command prompt
mConsole.write(">");
// read one command line
char c;
while((c=mConsole.read())!='\n' && c!='\r')
{
if(c>=32 && c<=126 && (mLinePtr-&(mLineBuffer[0]))<sLineBufferSize)
{
mConsole.write(c);
*mLinePtr=c;
++mLinePtr;
}
else if(c==8 && mLinePtr>(&(mLineBuffer[0])))
{
mConsole.write(c);
--mLinePtr;
}
}
//new line
mConsole.write("\n\r");
// run command
run();
// reset buffer
mLinePtr=&(mLineBuffer[0]);
}
void DynamixelConsole::run()
{
char *argv[16];
int argc=parseCmd(argv);
const int commandNumber=sizeof(sCommand)/sizeof(DynamixelCommand);
for(int i=0; i<commandNumber; ++i)
{
if(strcmp(argv[0],sCommand[i].mName)==0)
{
DynamixelStatus status=(this->*(sCommand[i].mCallback))(argc, argv);
printStatus(status);
break;
}
}
}
int DynamixelConsole::parseCmd(char **argv)
{
int argc=0;
char *ptr=&mLineBuffer[0];
while(argc<15)
{
while(*ptr==' ' && ptr<mLinePtr)
{
++ptr;
}
if(ptr>=mLinePtr)
{
break;
}
argv[argc]=ptr;
while(*ptr!=' ' && ptr<mLinePtr)
{
++ptr;
}
*ptr='\0';
++ptr;
++argc;
}
argv[argc]=0;
return argc;
}
void DynamixelConsole::printStatus(DynamixelStatus aStatus)
{
if(aStatus==DYN_STATUS_INTERNAL_ERROR)
{
mConsole.print("Invalid command parameters\n\r");
return;
}
mConsole.print("Status : ");
if(aStatus==DYN_STATUS_OK)
{
mConsole.print("ok");
}
else if(aStatus&DYN_STATUS_COM_ERROR)
{
mConsole.print("communication error");
if(aStatus&DYN_STATUS_TIMEOUT)
{
mConsole.print(", timeout");
}
else if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
{
mConsole.print(", invalid response checksum");
}
}
else
{
mConsole.print("communication ok");
if(aStatus&DYN_STATUS_INPUT_VOLTAGE_ERROR)
{
mConsole.print(", invalid input voltage");
}
if(aStatus&DYN_STATUS_ANGLE_LIMIT_ERROR)
{
mConsole.print(", angle limit error");
}
if(aStatus&DYN_STATUS_OVERHEATING_ERROR)
{
mConsole.print(", overheating");
}
if(aStatus&DYN_STATUS_RANGE_ERROR)
{
mConsole.print(", out of range value");
}
if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
{
mConsole.print(", invalid command checksum");
}
if(aStatus&DYN_STATUS_OVERLOAD_ERROR)
{
mConsole.print(", overload");
}
if(aStatus&DYN_STATUS_INSTRUCTION_ERROR)
{
mConsole.print(", invalid instruction");
}
}
mConsole.print("\n\r");
}
void DynamixelConsole::printData(const uint8_t *data, uint8_t length)
{
for(uint8_t i=0; i<length; ++i)
{
mConsole.print(data[i]);
mConsole.print(" ");
}
mConsole.print("\n\r");
}
DynamixelStatus DynamixelConsole::ping(int argc, char **argv)
{
int id=0;
if(argc<2)
{
mConsole.print("Usage : ping <id>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id<1 || id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
return mInterface.ping(id);
}
DynamixelStatus DynamixelConsole::read(int argc, char **argv)
{
int id=0, addr=0, length=1;
if(argc<3)
{
mConsole.print("Usage : read <id> <address> <length=1>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id<1 || id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
addr=atoi(argv[2]);
if(argc>3)
{
length=atoi(argv[3]);
}
if(length>255)
{
return DYN_STATUS_INTERNAL_ERROR;
}
uint8_t *ptr=new uint8_t[length];
DynamixelStatus result=mInterface.read(id, addr, length, ptr);
printData(ptr,length);
delete ptr;
return result;
}
DynamixelStatus DynamixelConsole::write(int argc, char **argv)
{
int id=0, addr=0, length=0;
if(argc<4)
{
mConsole.print("Usage : write <id> <address> <data_1> ... <data_N>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id<1 || id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
addr=atoi(argv[2]);
length=argc-3;
if(length>255)
{
return DYN_STATUS_INTERNAL_ERROR;
}
uint8_t *ptr=new uint8_t[length];
for(uint8_t i=0; i<length; ++i)
{
ptr[i]=atoi(argv[i+3]);
}
DynamixelStatus result=mInterface.write(id, addr, length, ptr);
delete ptr;
return result;
}
DynamixelStatus DynamixelConsole::reset(int argc, char **argv)
{
int id=0;
if(argc<2)
{
mConsole.print("Usage : reset <id>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id<1 || id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
DynamixelStatus result=mInterface.reset(id);
return result;
}
<commit_msg>zero is a valid id<commit_after>#include "DynamixelConsole.h"
const DynamixelCommand DynamixelConsole::sCommand[] =
{{"ping", &DynamixelConsole::ping},
{"read", &DynamixelConsole::read},
{"write", &DynamixelConsole::write},
{"reset", &DynamixelConsole::reset}};
DynamixelConsole::DynamixelConsole(DynamixelInterface &aInterface, Stream &aConsole):
mInterface(aInterface), mConsole(aConsole)
{
mLinePtr=&(mLineBuffer[0]);
mLineBuffer[sLineBufferSize]=0;
}
void DynamixelConsole::loop()
{
//empty input buffer
while(mConsole.available())
mConsole.read();
//write new command prompt
mConsole.write(">");
// read one command line
char c;
while((c=mConsole.read())!='\n' && c!='\r')
{
if(c>=32 && c<=126 && (mLinePtr-&(mLineBuffer[0]))<sLineBufferSize)
{
mConsole.write(c);
*mLinePtr=c;
++mLinePtr;
}
else if(c==8 && mLinePtr>(&(mLineBuffer[0])))
{
mConsole.write(c);
--mLinePtr;
}
}
//new line
mConsole.write("\n\r");
// run command
run();
// reset buffer
mLinePtr=&(mLineBuffer[0]);
}
void DynamixelConsole::run()
{
char *argv[16];
int argc=parseCmd(argv);
const int commandNumber=sizeof(sCommand)/sizeof(DynamixelCommand);
for(int i=0; i<commandNumber; ++i)
{
if(strcmp(argv[0],sCommand[i].mName)==0)
{
DynamixelStatus status=(this->*(sCommand[i].mCallback))(argc, argv);
printStatus(status);
break;
}
}
}
int DynamixelConsole::parseCmd(char **argv)
{
int argc=0;
char *ptr=&mLineBuffer[0];
while(argc<15)
{
while(*ptr==' ' && ptr<mLinePtr)
{
++ptr;
}
if(ptr>=mLinePtr)
{
break;
}
argv[argc]=ptr;
while(*ptr!=' ' && ptr<mLinePtr)
{
++ptr;
}
*ptr='\0';
++ptr;
++argc;
}
argv[argc]=0;
return argc;
}
void DynamixelConsole::printStatus(DynamixelStatus aStatus)
{
if(aStatus==DYN_STATUS_INTERNAL_ERROR)
{
mConsole.print("Invalid command parameters\n\r");
return;
}
mConsole.print("Status : ");
if(aStatus==DYN_STATUS_OK)
{
mConsole.print("ok");
}
else if(aStatus&DYN_STATUS_COM_ERROR)
{
mConsole.print("communication error");
if(aStatus&DYN_STATUS_TIMEOUT)
{
mConsole.print(", timeout");
}
else if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
{
mConsole.print(", invalid response checksum");
}
}
else
{
mConsole.print("communication ok");
if(aStatus&DYN_STATUS_INPUT_VOLTAGE_ERROR)
{
mConsole.print(", invalid input voltage");
}
if(aStatus&DYN_STATUS_ANGLE_LIMIT_ERROR)
{
mConsole.print(", angle limit error");
}
if(aStatus&DYN_STATUS_OVERHEATING_ERROR)
{
mConsole.print(", overheating");
}
if(aStatus&DYN_STATUS_RANGE_ERROR)
{
mConsole.print(", out of range value");
}
if(aStatus&DYN_STATUS_CHECKSUM_ERROR)
{
mConsole.print(", invalid command checksum");
}
if(aStatus&DYN_STATUS_OVERLOAD_ERROR)
{
mConsole.print(", overload");
}
if(aStatus&DYN_STATUS_INSTRUCTION_ERROR)
{
mConsole.print(", invalid instruction");
}
}
mConsole.print("\n\r");
}
void DynamixelConsole::printData(const uint8_t *data, uint8_t length)
{
for(uint8_t i=0; i<length; ++i)
{
mConsole.print(data[i]);
mConsole.print(" ");
}
mConsole.print("\n\r");
}
DynamixelStatus DynamixelConsole::ping(int argc, char **argv)
{
int id=0;
if(argc<2)
{
mConsole.print("Usage : ping <id>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
return mInterface.ping(id);
}
DynamixelStatus DynamixelConsole::read(int argc, char **argv)
{
int id=0, addr=0, length=1;
if(argc<3)
{
mConsole.print("Usage : read <id> <address> <length=1>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
addr=atoi(argv[2]);
if(argc>3)
{
length=atoi(argv[3]);
}
if(length>255)
{
return DYN_STATUS_INTERNAL_ERROR;
}
uint8_t *ptr=new uint8_t[length];
DynamixelStatus result=mInterface.read(id, addr, length, ptr);
printData(ptr,length);
delete ptr;
return result;
}
DynamixelStatus DynamixelConsole::write(int argc, char **argv)
{
int id=0, addr=0, length=0;
if(argc<4)
{
mConsole.print("Usage : write <id> <address> <data_1> ... <data_N>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
addr=atoi(argv[2]);
length=argc-3;
if(length>255)
{
return DYN_STATUS_INTERNAL_ERROR;
}
uint8_t *ptr=new uint8_t[length];
for(uint8_t i=0; i<length; ++i)
{
ptr[i]=atoi(argv[i+3]);
}
DynamixelStatus result=mInterface.write(id, addr, length, ptr);
delete ptr;
return result;
}
DynamixelStatus DynamixelConsole::reset(int argc, char **argv)
{
int id=0;
if(argc<2)
{
mConsole.print("Usage : reset <id>\n\r");
return DYN_STATUS_INTERNAL_ERROR;
}
id=atoi(argv[1]);
if(id>254)
{
return DYN_STATUS_INTERNAL_ERROR;
}
DynamixelStatus result=mInterface.reset(id);
return result;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType1, typename TMatrixType2>
bool CheckEqual(TMatrixType1 const& Matrix1, TMatrixType2 const& Matrix2) {
for (int i = 0; i < Matrix1.size1(); i++)
for (int j = 0; j < Matrix1.size2(); j++)
if (Matrix1(i, j) != Matrix2(i, j))
return false;
return true;
}
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
TMatrixType mA;
TMatrixType mB;
TMatrixType mC;
void initialize(TMatrixType& TheMatrix, double Value) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = Value;
}
void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
AMatrix::Matrix<double, 3, 3> block;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
block(i, j) = 0.00;
block(0, 0) = std::cos(AngleInRadian);
block(0, 1) = -std::sin(AngleInRadian);
block(1, 0) = std::sin(AngleInRadian);
block(1, 1) = std::cos(AngleInRadian);
block(2, 2) = 1.00;
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++) {
auto block_i = i % 3;
auto block_j = j % 3;
TheMatrix(i, j) = block(block_i, block_j);
}
}
public:
ComparisonColumn() {
initialize(mA, 0.00);
initialize(mB, 0.00);
initialize(mC, 0.00);
}
TMatrixType& GetMatrixC() { return mC; }
Timer::duration_type MeasureSumTime() {
int repeat_number = 10000000;
initialize(mA, 0.01);
initialize(mB, 0.20);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC = mA + mB;
mB = mC;
}
return timer.elapsed().count();
}
Timer::duration_type MeasureMultTime() {
int repeat_number = 10000000;
initialize_rotation(mA, -0.0001);
initialize_rotation(mB, 0.0001);
TMatrixType D;
initialize(D, 1.00);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC = D * mA;
D = mC * mB;
}
return timer.elapsed().count();
}
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
Timer::duration_type MeasureProdTime() {
int repeat_number = 10000000;
initialize_rotation(mA, -0.0001);
initialize_rotation(mB, 0.0001);
TMatrixType D;
initialize(D, 1.00);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC = boost::numeric::ublas::prod(D, mA);
D = boost::numeric::ublas::prod(mC, mB);
}
return timer.elapsed().count();
}
#endif
};
void CompareSumTime() {
ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
std::cout << "C = A + B\t\t" << a_matrix_column.MeasureSumTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
std::cout << "\t\t" << eigen_column.MeasureSumTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
ublas_column;
std::cout << "\t\t" << ublas_column.MeasureSumTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
std::cout << std::endl;
}
void CompareMultTime() {
ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
std::cout << "C = A * B\t\t" << a_matrix_column.MeasureMultTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
std::cout << "\t\t" << eigen_column.MeasureMultTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
ublas_column;
std::cout << "\t\t" << ublas_column.MeasureProdTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
std::cout << std::endl;
// std::cout << "AMatrix C = " << a_matrix_column.GetMatrixC() << std::endl;
// std::cout << "Eigen C = " << eigen_column.GetMatrixC() << std::endl;
}
int main() {
std::cout << "operation\t\tAMatrix\t\tEigen\t\tUblas\t\tAtlas" << std::endl;
CompareSumTime();
CompareMultTime();
return 0;
}
<commit_msg>Correcting macro check errors<commit_after>
#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType1, typename TMatrixType2>
bool CheckEqual(TMatrixType1 const& Matrix1, TMatrixType2 const& Matrix2) {
for (int i = 0; i < Matrix1.size1(); i++)
for (int j = 0; j < Matrix1.size2(); j++)
if (Matrix1(i, j) != Matrix2(i, j))
return false;
return true;
}
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
TMatrixType mA;
TMatrixType mB;
TMatrixType mC;
void initialize(TMatrixType& TheMatrix, double Value) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = Value;
}
void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
AMatrix::Matrix<double, 3, 3> block;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
block(i, j) = 0.00;
block(0, 0) = std::cos(AngleInRadian);
block(0, 1) = -std::sin(AngleInRadian);
block(1, 0) = std::sin(AngleInRadian);
block(1, 1) = std::cos(AngleInRadian);
block(2, 2) = 1.00;
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++) {
auto block_i = i % 3;
auto block_j = j % 3;
TheMatrix(i, j) = block(block_i, block_j);
}
}
public:
ComparisonColumn() {
initialize(mA, 0.00);
initialize(mB, 0.00);
initialize(mC, 0.00);
}
TMatrixType& GetMatrixC() { return mC; }
Timer::duration_type MeasureSumTime() {
int repeat_number = 10000000;
initialize(mA, 0.01);
initialize(mB, 0.20);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC = mA + mB;
mB = mC;
}
return timer.elapsed().count();
}
Timer::duration_type MeasureMultTime() {
int repeat_number = 10000000;
initialize_rotation(mA, -0.0001);
initialize_rotation(mB, 0.0001);
TMatrixType D;
initialize(D, 1.00);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC = D * mA;
D = mC * mB;
}
return timer.elapsed().count();
}
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
Timer::duration_type MeasureProdTime() {
int repeat_number = 10000000;
initialize_rotation(mA, -0.0001);
initialize_rotation(mB, 0.0001);
TMatrixType D;
initialize(D, 1.00);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC = boost::numeric::ublas::prod(D, mA);
D = boost::numeric::ublas::prod(mC, mB);
}
return timer.elapsed().count();
}
#endif
};
void CompareSumTime() {
ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
std::cout << "C = A + B\t\t" << a_matrix_column.MeasureSumTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
std::cout << "\t\t" << eigen_column.MeasureSumTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
ublas_column;
std::cout << "\t\t" << ublas_column.MeasureSumTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
std::cout << std::endl;
}
void CompareMultTime() {
ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
std::cout << "C = A * B\t\t" << a_matrix_column.MeasureMultTime();
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
std::cout << "\t\t" << eigen_column.MeasureMultTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), eigen_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
ComparisonColumn<boost::numeric::ublas::bounded_matrix<double, 3, 3>, 3, 3>
ublas_column;
std::cout << "\t\t" << ublas_column.MeasureProdTime();
if (!CheckEqual(a_matrix_column.GetMatrixC(), ublas_column.GetMatrixC()))
std::cout << "(Failed!)";
#endif
std::cout << std::endl;
// std::cout << "AMatrix C = " << a_matrix_column.GetMatrixC() << std::endl;
// std::cout << "Eigen C = " << eigen_column.GetMatrixC() << std::endl;
}
int main() {
std::cout << "operation\t\tAMatrix\t\tEigen\t\tUblas\t\tAtlas" << std::endl;
CompareSumTime();
CompareMultTime();
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType1, typename TMatrixType2>
bool CheckEqual(TMatrixType1 const& Matrix1, TMatrixType2 const& Matrix2) {
for (int i = 0; i < Matrix1.size1(); i++)
for (int j = 0; j < Matrix1.size2(); j++)
if (Matrix1(i, j) != Matrix2(i, j))
return false;
return true;
}
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
std::string mColumnName;
protected:
TMatrixType mA;
TMatrixType mB;
TMatrixType mC;
void initialize(TMatrixType& TheMatrix, double Value) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = Value;
}
void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
AMatrix::Matrix<double, 3, 3> block;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
block(i, j) = 0.00;
block(0, 0) = std::cos(AngleInRadian);
block(0, 1) = -std::sin(AngleInRadian);
block(1, 0) = std::sin(AngleInRadian);
block(1, 1) = std::cos(AngleInRadian);
block(2, 2) = 1.00;
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++) {
auto block_i = i % 3;
auto block_j = j % 3;
TheMatrix(i, j) = block(block_i, block_j);
}
}
public:
ComparisonColumn() = delete;
ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
initialize(mA, 0.00);
initialize(mB, 0.00);
initialize(mC, 0.00);
}
std::string const& GetColumnName() { return mColumnName; }
TMatrixType& GetMatrixC() { return mC; }
void MeasureSumTime() {
int repeat_number = 10000000;
initialize(mA, 0.01);
initialize(mB, 0.20);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC.noalias() = mA + mB;
mB.noalias() = mC;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
int repeat_number = 10000000;
initialize_rotation(mA, -0.0001);
initialize_rotation(mB, 0.0001);
TMatrixType D;
initialize(D, 1.00);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mC.noalias() = mA * TMatrixType(D * mA);
D.noalias() = mB * TMatrixType(mC * mB);
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#endif
};
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class UblasComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
using BsaeType =
ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;
UblasComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
ColumnName) {}
void MeasureSumTime() {
int repeat_number = 10000000;
BsaeType::initialize(BsaeType::mA, 0.01);
BsaeType::initialize(BsaeType::mB, 0.20);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
boost::numeric::ublas::noalias(BsaeType::mC) =
BsaeType::mA + BsaeType::mB;
boost::numeric::ublas::noalias(BsaeType::mB) = BsaeType::mC;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
using namespace boost::numeric::ublas;
int repeat_number = 10000000;
BsaeType::initialize_rotation(BsaeType::mA, -0.0001);
BsaeType::initialize_rotation(BsaeType::mB, 0.0001);
TMatrixType D;
BsaeType::initialize(D, 1.00);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
noalias(BsaeType::mC) = prod(BsaeType::mA, TMatrixType(prod(D, BsaeType::mA)));
noalias(D) = prod(BsaeType::mB, TMatrixType(prod(BsaeType::mC, BsaeType::mB)));
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class EmptyComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
EmptyComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
void MeasureSumTime() {}
void MeasureMultTime() {}
};
template <int NumberOfRows, int NumberOfColumns>
class BenchmarkMatrix {
ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#elif
EmptyComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#elif
EmptyComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#endif
public:
BenchmarkMatrix()
: mAMatrixColumn("AMatrix"),
mEigenColumn("Eigen"),
mUblasColumn("Ublas") {
std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
<< "]";
std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
std::cout << "\t\t" << mEigenColumn.GetColumnName();
std::cout << "\t\t" << mUblasColumn.GetColumnName();
std::cout << std::endl;
}
void Run() {
std::cout << "C = A + B";
mAMatrixColumn.MeasureSumTime();
mEigenColumn.MeasureSumTime();
mUblasColumn.MeasureSumTime();
std::cout << std::endl;
std::cout << "C = A * B";
mAMatrixColumn.MeasureMultTime();
mEigenColumn.MeasureMultTime();
mUblasColumn.MeasureMultTime();
std::cout << std::endl;
std::cout << std::endl;
}
};
int main() {
BenchmarkMatrix<3, 3> benchmark_3_3;
benchmark_3_3.Run();
BenchmarkMatrix<4, 4> benchmark_4_4;
benchmark_4_4.Run();
BenchmarkMatrix<6, 6> benchmark_6_6;
benchmark_6_6.Run();
return 0;
}
<commit_msg>Fixing mulitiplication benchmarks<commit_after>#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
std::string mColumnName;
protected:
TMatrixType mA;
TMatrixType mB;
TMatrixType mResult;
void initialize(TMatrixType& TheMatrix) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = j + 1;
}
void initializeInverse(TMatrixType& TheMatrix) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = 1.00 / (i + 1);
}
void initialize(TMatrixType& TheMatrix, double Value) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = Value;
}
void initialize_rotation(TMatrixType& TheMatrix, double AngleInRadian) {
AMatrix::Matrix<double, 3, 3> block;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
block(i, j) = 0.00;
block(0, 0) = std::cos(AngleInRadian);
block(0, 1) = -std::sin(AngleInRadian);
block(1, 0) = std::sin(AngleInRadian);
block(1, 1) = std::cos(AngleInRadian);
block(2, 2) = 1.00;
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++) {
auto block_i = i % 3;
auto block_j = j % 3;
TheMatrix(i, j) = block(block_i, block_j);
}
}
public:
ComparisonColumn() = delete;
ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
initialize(mA, 0.00);
initialize(mB, 0.00);
initialize(mResult, 0.00);
}
std::string const& GetColumnName() { return mColumnName; }
TMatrixType& GetResult() { return mResult; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
if (mResult(i, j) != Reference(i, j))
return false;
return true;
}
void MeasureSumTime() {
int repeat_number = 10000000;
initialize(mA, 0.01);
initialize(mB, 0.20);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mResult.noalias() = mA + mB;
mB.noalias() = mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
int repeat_number = 10000000;
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mResult.noalias() = D * mA;
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
int repeat_number = 10000000;
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
mResult.noalias() = mA * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#endif
};
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class UblasComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
using BaseType =
ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;
UblasComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
ColumnName) {}
void MeasureSumTime() {
int repeat_number = 10000000;
BaseType::initialize(BaseType::mA, 0.01);
BaseType::initialize(BaseType::mB, 0.20);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
boost::numeric::ublas::noalias(BaseType::mResult) =
BaseType::mA + BaseType::mB;
boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
using namespace boost::numeric::ublas;
int repeat_number = 10000000;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
noalias(BaseType::mResult) = prod(D, BaseType::mA);
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
using namespace boost::numeric::ublas;
int repeat_number = 10000000;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
noalias(BaseType::mResult) =
prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class EmptyComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
EmptyComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
void MeasureSumTime() {}
void MeasureABAMultTime() {}
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
return true;
}
};
template <int NumberOfRows, int NumberOfColumns>
class BenchmarkMatrix {
ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#elif
EmptyComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#elif
EmptyComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#endif
public:
BenchmarkMatrix()
: mAMatrixColumn("AMatrix"),
mEigenColumn("Eigen"),
mUblasColumn("Ublas") {
std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
<< "]";
std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
std::cout << "\t\t" << mEigenColumn.GetColumnName();
std::cout << "\t\t" << mUblasColumn.GetColumnName();
std::cout << std::endl;
}
void Run() {
std::cout << "C = A + B";
mAMatrixColumn.MeasureSumTime();
mEigenColumn.MeasureSumTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureSumTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B";
mAMatrixColumn.MeasureMultTime();
mEigenColumn.MeasureMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B * A";
mAMatrixColumn.MeasureABAMultTime();
mEigenColumn.MeasureABAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureABAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
// std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
// std::cout << "Eigen : " << mEigenColumn.GetResult() << std::endl;
std::cout << std::endl;
}
};
int main() {
BenchmarkMatrix<3, 3> benchmark_3_3;
benchmark_3_3.Run();
BenchmarkMatrix<4, 4> benchmark_4_4;
benchmark_4_4.Run();
BenchmarkMatrix<6, 6> benchmark_6_6;
benchmark_6_6.Run();
BenchmarkMatrix<12, 12> benchmark_12_12;
benchmark_12_12.Run();
BenchmarkMatrix<16, 16> benchmark_16_16;
benchmark_16_16.Run();
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class ComparisonColumn {
protected:
static constexpr std::size_t mRepeat =
static_cast<std::size_t>(1e8 / (NumberOfRows * NumberOfColumns));
TMatrixType mA;
TMatrixType mB;
TMatrixType mResult;
std::string mColumnName;
void initialize(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = j + 1.00;
}
void initializeInverse(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = 1.00 / (i + 1);
}
public:
ComparisonColumn() = delete;
ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
initialize(mA);
initialize(mB);
initialize(mResult);
}
std::string const& GetColumnName() { return mColumnName; }
TMatrixType& GetResult() { return mResult; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
if (mResult(i, j) != Reference(i, j))
return false;
return true;
}
void MeasureSumTime() {
initialize(mA);
initialize(mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA + mB;
mB.noalias() = mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = D * mA;
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class UblasComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
using BaseType =
ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;
UblasComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
ColumnName) {}
void MeasureSumTime() {
BaseType::initialize(BaseType::mA);
BaseType::initialize(BaseType::mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
boost::numeric::ublas::noalias(BaseType::mResult) =
BaseType::mA + BaseType::mB;
boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) = prod(D, BaseType::mA);
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class EmptyComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
EmptyComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
void MeasureSumTime() { std::cout << "\t\t"; }
void MeasureMultTime() { std::cout << "\t\t"; }
void MeasureABAMultTime() { std::cout << "\t\t"; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
return true;
}
};
template <std::size_t NumberOfRows, std::size_t NumberOfColumns>
class BenchmarkMatrix {
ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mUblasColumn;
#endif
public:
BenchmarkMatrix()
: mAMatrixColumn("AMatrix"),
mEigenColumn("Eigen"),
mUblasColumn("Ublas") {
std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
<< "]";
std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
std::cout << "\t\t" << mEigenColumn.GetColumnName();
std::cout << "\t\t" << mUblasColumn.GetColumnName();
std::cout << std::endl;
}
~BenchmarkMatrix() = default;
void Run() {
std::cout << "C = A + B";
mAMatrixColumn.MeasureSumTime();
mEigenColumn.MeasureSumTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureSumTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B";
mAMatrixColumn.MeasureMultTime();
mEigenColumn.MeasureMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B * A";
mAMatrixColumn.MeasureABAMultTime();
mEigenColumn.MeasureABAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureABAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
// std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
// std::cout << "Eigen : " << mEigenColumn.GetResult() << std::endl;
std::cout << std::endl;
}
};
int main() {
BenchmarkMatrix<3, 3> benchmark_3_3;
benchmark_3_3.Run();
BenchmarkMatrix<4, 4> benchmark_4_4;
benchmark_4_4.Run();
BenchmarkMatrix<6, 6> benchmark_6_6;
benchmark_6_6.Run();
BenchmarkMatrix<12, 12> benchmark_12_12;
benchmark_12_12.Run();
BenchmarkMatrix<16, 16> benchmark_16_16;
benchmark_16_16.Run();
return 0;
}
<commit_msg>Adding A^T * B * A benchmarks<commit_after>#include <iostream>
#include <cmath>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
#include <boost/numeric/ublas/matrix.hpp>
#endif
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class ComparisonColumn {
protected:
static constexpr std::size_t mRepeat =
static_cast<std::size_t>(1e8 / (NumberOfRows * NumberOfColumns));
TMatrixType mA;
TMatrixType mB;
TMatrixType mResult;
std::string mColumnName;
void initialize(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = j + 1.00;
}
void initializeInverse(TMatrixType& TheMatrix) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = 1.00 / (i + 1);
}
public:
ComparisonColumn() = delete;
ComparisonColumn(std::string ColumnName) : mColumnName(ColumnName) {
initialize(mA);
initialize(mB);
initialize(mResult);
}
std::string const& GetColumnName() { return mColumnName; }
TMatrixType& GetResult() { return mResult; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
for (std::size_t i = 0; i < NumberOfRows; i++)
for (std::size_t j = 0; j < NumberOfColumns; j++)
if (mResult(i, j) != Reference(i, j))
return false;
return true;
}
void MeasureSumTime() {
initialize(mA);
initialize(mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA + mB;
mB.noalias() = mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = D * mA;
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureATransposeBAMultTime() {
initialize(mA);
initializeInverse(mB);
TMatrixType D;
initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) {
mResult.noalias() = mA.transpose() * TMatrixType(D * mA);
D.noalias() = mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class UblasComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
using BaseType =
ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>;
UblasComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>(
ColumnName) {}
void MeasureSumTime() {
BaseType::initialize(BaseType::mA);
BaseType::initialize(BaseType::mB);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
boost::numeric::ublas::noalias(BaseType::mResult) =
BaseType::mA + BaseType::mB;
boost::numeric::ublas::noalias(BaseType::mB) = BaseType::mResult;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) = prod(D, BaseType::mA);
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureABAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(BaseType::mA, TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
void MeasureATransposeBAMultTime() {
using namespace boost::numeric::ublas;
BaseType::initialize(BaseType::mA);
BaseType::initializeInverse(BaseType::mB);
TMatrixType D;
BaseType::initializeInverse(D);
Timer timer;
for (std::size_t i_repeat = 0; i_repeat < BaseType::mRepeat;
i_repeat++) {
noalias(BaseType::mResult) =
prod(trans(BaseType::mA), TMatrixType(prod(D, BaseType::mA)));
noalias(D) = BaseType::mB;
}
auto elapsed = timer.elapsed().count();
std::cout << "\t\t" << elapsed;
}
};
template <typename TMatrixType, std::size_t NumberOfRows,
std::size_t NumberOfColumns>
class EmptyComparisonColumn
: public ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns> {
public:
EmptyComparisonColumn(std::string ColumnName)
: ComparisonColumn<TMatrixType, NumberOfRows, NumberOfColumns>("") {}
void MeasureSumTime() { std::cout << "\t\t"; }
void MeasureMultTime() { std::cout << "\t\t"; }
void MeasureABAMultTime() { std::cout << "\t\t"; }
void MeasureATransposeBAMultTime() { std::cout << "\t\t"; }
template <typename TMatrixType2>
bool CheckResult(TMatrixType2 const& Reference) {
return true;
}
};
template <std::size_t NumberOfRows, std::size_t NumberOfColumns>
class BenchmarkMatrix {
ComparisonColumn<AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mAMatrixColumn;
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
ComparisonColumn<Eigen::Matrix<double, NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mEigenColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mEigenColumn;
#endif
#if defined(AMATRIX_COMPARE_WITH_UBLAS)
UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,
NumberOfRows, NumberOfColumns>,
NumberOfRows, NumberOfColumns>
mUblasColumn;
#else
EmptyComparisonColumn<
AMatrix::Matrix<double, NumberOfRows, NumberOfColumns>, NumberOfRows,
NumberOfColumns>
mUblasColumn;
#endif
public:
BenchmarkMatrix()
: mAMatrixColumn("AMatrix"),
mEigenColumn("Eigen"),
mUblasColumn("Ublas") {
std::cout << "Benchmark[" << NumberOfRows << "," << NumberOfColumns
<< "]";
std::cout << "\t\t" << mAMatrixColumn.GetColumnName();
std::cout << "\t\t" << mEigenColumn.GetColumnName();
std::cout << "\t\t" << mUblasColumn.GetColumnName();
std::cout << std::endl;
}
~BenchmarkMatrix() = default;
void Run() {
std::cout << "C = A + B";
mAMatrixColumn.MeasureSumTime();
mEigenColumn.MeasureSumTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureSumTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B";
mAMatrixColumn.MeasureMultTime();
mEigenColumn.MeasureMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A * B * A";
mAMatrixColumn.MeasureABAMultTime();
mEigenColumn.MeasureABAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureABAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
std::cout << "C = A^T * B * A";
mAMatrixColumn.MeasureATransposeBAMultTime();
mEigenColumn.MeasureATransposeBAMultTime();
if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
mUblasColumn.MeasureATransposeBAMultTime();
if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult()))
std::cout << "(Failed!)";
std::cout << std::endl;
// std::cout << "AMatrix : " << mAMatrixColumn.GetResult() << std::endl;
// std::cout << "Eigen : " << mEigenColumn.GetResult() << std::endl;
std::cout << std::endl;
}
};
int main() {
BenchmarkMatrix<3, 3> benchmark_3_3;
benchmark_3_3.Run();
BenchmarkMatrix<4, 4> benchmark_4_4;
benchmark_4_4.Run();
BenchmarkMatrix<6, 6> benchmark_6_6;
benchmark_6_6.Run();
BenchmarkMatrix<12, 12> benchmark_12_12;
benchmark_12_12.Run();
BenchmarkMatrix<16, 16> benchmark_16_16;
benchmark_16_16.Run();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdexcept>
#include "FractalGenerator.h"
#include "math_utils.h"
/*
* Public member functions
*/
FractalGenerator::FractalGenerator(fractalId id, v8::Isolate *isolate,
void (*doneCallback)(v8::Isolate *isolate,
v8::Local<v8::Object> nodeBuffer, bool halted,
void *doneCallbackData), v8::Local<v8::Object> buf,
void *doneCallbackData, int width, int height, double fractalWidth,
double fractalHeight, double fracgtalX, double fractalY, int iterations) :
id(id), doneCallback(doneCallback), doneCallbackData(doneCallbackData), width(
width), height(height), fractalWidth(fractalWidth), fractalHeight(
fractalHeight), fractalX(fractalX), fractalY(fractalY), iterations(
iterations) {
if (node::Buffer::Length(buf) < (width * height * 4)) {
throw new std::invalid_argument(
"node::Buffer::Length(buf) < (width * height * 4)");
}
nodeBuffer = new v8::Global<v8::Object>;
nodeBuffer->Reset(isolate, buf);
buffer = node::Buffer::Data(buf);
doneAsync = new uv_async_t;
// TODO switch to std::bind because c++ 11
doneAsync->data = this;
uv_loop_t *loop = uv_default_loop();
uv_async_init(loop, doneAsync, doneAsyncCallback);
}
FractalGenerator::~FractalGenerator() {
nodeBuffer->Reset();
delete nodeBuffer;
delete doneAsync;
}
void FractalGenerator::start() {
thread = new std::thread(&FractalGenerator::threadFunction, this);
}
void FractalGenerator::halt() {
halting.store(true);
}
int FractalGenerator::getProgress() {
return progress.load();
}
bool FractalGenerator::isGenerating() {
return generating.load();
}
/*
* Private member functions
*/
void FractalGenerator::doneAsyncCallback(uv_async_t *handle) {
// TODO switch to std::bind because c++ 11
FractalGenerator *self = ((FractalGenerator *) handle->data);
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
(*self->doneCallback)(isolate, self->nodeBuffer->Get(isolate),
self->halting.load(), self->doneCallbackData);
self->nodeBuffer->Reset();
}
void FractalGenerator::threadFunction() {
// build fractal here and call uv_async_send when done
generating.store(true);
progress.store(0);
// does this make things faster or is this redundant with g++ optimization?
float fx, fy, a, b, aa, bb, twoab;
int x, y, i, n;
RGBData color;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
if (halting.load()) {
generating.store(false);
uv_async_send(doneAsync);
return;
}
// get buffer index
i = x + y * width;
// pixel value generation
fx = x * fractalWidth / width + fractalX;
fy = y * fractalHeight / height + fractalY;
// z = (a + bi)
a = fx;
b = fy;
for (n = 0; n < iterations; n++) {
// z = z * z
aa = a * a;
bb = b * b;
twoab = 2.0f * a * b;
a = aa - bb + fx;
b = twoab + fy;
// if old sqrt(a * a + b * b) > 4
// z is outside a circle with radius 4 in the complex plane
if (aa + bb > 16) {
break;
}
}
// pixel coloring
if (n < iterations) {
// magic numbers
color = fromHSB(mod2(n * 3.3f, 0, 256.0f) / 256.0f, 1.0f,
mod2(n * 16.0f, 0, 256.0f) / 256.0f);
buffer[i] = color.r;
buffer[i + 1] = color.g;
buffer[i + 2] = color.b;
buffer[i + 3] = 0xFF;
} else {
buffer[i] = 0x00;
buffer[i + 1] = 0x00;
buffer[i + 2] = 0x00;
buffer[i + 3] = 0xFF;
}
progress++;
}
}
// set status
generating.store(false);
// send callback
uv_async_send(doneAsync);
}
<commit_msg>std::bind doesn't work with c function pointers<commit_after>#include <stdexcept>
#include "FractalGenerator.h"
#include "math_utils.h"
/*
* Public member functions
*/
FractalGenerator::FractalGenerator(fractalId id, v8::Isolate *isolate,
void (*doneCallback)(v8::Isolate *isolate,
v8::Local<v8::Object> nodeBuffer, bool halted,
void *doneCallbackData), v8::Local<v8::Object> buf,
void *doneCallbackData, int width, int height, double fractalWidth,
double fractalHeight, double fracgtalX, double fractalY, int iterations) :
id(id), doneCallback(doneCallback), doneCallbackData(doneCallbackData), width(
width), height(height), fractalWidth(fractalWidth), fractalHeight(
fractalHeight), fractalX(fractalX), fractalY(fractalY), iterations(
iterations) {
if (node::Buffer::Length(buf) < (width * height * 4)) {
throw new std::invalid_argument(
"node::Buffer::Length(buf) < (width * height * 4)");
}
nodeBuffer = new v8::Global<v8::Object>;
nodeBuffer->Reset(isolate, buf);
buffer = node::Buffer::Data(buf);
doneAsync = new uv_async_t;
doneAsync->data = this;
uv_loop_t *loop = uv_default_loop();
uv_async_init(loop, doneAsync, doneAsyncCallback);
}
FractalGenerator::~FractalGenerator() {
nodeBuffer->Reset();
delete nodeBuffer;
delete doneAsync;
}
void FractalGenerator::start() {
thread = new std::thread(&FractalGenerator::threadFunction, this);
}
void FractalGenerator::halt() {
halting.store(true);
}
int FractalGenerator::getProgress() {
return progress.load();
}
bool FractalGenerator::isGenerating() {
return generating.load();
}
/*
* Private member functions
*/
void FractalGenerator::doneAsyncCallback(uv_async_t *handle) {
FractalGenerator *self = ((FractalGenerator *) handle->data);
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
(*self->doneCallback)(isolate, self->nodeBuffer->Get(isolate),
self->halting.load(), self->doneCallbackData);
self->nodeBuffer->Reset();
}
void FractalGenerator::threadFunction() {
// build fractal here and call uv_async_send when done
generating.store(true);
progress.store(0);
// does this make things faster or is this redundant with g++ optimization?
float fx, fy, a, b, aa, bb, twoab;
int x, y, i, n;
RGBData color;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
if (halting.load()) {
generating.store(false);
uv_async_send(doneAsync);
return;
}
// get buffer index
i = x + y * width;
// pixel value generation
fx = x * fractalWidth / width + fractalX;
fy = y * fractalHeight / height + fractalY;
// z = (a + bi)
a = fx;
b = fy;
for (n = 0; n < iterations; n++) {
// z = z * z
aa = a * a;
bb = b * b;
twoab = 2.0f * a * b;
a = aa - bb + fx;
b = twoab + fy;
// if old sqrt(a * a + b * b) > 4
// z is outside a circle with radius 4 in the complex plane
if (aa + bb > 16) {
break;
}
}
// pixel coloring
if (n < iterations) {
// magic numbers
color = fromHSB(mod2(n * 3.3f, 0, 256.0f) / 256.0f, 1.0f,
mod2(n * 16.0f, 0, 256.0f) / 256.0f);
buffer[i] = color.r;
buffer[i + 1] = color.g;
buffer[i + 2] = color.b;
buffer[i + 3] = 0xFF;
} else {
buffer[i] = 0x00;
buffer[i + 1] = 0x00;
buffer[i + 2] = 0x00;
buffer[i + 3] = 0xFF;
}
progress++;
}
}
// set status
generating.store(false);
// send callback
uv_async_send(doneAsync);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/host_zoom_map.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
HostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {
const DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);
// Careful: The returned value could be NULL if the pref has never been set.
if (host_zoom_dictionary != NULL) {
for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());
i != host_zoom_dictionary->end_keys(); ++i) {
std::wstring wide_host(*i);
int zoom_level = 0;
bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(
wide_host, &zoom_level);
DCHECK(success);
host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;
}
}
}
// static
void HostZoomMap::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);
}
int HostZoomMap::GetZoomLevel(const std::string& host) const {
AutoLock auto_lock(lock_);
HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));
return (i == host_zoom_levels_.end()) ? 0 : i->second;
}
void HostZoomMap::SetZoomLevel(const std::string& host, int level) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (host.empty())
return;
{
AutoLock auto_lock(lock_);
if (level == 0)
host_zoom_levels_.erase(host);
else
host_zoom_levels_[host] = level;
}
DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);
std::wstring wide_host(UTF8ToWide(host));
if (level == 0) {
host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);
} else {
host_zoom_dictionary->SetWithoutPathExpansion(wide_host,
Value::CreateIntegerValue(level));
}
}
void HostZoomMap::ResetToDefaults() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
host_zoom_levels_.clear();
profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);
}
HostZoomMap::~HostZoomMap() {
}
<commit_msg>One more place I forgot to lock.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/host_zoom_map.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
HostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {
const DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);
// Careful: The returned value could be NULL if the pref has never been set.
if (host_zoom_dictionary != NULL) {
for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());
i != host_zoom_dictionary->end_keys(); ++i) {
std::wstring wide_host(*i);
int zoom_level = 0;
bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(
wide_host, &zoom_level);
DCHECK(success);
host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;
}
}
}
// static
void HostZoomMap::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);
}
int HostZoomMap::GetZoomLevel(const std::string& host) const {
AutoLock auto_lock(lock_);
HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));
return (i == host_zoom_levels_.end()) ? 0 : i->second;
}
void HostZoomMap::SetZoomLevel(const std::string& host, int level) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (host.empty())
return;
{
AutoLock auto_lock(lock_);
if (level == 0)
host_zoom_levels_.erase(host);
else
host_zoom_levels_[host] = level;
}
DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);
std::wstring wide_host(UTF8ToWide(host));
if (level == 0) {
host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);
} else {
host_zoom_dictionary->SetWithoutPathExpansion(wide_host,
Value::CreateIntegerValue(level));
}
}
void HostZoomMap::ResetToDefaults() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
{
AutoLock auto_lock(lock_);
host_zoom_levels_.clear();
}
profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);
}
HostZoomMap::~HostZoomMap() {
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a file for random testcases that we run into that at one point or
// another have crashed the program.
#include "chrome/test/ui/ui_test.h"
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/net_util.h"
class GoogleTest : public UITest {
protected:
GoogleTest() : UITest() {
FilePath test_file =
test_data_directory_.AppendASCII("google").AppendASCII("google.html");
homepage_ = GURL(net::FilePathToFileURL(test_file)).spec();
}
};
TEST_F(GoogleTest, Crash) {
std::wstring page_title = L"Google";
// Make sure the navigation succeeded.
EXPECT_EQ(page_title, GetActiveTabTitle());
// UITest will check if this crashed.
}
class ColumnLayout : public UITest {
protected:
ColumnLayout() : UITest() {
FilePath test_file = test_data_directory_.AppendASCII("columns.html");
homepage_ = GURL(net::FilePathToFileURL(test_file)).spec();
}
};
TEST_F(ColumnLayout, Crash) {
std::wstring page_title = L"Column test";
// Make sure the navigation succeeded.
EXPECT_EQ(page_title, GetActiveTabTitle());
// UITest will check if this crashed.
}
// By passing kTryChromeAgain with a magic value > 10000 we cause chrome
// to exit fairly early. This was the cause of crashes. See bug 34799.
class EarlyReturnTest : public UITest {
public:
EarlyReturnTest() {
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitchASCII(switches::kTryChromeAgain, "10001");
}
};
// Flaky: http://crbug.com/45115
TEST_F(EarlyReturnTest, FLAKY_ToastCrasher) {
// UITest will check if this crashed.
}
<commit_msg>ui_tests: disable EarlyReturnTest.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a file for random testcases that we run into that at one point or
// another have crashed the program.
#include "chrome/test/ui/ui_test.h"
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/net_util.h"
class GoogleTest : public UITest {
protected:
GoogleTest() : UITest() {
FilePath test_file =
test_data_directory_.AppendASCII("google").AppendASCII("google.html");
homepage_ = GURL(net::FilePathToFileURL(test_file)).spec();
}
};
TEST_F(GoogleTest, Crash) {
std::wstring page_title = L"Google";
// Make sure the navigation succeeded.
EXPECT_EQ(page_title, GetActiveTabTitle());
// UITest will check if this crashed.
}
class ColumnLayout : public UITest {
protected:
ColumnLayout() : UITest() {
FilePath test_file = test_data_directory_.AppendASCII("columns.html");
homepage_ = GURL(net::FilePathToFileURL(test_file)).spec();
}
};
TEST_F(ColumnLayout, Crash) {
std::wstring page_title = L"Column test";
// Make sure the navigation succeeded.
EXPECT_EQ(page_title, GetActiveTabTitle());
// UITest will check if this crashed.
}
// By passing kTryChromeAgain with a magic value > 10000 we cause Chrome
// to exit fairly early.
// Quickly exiting Chrome (regardless of this particular flag -- it
// doesn't do anything other than cause Chrome to quit on startup on
// non-Windows) was a cause of crashes (see bug 34799 for example) so
// this is a useful test of the startup/quick-shutdown cycle.
class EarlyReturnTest : public UITest {
public:
EarlyReturnTest() {
wait_for_initial_loads_ = false; // Don't wait for any pages to load.
launch_arguments_.AppendSwitchASCII(switches::kTryChromeAgain, "10001");
}
};
// Disabled: http://crbug.com/45115
// Due to limitations in our test infrastructure, this test currently doesn't
// work.
TEST_F(EarlyReturnTest, DISABLED_ToastCrasher) {
// UITest will check if this crashed.
}
<|endoftext|> |
<commit_before><commit_msg>Fix chrome frame build.<commit_after><|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string>
#include <string.h>
#include <vector>
#include <iostream>
#include "../../include/Helper/fileUtils.h"
std::vector<std::string>* Helper::readLinesFromFile(std::ifstream& inFromFile)
{
std::vector<std::string>* returnStrings = new std::vector<std::string>();
std::string curLine;
while(std::getline(inFromFile, curLine))
{
returnStrings->push_back(curLine);
}
return returnStrings;
}
void Helper::stripBrackets(std::string &stripString)
{
std::string retString;
for(int i = 0; i < stripString.length(); i++)
{
if(stripString.at(i) == '[' || stripString.at(i) == ']')
continue;
else
retString += stripString.at(i);
}
stripString = retString;
}
std::vector<int>* Helper::csvToInt(std::string &convertString)
{
std::vector<int>* returnVector = new std::vector<int>();
const char *cstrConvertString = convertString.c_str();
char* tmpString = strtok((char*)cstrConvertString, " ,");
while(tmpString != NULL)
{
int tmp = atoi(tmpString);
returnVector->push_back(tmp);
tmpString = strtok(NULL, " ,");
}
return returnVector;
}
std::vector<std::vector<int>*>* Helper::processMSSFile(std::ifstream &inStream)
{
std::vector<std::vector<int>*>* convertedLines = new std::vector<std::vector<int>*>();
std::vector<std::string>* MSSFileLines = Helper::readLinesFromFile(inStream);
for(int i = 0; i < MSSFileLines->size(); i++)
{
Helper::stripBrackets(MSSFileLines->at(i));
convertedLines->push_back(Helper::csvToInt(MSSFileLines->at(i)));
}
return convertedLines;
}
void Helper::WriteResultsToFile(std::ofstream &outStream, std::vector<int>& results, int start, int end, int total)
{
outStream << "[";
for(int i = 0; i < results.size() - 1; i++)
outStream << results.at(i) << ", ";
outStream << results.at(results.size() - 1) << "]" << std::endl;
outStream << "[";
for(int i = start; i < end; i++)
outStream << results.at(i) << ", ";
outStream << results.at(end) << ']' << std::endl;
outStream << total << std::endl;
}
<commit_msg>Fix some unsigned warnings in fileUtils<commit_after>#include <stdlib.h>
#include <string>
#include <string.h>
#include <vector>
#include <iostream>
#include "../../include/Helper/fileUtils.h"
std::vector<std::string>* Helper::readLinesFromFile(std::ifstream& inFromFile)
{
std::vector<std::string>* returnStrings = new std::vector<std::string>();
std::string curLine;
while(std::getline(inFromFile, curLine))
{
returnStrings->push_back(curLine);
}
return returnStrings;
}
void Helper::stripBrackets(std::string &stripString)
{
std::string retString;
for(int i = 0; i < stripString.length(); i++)
{
if(stripString.at((unsigned)i) == '[' || stripString.at((unsigned)i) == ']')
continue;
else
retString += stripString.at((unsigned)i);
}
stripString = retString;
}
std::vector<int>* Helper::csvToInt(std::string &convertString)
{
std::vector<int>* returnVector = new std::vector<int>();
const char *cstrConvertString = convertString.c_str();
char* tmpString = strtok((char*)cstrConvertString, " ,");
while(tmpString != NULL)
{
int tmp = atoi(tmpString);
returnVector->push_back(tmp);
tmpString = strtok(NULL, " ,");
}
return returnVector;
}
std::vector<std::vector<int>*>* Helper::processMSSFile(std::ifstream &inStream)
{
std::vector<std::vector<int>*>* convertedLines = new std::vector<std::vector<int>*>();
std::vector<std::string>* MSSFileLines = Helper::readLinesFromFile(inStream);
for(int i = 0; i < MSSFileLines->size(); i++)
{
Helper::stripBrackets(MSSFileLines->at(i));
convertedLines->push_back(Helper::csvToInt(MSSFileLines->at(i)));
}
return convertedLines;
}
void Helper::WriteResultsToFile(std::ofstream &outStream, std::vector<int>& results, int start, int end, int total)
{
outStream << "[";
for(int i = 0; i < results.size() - 1; i++)
outStream << results.at((unsigned)i) << ", ";
outStream << results.at(results.size() - 1) << "]" << std::endl;
outStream << "[";
for(int i = start; i < end; i++)
outStream << results.at((unsigned)i) << ", ";
outStream << results.at((unsigned)end) << ']' << std::endl;
outStream << total << std::endl;
}
<|endoftext|> |
<commit_before>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2017 Dmitry Sovetov
https://github.com/dmsovetov
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 "Dto.h"
#include <cassert>
#include <memory.h>
DTO_BEGIN
// ------------------------------------------------------ Dto ------------------------------------------------------ //
// ** Dto::Dto
Dto::Dto()
: m_data(0)
, m_capacity(0)
{
}
// ** Dto::Dto
Dto::Dto(byte* data, int32 capacity)
: m_data(data)
, m_capacity(capacity)
{
assert(capacity >= 0);
assert(data != 0);
}
// ** Dto::operator bool
Dto::operator bool() const
{
return m_capacity > 0 && m_data != 0;
}
// ** Dto::capacity
int32 Dto::capacity() const
{
return m_capacity;
}
// ** Dto::length
int32 Dto::length() const
{
return *reinterpret_cast<const int32*>(m_data);
}
// ** Dto::data
const byte* Dto::data() const
{
return m_data;
}
// ** Dto::data
byte* Dto::data()
{
return m_data;
}
// ** Dto::iter
DtoIter Dto::iter() const
{
return DtoIter(m_data + sizeof(int32), m_capacity);
}
// ---------------------------------------------------- DtoIter ---------------------------------------------------- //
// ** DtoIter::DtoIter
DtoIter::DtoIter(const byte* input, int32 length)
: m_input(input)
, m_length(length)
, m_type(DtoEnd)
{
memset(&m_key, 0, sizeof(m_key));
memset(&m_value, 0, sizeof(m_value));
}
// ** DtoIter::next
bool DtoIter::next()
{
// Decode next entry from an input stream.
DtoByteBufferInput input(m_input, m_length);
m_input += BinaryDtoReader::decode(input, m_key, m_value);
// Skip a nested DTO body
if (m_value.type == DtoKeyValue || m_value.type == DtoSequence)
{
m_input += m_value.binary.length - sizeof(int32);
}
bool isValid = m_value.type != DtoEnd;
return isValid;
}
// ** DtoIter::type
DtoValueType DtoIter::type() const
{
return m_type;
}
// ** DtoIter::key
const DtoStringView& DtoIter::key() const
{
return m_key;
}
// ** DtoIter::toBool
bool DtoIter::toBool() const
{
assert(m_type == DtoBool);
return m_value.boolean;
}
// ** DtoIter::toString
const DtoStringView& DtoIter::toString() const
{
assert(m_type == DtoString);
return m_value.string;
}
// ** DtoIter::toInt32
int32 DtoIter::toInt32() const
{
assert(m_type == DtoInt32);
return m_value.int32;
}
// ** DtoIter::toDouble
double DtoIter::toDouble() const
{
assert(m_type == DtoDouble);
return m_value.number;
}
DTO_END<commit_msg>Fixed: Dto::length method<commit_after>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2017 Dmitry Sovetov
https://github.com/dmsovetov
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 "Dto.h"
#include <cassert>
#include <memory.h>
DTO_BEGIN
// ------------------------------------------------------ Dto ------------------------------------------------------ //
// ** Dto::Dto
Dto::Dto()
: m_data(0)
, m_capacity(0)
{
}
// ** Dto::Dto
Dto::Dto(byte* data, int32 capacity)
: m_data(data)
, m_capacity(capacity)
{
assert(capacity >= 0);
assert(data != 0);
}
// ** Dto::operator bool
Dto::operator bool() const
{
return m_capacity > 0 && m_data != 0;
}
// ** Dto::capacity
int32 Dto::capacity() const
{
return m_capacity;
}
// ** Dto::length
int32 Dto::length() const
{
if (m_data)
{
return *reinterpret_cast<const int32*>(m_data);
}
return 0;
}
// ** Dto::data
const byte* Dto::data() const
{
return m_data;
}
// ** Dto::data
byte* Dto::data()
{
return m_data;
}
// ** Dto::iter
DtoIter Dto::iter() const
{
return DtoIter(m_data + sizeof(int32), m_capacity);
}
// ---------------------------------------------------- DtoIter ---------------------------------------------------- //
// ** DtoIter::DtoIter
DtoIter::DtoIter(const byte* input, int32 length)
: m_input(input)
, m_length(length)
, m_type(DtoEnd)
{
memset(&m_key, 0, sizeof(m_key));
memset(&m_value, 0, sizeof(m_value));
}
// ** DtoIter::next
bool DtoIter::next()
{
// Decode next entry from an input stream.
DtoByteBufferInput input(m_input, m_length);
m_input += BinaryDtoReader::decode(input, m_key, m_value);
// Skip a nested DTO body
if (m_value.type == DtoKeyValue || m_value.type == DtoSequence)
{
m_input += m_value.binary.length - sizeof(int32);
}
bool isValid = m_value.type != DtoEnd;
return isValid;
}
// ** DtoIter::type
DtoValueType DtoIter::type() const
{
return m_type;
}
// ** DtoIter::key
const DtoStringView& DtoIter::key() const
{
return m_key;
}
// ** DtoIter::toBool
bool DtoIter::toBool() const
{
assert(m_type == DtoBool);
return m_value.boolean;
}
// ** DtoIter::toString
const DtoStringView& DtoIter::toString() const
{
assert(m_type == DtoString);
return m_value.string;
}
// ** DtoIter::toInt32
int32 DtoIter::toInt32() const
{
assert(m_type == DtoInt32);
return m_value.int32;
}
// ** DtoIter::toDouble
double DtoIter::toDouble() const
{
assert(m_type == DtoDouble);
return m_value.number;
}
DTO_END<|endoftext|> |
<commit_before>// -*- mode: c++ , coding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012, 2013 Mattias Andrée (maandree@kth.se)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InventoryExaminor.hpp"
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <maandree@kth.se>
*/
namespace tbrpg
{
#define __store_tty() \
struct termios saved_stty; \
struct termios stty; \
tcgetattr(STDIN_FILENO, &saved_stty); \
tcgetattr(STDIN_FILENO, &stty); \
stty.c_lflag &= ~(ICANON | ECHO | ISIG); \
tcsetattr(STDIN_FILENO, TCSAFLUSH, &stty)
#define __restore_tty() \
tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_stty)
#define ESC "\033" /* since \e generates a non-ISO-standard warning */
#define CSI ESC "["
/**
* Construction
*/
InventoryExaminor::InventoryExaminor()
{
// Do nothing
}
/**
* Destructor
*/
InventoryExaminor::~InventoryExaminor()
{
// Do nothing
}
/**
* Examine a characters inventory
*
* @param character The index of the active character
* @param characters The party members
*/
void InventoryExaminor::examine(long character, std::vector<GameCharacter*>* characters) const
{
#define __print(X, Y) \
std::cout << (i == index ? CSI "02m" : "") \
<< X \
<< (Y == nullptr ? "(empty)" : Y->name); \
if ((Y != nullptr) && (Y->quantity_limit > 1)) \
std::cout << " (" << Y->quantity << ")"; \
std::cout << CSI "22m" << std::endl
__store_tty();
std::cout << CSI "?25l";
Item* hand = nullptr;
size_t page = 0, index = 0;
Inventory& inventory = (*(characters))[character]->character->record.inventory;
std::vector<Item*>& personal = inventory.personal;
std::vector<Item*>& ground = (*(characters))[character]->area->items;
char c;
bool reading = true;
while (reading)
{
std::flush(std::cout);
if (read(STDIN_FILENO, &c, 1) <= 0)
c = CTRL('G');
bool readinginner = true;
while (readinginner)
{
readinginner = false;
switch (c)
{
case '\033':
if (read(STDIN_FILENO, &c, 1) <= 0)
break;
if (c == 'O')
{
read(STDIN_FILENO, &c, 1);
switch (c)
{
case 'P':
c = '1';
readinginner = true;
break;
case 'Q':
c = '2';
readinginner = true;
break;
case 'R':
c = '3';
readinginner = true;
break;
}
}
else if (c == '[')
{
read(STDIN_FILENO, &c, 1);
if (c == '1')
{
switch (c)
{
case '1':
case '2':
case '3':
readinginner = true;
break;
}
read(STDIN_FILENO, &c, 1);
if (c != '~')
readinginner = false;
}
else if ((c == 'A') || (c == 'B'))
{
c = CTRL((c == 'A' ? 'P' : 'N'));
readinginner = true;
}
}
break;
case '1': /* Equipped items */
case '2': /* Personal inventory */
case '3': /* Item on the ground */
page = c - '1';
index = 0;
index++;
case CTRL('P'): /* Navigate up */ /* XXX this could be speed up */
index -= 2;
case CTRL('N'): /* Navigate down */
index++;
if (index < 0)
index = 0;
else
{
size_t n = page == 2 ? ground.size() + 1
: page = 1 ? personal.size()
: inventory.left_hand.size() + inventory.quiver.size()
+ inventory.quick_items.size() + inventory.rings.size() + 8;
if (index >= n)
index = n - 1;
}
case CTRL('L'): /* Redraw */
std::cout << CSI "H" CSI "2J"
<< "Temporary slot: "
<< (hand == nullptr ? "(empty)" : hand->name);
if ((hand != nullptr) && (hand->quantity_limit > 1))
std::cout << " (" << hand->quantity << ")";
std::cout << std::endl << std::endl;
if (page == 0)
{
size_t i = 0;
for (size_t j = 0, n = inventory.left_hand.size(); j < n; j++)
{
__print("Left hand " << j << " ", inventory.left_hand[j]); i++;
}
for (size_t j = 0, n = inventory.quiver.size(); j < n; j++)
{
__print("Quiver " << j << " ", inventory.quiver[j]); i++;
}
for (size_t j = 0, n = inventory.quick_items.size(); j < n; j++)
{
__print("Quick item " << j << "", inventory.quick_items[j]); i++;
}
__print("Right hand ", inventory.right_hand); i++;
__print("Headgear ", inventory.headgear); i++;
__print("Amulet ", inventory.amulet); i++;
for (size_t j = 0, n = inventory.rings.size(); j < n; j++)
{
__print("Ring " << j << " ", inventory.rings[j]); i++;
}
__print("Body ", inventory.body); i++;
__print("Gauntlets ", inventory.gauntlets); i++;
__print("Girdle ", inventory.girdle); i++;
__print("Boots ", inventory.boots); i++;
__print("Cloak ", inventory.cloak); i++;
}
else if (page == 1)
for (size_t i = 0, n = personal.size(); i < n; i++)
{
__print((i < 10 ? "Personal " : "Personal ") << i, personal[i]);
}
else if (page == 2)
{
for (size_t i = 0, n = ground.size(); i < n; i++)
{
__print("Ground " << i, ground[i]);
}
size_t i = ground.size();
__print("Ground " << i, nullptr);
}
break;
/* XXX many things here gound be speed up */
case 'd': /* Drop temporary slot item on the ground */
if (hand == nullptr)
break;
ground.push_back(hand);
hand = nullptr;
readinginner = true;
c = CTRL('L');
break;
case 'D': /* Drop item on the ground */
break;
case 'p': /* Pick up item to temporary slot */
break;
case 's': /* Swap item with temporary slot */
break;
case 'e': /* Examine item in slot */
break;
case 'E': /* Examine item in temporary slot */
break;
case 'P': /* Give item to another party member */
break;
case CTRL('G'): /* Abort */
if ((hand))
ground.push_back(hand);
hand = nullptr;
case CTRL('D'): /* Complete */
if (hand == nullptr)
reading = false;
break;
}
}
}
std::flush(std::cout << CSI "?25l");
__restore_tty();
#undef __print
}
}
<commit_msg>dropping some of the items to the ground<commit_after>// -*- mode: c++ , coding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012, 2013 Mattias Andrée (maandree@kth.se)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InventoryExaminor.hpp"
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <maandree@kth.se>
*/
namespace tbrpg
{
#define __store_tty() \
struct termios saved_stty; \
struct termios stty; \
tcgetattr(STDIN_FILENO, &saved_stty); \
tcgetattr(STDIN_FILENO, &stty); \
stty.c_lflag &= ~(ICANON | ECHO | ISIG); \
tcsetattr(STDIN_FILENO, TCSAFLUSH, &stty)
#define __restore_tty() \
tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_stty)
#define ESC "\033" /* since \e generates a non-ISO-standard warning */
#define CSI ESC "["
/**
* Construction
*/
InventoryExaminor::InventoryExaminor()
{
// Do nothing
}
/**
* Destructor
*/
InventoryExaminor::~InventoryExaminor()
{
// Do nothing
}
/**
* Examine a characters inventory
*
* @param character The index of the active character
* @param characters The party members
*/
void InventoryExaminor::examine(long character, std::vector<GameCharacter*>* characters) const
{
#define __print(X, Y) \
std::cout << (i == index ? CSI "02m" : "") \
<< X \
<< (Y == nullptr ? "(empty)" : Y->name); \
if ((Y != nullptr) && (Y->quantity_limit > 1)) \
std::cout << " (" << Y->quantity << ")"; \
std::cout << CSI "22m" << std::endl
__store_tty();
std::cout << CSI "?25l";
Item* hand = nullptr;
size_t page = 0, index = 0;
Inventory& inventory = (*(characters))[character]->character->record.inventory;
std::vector<Item*>& personal = inventory.personal;
std::vector<Item*>& ground = (*(characters))[character]->area->items;
char c;
bool reading = true;
while (reading)
{
std::flush(std::cout);
if (read(STDIN_FILENO, &c, 1) <= 0)
c = CTRL('G');
bool readinginner = true;
while (readinginner)
{
readinginner = false;
switch (c)
{
case '\033':
if (read(STDIN_FILENO, &c, 1) <= 0)
break;
if (c == 'O')
{
read(STDIN_FILENO, &c, 1);
switch (c)
{
case 'P':
c = '1';
readinginner = true;
break;
case 'Q':
c = '2';
readinginner = true;
break;
case 'R':
c = '3';
readinginner = true;
break;
}
}
else if (c == '[')
{
read(STDIN_FILENO, &c, 1);
if (c == '1')
{
switch (c)
{
case '1':
case '2':
case '3':
readinginner = true;
break;
}
read(STDIN_FILENO, &c, 1);
if (c != '~')
readinginner = false;
}
else if ((c == 'A') || (c == 'B'))
{
c = CTRL((c == 'A' ? 'P' : 'N'));
readinginner = true;
}
}
break;
case '1': /* Equipped items */
case '2': /* Personal inventory */
case '3': /* Item on the ground */
page = c - '1';
index = 0;
index++;
case CTRL('P'): /* Navigate up */ /* XXX this could be speed up */
index -= 2;
case CTRL('N'): /* Navigate down */
index++;
if (index < 0)
index = 0;
else
{
size_t n = page == 2 ? ground.size() + 1
: page = 1 ? personal.size()
: inventory.left_hand.size() + inventory.quiver.size()
+ inventory.quick_items.size() + inventory.rings.size() + 8;
if (index >= n)
index = n - 1;
}
case CTRL('L'): /* Redraw */
std::cout << CSI "H" CSI "2J"
<< "Temporary slot: "
<< (hand == nullptr ? "(empty)" : hand->name);
if ((hand != nullptr) && (hand->quantity_limit > 1))
std::cout << " (" << hand->quantity << ")";
std::cout << std::endl << std::endl;
if (page == 0)
{
size_t i = 0;
for (size_t j = 0, n = inventory.left_hand.size(); j < n; j++)
{
__print("Left hand " << j << " ", inventory.left_hand[j]); i++;
}
for (size_t j = 0, n = inventory.quiver.size(); j < n; j++)
{
__print("Quiver " << j << " ", inventory.quiver[j]); i++;
}
for (size_t j = 0, n = inventory.quick_items.size(); j < n; j++)
{
__print("Quick item " << j << "", inventory.quick_items[j]); i++;
}
__print("Right hand ", inventory.right_hand); i++;
__print("Headgear ", inventory.headgear); i++;
__print("Amulet ", inventory.amulet); i++;
for (size_t j = 0, n = inventory.rings.size(); j < n; j++)
{
__print("Ring " << j << " ", inventory.rings[j]); i++;
}
__print("Body ", inventory.body); i++;
__print("Gauntlets ", inventory.gauntlets); i++;
__print("Girdle ", inventory.girdle); i++;
__print("Boots ", inventory.boots); i++;
__print("Cloak ", inventory.cloak); i++;
}
else if (page == 1)
for (size_t i = 0, n = personal.size(); i < n; i++)
{
__print((i < 10 ? "Personal " : "Personal ") << i, personal[i]);
}
else if (page == 2)
{
for (size_t i = 0, n = ground.size(); i < n; i++)
{
__print("Ground " << i, ground[i]);
}
size_t i = ground.size();
__print("Ground " << i, nullptr);
}
break;
/* XXX many things here gound be speed up */
case 'd': /* Drop temporary slot item on the ground */
if (hand == nullptr)
break;
ground.push_back(hand);
hand = nullptr;
readinginner = true;
c = CTRL('L');
break;
case 'D': /* Drop item on the ground */
if ((page == 2) && (index < ground.size()))
{
ground.push_back(ground[index]);
ground.erase(index);
readinginner = true;
c = CTRL('L');
}
else if ((page == 1) && (personal[index] != nullptr))
{
ground.push_back(personal[index]);
personal[index] = nullptr;
readinginner = true;
c = CTRL('L');
}
else if (page == 0)
{
;
}
break;
case 'p': /* Pick up item to temporary slot */
break;
case 's': /* Swap item with temporary slot */
break;
case 'e': /* Examine item in slot */
break;
case 'E': /* Examine item in temporary slot */
break;
case 'P': /* Give item to another party member */
break;
case CTRL('G'): /* Abort */
if ((hand))
ground.push_back(hand);
hand = nullptr;
case CTRL('D'): /* Complete */
if (hand == nullptr)
reading = false;
break;
}
}
}
std::flush(std::cout << CSI "?25l");
__restore_tty();
#undef __print
}
}
<|endoftext|> |
<commit_before>#include <unit_test/unit_test.h>
#include <systemlib/err.h>
#include <stdio.h>
#include <unistd.h>
#include <drivers/drv_hrt.h>
#define DSM_DEBUG
#include <lib/rc/sbus.h>
#include <lib/rc/dsm.h>
#include <lib/rc/st24.h>
#include <lib/rc/sumd.h>
#if !defined(CONFIG_ARCH_BOARD_SITL)
#define TEST_DATA_PATH "/fs/microsd"
#else
#define TEST_DATA_PATH "./test_data/"
#endif
extern "C" __EXPORT int rc_tests_main(int argc, char *argv[]);
class RCTest : public UnitTest
{
public:
virtual bool run_tests(void);
private:
bool dsmTest();
bool sbus2Test();
bool st24Test();
bool sumdTest();
};
bool RCTest::run_tests(void)
{
ut_run_test(dsmTest);
ut_run_test(sbus2Test);
ut_run_test(st24Test);
ut_run_test(sumdTest);
return (_tests_failed == 0);
}
bool RCTest::dsmTest(void)
{
const char *filepath = TEST_DATA_PATH "dsm_x_data.txt";
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
//warnx("loading data from: %s", filepath);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
// Init the parser
uint8_t frame[20];
uint16_t rc_values[18];
uint16_t num_values;
bool dsm_11_bit;
unsigned dsm_frame_drops = 0;
uint16_t max_channels = sizeof(rc_values) / sizeof(rc_values[0]);
int rate_limiter = 0;
unsigned last_drop = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
frame[0] = x;
unsigned len = 1;
// Pipe the data into the parser
bool result = dsm_parse(f * 1e6f, &frame[0], len, rc_values, &num_values,
&dsm_11_bit, &dsm_frame_drops, max_channels);
if (result) {
//warnx("decoded packet with %d channels and %s encoding:", num_values, (dsm_11_bit) ? "11 bit" : "10 bit");
for (unsigned i = 0; i < num_values; i++) {
//printf("chan #%u:\t%d\n", i, (int)rc_values[i]);
}
}
if (last_drop != (dsm_frame_drops)) {
//warnx("frame dropped, now #%d", (dsm_frame_drops));
last_drop = dsm_frame_drops;
}
rate_limiter++;
}
ut_test(ret == EOF);
return true;
}
bool RCTest::sbus2Test(void)
{
const char *filepath = TEST_DATA_PATH "sbus2_r7008SB.txt";
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
//warnx("loading data from: %s", filepath);
// if (argc < 2)
// errx(1, "Need a filename for the input file");
//int byte_offset = 7;
// if (argc > 2) {
// char* end;
// byte_offset = strtol(argv[2],&end,10);
// }
//warnx("RUNNING TEST WITH BYTE OFFSET OF: %d", byte_offset);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
// Init the parser
uint8_t frame[SBUS_BUFFER_SIZE];
uint16_t rc_values[18];
uint16_t num_values;
unsigned sbus_frame_drops = 0;
unsigned sbus_frame_resets = 0;
bool sbus_failsafe;
bool sbus_frame_drop;
uint16_t max_channels = sizeof(rc_values) / sizeof(rc_values[0]);
int rate_limiter = 0;
unsigned last_drop = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
frame[0] = x;
unsigned len = 1;
// Pipe the data into the parser
hrt_abstime now = hrt_absolute_time();
// if (rate_limiter % byte_offset == 0) {
bool result = sbus_parse(now, &frame[0], len, rc_values, &num_values,
&sbus_failsafe, &sbus_frame_drop, &sbus_frame_drops, max_channels);
if (result) {
//warnx("decoded packet");
}
// }
if (last_drop != (sbus_frame_drops + sbus_frame_resets)) {
warnx("frame dropped, now #%d", (sbus_frame_drops + sbus_frame_resets));
last_drop = sbus_frame_drops + sbus_frame_resets;
}
rate_limiter++;
}
ut_test(ret == EOF);
return true;
}
bool RCTest::st24Test(void)
{
const char *filepath = TEST_DATA_PATH "st24_data.txt";
//warnx("loading data from: %s", filepath);
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
float last_time = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
if (((f - last_time) * 1000 * 1000) > 3000) {
// warnx("FRAME RESET\n\n");
}
uint8_t b = static_cast<uint8_t>(x);
last_time = f;
// Pipe the data into the parser
//hrt_abstime now = hrt_absolute_time();
uint8_t rssi;
uint8_t rx_count;
uint16_t channel_count;
uint16_t channels[20];
if (!st24_decode(b, &rssi, &rx_count, &channel_count, channels, sizeof(channels) / sizeof(channels[0]))) {
//warnx("decoded: %u channels (converted to PPM range)", (unsigned)channel_count);
for (unsigned i = 0; i < channel_count; i++) {
//int16_t val = channels[i];
//warnx("channel %u: %d 0x%03X", i, static_cast<int>(val), static_cast<int>(val));
}
}
}
ut_test(ret == EOF);
return true;
}
bool RCTest::sumdTest(void)
{
const char *filepath = TEST_DATA_PATH "sumd_data.txt";
//warnx("loading data from: %s", filepath);
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
float last_time = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
if (((f - last_time) * 1000 * 1000) > 3000) {
// warnx("FRAME RESET\n\n");
}
uint8_t b = static_cast<uint8_t>(x);
last_time = f;
// Pipe the data into the parser
//hrt_abstime now = hrt_absolute_time();
uint8_t rssi;
uint8_t rx_count;
uint16_t channel_count;
uint16_t channels[32];
if (!sumd_decode(b, &rssi, &rx_count, &channel_count, channels, 32)) {
//warnx("decoded: %u channels (converted to PPM range)", (unsigned)channel_count);
for (unsigned i = 0; i < channel_count; i++) {
//int16_t val = channels[i];
//warnx("channel %u: %d 0x%03X", i, static_cast<int>(val), static_cast<int>(val));
}
}
}
ut_test(ret == EOF);
return true;
}
ut_declare_test_c(rc_tests_main, RCTest)
<commit_msg>Expand RC test to 2nd receiver with 12 channels<commit_after>#include <unit_test/unit_test.h>
#include <systemlib/err.h>
#include <stdio.h>
#include <unistd.h>
#include <drivers/drv_hrt.h>
#define DSM_DEBUG
#include <lib/rc/sbus.h>
#include <lib/rc/dsm.h>
#include <lib/rc/st24.h>
#include <lib/rc/sumd.h>
#if !defined(CONFIG_ARCH_BOARD_SITL)
#define TEST_DATA_PATH "/fs/microsd"
#else
#define TEST_DATA_PATH "./test_data/"
#endif
extern "C" __EXPORT int rc_tests_main(int argc, char *argv[]);
class RCTest : public UnitTest
{
public:
virtual bool run_tests(void);
private:
bool dsmTest(const char *filepath, unsigned expected_chancount, unsigned expected_dropcount, unsigned chan0);
bool dsmTest10Ch();
bool dsmTest12Ch();
bool sbus2Test();
bool st24Test();
bool sumdTest();
};
bool RCTest::run_tests(void)
{
ut_run_test(dsmTest10Ch);
ut_run_test(dsmTest12Ch);
ut_run_test(sbus2Test);
ut_run_test(st24Test);
ut_run_test(sumdTest);
return (_tests_failed == 0);
}
bool RCTest::dsmTest10Ch()
{
return dsmTest(TEST_DATA_PATH "dsm_x_data.txt", 10, 6, 0);
}
bool RCTest::dsmTest12Ch()
{
return dsmTest(TEST_DATA_PATH "dsm_x_dx9_data.txt", 12, 11, 1500);
}
bool RCTest::dsmTest(const char *filepath, unsigned expected_chancount, unsigned expected_dropcount, unsigned chan0)
{
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
//PX4_INFO("loading data from: %s", filepath);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
// Init the parser
uint8_t frame[20];
uint16_t rc_values[18];
uint16_t num_values;
bool dsm_11_bit;
unsigned dsm_frame_drops = 0;
uint16_t max_channels = sizeof(rc_values) / sizeof(rc_values[0]);
int rate_limiter = 0;
unsigned last_drop = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
frame[0] = x;
unsigned len = 1;
// Pipe the data into the parser
bool result = dsm_parse(f * 1e6f, &frame[0], len, rc_values, &num_values,
&dsm_11_bit, &dsm_frame_drops, max_channels);
if (result) {
ut_test(num_values == expected_chancount);
if (chan0 > 0) {
ut_test((chan0 - rc_values[0]) < 3);
}
//PX4_INFO("decoded packet with %d channels and %s encoding:", num_values, (dsm_11_bit) ? "11 bit" : "10 bit");
for (unsigned i = 0; i < num_values; i++) {
//PX4_INFO("chan #%u:\t%d", i, (int)rc_values[i]);
}
}
if (last_drop != (dsm_frame_drops)) {
//PX4_INFO("frame dropped, now #%d", (dsm_frame_drops));
last_drop = dsm_frame_drops;
}
rate_limiter++;
}
ut_test(ret == EOF);
PX4_INFO("drop: %d", (int)last_drop);
ut_test(last_drop == expected_dropcount);
return true;
}
bool RCTest::sbus2Test(void)
{
const char *filepath = TEST_DATA_PATH "sbus2_r7008SB.txt";
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
//warnx("loading data from: %s", filepath);
// if (argc < 2)
// errx(1, "Need a filename for the input file");
//int byte_offset = 7;
// if (argc > 2) {
// char* end;
// byte_offset = strtol(argv[2],&end,10);
// }
//warnx("RUNNING TEST WITH BYTE OFFSET OF: %d", byte_offset);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
// Init the parser
uint8_t frame[SBUS_BUFFER_SIZE];
uint16_t rc_values[18];
uint16_t num_values;
unsigned sbus_frame_drops = 0;
unsigned sbus_frame_resets = 0;
bool sbus_failsafe;
bool sbus_frame_drop;
uint16_t max_channels = sizeof(rc_values) / sizeof(rc_values[0]);
int rate_limiter = 0;
unsigned last_drop = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
frame[0] = x;
unsigned len = 1;
// Pipe the data into the parser
hrt_abstime now = hrt_absolute_time();
// if (rate_limiter % byte_offset == 0) {
bool result = sbus_parse(now, &frame[0], len, rc_values, &num_values,
&sbus_failsafe, &sbus_frame_drop, &sbus_frame_drops, max_channels);
if (result) {
//warnx("decoded packet");
}
// }
if (last_drop != (sbus_frame_drops + sbus_frame_resets)) {
PX4_WARN("frame dropped, now #%d", (sbus_frame_drops + sbus_frame_resets));
last_drop = sbus_frame_drops + sbus_frame_resets;
}
rate_limiter++;
}
ut_test(ret == EOF);
return true;
}
bool RCTest::st24Test(void)
{
const char *filepath = TEST_DATA_PATH "st24_data.txt";
//warnx("loading data from: %s", filepath);
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
float last_time = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
if (((f - last_time) * 1000 * 1000) > 3000) {
// warnx("FRAME RESET\n\n");
}
uint8_t b = static_cast<uint8_t>(x);
last_time = f;
// Pipe the data into the parser
//hrt_abstime now = hrt_absolute_time();
uint8_t rssi;
uint8_t rx_count;
uint16_t channel_count;
uint16_t channels[20];
if (!st24_decode(b, &rssi, &rx_count, &channel_count, channels, sizeof(channels) / sizeof(channels[0]))) {
//warnx("decoded: %u channels (converted to PPM range)", (unsigned)channel_count);
for (unsigned i = 0; i < channel_count; i++) {
//int16_t val = channels[i];
//warnx("channel %u: %d 0x%03X", i, static_cast<int>(val), static_cast<int>(val));
}
}
}
ut_test(ret == EOF);
return true;
}
bool RCTest::sumdTest(void)
{
const char *filepath = TEST_DATA_PATH "sumd_data.txt";
//warnx("loading data from: %s", filepath);
FILE *fp;
fp = fopen(filepath, "rt");
ut_test(fp != nullptr);
float f;
unsigned x;
int ret;
// Trash the first 20 lines
for (unsigned i = 0; i < 20; i++) {
char buf[200];
(void)fgets(buf, sizeof(buf), fp);
}
float last_time = 0;
while (EOF != (ret = fscanf(fp, "%f,%x,,", &f, &x))) {
ut_test(ret > 0);
if (((f - last_time) * 1000 * 1000) > 3000) {
// warnx("FRAME RESET\n\n");
}
uint8_t b = static_cast<uint8_t>(x);
last_time = f;
// Pipe the data into the parser
//hrt_abstime now = hrt_absolute_time();
uint8_t rssi;
uint8_t rx_count;
uint16_t channel_count;
uint16_t channels[32];
if (!sumd_decode(b, &rssi, &rx_count, &channel_count, channels, 32)) {
//PX4_INFO("decoded: %u channels (converted to PPM range)", (unsigned)channel_count);
for (unsigned i = 0; i < channel_count; i++) {
//int16_t val = channels[i];
//PX4_INFO("channel %u: %d 0x%03X", i, static_cast<int>(val), static_cast<int>(val));
}
}
}
ut_test(ret == EOF);
return true;
}
ut_declare_test_c(rc_tests_main, RCTest)
<|endoftext|> |
<commit_before>/* Copyright (C) Teemu Suutari */
#include <array>
#include "LZCBDecompressor.hpp"
#include "RangeDecoder.hpp"
#include "InputStream.hpp"
#include "OutputStream.hpp"
template<size_t T>
class FrequencyTree
{
public:
FrequencyTree()
{
for (uint32_t i=0;i<_size;i++)
_tree[i]=0;
}
~FrequencyTree()
{
// nothing needed
}
uint16_t decode(uint16_t value,uint16_t &low,uint16_t &freq) const
{
if (value>=_tree[_size-1])
throw Decompressor::DecompressionError();
uint16_t symbol=0;
low=0;
for (uint32_t i=_levels-2;;i--)
{
uint16_t tmp=_tree[_levelOffsets[i]+symbol];
if (uint32_t(symbol+1)<_levelSizes[i] && value>=tmp)
{
symbol++;
low+=tmp;
value-=tmp;
}
if (!i) break;
symbol<<=1;
}
freq=_tree[symbol];
return symbol;
}
bool exists(uint16_t symbol) const
{
return _tree[symbol];
}
void increment(uint16_t symbol)
{
for (uint16_t i=0;i<_levels;i++)
{
_tree[_levelOffsets[i]+symbol]++;
symbol>>=1;
}
}
void halve()
{
// non-standard way
for (uint32_t i=0;i<T;i++)
_tree[i]>>=1;
for (uint32_t i=T;i<_size;i++)
_tree[i]=0;
for (uint32_t i=0,length=T;i<_levels-1;i++,length=(length+1)>>1)
{
for (uint32_t j=0;j<length;j++)
_tree[_levelOffsets[i+1]+(j>>1)]+=_tree[_levelOffsets[i]+j];
}
}
uint32_t getTotal() const
{
return _tree[_size-1];
}
private:
static constexpr uint32_t levelSize(uint32_t level)
{
uint32_t ret=T;
for (uint32_t i=0;i<level;i++)
{
ret=(ret+1)>>1;
}
return ret;
}
static constexpr uint32_t levels()
{
uint32_t ret=0;
while (levelSize(ret)!=1) ret++;
return ret+1;
}
static constexpr uint32_t size()
{
uint32_t ret=0;
for (uint32_t i=0;i<levels();i++)
ret+=levelSize(i);
return ret;
}
static constexpr uint32_t levelOffset(uint32_t level)
{
uint32_t ret=0;
for (uint32_t i=0;i<level;i++)
ret+=levelSize(i);
return ret;
}
template<uint32_t... I>
static constexpr auto makeLevelOffsetSequence(std::integer_sequence<uint32_t,I...>)
{
return std::integer_sequence<uint32_t,levelOffset(I)...>{};
}
template<uint32_t... I>
static constexpr auto makeLevelSizeSequence(std::integer_sequence<uint32_t,I...>)
{
return std::integer_sequence<uint32_t,levelSize(I)...>{};
}
template<uint32_t... I>
static constexpr std::array<uint32_t,sizeof...(I)> makeArray(std::integer_sequence<uint32_t,I...>)
{
return std::array<uint32_t,sizeof...(I)>{{I...}};
}
static constexpr uint32_t _size=size();
static constexpr uint32_t _levels=levels();
static constexpr std::array<uint32_t,levels()> _levelOffsets=makeArray(makeLevelOffsetSequence(std::make_integer_sequence<uint32_t,levels()>{}));
static constexpr std::array<uint32_t,levels()> _levelSizes=makeArray(makeLevelSizeSequence(std::make_integer_sequence<uint32_t,levels()>{}));
uint16_t _tree[size()];
};
#if __cplusplus < 201703L
// difference on semantics on C++14 / C++17
template<size_t T>
constexpr std::array<uint32_t,FrequencyTree<T>::levels()> FrequencyTree<T>::_levelOffsets;
template<size_t T>
constexpr std::array<uint32_t,FrequencyTree<T>::levels()> FrequencyTree<T>::_levelSizes;
#endif
template<size_t T>
class FrequencyDecoder
{
public:
FrequencyDecoder(RangeDecoder &decoder) :
_decoder(decoder)
{
// nothing needed
}
~FrequencyDecoder()
{
// nothing needed
}
template<typename F>
uint16_t decode(F readFunc)
{
uint16_t freq=0,symbol,value=_decoder.decode(_threshold+_tree.getTotal());
if (value>=_threshold)
{
uint16_t low;
symbol=_tree.decode(value-_threshold,low,freq);
_decoder.scale(_threshold+low,_threshold+low+freq,_threshold+_tree.getTotal());
if (freq==1 && _threshold>1)
_threshold--;
} else {
_decoder.scale(0,_threshold,_threshold+_tree.getTotal());
symbol=readFunc();
// A bug in the encoder
if (!symbol && _tree.exists(symbol)) symbol=T;
_threshold++;
}
_tree.increment(symbol);
if (_threshold+_tree.getTotal()>=0x3ffdU)
{
_tree.halve();
_threshold=(_threshold>>1)+1;
}
return symbol;
}
private:
RangeDecoder &_decoder;
FrequencyTree<T+1> _tree;
uint16_t _threshold=1;
};
bool LZCBDecompressor::detectHeaderXPK(uint32_t hdr) noexcept
{
return hdr==FourCC("LZCB");
}
std::unique_ptr<XPKDecompressor> LZCBDecompressor::create(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::unique_ptr<XPKDecompressor::State> &state,bool verify)
{
return std::make_unique<LZCBDecompressor>(hdr,recursionLevel,packedData,state,verify);
}
LZCBDecompressor::LZCBDecompressor(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::unique_ptr<XPKDecompressor::State> &state,bool verify) :
XPKDecompressor(recursionLevel),
_packedData(packedData)
{
if (packedData.size()<2) throw Decompressor::InvalidFormatError();
}
LZCBDecompressor::~LZCBDecompressor()
{
// nothing needed
}
const std::string &LZCBDecompressor::getSubName() const noexcept
{
static std::string name="XPK-LZCB: LZ-compressor";
return name;
}
void LZCBDecompressor::decompressImpl(Buffer &rawData,const Buffer &previousData,bool verify)
{
class BitReader : public RangeDecoder::BitReader
{
public:
BitReader(ForwardInputStream &stream) :
_reader(stream)
{
// nothing needed
}
virtual ~BitReader()
{
// nothing needed
}
virtual uint32_t readBit() override final
{
return _reader.readBitsBE32(1);
}
uint32_t readBits(uint32_t bitCount)
{
return _reader.readBitsBE32(bitCount);
}
private:
MSBBitReader<ForwardInputStream> _reader;
};
ForwardInputStream inputStream(_packedData,0,_packedData.size(),true);
ForwardOutputStream outputStream(rawData,0,rawData.size());
BitReader bitReader(inputStream);
RangeDecoder rangeDecoder(bitReader,bitReader.readBits(16));
// Ugly duplicates
auto readByte=[&]()->uint16_t
{
uint16_t ret=rangeDecoder.decode(0x100U);
rangeDecoder.scale(ret,ret+1,0x100U);
return ret;
};
auto readCount=[&]()->uint16_t
{
uint16_t ret=rangeDecoder.decode(0x101U);
rangeDecoder.scale(ret,ret+1,0x101U);
return ret;
};
FrequencyDecoder<256> baseLiteralDecoder(rangeDecoder);
FrequencyDecoder<257> repeatCountDecoder(rangeDecoder);
FrequencyDecoder<257> literalCountDecoder(rangeDecoder);
FrequencyDecoder<256> distanceDecoder(rangeDecoder);
std::unique_ptr<FrequencyDecoder<256>> literalDecoders[256];
uint8_t ch=baseLiteralDecoder.decode(readByte);
outputStream.writeByte(ch);
bool lastIsLiteral=true;
while (!outputStream.eof())
{
uint32_t count=repeatCountDecoder.decode(readCount);
if (count)
{
if (count==0x100U)
{
uint32_t tmp;
do
{
tmp=readByte();
count+=tmp;
} while (tmp==0xffU);
}
count+=lastIsLiteral?5:4;
uint32_t distance=distanceDecoder.decode(readByte)<<8;
distance|=readByte();
ch=outputStream.copy(distance,count);
lastIsLiteral=false;
} else {
uint16_t literalCount;
do
{
literalCount=literalCountDecoder.decode(readCount);
if (!literalCount) throw Decompressor::DecompressionError();
for (uint32_t i=0;i<literalCount;i++)
{
auto &literalDecoder=literalDecoders[ch];
if (!literalDecoder) literalDecoder=std::make_unique<FrequencyDecoder<256>>(rangeDecoder);
ch=literalDecoder->decode([&]()
{
return baseLiteralDecoder.decode(readByte);
});
outputStream.writeByte(ch);
}
} while (literalCount==0x100U);
lastIsLiteral=true;
}
}
}
XPKDecompressor::Registry<LZCBDecompressor> LZCBDecompressor::_XPKregistration;
<commit_msg>MSVC support. Dropping c++14 compatibility<commit_after>/* Copyright (C) Teemu Suutari */
#include <array>
#include "LZCBDecompressor.hpp"
#include "RangeDecoder.hpp"
#include "InputStream.hpp"
#include "OutputStream.hpp"
template<size_t T>
class FrequencyTree
{
public:
FrequencyTree()
{
for (uint32_t i=0;i<_size;i++)
_tree[i]=0;
}
~FrequencyTree()
{
// nothing needed
}
uint16_t decode(uint16_t value,uint16_t &low,uint16_t &freq) const
{
if (value>=_tree[_size-1])
throw Decompressor::DecompressionError();
uint16_t symbol=0;
low=0;
for (uint32_t i=_levels-2;;i--)
{
uint16_t tmp=_tree[_levelOffsets[i]+symbol];
if (uint32_t(symbol+1)<_levelSizes[i] && value>=tmp)
{
symbol++;
low+=tmp;
value-=tmp;
}
if (!i) break;
symbol<<=1;
}
freq=_tree[symbol];
return symbol;
}
bool exists(uint16_t symbol) const
{
return _tree[symbol];
}
void increment(uint16_t symbol)
{
for (uint16_t i=0;i<_levels;i++)
{
_tree[_levelOffsets[i]+symbol]++;
symbol>>=1;
}
}
void halve()
{
// non-standard way
for (uint32_t i=0;i<T;i++)
_tree[i]>>=1;
for (uint32_t i=T;i<_size;i++)
_tree[i]=0;
for (uint32_t i=0,length=T;i<_levels-1;i++,length=(length+1)>>1)
{
for (uint32_t j=0;j<length;j++)
_tree[_levelOffsets[i+1]+(j>>1)]+=_tree[_levelOffsets[i]+j];
}
}
uint32_t getTotal() const
{
return _tree[_size-1];
}
private:
static constexpr uint32_t levelSize(uint32_t level)
{
uint32_t ret=T;
for (uint32_t i=0;i<level;i++)
{
ret=(ret+1)>>1;
}
return ret;
}
static constexpr uint32_t levels()
{
uint32_t ret=0;
while (levelSize(ret)!=1) ret++;
return ret+1;
}
static constexpr uint32_t size()
{
uint32_t ret=0;
for (uint32_t i=0;i<levels();i++)
ret+=levelSize(i);
return ret;
}
static constexpr uint32_t levelOffset(uint32_t level)
{
uint32_t ret=0;
for (uint32_t i=0;i<level;i++)
ret+=levelSize(i);
return ret;
}
template<uint32_t... I>
static constexpr auto makeLevelOffsetSequence(std::integer_sequence<uint32_t,I...>)
{
return std::integer_sequence<uint32_t,levelOffset(I)...>{};
}
template<uint32_t... I>
static constexpr auto makeLevelSizeSequence(std::integer_sequence<uint32_t,I...>)
{
return std::integer_sequence<uint32_t,levelSize(I)...>{};
}
template<uint32_t... I>
static constexpr std::array<uint32_t,sizeof...(I)> makeArray(std::integer_sequence<uint32_t,I...>)
{
return std::array<uint32_t,sizeof...(I)>{{I...}};
}
static constexpr uint32_t _size=size();
static constexpr uint32_t _levels=levels();
static constexpr std::array<uint32_t,_levels> _levelOffsets=makeArray(makeLevelOffsetSequence(std::make_integer_sequence<uint32_t,levels()>{}));
static constexpr std::array<uint32_t,_levels> _levelSizes=makeArray(makeLevelSizeSequence(std::make_integer_sequence<uint32_t,levels()>{}));
uint16_t _tree[size()];
};
template<size_t T>
class FrequencyDecoder
{
public:
FrequencyDecoder(RangeDecoder &decoder) :
_decoder(decoder)
{
// nothing needed
}
~FrequencyDecoder()
{
// nothing needed
}
template<typename F>
uint16_t decode(F readFunc)
{
uint16_t freq=0,symbol,value=_decoder.decode(_threshold+_tree.getTotal());
if (value>=_threshold)
{
uint16_t low;
symbol=_tree.decode(value-_threshold,low,freq);
_decoder.scale(_threshold+low,_threshold+low+freq,_threshold+_tree.getTotal());
if (freq==1 && _threshold>1)
_threshold--;
} else {
_decoder.scale(0,_threshold,_threshold+_tree.getTotal());
symbol=readFunc();
// A bug in the encoder
if (!symbol && _tree.exists(symbol)) symbol=T;
_threshold++;
}
_tree.increment(symbol);
if (_threshold+_tree.getTotal()>=0x3ffdU)
{
_tree.halve();
_threshold=(_threshold>>1)+1;
}
return symbol;
}
private:
RangeDecoder &_decoder;
FrequencyTree<T+1> _tree;
uint16_t _threshold=1;
};
bool LZCBDecompressor::detectHeaderXPK(uint32_t hdr) noexcept
{
return hdr==FourCC("LZCB");
}
std::unique_ptr<XPKDecompressor> LZCBDecompressor::create(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::unique_ptr<XPKDecompressor::State> &state,bool verify)
{
return std::make_unique<LZCBDecompressor>(hdr,recursionLevel,packedData,state,verify);
}
LZCBDecompressor::LZCBDecompressor(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::unique_ptr<XPKDecompressor::State> &state,bool verify) :
XPKDecompressor(recursionLevel),
_packedData(packedData)
{
if (packedData.size()<2) throw Decompressor::InvalidFormatError();
}
LZCBDecompressor::~LZCBDecompressor()
{
// nothing needed
}
const std::string &LZCBDecompressor::getSubName() const noexcept
{
static std::string name="XPK-LZCB: LZ-compressor";
return name;
}
void LZCBDecompressor::decompressImpl(Buffer &rawData,const Buffer &previousData,bool verify)
{
class BitReader : public RangeDecoder::BitReader
{
public:
BitReader(ForwardInputStream &stream) :
_reader(stream)
{
// nothing needed
}
virtual ~BitReader()
{
// nothing needed
}
virtual uint32_t readBit() override final
{
return _reader.readBitsBE32(1);
}
uint32_t readBits(uint32_t bitCount)
{
return _reader.readBitsBE32(bitCount);
}
private:
MSBBitReader<ForwardInputStream> _reader;
};
ForwardInputStream inputStream(_packedData,0,_packedData.size(),true);
ForwardOutputStream outputStream(rawData,0,rawData.size());
BitReader bitReader(inputStream);
RangeDecoder rangeDecoder(bitReader,bitReader.readBits(16));
// Ugly duplicates
auto readByte=[&]()->uint16_t
{
uint16_t ret=rangeDecoder.decode(0x100U);
rangeDecoder.scale(ret,ret+1,0x100U);
return ret;
};
auto readCount=[&]()->uint16_t
{
uint16_t ret=rangeDecoder.decode(0x101U);
rangeDecoder.scale(ret,ret+1,0x101U);
return ret;
};
FrequencyDecoder<256> baseLiteralDecoder(rangeDecoder);
FrequencyDecoder<257> repeatCountDecoder(rangeDecoder);
FrequencyDecoder<257> literalCountDecoder(rangeDecoder);
FrequencyDecoder<256> distanceDecoder(rangeDecoder);
std::unique_ptr<FrequencyDecoder<256>> literalDecoders[256];
uint8_t ch=baseLiteralDecoder.decode(readByte);
outputStream.writeByte(ch);
bool lastIsLiteral=true;
while (!outputStream.eof())
{
uint32_t count=repeatCountDecoder.decode(readCount);
if (count)
{
if (count==0x100U)
{
uint32_t tmp;
do
{
tmp=readByte();
count+=tmp;
} while (tmp==0xffU);
}
count+=lastIsLiteral?5:4;
uint32_t distance=distanceDecoder.decode(readByte)<<8;
distance|=readByte();
ch=outputStream.copy(distance,count);
lastIsLiteral=false;
} else {
uint16_t literalCount;
do
{
literalCount=literalCountDecoder.decode(readCount);
if (!literalCount) throw Decompressor::DecompressionError();
for (uint32_t i=0;i<literalCount;i++)
{
auto &literalDecoder=literalDecoders[ch];
if (!literalDecoder) literalDecoder=std::make_unique<FrequencyDecoder<256>>(rangeDecoder);
ch=literalDecoder->decode([&]()
{
return baseLiteralDecoder.decode(readByte);
});
outputStream.writeByte(ch);
}
} while (literalCount==0x100U);
lastIsLiteral=true;
}
}
}
XPKDecompressor::Registry<LZCBDecompressor> LZCBDecompressor::_XPKregistration;
<|endoftext|> |
<commit_before>#include "dp.h"
#include <memory>
DynamicParallelism::DynamicParallelism()
{
runtime = clRuntime::getInstance();
file = clFile::getInstance();
platform = runtime->getPlatformID();
device = runtime->getDevice();
context = runtime->getContext();
cmdQueue = runtime->getCmdQueue(0);
glbSize = 8192;
locSize = 256;
factor = 2.3f;
init();
}
DynamicParallelism::~DynamicParallelism()
{
clean();
}
void DynamicParallelism::init()
{
initKernel();
initBuffer();
}
void DynamicParallelism::initKernel()
{
cl_int err;
// Open kernel file
file->open("dp_Kernels.cl");
// Create program
const char *source = file->getSourceChar();
program = clCreateProgramWithSource(context, 1,
(const char **)&source, NULL, &err);
checkOpenCLErrors(err, "Failed to create Program with source\n");
// Create program with OpenCL 2.0 support
err = clBuildProgram(program, 0, NULL, "-I. -cl-std=CL2.0", NULL, NULL);
checkOpenCLErrors(err, "Failed to build program...\n");
// Create kernels
kernel_saxpy_naive = clCreateKernel(program, "saxpy_naive", &err);
checkOpenCLErrors(err, "Failed to create saxpy_naive kernel");
kernel_saxpy_stride = clCreateKernel(program, "saxpy_stride", &err);
checkOpenCLErrors(err, "Failed to create saxpy_stride kernel");
kernel_saxpy_dp = clCreateKernel(program, "saxpy_dp", &err);
checkOpenCLErrors(err, "Failed to create saxpy_dp kernel");
}
void DynamicParallelism::initBuffer()
{
cl_int err;
size_t glbSizeBytes = glbSize * sizeof(float);
saxpy_src_0 = (float *)clSVMAlloc(context, CL_MEM_READ_ONLY, glbSizeBytes, 0);
saxpy_src_1 = (float *)clSVMAlloc(context, CL_MEM_READ_ONLY, glbSizeBytes, 0);
saxpy_dst_0 = (float *)clSVMAlloc(context, CL_MEM_READ_WRITE, glbSizeBytes, 0);
// Map SVM buffers
err = clEnqueueSVMMap(cmdQueue, true, CL_MEM_READ_WRITE, saxpy_src_0, glbSizeBytes, 0, NULL, NULL);
err |= clEnqueueSVMMap(cmdQueue, true, CL_MEM_READ_WRITE, saxpy_src_1, glbSizeBytes, 0, NULL, NULL);
checkOpenCLErrors(err, "Failed to map SVM buffers for initialization");
// Initialize buffers
for (int i = 0; i < glbSize; ++i)
{
saxpy_src_0[i] = (float)i;
saxpy_src_1[i] = (float)i;
}
// Unmap SVM buffers
err = clEnqueueSVMUnmap(cmdQueue, saxpy_src_0, 0, NULL, NULL);
err |= clEnqueueSVMUnmap(cmdQueue, saxpy_src_1, 0, NULL, NULL);
checkOpenCLErrors(err, "Failed to unmap SVM buffers after initialization");
}
void DynamicParallelism::clean()
{
cleanKernel();
cleanBuffer();
}
void DynamicParallelism::cleanKernel()
{
cl_int err;
err = clReleaseKernel(kernel_saxpy_naive);
err |= clReleaseKernel(kernel_saxpy_stride);
err |= clReleaseKernel(kernel_saxpy_dp);
checkOpenCLErrors(err, "Failed to release kernels");
err = clReleaseProgram(program);
checkOpenCLErrors(err, "Failed to release program");
}
void DynamicParallelism::cleanBuffer()
{
clSVMFreeSafe(context, saxpy_src_0);
clSVMFreeSafe(context, saxpy_src_1);
clSVMFreeSafe(context, saxpy_dst_0);
}
void DynamicParallelism::runNaive()
{
cl_int err;
size_t globalSize = glbSize;
size_t localSize = locSize;
err = clSetKernelArg(kernel_saxpy_naive, 0, sizeof(int), (void *)&glbSize);
err |= clSetKernelArg(kernel_saxpy_naive, 1, sizeof(int), (void *)&factor);
err |= clSetKernelArgSVMPointer(kernel_saxpy_naive, 2, saxpy_src_0);
err |= clSetKernelArgSVMPointer(kernel_saxpy_naive, 3, saxpy_src_1);
err |= clSetKernelArgSVMPointer(kernel_saxpy_naive, 4, saxpy_dst_0);
checkOpenCLErrors(err, "Failed to set args in saxpy_naive kernel");
err = clEnqueueNDRangeKernel(
cmdQueue,
kernel_saxpy_naive,
1,
0, &globalSize, &localSize,
0, 0, 0
);
checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel");
}
void DynamicParallelism::runStride()
{
}
void DynamicParallelism::runDP()
{
}
int main(int argc, char const *argv[])
{
std::unique_ptr<DynamicParallelism> dp(new DynamicParallelism());
dp->runNaive();
dp->runStride();
dp->runDP();
printf("Done!\n");
return 0;
}<commit_msg>Result check<commit_after>#include "dp.h"
#include <memory>
DynamicParallelism::DynamicParallelism()
{
runtime = clRuntime::getInstance();
file = clFile::getInstance();
platform = runtime->getPlatformID();
device = runtime->getDevice();
context = runtime->getContext();
cmdQueue = runtime->getCmdQueue(0);
glbSize = 8192;
locSize = 256;
factor = 2.3f;
init();
}
DynamicParallelism::~DynamicParallelism()
{
clean();
}
void DynamicParallelism::init()
{
initKernel();
initBuffer();
}
void DynamicParallelism::initKernel()
{
cl_int err;
// Open kernel file
file->open("dp_Kernels.cl");
// Create program
const char *source = file->getSourceChar();
program = clCreateProgramWithSource(context, 1,
(const char **)&source, NULL, &err);
checkOpenCLErrors(err, "Failed to create Program with source\n");
// Create program with OpenCL 2.0 support
err = clBuildProgram(program, 0, NULL, "-I. -cl-std=CL2.0", NULL, NULL);
checkOpenCLErrors(err, "Failed to build program...\n");
// Create kernels
kernel_saxpy_naive = clCreateKernel(program, "saxpy_naive", &err);
checkOpenCLErrors(err, "Failed to create saxpy_naive kernel");
kernel_saxpy_stride = clCreateKernel(program, "saxpy_stride", &err);
checkOpenCLErrors(err, "Failed to create saxpy_stride kernel");
kernel_saxpy_dp = clCreateKernel(program, "saxpy_dp", &err);
checkOpenCLErrors(err, "Failed to create saxpy_dp kernel");
}
void DynamicParallelism::initBuffer()
{
cl_int err;
size_t glbSizeBytes = glbSize * sizeof(float);
saxpy_src_0 = (float *)clSVMAlloc(context, CL_MEM_READ_ONLY, glbSizeBytes, 0);
saxpy_src_1 = (float *)clSVMAlloc(context, CL_MEM_READ_ONLY, glbSizeBytes, 0);
saxpy_dst_0 = (float *)clSVMAlloc(context, CL_MEM_READ_WRITE, glbSizeBytes, 0);
// Map SVM buffers
err = clEnqueueSVMMap(cmdQueue, true, CL_MEM_READ_WRITE, saxpy_src_0, glbSizeBytes, 0, NULL, NULL);
err |= clEnqueueSVMMap(cmdQueue, true, CL_MEM_READ_WRITE, saxpy_src_1, glbSizeBytes, 0, NULL, NULL);
checkOpenCLErrors(err, "Failed to map SVM buffers for initialization");
// Initialize buffers
for (int i = 0; i < glbSize; ++i)
{
saxpy_src_0[i] = (float)i;
saxpy_src_1[i] = (float)i;
}
// Unmap SVM buffers
err = clEnqueueSVMUnmap(cmdQueue, saxpy_src_0, 0, NULL, NULL);
err |= clEnqueueSVMUnmap(cmdQueue, saxpy_src_1, 0, NULL, NULL);
checkOpenCLErrors(err, "Failed to unmap SVM buffers after initialization");
}
void DynamicParallelism::clean()
{
cleanKernel();
cleanBuffer();
}
void DynamicParallelism::cleanKernel()
{
cl_int err;
err = clReleaseKernel(kernel_saxpy_naive);
err |= clReleaseKernel(kernel_saxpy_stride);
err |= clReleaseKernel(kernel_saxpy_dp);
checkOpenCLErrors(err, "Failed to release kernels");
err = clReleaseProgram(program);
checkOpenCLErrors(err, "Failed to release program");
}
void DynamicParallelism::cleanBuffer()
{
clSVMFreeSafe(context, saxpy_src_0);
clSVMFreeSafe(context, saxpy_src_1);
clSVMFreeSafe(context, saxpy_dst_0);
}
void DynamicParallelism::runNaive()
{
cl_int err;
size_t globalSize = glbSize;
size_t localSize = locSize;
err = clSetKernelArg(kernel_saxpy_naive, 0, sizeof(int), (void *)&glbSize);
err |= clSetKernelArg(kernel_saxpy_naive, 1, sizeof(int), (void *)&factor);
err |= clSetKernelArgSVMPointer(kernel_saxpy_naive, 2, saxpy_src_0);
err |= clSetKernelArgSVMPointer(kernel_saxpy_naive, 3, saxpy_src_1);
err |= clSetKernelArgSVMPointer(kernel_saxpy_naive, 4, saxpy_dst_0);
checkOpenCLErrors(err, "Failed to set args in saxpy_naive kernel");
err = clEnqueueNDRangeKernel(
cmdQueue,
kernel_saxpy_naive,
1,
0, &globalSize, &localSize,
0, 0, 0
);
checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel");
// Map SVM buffers
size_t glbSizeBytes = glbSize * sizeof(float);
err = clEnqueueSVMMap(cmdQueue, true, CL_MEM_READ_ONLY, saxpy_dst_0, glbSizeBytes, 0, NULL, NULL);
checkOpenCLErrors(err, "Failed to map SVM buffers for checking result");
// Check result
for (int i = 0; i < glbSize / locSize; ++i)
printf("%f\n", saxpy_dst_0[i]);
// Unmap SVM buffers
err = clEnqueueSVMUnmap(cmdQueue, saxpy_src_0, 0, NULL, NULL);
err |= clEnqueueSVMUnmap(cmdQueue, saxpy_src_1, 0, NULL, NULL);
checkOpenCLErrors(err, "Failed to unmap SVM buffers after checking result");
}
void DynamicParallelism::runStride()
{
}
void DynamicParallelism::runDP()
{
}
int main(int argc, char const *argv[])
{
std::unique_ptr<DynamicParallelism> dp(new DynamicParallelism());
printf("Running...\n");
dp->runNaive();
dp->runStride();
dp->runDP();
printf("Done!\n");
return 0;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: pe_tpltp.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2005-01-27 11:24:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef ADC_CPP_PE_TPLTP_HXX
#define ADC_CPP_PE_TPLTP_HXX
// USED SERVICES
// BASE CLASSES
#include "cpp_pe.hxx"
// COMPONENTS
#include <semantic/callf.hxx>
#include <semantic/sub_peu.hxx>
// PARAMETERS
namespace cpp {
class PE_TemplateTop : public cpp::Cpp_PE
{
public:
enum E_State
{
start,
expect_qualifier,
expect_name,
expect_separator,
size_of_states
};
PE_TemplateTop(
Cpp_PE * i_pParent );
~PE_TemplateTop();
const StringVector &
Result_Parameters() const;
virtual void Call_Handler(
const cpp::Token & i_rTok );
private:
void Setup_StatusFunctions();
virtual void InitData();
virtual void TransferData();
void Hdl_SyntaxError(const char *);
void On_start_Less(const char *);
void On_expect_qualifier_ClassOrTypename(const char *);
void On_expect_qualifier_Other(const char *);
void On_expect_name_Identifier(const char *);
void On_expect_separator_Comma(const char *);
void On_expect_separator_Greater(const char *);
// DATA
Dyn< PeStatusArray<PE_TemplateTop> >
pStati;
StringVector
aResult_Parameters;
bool bCurIsConstant;
};
// IMPLEMENTATION
inline const StringVector &
PE_TemplateTop::Result_Parameters() const
{ return aResult_Parameters; }
} // namespace cpp
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.16); FILE MERGED 2005/09/05 13:11:49 rt 1.2.16.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_tpltp.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:29:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_CPP_PE_TPLTP_HXX
#define ADC_CPP_PE_TPLTP_HXX
// USED SERVICES
// BASE CLASSES
#include "cpp_pe.hxx"
// COMPONENTS
#include <semantic/callf.hxx>
#include <semantic/sub_peu.hxx>
// PARAMETERS
namespace cpp {
class PE_TemplateTop : public cpp::Cpp_PE
{
public:
enum E_State
{
start,
expect_qualifier,
expect_name,
expect_separator,
size_of_states
};
PE_TemplateTop(
Cpp_PE * i_pParent );
~PE_TemplateTop();
const StringVector &
Result_Parameters() const;
virtual void Call_Handler(
const cpp::Token & i_rTok );
private:
void Setup_StatusFunctions();
virtual void InitData();
virtual void TransferData();
void Hdl_SyntaxError(const char *);
void On_start_Less(const char *);
void On_expect_qualifier_ClassOrTypename(const char *);
void On_expect_qualifier_Other(const char *);
void On_expect_name_Identifier(const char *);
void On_expect_separator_Comma(const char *);
void On_expect_separator_Greater(const char *);
// DATA
Dyn< PeStatusArray<PE_TemplateTop> >
pStati;
StringVector
aResult_Parameters;
bool bCurIsConstant;
};
// IMPLEMENTATION
inline const StringVector &
PE_TemplateTop::Result_Parameters() const
{ return aResult_Parameters; }
} // namespace cpp
#endif
<|endoftext|> |
<commit_before>#include <string.h>
#include <node.h>
#include <node_buffer.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/ecdh.h>
#include "eckey.h"
using namespace v8;
using namespace node;
static Handle<Value> V8Exception(const char* msg) {
HandleScope scope;
return ThrowException(Exception::Error(String::New(msg)));
}
// Not sure where this came from. but looks like a function that should be part of openssl
int static inline EC_KEY_regenerate_key(EC_KEY *eckey, const BIGNUM *priv_key) {
if (!eckey) return 0;
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey, priv_key);
EC_KEY_set_public_key(eckey, pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return ok;
}
ECKey::ECKey(int curve) {
mHasPrivateKey = false;
mCurve = curve;
mKey = EC_KEY_new_by_curve_name(mCurve);
if (!mKey) {
V8Exception("EC_KEY_new_by_curve_name Invalid curve?");
return;
}
}
ECKey::~ECKey() {
if (mKey) {
EC_KEY_free(mKey);
}
}
// Node module init
void ECKey::Init(Handle<Object> exports) {
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("ECKey"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
//Accessors
tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("HasPrivateKey"), GetHasPrivateKey);
tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PublicKey"), GetPublicKey);
tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PrivateKey"), GetPrivateKey);
//Methods (Prototype)
tpl->PrototypeTemplate()->Set(String::NewSymbol("sign"), FunctionTemplate::New(Sign)->GetFunction());
tpl->PrototypeTemplate()->Set(String::NewSymbol("verifySignature"), FunctionTemplate::New(VerifySignature)->GetFunction());
tpl->PrototypeTemplate()->Set(String::NewSymbol("deriveSharedSecret"), FunctionTemplate::New(DeriveSharedSecret)->GetFunction());
Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
exports->Set(String::NewSymbol("ECKey"), constructor);
}
// Node constructor function
// new ECKey(curve, buffer, isPrivate)
Handle<Value> ECKey::New(const Arguments &args) {
if (!args.IsConstructCall()) {
return V8Exception("Must use new keyword");
}
if (args[0]->IsUndefined()) {
return V8Exception("First argument must be an ECCurve");
}
HandleScope scope;
ECKey *eckey = new ECKey(args[0]->NumberValue());
if (!args[1]->IsUndefined()) {
//we have a second parameter, check the third to see if it is public or private.
if (!Buffer::HasInstance(args[1])) {
return V8Exception("Second parameter must be a buffer");
}
Handle<Object> buffer = args[1]->ToObject();
const unsigned char *bufferData = (unsigned char *) Buffer::Data(buffer);
if ((args[2]->IsUndefined()) || (args[2]->BooleanValue() == false)) {
// it's a private key
BIGNUM *bn = BN_bin2bn(bufferData, Buffer::Length(buffer), BN_new());
if (EC_KEY_regenerate_key(eckey->mKey, bn) == 0) {
BN_clear_free(bn);
return V8Exception("Invalid private key");
}
BN_clear_free(bn);
eckey->mHasPrivateKey = true;
} else {
// it's a public key
if (!o2i_ECPublicKey(&(eckey->mKey), &bufferData, Buffer::Length(buffer))) {
return V8Exception("o2i_ECPublicKey failed");
}
}
} else {
if (!EC_KEY_generate_key(eckey->mKey)) {
return V8Exception("EC_KEY_generate_key failed");
}
eckey->mHasPrivateKey = true;
}
eckey->Wrap(args.Holder());
return args.Holder();
}
// Node properity functions
Handle<Value> ECKey::GetHasPrivateKey(Local<String> property, const AccessorInfo &info) {
HandleScope scope;
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder());
return scope.Close(Boolean::New(eckey->mHasPrivateKey));
}
Handle<Value> ECKey::GetPublicKey(Local<String> property, const AccessorInfo &info) {
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder());
const EC_GROUP *group = EC_KEY_get0_group(eckey->mKey);
const EC_POINT *point = EC_KEY_get0_public_key(eckey->mKey);
unsigned int nReq = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL);
if (!nReq) {
return V8Exception("EC_POINT_point2oct error");
}
unsigned char *buf, *buf2;
buf = buf2 = (unsigned char *)malloc(nReq);
if (EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, buf, nReq, NULL) != nReq) {
return V8Exception("EC_POINT_point2oct didn't return correct size");
}
HandleScope scope;
Buffer *buffer = Buffer::New(nReq);
memcpy(Buffer::Data(buffer), buf2, nReq);
free(buf2);
return scope.Close(buffer->handle_);
}
Handle<Value> ECKey::GetPrivateKey(Local<String> property, const AccessorInfo &info) {
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder());
const BIGNUM *bn = EC_KEY_get0_private_key(eckey->mKey);
if (bn == NULL) {
return V8Exception("EC_KEY_get0_private_key failed");
}
int priv_size = BN_num_bytes(bn);
unsigned char *priv_buf = (unsigned char *)malloc(priv_size);
int n = BN_bn2bin(bn, priv_buf);
if (n != priv_size) {
return V8Exception("BN_bn2bin didn't return priv_size");
}
HandleScope scope;
Buffer *buffer = Buffer::New(priv_size);
memcpy(Buffer::Data(buffer), priv_buf, priv_size);
free(priv_buf);
return scope.Close(buffer->handle_);
}
// Node method functions
Handle<Value> ECKey::Sign(const Arguments &args) {
HandleScope scope;
ECKey * eckey = ObjectWrap::Unwrap<ECKey>(args.Holder());
if (!Buffer::HasInstance(args[0])) {
return V8Exception("digest must be a buffer");
}
if (!eckey->mHasPrivateKey) {
return V8Exception("cannot sign without private key");
}
Handle<Object> digest = args[0]->ToObject();
const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest);
unsigned int digest_len = Buffer::Length(digest);
ECDSA_SIG *sig = ECDSA_do_sign(digest_data, digest_len, eckey->mKey);
if (!sig) {
return V8Exception("ECDSA_do_sign");
}
int sig_len = i2d_ECDSA_SIG(sig, NULL);
if (!sig_len) {
return V8Exception("i2d_ECDSA_SIG");
}
unsigned char *sig_data, *sig_data2;
sig_data = sig_data2 = (unsigned char *)malloc(sig_len);
if (i2d_ECDSA_SIG(sig, &sig_data) != sig_len) {
ECDSA_SIG_free(sig);
free(sig_data2);
return V8Exception("i2d_ECDSA_SIG didnot return correct length");
}
ECDSA_SIG_free(sig);
Buffer *result = Buffer::New(sig_len);
memcpy(Buffer::Data(result), sig_data2, sig_len);
free(sig_data2);
return scope.Close(result->handle_);
}
Handle<Value> ECKey::VerifySignature(const Arguments &args) {
HandleScope scope;
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder());
if (!Buffer::HasInstance(args[0])) {
return V8Exception("digest must be a buffer");
}
if (!Buffer::HasInstance(args[1])) {
return V8Exception("signature must be a buffer");
}
Handle<Object> digest = args[0]->ToObject();
Handle<Object> signature = args[1]->ToObject();
const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest);
const unsigned char *signature_data = (unsigned char *)Buffer::Data(signature);
unsigned int digest_len = Buffer::Length(digest);
unsigned int signature_len = Buffer::Length(signature);
int result = ECDSA_verify(0, digest_data, digest_len, signature_data, signature_len, eckey->mKey);
if (result == -1) {
return V8Exception("ECDSA_verify");
} else if (result == 0) {
return scope.Close(Boolean::New(false));
} else if (result == 1) {
return scope.Close(Boolean::New(true));
} else {
return V8Exception("ECDSA_verify gave an unexpected return value");
}
}
Handle<Value> ECKey::DeriveSharedSecret(const Arguments &args) {
HandleScope scope;
if (args[0]->IsUndefined()) {
return V8Exception("other is required");
}
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder());
ECKey *other = ObjectWrap::Unwrap<ECKey>(args[0]->ToObject());
if (!other) {
return V8Exception("other must be an ECKey");
}
unsigned char *secret = (unsigned char*)malloc(512);
int len = ECDH_compute_key(secret, 512, EC_KEY_get0_public_key(other->mKey), eckey->mKey, NULL);
Buffer *result = Buffer::New(len);
memcpy(Buffer::Data(result), secret, len);
free(secret);
return scope.Close(result->handle_);
}
<commit_msg>correct incorrect comment<commit_after>#include <string.h>
#include <node.h>
#include <node_buffer.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/ecdh.h>
#include "eckey.h"
using namespace v8;
using namespace node;
static Handle<Value> V8Exception(const char* msg) {
HandleScope scope;
return ThrowException(Exception::Error(String::New(msg)));
}
// Not sure where this came from. but looks like a function that should be part of openssl
int static inline EC_KEY_regenerate_key(EC_KEY *eckey, const BIGNUM *priv_key) {
if (!eckey) return 0;
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey, priv_key);
EC_KEY_set_public_key(eckey, pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return ok;
}
ECKey::ECKey(int curve) {
mHasPrivateKey = false;
mCurve = curve;
mKey = EC_KEY_new_by_curve_name(mCurve);
if (!mKey) {
V8Exception("EC_KEY_new_by_curve_name Invalid curve?");
return;
}
}
ECKey::~ECKey() {
if (mKey) {
EC_KEY_free(mKey);
}
}
// Node module init
void ECKey::Init(Handle<Object> exports) {
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("ECKey"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
//Accessors
tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("HasPrivateKey"), GetHasPrivateKey);
tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PublicKey"), GetPublicKey);
tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PrivateKey"), GetPrivateKey);
//Methods (Prototype)
tpl->PrototypeTemplate()->Set(String::NewSymbol("sign"), FunctionTemplate::New(Sign)->GetFunction());
tpl->PrototypeTemplate()->Set(String::NewSymbol("verifySignature"), FunctionTemplate::New(VerifySignature)->GetFunction());
tpl->PrototypeTemplate()->Set(String::NewSymbol("deriveSharedSecret"), FunctionTemplate::New(DeriveSharedSecret)->GetFunction());
Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
exports->Set(String::NewSymbol("ECKey"), constructor);
}
// Node constructor function
// new ECKey(curve, buffer, isPublic)
Handle<Value> ECKey::New(const Arguments &args) {
if (!args.IsConstructCall()) {
return V8Exception("Must use new keyword");
}
if (args[0]->IsUndefined()) {
return V8Exception("First argument must be an ECCurve");
}
HandleScope scope;
ECKey *eckey = new ECKey(args[0]->NumberValue());
if (!args[1]->IsUndefined()) {
if (!Buffer::HasInstance(args[1])) {
return V8Exception("Second parameter must be a buffer");
}
//we have a second parameter, check the third to see if it is public or private.
Handle<Object> buffer = args[1]->ToObject();
const unsigned char *bufferData = (unsigned char *) Buffer::Data(buffer);
if ((args[2]->IsUndefined()) || (args[2]->BooleanValue() == false)) {
// it's a private key
BIGNUM *bn = BN_bin2bn(bufferData, Buffer::Length(buffer), BN_new());
if (EC_KEY_regenerate_key(eckey->mKey, bn) == 0) {
BN_clear_free(bn);
return V8Exception("Invalid private key");
}
BN_clear_free(bn);
eckey->mHasPrivateKey = true;
} else {
// it's a public key
if (!o2i_ECPublicKey(&(eckey->mKey), &bufferData, Buffer::Length(buffer))) {
return V8Exception("o2i_ECPublicKey failed");
}
}
} else {
if (!EC_KEY_generate_key(eckey->mKey)) {
return V8Exception("EC_KEY_generate_key failed");
}
eckey->mHasPrivateKey = true;
}
eckey->Wrap(args.Holder());
return args.Holder();
}
// Node properity functions
Handle<Value> ECKey::GetHasPrivateKey(Local<String> property, const AccessorInfo &info) {
HandleScope scope;
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder());
return scope.Close(Boolean::New(eckey->mHasPrivateKey));
}
Handle<Value> ECKey::GetPublicKey(Local<String> property, const AccessorInfo &info) {
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder());
const EC_GROUP *group = EC_KEY_get0_group(eckey->mKey);
const EC_POINT *point = EC_KEY_get0_public_key(eckey->mKey);
unsigned int nReq = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL);
if (!nReq) {
return V8Exception("EC_POINT_point2oct error");
}
unsigned char *buf, *buf2;
buf = buf2 = (unsigned char *)malloc(nReq);
if (EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, buf, nReq, NULL) != nReq) {
return V8Exception("EC_POINT_point2oct didn't return correct size");
}
HandleScope scope;
Buffer *buffer = Buffer::New(nReq);
memcpy(Buffer::Data(buffer), buf2, nReq);
free(buf2);
return scope.Close(buffer->handle_);
}
Handle<Value> ECKey::GetPrivateKey(Local<String> property, const AccessorInfo &info) {
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder());
const BIGNUM *bn = EC_KEY_get0_private_key(eckey->mKey);
if (bn == NULL) {
return V8Exception("EC_KEY_get0_private_key failed");
}
int priv_size = BN_num_bytes(bn);
unsigned char *priv_buf = (unsigned char *)malloc(priv_size);
int n = BN_bn2bin(bn, priv_buf);
if (n != priv_size) {
return V8Exception("BN_bn2bin didn't return priv_size");
}
HandleScope scope;
Buffer *buffer = Buffer::New(priv_size);
memcpy(Buffer::Data(buffer), priv_buf, priv_size);
free(priv_buf);
return scope.Close(buffer->handle_);
}
// Node method functions
Handle<Value> ECKey::Sign(const Arguments &args) {
HandleScope scope;
ECKey * eckey = ObjectWrap::Unwrap<ECKey>(args.Holder());
if (!Buffer::HasInstance(args[0])) {
return V8Exception("digest must be a buffer");
}
if (!eckey->mHasPrivateKey) {
return V8Exception("cannot sign without private key");
}
Handle<Object> digest = args[0]->ToObject();
const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest);
unsigned int digest_len = Buffer::Length(digest);
ECDSA_SIG *sig = ECDSA_do_sign(digest_data, digest_len, eckey->mKey);
if (!sig) {
return V8Exception("ECDSA_do_sign");
}
int sig_len = i2d_ECDSA_SIG(sig, NULL);
if (!sig_len) {
return V8Exception("i2d_ECDSA_SIG");
}
unsigned char *sig_data, *sig_data2;
sig_data = sig_data2 = (unsigned char *)malloc(sig_len);
if (i2d_ECDSA_SIG(sig, &sig_data) != sig_len) {
ECDSA_SIG_free(sig);
free(sig_data2);
return V8Exception("i2d_ECDSA_SIG didnot return correct length");
}
ECDSA_SIG_free(sig);
Buffer *result = Buffer::New(sig_len);
memcpy(Buffer::Data(result), sig_data2, sig_len);
free(sig_data2);
return scope.Close(result->handle_);
}
Handle<Value> ECKey::VerifySignature(const Arguments &args) {
HandleScope scope;
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder());
if (!Buffer::HasInstance(args[0])) {
return V8Exception("digest must be a buffer");
}
if (!Buffer::HasInstance(args[1])) {
return V8Exception("signature must be a buffer");
}
Handle<Object> digest = args[0]->ToObject();
Handle<Object> signature = args[1]->ToObject();
const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest);
const unsigned char *signature_data = (unsigned char *)Buffer::Data(signature);
unsigned int digest_len = Buffer::Length(digest);
unsigned int signature_len = Buffer::Length(signature);
int result = ECDSA_verify(0, digest_data, digest_len, signature_data, signature_len, eckey->mKey);
if (result == -1) {
return V8Exception("ECDSA_verify");
} else if (result == 0) {
return scope.Close(Boolean::New(false));
} else if (result == 1) {
return scope.Close(Boolean::New(true));
} else {
return V8Exception("ECDSA_verify gave an unexpected return value");
}
}
Handle<Value> ECKey::DeriveSharedSecret(const Arguments &args) {
HandleScope scope;
if (args[0]->IsUndefined()) {
return V8Exception("other is required");
}
ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder());
ECKey *other = ObjectWrap::Unwrap<ECKey>(args[0]->ToObject());
if (!other) {
return V8Exception("other must be an ECKey");
}
unsigned char *secret = (unsigned char*)malloc(512);
int len = ECDH_compute_key(secret, 512, EC_KEY_get0_public_key(other->mKey), eckey->mKey, NULL);
Buffer *result = Buffer::New(len);
memcpy(Buffer::Data(result), secret, len);
free(secret);
return scope.Close(result->handle_);
}
<|endoftext|> |
<commit_before>// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#include <cstring>
#include "common.h"
#include "sentencepiece_processor.h"
namespace sentencepiece {
namespace error {
int gTestCounter = 0;
void Abort() {
if (GetTestCounter() == 1) {
SetTestCounter(2);
} else {
std::cerr << "Program terminated with an unrecoverable error." << std::endl;
exit(-1);
}
}
void Exit(int code) {
if (GetTestCounter() == 1) {
SetTestCounter(2);
} else {
exit(code);
}
}
void SetTestCounter(int c) { gTestCounter = c; }
bool GetTestCounter() { return gTestCounter; }
} // namespace error
namespace util {
Status::Status() {}
Status::~Status() {}
struct Status::Rep {
error::Code code;
std::string error_message;
};
Status::Status(error::Code code, const char* error_message) : rep_(new Rep) {
rep_->code = code;
rep_->error_message = error_message;
}
Status::Status(error::Code code, const std::string& error_message)
: rep_(new Rep) {
rep_->code = code;
rep_->error_message = error_message;
}
Status::Status(const Status& s)
: rep_((s.rep_ == nullptr) ? nullptr : new Rep(*s.rep_)) {}
void Status::operator=(const Status& s) {
if (rep_ != s.rep_)
rep_.reset((s.rep_ == nullptr) ? nullptr : new Rep(*s.rep_));
}
bool Status::operator==(const Status& s) const { return (rep_ == s.rep_); }
bool Status::operator!=(const Status& s) const { return (rep_ != s.rep_); }
const char* Status::error_message() const {
return ok() ? "" : rep_->error_message.c_str();
}
void Status::set_error_message(const char* str) {
if (rep_ == nullptr) rep_.reset(new Rep);
rep_->error_message = str;
}
error::Code Status::code() const { return ok() ? error::OK : rep_->code; }
std::string Status::ToString() const {
if (rep_ == nullptr) return "OK";
std::string result;
switch (code()) {
case error::CANCELLED:
result = "Cancelled";
break;
case error::UNKNOWN:
result = "Unknown";
break;
case error::INVALID_ARGUMENT:
result = "Invalid argument";
break;
case error::DEADLINE_EXCEEDED:
result = "Deadline exceeded";
break;
case error::NOT_FOUND:
result = "Not found";
break;
case error::ALREADY_EXISTS:
result = "Already exists";
break;
case error::PERMISSION_DENIED:
result = "Permission denied";
break;
case error::UNAUTHENTICATED:
result = "Unauthenticated";
break;
case error::RESOURCE_EXHAUSTED:
result = "Resource exhausted";
break;
case error::FAILED_PRECONDITION:
result = "Failed precondition";
break;
case error::ABORTED:
result = "Aborted";
break;
case error::OUT_OF_RANGE:
result = "Out of range";
break;
case error::UNIMPLEMENTED:
result = "Unimplemented";
break;
case error::INTERNAL:
result = "Internal";
break;
case error::UNAVAILABLE:
result = "Unavailable";
break;
case error::DATA_LOSS:
result = "Data loss";
break;
default:
result = "Unkown code:";
break;
}
result += ": ";
result += rep_->error_message;
return result;
}
void Status::IgnoreError() {}
} // namespace util
} // namespace sentencepiece
<commit_msg>Fix a typo<commit_after>// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#include <cstring>
#include "common.h"
#include "sentencepiece_processor.h"
namespace sentencepiece {
namespace error {
int gTestCounter = 0;
void Abort() {
if (GetTestCounter() == 1) {
SetTestCounter(2);
} else {
std::cerr << "Program terminated with an unrecoverable error." << std::endl;
exit(-1);
}
}
void Exit(int code) {
if (GetTestCounter() == 1) {
SetTestCounter(2);
} else {
exit(code);
}
}
void SetTestCounter(int c) { gTestCounter = c; }
bool GetTestCounter() { return gTestCounter; }
} // namespace error
namespace util {
Status::Status() {}
Status::~Status() {}
struct Status::Rep {
error::Code code;
std::string error_message;
};
Status::Status(error::Code code, const char* error_message) : rep_(new Rep) {
rep_->code = code;
rep_->error_message = error_message;
}
Status::Status(error::Code code, const std::string& error_message)
: rep_(new Rep) {
rep_->code = code;
rep_->error_message = error_message;
}
Status::Status(const Status& s)
: rep_((s.rep_ == nullptr) ? nullptr : new Rep(*s.rep_)) {}
void Status::operator=(const Status& s) {
if (rep_ != s.rep_)
rep_.reset((s.rep_ == nullptr) ? nullptr : new Rep(*s.rep_));
}
bool Status::operator==(const Status& s) const { return (rep_ == s.rep_); }
bool Status::operator!=(const Status& s) const { return (rep_ != s.rep_); }
const char* Status::error_message() const {
return ok() ? "" : rep_->error_message.c_str();
}
void Status::set_error_message(const char* str) {
if (rep_ == nullptr) rep_.reset(new Rep);
rep_->error_message = str;
}
error::Code Status::code() const { return ok() ? error::OK : rep_->code; }
std::string Status::ToString() const {
if (rep_ == nullptr) return "OK";
std::string result;
switch (code()) {
case error::CANCELLED:
result = "Cancelled";
break;
case error::UNKNOWN:
result = "Unknown";
break;
case error::INVALID_ARGUMENT:
result = "Invalid argument";
break;
case error::DEADLINE_EXCEEDED:
result = "Deadline exceeded";
break;
case error::NOT_FOUND:
result = "Not found";
break;
case error::ALREADY_EXISTS:
result = "Already exists";
break;
case error::PERMISSION_DENIED:
result = "Permission denied";
break;
case error::UNAUTHENTICATED:
result = "Unauthenticated";
break;
case error::RESOURCE_EXHAUSTED:
result = "Resource exhausted";
break;
case error::FAILED_PRECONDITION:
result = "Failed precondition";
break;
case error::ABORTED:
result = "Aborted";
break;
case error::OUT_OF_RANGE:
result = "Out of range";
break;
case error::UNIMPLEMENTED:
result = "Unimplemented";
break;
case error::INTERNAL:
result = "Internal";
break;
case error::UNAVAILABLE:
result = "Unavailable";
break;
case error::DATA_LOSS:
result = "Data loss";
break;
default:
result = "Unknown code:";
break;
}
result += ": ";
result += rep_->error_message;
return result;
}
void Status::IgnoreError() {}
} // namespace util
} // namespace sentencepiece
<|endoftext|> |
<commit_before>#include <DuiApplicationWindow>
#include <DuiApplication>
#include <QDBusInterface>
#include <QDebug>
#include "lockscreenui.h"
#include "lockscreenbusinesslogic.h"
LockScreenBusinessLogic::LockScreenBusinessLogic() : QObject()
{
eventEater = new EventEater();
screenLock = false,
sleepMode = false;
isDisabled = false;
touchPadLocker = new QmLocks();
//display = new QmDisplayState(); //this should be handled by the displaybusinesslogic
//toggleDisplayStateListener(true); //this should be handled by the displaybusinesslogic
toggleSleepMode(false);
lockUI = new LockScreenUI;
connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen()));
dbusIf = new QDBusInterface("org.maemo.dui.NotificationManager", "/systemui",
"org.maemo.dui.NotificationManager.MissedEvents",
QDBusConnection::sessionBus());
connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)),
this, SLOT(updateMissedEventAmounts(int, int, int, int)));
dbusIf->call(QDBus::NoBlock, QString("missedEventAmountsRequired"));
}
LockScreenBusinessLogic::~LockScreenBusinessLogic()
{
delete touchPadLocker;
touchPadLocker = NULL;
//delete display; //this should be handled by the displaybusinesslogic
//display = NULL; //this should be handled by the displaybusinesslogic
delete eventEater;
eventEater = NULL;
if (lockUI) {
delete lockUI;
lockUI = NULL;
}
}
void LockScreenBusinessLogic::shortPowerKeyPressOccured()
{
if(!isDisabled) {
if(screenLock) {
if(sleepMode)
toggleSleepMode(false);
else
toggleSleepMode(true);
}
else {
toggleScreenLock(true);
toggleSleepMode(true);
}
}
}
void LockScreenBusinessLogic::toggleScreenLock(bool toggle)
{
if(!toggle) {
emit lockScreenOff();
DuiApplication::instance()->applicationWindow()->hide();
}
else {
DuiApplication::instance()->applicationWindow()->show();
lockUI->appear();
}
screenLock = toggle;
}
//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state)
{
switch(state) {
case QmDisplayState::Off:
//idle timer turns off the display, so we will turn on sleep mode and screen lock
toggleSleepMode(true);
toggleScreenLock(true);
break;
case QmDisplayState::Dimmed:
//we turn on the eventeater
eventEater->toggle(true);
break;
case QmDisplayState::On:
//we trun off the event eater
eventEater->toggle(false);
break;
}
}
*/
void LockScreenBusinessLogic::sleepModeOff()
{
if(sleepMode)
toggleSleepMode(false);
}
void LockScreenBusinessLogic::unlockScreen()
{
toggleScreenLock(false);
}
void LockScreenBusinessLogic::toggleSleepMode(bool toggle)
{
if(toggle) {
//we turn on the sleep mode and lock the touchpad + turn off the display
touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Locked);
/*
if(display->get() != QmDisplayState::Off) {
//we don't need to listen display signals when we change the state by ourself
toggleDisplayStateListener(false);
display->set(QmDisplayState::Off);
toggleDisplayStateListener(true);
}
*/
}
else {
//we turn off the sleep mode and unlock the touchpad + turn on the display
touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Unlocked);
/*
if(display->get() != QmDisplayState::On) {
//we don't need to listen display signals when we change the state by ourself
toggleDisplayStateListener(false);
display->set(QmDisplayState::On);
toggleDisplayStateListener(true);
}
*/
}
sleepMode = toggle;
}
//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::toggleDisplayStateListener(bool toggle)
{
if(toggle)
connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
else
disconnect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
}
*/
void LockScreenBusinessLogic::disable(bool disable)
{
isDisabled = disable;
}
void LockScreenBusinessLogic::updateMissedEventAmounts(int calls, int messages, int emails, int chatMessages)
{
qDebug() << "LockScreenBusinessLogic::updateMissedEventAmounts(" << calls << ", " << messages << ", " << emails << ", " << chatMessages << ")";
lockUI->updateMissedEventAmounts(calls, messages, emails, chatMessages);
}
<commit_msg>Some logging added<commit_after>#include <DuiApplicationWindow>
#include <DuiApplication>
#include <QDBusInterface>
#include <QDebug>
#include "lockscreenui.h"
#include "lockscreenbusinesslogic.h"
LockScreenBusinessLogic::LockScreenBusinessLogic() : QObject()
{
eventEater = new EventEater();
screenLock = false,
sleepMode = false;
isDisabled = false;
touchPadLocker = new QmLocks();
//display = new QmDisplayState(); //this should be handled by the displaybusinesslogic
//toggleDisplayStateListener(true); //this should be handled by the displaybusinesslogic
toggleSleepMode(false);
lockUI = new LockScreenUI;
connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen()));
dbusIf = new QDBusInterface("org.maemo.dui.NotificationManager", "/systemui",
"org.maemo.dui.NotificationManager.MissedEvents",
QDBusConnection::sessionBus());
connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)),
this, SLOT(updateMissedEventAmounts(int, int, int, int)));
dbusIf->call(QDBus::NoBlock, QString("missedEventAmountsRequired"));
}
LockScreenBusinessLogic::~LockScreenBusinessLogic()
{
delete touchPadLocker;
touchPadLocker = NULL;
//delete display; //this should be handled by the displaybusinesslogic
//display = NULL; //this should be handled by the displaybusinesslogic
delete eventEater;
eventEater = NULL;
if (lockUI) {
delete lockUI;
lockUI = NULL;
}
}
void LockScreenBusinessLogic::shortPowerKeyPressOccured()
{
qDebug() << Q_FUNC_INFO << "isDisabled:" << isDisabled << "screenLock:" << screenLock << "sleepMode:" << sleepMode;
if(!isDisabled) {
if(screenLock) {
if(sleepMode)
toggleSleepMode(false);
else
toggleSleepMode(true);
}
else {
toggleScreenLock(true);
toggleSleepMode(true);
}
}
}
void LockScreenBusinessLogic::toggleScreenLock(bool toggle)
{
qDebug() << Q_FUNC_INFO << toggle;
if(!toggle) {
emit lockScreenOff();
DuiApplication::instance()->applicationWindow()->hide();
}
else {
DuiApplication::instance()->applicationWindow()->show();
lockUI->appear();
}
screenLock = toggle;
}
//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state)
{
switch(state) {
case QmDisplayState::Off:
//idle timer turns off the display, so we will turn on sleep mode and screen lock
toggleSleepMode(true);
toggleScreenLock(true);
break;
case QmDisplayState::Dimmed:
//we turn on the eventeater
eventEater->toggle(true);
break;
case QmDisplayState::On:
//we trun off the event eater
eventEater->toggle(false);
break;
}
}
*/
void LockScreenBusinessLogic::sleepModeOff()
{
if(sleepMode)
toggleSleepMode(false);
}
void LockScreenBusinessLogic::unlockScreen()
{
toggleScreenLock(false);
}
void LockScreenBusinessLogic::toggleSleepMode(bool toggle)
{
if(toggle) {
//we turn on the sleep mode and lock the touchpad + turn off the display
touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Locked);
/*
if(display->get() != QmDisplayState::Off) {
//we don't need to listen display signals when we change the state by ourself
toggleDisplayStateListener(false);
display->set(QmDisplayState::Off);
toggleDisplayStateListener(true);
}
*/
}
else {
//we turn off the sleep mode and unlock the touchpad + turn on the display
touchPadLocker->setState(QmLocks::TouchAndKeyboard, QmLocks::Unlocked);
/*
if(display->get() != QmDisplayState::On) {
//we don't need to listen display signals when we change the state by ourself
toggleDisplayStateListener(false);
display->set(QmDisplayState::On);
toggleDisplayStateListener(true);
}
*/
}
sleepMode = toggle;
}
//this should be handled by the displaybusinesslogic
/*
void LockScreenBusinessLogic::toggleDisplayStateListener(bool toggle)
{
if(toggle)
connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
else
disconnect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),
this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));
}
*/
void LockScreenBusinessLogic::disable(bool disable)
{
isDisabled = disable;
}
void LockScreenBusinessLogic::updateMissedEventAmounts(int calls, int messages, int emails, int chatMessages)
{
qDebug() << "LockScreenBusinessLogic::updateMissedEventAmounts(" << calls << ", " << messages << ", " << emails << ", " << chatMessages << ")";
lockUI->updateMissedEventAmounts(calls, messages, emails, chatMessages);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanotree.h"
class NanoTreeUnitTest : public QObject
{
Q_OBJECT
private:
NanoTree buildBasic();
NanoTree buildComplex();
private slots:
void keyValue1();
void keyValue2();
void keys();
};
NanoTree NanoTreeUnitTest::buildBasic()
{
QVariantList param1;
param1 << QVariant("param1");
param1 << QVariant("value1");
QVariantList param2;
param2 << QVariant("param2");
param2 << QVariant("value2");
QVariantList tree;
tree << QVariant(param1);
tree << QVariant(param2);
return NanoTree(tree);
}
NanoTree NanoTreeUnitTest::buildComplex()
{
QVariantList params;
params << QVariant("params");
QVariantList param1;
param1 << QVariant("param1");
param1 << QVariant("value1");
QVariantList param2;
param2 << QVariant("param2");
param2 << QVariant("value2");
params << QVariant(param1);
params << QVariant(param2);
QVariantList doc;
doc << QVariant("doc");
doc << QVariant("documentation");
QVariantList tree;
tree << QVariant(params);
tree << QVariant(doc);
return NanoTree(tree);
}
void NanoTreeUnitTest::keyValue1()
{
NanoTree tree = buildBasic();
QCOMPARE(tree.keyValue("param1").toString(), QString("value1"));
QCOMPARE(tree.keyValue("param2").toString(), QString("value2"));
}
void NanoTreeUnitTest::keyValue2()
{
NanoTree tree = buildComplex();
QCOMPARE(tree.keyValue("params", "param1").toString(), QString("value1"));
QCOMPARE(tree.keyValue("params", "param2").toString(), QString("value2"));
QCOMPARE(tree.keyValue("doc").toString(), QString("documentation"));
}
void NanoTreeUnitTest::keys()
{
NanoTree tree = buildComplex();
QStringList lst1 = tree.keys();
QCOMPARE(lst1.size(), 2);
QVERIFY(lst1.contains("params"));
QVERIFY(lst1.contains("doc"));
QStringList lst2 = tree.keyNode("params").keys();
QCOMPARE(lst2.size(), 2);
QVERIFY(lst2.contains("param1"));
QVERIFY(lst2.contains("param2"));
QStringList lst3 = tree.keyNode("doc").keys();
QCOMPARE(lst3.size(), 0);
}
#include "nanotreeunittest.moc"
QTEST_MAIN(NanoTreeUnitTest);
<commit_msg>keySub tests.<commit_after>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanotree.h"
class NanoTreeUnitTest : public QObject
{
Q_OBJECT
private:
NanoTree buildBasic();
NanoTree buildComplex();
private slots:
void keyValue1();
void keyValue2();
void keys();
void keySub();
};
NanoTree NanoTreeUnitTest::buildBasic()
{
QVariantList param1;
param1 << QVariant("param1");
param1 << QVariant("value1");
QVariantList param2;
param2 << QVariant("param2");
param2 << QVariant("value2");
QVariantList tree;
tree << QVariant(param1);
tree << QVariant(param2);
return NanoTree(tree);
}
NanoTree NanoTreeUnitTest::buildComplex()
{
QVariantList params;
params << QVariant("params");
QVariantList param1;
param1 << QVariant("param1");
param1 << QVariant("value1");
QVariantList param2;
param2 << QVariant("param2");
param2 << QVariant("value2");
params << QVariant(param1);
params << QVariant(param2);
QVariantList doc;
doc << QVariant("doc");
doc << QVariant("documentation");
QVariantList tree;
tree << QVariant(params);
tree << QVariant(doc);
return NanoTree(tree);
}
void NanoTreeUnitTest::keyValue1()
{
NanoTree tree = buildBasic();
QCOMPARE(tree.keyValue("param1").toString(), QString("value1"));
QCOMPARE(tree.keyValue("param2").toString(), QString("value2"));
}
void NanoTreeUnitTest::keyValue2()
{
NanoTree tree = buildComplex();
QCOMPARE(tree.keyValue("params", "param1").toString(), QString("value1"));
QCOMPARE(tree.keyValue("params", "param2").toString(), QString("value2"));
QCOMPARE(tree.keyValue("doc").toString(), QString("documentation"));
}
void NanoTreeUnitTest::keys()
{
NanoTree tree = buildComplex();
QStringList lst1 = tree.keys();
QCOMPARE(lst1.size(), 2);
QVERIFY(lst1.contains("params"));
QVERIFY(lst1.contains("doc"));
QStringList lst2 = tree.keyNode("params").keys();
QCOMPARE(lst2.size(), 2);
QVERIFY(lst2.contains("param1"));
QVERIFY(lst2.contains("param2"));
QStringList lst3 = tree.keyNode("doc").keys();
QCOMPARE(lst3.size(), 0);
}
void NanoTreeUnitTest::keySub()
{
NanoTree tree1 = buildBasic();
NanoTree sub1 = tree1.keySub("param1");
QVERIFY(sub1.type() == QVariant::List);
QCOMPARE(sub1.toList().size(), 1);
QCOMPARE(sub1.toList().at(0).toString(), QString("value1"));
NanoTree tree2 = buildComplex();
NanoTree sub2 = tree2.keySub("params");
QVERIFY(sub2.type() == QVariant::List);
QCOMPARE(sub2.toList().size(), 2);
QCOMPARE(sub2.keyValue("param1").toString(), QString("value1"));
}
#include "nanotreeunittest.moc"
QTEST_MAIN(NanoTreeUnitTest);
<|endoftext|> |
<commit_before>#include "MMAcquisition.h"
#include "../MMDevice/ImageMetadata.h"
#include "boost/foreach.hpp"
///////////////////////////////////
// MMAquisitionEngine::ImageTask //
///////////////////////////////////
ImageTask::ImageTask(MMAcquisitionEngine * eng, ImageRequest imageRequest) {
eng_ = eng;
imageRequest_ = imageRequest;
type = IMAGE;
}
void ImageTask::run() {
if (!eng_->StopHasBeenRequested())
updatePosition();
if (!eng_->StopHasBeenRequested())
updateSlice();
if (!eng_->StopHasBeenRequested())
updateChannel();
if (!eng_->StopHasBeenRequested())
wait();
if (!eng_->StopHasBeenRequested())
autofocus();
if (!eng_->StopHasBeenRequested())
acquireImage();
}
void ImageTask::updateSlice() {
double chanZOffset = 0;
double sliceZ;
if (imageRequest_.useChannel)
chanZOffset = imageRequest_.channel.zOffset;
if (imageRequest_.useSlice)
sliceZ = imageRequest_.slicePosition;
else
eng_->coreCallback_->GetFocusPosition(sliceZ);
if (imageRequest_.useSlice || (chanZOffset != 0)) {
eng_->coreCallback_->SetFocusPosition(sliceZ + chanZOffset);
eng_->core_->logMessage("z position set\n");
}
}
void ImageTask::updatePosition() {
if (imageRequest_.usePosition) {
map<string, double>::iterator it1;
MultiAxisPosition pos = imageRequest_.multiAxisPosition;
for (it1 = pos.singleAxisPositions.begin(); it1 != pos.singleAxisPositions.end(); ++it1) {
eng_->core_->setPosition(it1->first.c_str(), it1->second);
}
map<string, pair<double, double> >::iterator it2;
for (it2 = pos.doubleAxisPositions.begin(); it2 != pos.doubleAxisPositions.end(); ++it2) {
point2D xy = it2->second;
eng_->core_->setXYPosition(it2->first.c_str(), xy.first, xy.second);
}
eng_->core_->logMessage("position set\n");
}
}
void ImageTask::updateChannel() {
if (imageRequest_.useChannel) {
eng_->coreCallback_->SetExposure(imageRequest_.channel.exposure);
imageRequest_.exposure = imageRequest_.channel.exposure;
string chanGroup = imageRequest_.channel.group;
if (chanGroup.size() == 0)
chanGroup = eng_->core_->getChannelGroup();
eng_->coreCallback_->SetConfig(chanGroup.c_str(), imageRequest_.channel.name.c_str());
eng_->core_->logMessage("channel set\n");
}
}
void ImageTask::wait() {
if (imageRequest_.useTime) {
while (!eng_->StopHasBeenRequested() && eng_->lastWakeTime_ > 0) {
MM::MMTime sleepTime = min(MM::MMTime(10000), (eng_->lastWakeTime_ + imageRequest_.waitTime) - eng_->coreCallback_->GetCurrentMMTime());
if (sleepTime > MM::MMTime(0, 0))
eng_->coreCallback_->Sleep(NULL, sleepTime.getMsec());
else
break;
}
eng_->core_->logMessage("wait finished\n");
eng_->lastWakeTime_ = eng_->coreCallback_->GetCurrentMMTime();
}
}
void ImageTask::autofocus() {
if (imageRequest_.runAutofocus && imageRequest_.channelIndex == 0 && imageRequest_.positionIndex == 0)
eng_->core_->fullFocus();
}
void ImageTask::acquireImage() {
int w, h, d;
if (!eng_->core_->getShutterOpen()) {
eng_->core_->setShutterOpen(true);
eng_->core_->logMessage("opened shutter");
}
eng_->core_->snapImage();
eng_->core_->logMessage("snapped image");
if (imageRequest_.closeShutter) {
eng_->core_->setShutterOpen(false);
eng_->core_->logMessage("closed shutter");
}
void * img = eng_->core_->getImage(); // Snaps and retrieves image.
eng_->core_->logMessage("retrieved image");
Metadata md;
md.frameData["Slice"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.sliceIndex));
md.frameData["Channel"] = imageRequest_.channel.name;
md.frameData["Position"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.positionIndex));
md.frameData["ChannelIndex"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.channelIndex));
md.frameData["Frame"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.timeIndex));
md.frameData["ExposureMs"] = CDeviceUtils::ConvertToString(imageRequest_.exposure);
if (imageRequest_.usePosition)
md.frameData["PositionName"] = imageRequest_.multiAxisPosition.name;
eng_->ApplyDiffPropertyMap(md.frameData);
eng_->coreCallback_->GetImageDimensions(w, h, d);
md.frameData["Width"] = CDeviceUtils::ConvertToString(w);
md.frameData["Height"] = CDeviceUtils::ConvertToString(h);
md.frameData["Depth"] = CDeviceUtils::ConvertToString(d);
eng_->coreCallback_->InsertImage(NULL, (const unsigned char *) img, w, h, d, &md);
eng_->core_->logMessage("Grabbed image.\n");
}
/////////////////////////
// MMAcquisitionEngine //
/////////////////////////
map<string, string> MMAcquisitionEngine::GetCurrentPropertyMap() {
Configuration config = core_->getSystemStateCache();
map<string, string> frameData;
for (unsigned long i = 0; i < config.size(); i++) {
PropertySetting setting = config.getSetting(i);
frameData[setting.getDeviceLabel() + "-" + setting.getPropertyName()] = setting.getPropertyValue();
}
return frameData;
}
void MMAcquisitionEngine::ApplyDiffPropertyMap(map<string, string> &dest) {
map<string, string> curMap = GetCurrentPropertyMap();
pair<string, string> curProp;
BOOST_FOREACH(curProp, curMap)
{
if (initialPropertyMap_[curProp.first] != curProp.second)
dest[curProp.first] = curProp.second;
}
}
map<string, string> MMAcquisitionEngine::GetInitPropertyMap() {
return initialPropertyMap_;
}
Metadata MMAcquisitionEngine::GetInitMetadata() {
while (!started_)
coreCallback_->Sleep(NULL, 1);
Metadata md;
md.frameData = initialPropertyMap_;
return md;
}
void MMAcquisitionEngine::Start(AcquisitionSettings acquisitionSettings) {
defaultExposure_ = core_->getExposure();
GenerateSequence(acquisitionSettings);
stopRequested_ = false;
pauseRequested_ = false;
finished_ = false;
initialPropertyMap_ = GetCurrentPropertyMap();
activate();
started_ = true;
}
void MMAcquisitionEngine::Run() {
bool initialAutoshutter = core_->getAutoShutter();
core_->setAutoShutter(false);
for (unsigned int i = 0; i < tasks_.size(); ++i) {
if (stopRequested_)
break;
stringstream msg;
msg << "Task " << i << " started, type " << tasks_[i]->type << ".";
core_->logMessage(msg.str().c_str());
tasks_[i]->run();
}
core_->setAutoShutter(initialAutoshutter);
finished_ = true;
}
bool MMAcquisitionEngine::IsFinished() {
return finished_;
}
void MMAcquisitionEngine::Stop() {
stopRequested_ = true;
}
void MMAcquisitionEngine::Pause() {
pauseRequested_ = true;
}
void MMAcquisitionEngine::Resume() {
pauseRequested_ = false;
}
void MMAcquisitionEngine::Step() {
}
bool MMAcquisitionEngine::StopHasBeenRequested() {
return stopRequested_;
}
void MMAcquisitionEngine::SetTasks(TaskVector tasks) {
tasks_ = tasks;
}
void MMAcquisitionEngine::GenerateSequence(AcquisitionSettings acquisitionSettings) {
ImageRequest imageRequest, lastImageRequest;
imageRequest.usePosition = (acquisitionSettings.positionList.size() > 0);
imageRequest.useTime = (acquisitionSettings.timeSeries.size() > 0);
imageRequest.useChannel = (acquisitionSettings.channelList.size() > 0);
imageRequest.useSlice = (acquisitionSettings.zStack.size() > 0);
imageRequest.exposure = defaultExposure_;
int numPositions = max(1, (int) acquisitionSettings.positionList.size());
int numFrames = max(1, (int) acquisitionSettings.timeSeries.size());
int numChannels = max(1, (int) acquisitionSettings.channelList.size());
int numSlices = max(1, (int) acquisitionSettings.zStack.size());
int numImages = numPositions * numFrames * numChannels * numSlices;
for (int imageIndex = 0; imageIndex < (1 + numImages); ++imageIndex) {
imageRequest.skipImage = false;
imageRequest.closeShutter = true;
if (acquisitionSettings.channelsFirst) {
imageRequest.channelIndex = imageIndex % numChannels;
imageRequest.sliceIndex = (imageIndex / numChannels) % numSlices;
} else // slices first
{
imageRequest.sliceIndex = imageIndex % numSlices;
imageRequest.channelIndex = (imageIndex / numSlices) % numChannels;
}
if (acquisitionSettings.positionsFirst) {
imageRequest.positionIndex = (imageIndex / (numChannels * numSlices)) % numPositions;
imageRequest.timeIndex = (imageIndex / (numChannels * numSlices * numPositions)) % numFrames;
} else // time first
{
imageRequest.timeIndex = (imageIndex / (numChannels * numSlices)) % numFrames;
imageRequest.positionIndex = (imageIndex / (numChannels * numSlices * numFrames)) % numPositions;
}
if (imageRequest.useTime && imageRequest.timeIndex > 0 && imageRequest.positionIndex <= 0 // &&
&& imageRequest.channelIndex <= 0 && imageRequest.sliceIndex <= 0)
imageRequest.waitTime = MM::MMTime(acquisitionSettings.timeSeries[imageRequest.timeIndex] * 1000);
else
imageRequest.waitTime = 0;
if (imageRequest.usePosition)
imageRequest.multiAxisPosition = acquisitionSettings.positionList[imageRequest.positionIndex];
if (imageRequest.useSlice)
imageRequest.slicePosition = acquisitionSettings.zStack[imageRequest.sliceIndex];
if (imageRequest.useChannel) {
imageRequest.channel = acquisitionSettings.channelList[imageRequest.channelIndex];
if (0 != (imageRequest.timeIndex % (imageRequest.channel.skipFrames + 1)))
imageRequest.skipImage = true;
}
if (imageRequest.useChannel && imageRequest.useSlice) {
if (!imageRequest.channel.useZStack && ((unsigned) imageRequest.sliceIndex != (acquisitionSettings.zStack.size() - 1) / 2))
imageRequest.skipImage = true;
}
imageRequest.runAutofocus = acquisitionSettings.useAutofocus;
if (imageRequest.timeIndex > -1) {
imageRequest.runAutofocus = imageRequest.runAutofocus
&& (0 == (imageRequest.timeIndex % (1 + acquisitionSettings.autofocusSkipFrames)));
}
if (imageIndex > 0)
{
if (imageRequest.timeIndex == lastImageRequest.timeIndex
&& imageRequest.positionIndex == lastImageRequest.positionIndex) {
if (acquisitionSettings.keepShutterOpenChannels
&& !acquisitionSettings.keepShutterOpenSlices) {
if (imageRequest.sliceIndex == lastImageRequest.sliceIndex)
lastImageRequest.closeShutter = false;
}
if (acquisitionSettings.keepShutterOpenSlices
&& !acquisitionSettings.keepShutterOpenChannels) {
if (imageRequest.channelIndex == lastImageRequest.channelIndex)
lastImageRequest.closeShutter = false;
}
if (acquisitionSettings.keepShutterOpenSlices
&& acquisitionSettings.keepShutterOpenChannels) {
lastImageRequest.closeShutter = false;
}
}
if (!lastImageRequest.skipImage)
tasks_.push_back(new ImageTask(this, lastImageRequest));
}
if (imageIndex == 0 || !imageRequest.skipImage)
lastImageRequest = imageRequest;
}
}
<commit_msg>Make core acquisition engine respond to autoshutter.<commit_after>#include "MMAcquisition.h"
#include "../MMDevice/ImageMetadata.h"
#include "boost/foreach.hpp"
///////////////////////////////////
// MMAquisitionEngine::ImageTask //
///////////////////////////////////
ImageTask::ImageTask(MMAcquisitionEngine * eng, ImageRequest imageRequest) {
eng_ = eng;
imageRequest_ = imageRequest;
type = IMAGE;
}
void ImageTask::run() {
if (!eng_->StopHasBeenRequested())
updatePosition();
if (!eng_->StopHasBeenRequested())
updateSlice();
if (!eng_->StopHasBeenRequested())
updateChannel();
if (!eng_->StopHasBeenRequested())
wait();
if (!eng_->StopHasBeenRequested())
autofocus();
if (!eng_->StopHasBeenRequested())
acquireImage();
}
void ImageTask::updateSlice() {
double chanZOffset = 0;
double sliceZ;
if (imageRequest_.useChannel)
chanZOffset = imageRequest_.channel.zOffset;
if (imageRequest_.useSlice)
sliceZ = imageRequest_.slicePosition;
else
eng_->coreCallback_->GetFocusPosition(sliceZ);
if (imageRequest_.useSlice || (chanZOffset != 0)) {
eng_->coreCallback_->SetFocusPosition(sliceZ + chanZOffset);
eng_->core_->logMessage("z position set\n");
}
}
void ImageTask::updatePosition() {
if (imageRequest_.usePosition) {
map<string, double>::iterator it1;
MultiAxisPosition pos = imageRequest_.multiAxisPosition;
for (it1 = pos.singleAxisPositions.begin(); it1 != pos.singleAxisPositions.end(); ++it1) {
eng_->core_->setPosition(it1->first.c_str(), it1->second);
}
map<string, pair<double, double> >::iterator it2;
for (it2 = pos.doubleAxisPositions.begin(); it2 != pos.doubleAxisPositions.end(); ++it2) {
point2D xy = it2->second;
eng_->core_->setXYPosition(it2->first.c_str(), xy.first, xy.second);
}
eng_->core_->logMessage("position set\n");
}
}
void ImageTask::updateChannel() {
if (imageRequest_.useChannel) {
eng_->coreCallback_->SetExposure(imageRequest_.channel.exposure);
imageRequest_.exposure = imageRequest_.channel.exposure;
string chanGroup = imageRequest_.channel.group;
if (chanGroup.size() == 0)
chanGroup = eng_->core_->getChannelGroup();
eng_->coreCallback_->SetConfig(chanGroup.c_str(), imageRequest_.channel.name.c_str());
eng_->core_->logMessage("channel set\n");
}
}
void ImageTask::wait() {
if (imageRequest_.useTime) {
while (!eng_->StopHasBeenRequested() && eng_->lastWakeTime_ > 0) {
MM::MMTime sleepTime = min(MM::MMTime(10000), (eng_->lastWakeTime_ + imageRequest_.waitTime) - eng_->coreCallback_->GetCurrentMMTime());
if (sleepTime > MM::MMTime(0, 0))
eng_->coreCallback_->Sleep(NULL, sleepTime.getMsec());
else
break;
}
eng_->core_->logMessage("wait finished\n");
eng_->lastWakeTime_ = eng_->coreCallback_->GetCurrentMMTime();
}
}
void ImageTask::autofocus() {
if (imageRequest_.runAutofocus && imageRequest_.channelIndex == 0 && imageRequest_.positionIndex == 0)
eng_->core_->fullFocus();
}
void ImageTask::acquireImage() {
int w, h, d;
if (eng_->core_->getAutoShutter() && !eng_->core_->getShutterOpen()) {
eng_->core_->setShutterOpen(true);
eng_->core_->logMessage("opened shutter");
}
eng_->core_->snapImage();
eng_->core_->logMessage("snapped image");
if (eng_->core_->getAutoShutter() && imageRequest_.closeShutter) {
eng_->core_->setShutterOpen(false);
eng_->core_->logMessage("closed shutter");
}
void * img = eng_->core_->getImage(); // Snaps and retrieves image.
eng_->core_->logMessage("retrieved image");
Metadata md;
md.frameData["Slice"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.sliceIndex));
md.frameData["Channel"] = imageRequest_.channel.name;
md.frameData["Position"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.positionIndex));
md.frameData["ChannelIndex"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.channelIndex));
md.frameData["Frame"] = CDeviceUtils::ConvertToString(max(0, imageRequest_.timeIndex));
md.frameData["ExposureMs"] = CDeviceUtils::ConvertToString(imageRequest_.exposure);
if (imageRequest_.usePosition)
md.frameData["PositionName"] = imageRequest_.multiAxisPosition.name;
eng_->ApplyDiffPropertyMap(md.frameData);
eng_->coreCallback_->GetImageDimensions(w, h, d);
md.frameData["Width"] = CDeviceUtils::ConvertToString(w);
md.frameData["Height"] = CDeviceUtils::ConvertToString(h);
md.frameData["Depth"] = CDeviceUtils::ConvertToString(d);
eng_->coreCallback_->InsertImage(NULL, (const unsigned char *) img, w, h, d, &md);
eng_->core_->logMessage("Grabbed image.\n");
}
/////////////////////////
// MMAcquisitionEngine //
/////////////////////////
map<string, string> MMAcquisitionEngine::GetCurrentPropertyMap() {
Configuration config = core_->getSystemStateCache();
map<string, string> frameData;
for (unsigned long i = 0; i < config.size(); i++) {
PropertySetting setting = config.getSetting(i);
frameData[setting.getDeviceLabel() + "-" + setting.getPropertyName()] = setting.getPropertyValue();
}
return frameData;
}
void MMAcquisitionEngine::ApplyDiffPropertyMap(map<string, string> &dest) {
map<string, string> curMap = GetCurrentPropertyMap();
pair<string, string> curProp;
BOOST_FOREACH(curProp, curMap)
{
if (initialPropertyMap_[curProp.first] != curProp.second)
dest[curProp.first] = curProp.second;
}
}
map<string, string> MMAcquisitionEngine::GetInitPropertyMap() {
return initialPropertyMap_;
}
Metadata MMAcquisitionEngine::GetInitMetadata() {
while (!started_)
coreCallback_->Sleep(NULL, 1);
Metadata md;
md.frameData = initialPropertyMap_;
return md;
}
void MMAcquisitionEngine::Start(AcquisitionSettings acquisitionSettings) {
defaultExposure_ = core_->getExposure();
GenerateSequence(acquisitionSettings);
stopRequested_ = false;
pauseRequested_ = false;
finished_ = false;
initialPropertyMap_ = GetCurrentPropertyMap();
activate();
started_ = true;
}
void MMAcquisitionEngine::Run() {
bool initialAutoshutter = core_->getAutoShutter();
core_->setAutoShutter(false);
for (unsigned int i = 0; i < tasks_.size(); ++i) {
if (stopRequested_)
break;
stringstream msg;
msg << "Task " << i << " started, type " << tasks_[i]->type << ".";
core_->logMessage(msg.str().c_str());
tasks_[i]->run();
}
core_->setAutoShutter(initialAutoshutter);
finished_ = true;
}
bool MMAcquisitionEngine::IsFinished() {
return finished_;
}
void MMAcquisitionEngine::Stop() {
stopRequested_ = true;
}
void MMAcquisitionEngine::Pause() {
pauseRequested_ = true;
}
void MMAcquisitionEngine::Resume() {
pauseRequested_ = false;
}
void MMAcquisitionEngine::Step() {
}
bool MMAcquisitionEngine::StopHasBeenRequested() {
return stopRequested_;
}
void MMAcquisitionEngine::SetTasks(TaskVector tasks) {
tasks_ = tasks;
}
void MMAcquisitionEngine::GenerateSequence(AcquisitionSettings acquisitionSettings) {
ImageRequest imageRequest, lastImageRequest;
imageRequest.usePosition = (acquisitionSettings.positionList.size() > 0);
imageRequest.useTime = (acquisitionSettings.timeSeries.size() > 0);
imageRequest.useChannel = (acquisitionSettings.channelList.size() > 0);
imageRequest.useSlice = (acquisitionSettings.zStack.size() > 0);
imageRequest.exposure = defaultExposure_;
int numPositions = max(1, (int) acquisitionSettings.positionList.size());
int numFrames = max(1, (int) acquisitionSettings.timeSeries.size());
int numChannels = max(1, (int) acquisitionSettings.channelList.size());
int numSlices = max(1, (int) acquisitionSettings.zStack.size());
int numImages = numPositions * numFrames * numChannels * numSlices;
for (int imageIndex = 0; imageIndex < (1 + numImages); ++imageIndex) {
imageRequest.skipImage = false;
imageRequest.closeShutter = true;
if (acquisitionSettings.channelsFirst) {
imageRequest.channelIndex = imageIndex % numChannels;
imageRequest.sliceIndex = (imageIndex / numChannels) % numSlices;
} else // slices first
{
imageRequest.sliceIndex = imageIndex % numSlices;
imageRequest.channelIndex = (imageIndex / numSlices) % numChannels;
}
if (acquisitionSettings.positionsFirst) {
imageRequest.positionIndex = (imageIndex / (numChannels * numSlices)) % numPositions;
imageRequest.timeIndex = (imageIndex / (numChannels * numSlices * numPositions)) % numFrames;
} else // time first
{
imageRequest.timeIndex = (imageIndex / (numChannels * numSlices)) % numFrames;
imageRequest.positionIndex = (imageIndex / (numChannels * numSlices * numFrames)) % numPositions;
}
if (imageRequest.useTime && imageRequest.timeIndex > 0 && imageRequest.positionIndex <= 0 // &&
&& imageRequest.channelIndex <= 0 && imageRequest.sliceIndex <= 0)
imageRequest.waitTime = MM::MMTime(acquisitionSettings.timeSeries[imageRequest.timeIndex] * 1000);
else
imageRequest.waitTime = 0;
if (imageRequest.usePosition)
imageRequest.multiAxisPosition = acquisitionSettings.positionList[imageRequest.positionIndex];
if (imageRequest.useSlice)
imageRequest.slicePosition = acquisitionSettings.zStack[imageRequest.sliceIndex];
if (imageRequest.useChannel) {
imageRequest.channel = acquisitionSettings.channelList[imageRequest.channelIndex];
if (0 != (imageRequest.timeIndex % (imageRequest.channel.skipFrames + 1)))
imageRequest.skipImage = true;
}
if (imageRequest.useChannel && imageRequest.useSlice) {
if (!imageRequest.channel.useZStack && ((unsigned) imageRequest.sliceIndex != (acquisitionSettings.zStack.size() - 1) / 2))
imageRequest.skipImage = true;
}
imageRequest.runAutofocus = acquisitionSettings.useAutofocus;
if (imageRequest.timeIndex > -1) {
imageRequest.runAutofocus = imageRequest.runAutofocus
&& (0 == (imageRequest.timeIndex % (1 + acquisitionSettings.autofocusSkipFrames)));
}
if (imageIndex > 0)
{
if (imageRequest.timeIndex == lastImageRequest.timeIndex
&& imageRequest.positionIndex == lastImageRequest.positionIndex) {
if (acquisitionSettings.keepShutterOpenChannels
&& !acquisitionSettings.keepShutterOpenSlices) {
if (imageRequest.sliceIndex == lastImageRequest.sliceIndex)
lastImageRequest.closeShutter = false;
}
if (acquisitionSettings.keepShutterOpenSlices
&& !acquisitionSettings.keepShutterOpenChannels) {
if (imageRequest.channelIndex == lastImageRequest.channelIndex)
lastImageRequest.closeShutter = false;
}
if (acquisitionSettings.keepShutterOpenSlices
&& acquisitionSettings.keepShutterOpenChannels) {
lastImageRequest.closeShutter = false;
}
}
if (!lastImageRequest.skipImage)
tasks_.push_back(new ImageTask(this, lastImageRequest));
}
if (imageIndex == 0 || !imageRequest.skipImage)
lastImageRequest = imageRequest;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include <sstream>
#include <MQ/Web/Controller.h>
#include <MQ/MQSubsystem.h>
#include <Poco/Util/Application.h>
#include <Poco/NullStream.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
#include <Poco/JSON/TemplateCache.h>
namespace MQ
{
namespace Web
{
Controller::Controller() : _data(new Poco::JSON::Object())
{
}
Controller::~Controller()
{
}
void Controller::handlePart(const Poco::Net::MessageHeader& header, std::istream& stream)
{
//TODO
}
void Controller::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
_parameters = parameters;
_request = &request;
_response = &response;
if ( _parameters.size() > 0 )
{
_action = _parameters.front();
_parameters.erase(_parameters.begin());
}
else
{
_action = getDefaultAction();
}
for(std::vector<std::string>::iterator it = _parameters.begin(); it != _parameters.end(); ++it)
{
int pos = it->find_first_of(':');
if ( pos != std::string::npos )
{
std::string name = it->substr(0, pos);
std::string value = it->substr(pos+1);
_namedParameters[name] = value;
}
}
_form.load(request, request.stream(), *this);
// Make sure everything is read, otherwise this can result
// in Bad Request error in the next call.
Poco::NullOutputStream nos;
Poco::StreamCopier::copyStream(request.stream(), nos);
try
{
beforeAction();
if ( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK
|| _data->has("error") )
{
//TODO: return error template file or json error
}
const ActionMap& actions = getActions();
ActionMap::const_iterator it = actions.find(_action);
if ( it != actions.end() )
{
ActionFn action = it->second;
(this->*action)();
}
afterAction();
}
catch(...)
{
//TODO: redirect to an error page
}
}
void Controller::render(const std::string& templateFile)
{
Poco::JSON::Template::Ptr tpl = Poco::JSON::TemplateCache::instance()->getTemplate(Poco::Path(templateFile));
poco_assert_dbg(!tpl.isNull());
_response->setChunkedTransferEncoding(true);
_response->setContentType("text/html");
// Don't cache are views
_response->set("Cache-Control", "no-cache,no-store,must-revalidate");
_response->set("Pragma", "no-cache");
_response->set("Expires", "0");
tpl->render(_data, _response->send());
}
void Controller::render()
{
_response->setChunkedTransferEncoding(true);
_response->setContentType("application/json");
_data->stringify(_response->send());
}
std::string Controller::htmlize(const std::string &str)
{
std::string::const_iterator it(str.begin());
std::string::const_iterator end(str.end());
std::string html;
for (; it != end; ++it)
{
switch (*it)
{
case '<': html += "<"; break;
case '>': html += ">"; break;
case '"': html += """; break;
case '&': html += "&"; break;
default: html += *it; break;
}
}
return html;
}
} } // Namespace MQ::Web
<commit_msg>Send HTTP_INTERNAL_SERVER error when we can't render a template<commit_after>/*
* Copyright 2010 MQWeb - Franky Braem
*
* Licensed under the EUPL, Version 1.1 or – as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
#include <sstream>
#include <MQ/Web/Controller.h>
#include <MQ/MQSubsystem.h>
#include <Poco/Util/Application.h>
#include <Poco/NullStream.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
#include <Poco/JSON/TemplateCache.h>
namespace MQ
{
namespace Web
{
Controller::Controller() : _data(new Poco::JSON::Object())
{
}
Controller::~Controller()
{
}
void Controller::handlePart(const Poco::Net::MessageHeader& header, std::istream& stream)
{
//TODO
}
void Controller::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
_parameters = parameters;
_request = &request;
_response = &response;
if ( _parameters.size() > 0 )
{
_action = _parameters.front();
_parameters.erase(_parameters.begin());
}
else
{
_action = getDefaultAction();
}
for(std::vector<std::string>::iterator it = _parameters.begin(); it != _parameters.end(); ++it)
{
int pos = it->find_first_of(':');
if ( pos != std::string::npos )
{
std::string name = it->substr(0, pos);
std::string value = it->substr(pos+1);
_namedParameters[name] = value;
}
}
_form.load(request, request.stream(), *this);
// Make sure everything is read, otherwise this can result
// in Bad Request error in the next call.
Poco::NullOutputStream nos;
Poco::StreamCopier::copyStream(request.stream(), nos);
try
{
beforeAction();
if ( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK
|| _data->has("error") )
{
//TODO: return error template file or json error
}
const ActionMap& actions = getActions();
ActionMap::const_iterator it = actions.find(_action);
if ( it != actions.end() )
{
ActionFn action = it->second;
(this->*action)();
}
afterAction();
}
catch(...)
{
//TODO: redirect to an error page
}
}
void Controller::render(const std::string& templateFile)
{
Poco::JSON::Template::Ptr tpl;
try
{
tpl = Poco::JSON::TemplateCache::instance()->getTemplate(Poco::Path(templateFile));
_response->setChunkedTransferEncoding(true);
_response->setContentType("text/html");
// Don't cache are views
_response->set("Cache-Control", "no-cache,no-store,must-revalidate");
_response->set("Pragma", "no-cache");
_response->set("Expires", "0");
tpl->render(_data, _response->send());
}
catch(Poco::FileNotFoundException&)
{
poco_error_f1(Poco::Logger::get("mq.web"), "Can't render template %s", templateFile);
//TODO: redirect to an error page
_response->setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, "Can't render template. Please check the MQWeb configuration.");
_response->send();
}
}
void Controller::render()
{
_response->setChunkedTransferEncoding(true);
_response->setContentType("application/json");
_data->stringify(_response->send());
}
std::string Controller::htmlize(const std::string &str)
{
std::string::const_iterator it(str.begin());
std::string::const_iterator end(str.end());
std::string html;
for (; it != end; ++it)
{
switch (*it)
{
case '<': html += "<"; break;
case '>': html += ">"; break;
case '"': html += """; break;
case '&': html += "&"; break;
default: html += *it; break;
}
}
return html;
}
} } // Namespace MQ::Web
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2019 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 writingraph, 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 <list>
#include <votca/tools/graph.h>
#include <votca/tools/graph_bf_visitor.h>
#include <votca/tools/graph_df_visitor.h>
#include <votca/tools/graphalgorithm.h>
#include <votca/tools/graphvisitor.h>
using namespace std;
namespace votca {
namespace tools {
/**********************
* Internal Functions *
**********************/
list<int> vectorToList_(vector<int> values) {
list<int> values_list;
copy(values.begin(), values.end(), back_inserter(values_list));
return values_list;
}
vector<Edge> edgeSetToVector_(set<Edge> edges) {
vector<Edge> edges_vector;
copy(edges.begin(), edges.end(), back_inserter(edges_vector));
return edges_vector;
}
/********************
* Public Functions *
********************/
bool singleNetwork(Graph& graph, GraphVisitor& graph_visitor) {
exploreGraph(graph, graph_visitor);
return graph_visitor.getExploredVertices().size() ==
graph.getVertices().size() &&
graph.getIsolatedNodes().size() == 0;
}
std::set<Edge> exploreBranch(Graph g, int starting_vertex, const Edge& edge) {
// Check if the starting vertex is in the graph
if (!g.vertexExist(starting_vertex)) {
throw invalid_argument(
"Cannot explore a branch of the graph when the "
"exploration is started from a vertex that does not exist within the "
"graph.");
}
if (!g.edgeExist(edge)) {
throw invalid_argument(
"Edge does not exist in the graph so exploration of"
" the graph branch cannot continue");
}
if (!edge.contains(starting_vertex)) {
throw invalid_argument(
"The edge determining which branch to explore does "
"not contain the starting vertex.");
}
set<Edge> branch_edges;
if (edge.getEndPoint1() == edge.getEndPoint2()) {
branch_edges.insert(edge);
return branch_edges;
}
Graph_BF_Visitor gv_breadth_first;
GraphNode gn;
pair<int, GraphNode> pr_gn(starting_vertex, gn);
gv_breadth_first.exploreNode(pr_gn, g);
gv_breadth_first.setStartingVertex(edge.getOtherEndPoint(starting_vertex));
gv_breadth_first.initialize(g);
branch_edges.insert(edge);
while (!gv_breadth_first.queEmpty()) {
Edge ed = gv_breadth_first.nextEdge(g);
branch_edges.insert(ed);
gv_breadth_first.exec(g, ed);
}
vector<Edge> neigh_edges = g.getNeighEdges(starting_vertex);
for (Edge& ed : neigh_edges) {
int neigh_vertex = ed.getOtherEndPoint(starting_vertex);
if (neigh_vertex != starting_vertex) {
if (gv_breadth_first.vertexExplored(neigh_vertex)) {
branch_edges.insert(ed);
}
}
}
return branch_edges;
}
ReducedGraph reduceGraph(Graph graph) {
/****************************
* Internal Function Class
****************************/
/**
* \brief This class is to help keep track of which vertices have and have not
* been explored.
*
* It is only used within the function and hence the encapsulation, it is not
* a public class and is not meant to be.
**/
class ExplorationRecord {
private:
unordered_map<int, std::pair<bool, int>> vertex_explored_;
size_t unexplored_vertex_count_;
public:
ExplorationRecord(unordered_map<int, std::pair<bool, int>> vertex_explored)
: vertex_explored_(vertex_explored),
unexplored_vertex_count_(vertex_explored.size()){};
void explore(int vertex) {
vertex_explored_[vertex].first = true;
--unexplored_vertex_count_;
}
bool unexploredVerticesExist() { return unexplored_vertex_count_ > 0; }
int getUnexploredVertex() {
vector<int> remaining_unexplored;
for (const pair<int, pair<bool, int>>& vertex_record : vertex_explored_) {
bool vertex_explored = vertex_record.second.first;
if (!vertex_explored) {
int degree = vertex_record.second.second;
if (degree > 2) {
return vertex_record.first;
}
remaining_unexplored.push_back(vertex_record.first);
}
}
// Search tips next
for (const int& vertex : remaining_unexplored) {
if (vertex_explored_[vertex].second == 1) {
return vertex;
}
}
// Finally if there are no tips or junctions left we will return a vertex
// of degree 2 if one exists
for (const int& vertex : remaining_unexplored) {
if (!vertex_explored_[vertex].first) return vertex;
}
throw runtime_error(
"You cannot get an unexplored vertex as they have all"
" been explored.");
}
}; // Class ExplorationRecord
unordered_map<int, pair<bool, int>> unexplored_vertices;
vector<int> vertices = graph.getVertices();
for (const int& vertex : vertices) {
unexplored_vertices[vertex] =
pair<bool, int>(false, graph.getDegree(vertex));
}
ExplorationRecord exploration_record(unexplored_vertices);
vector<vector<int>> chains;
while (exploration_record.unexploredVerticesExist()) {
Graph_DF_Visitor graph_visitor;
int starting_vertex = exploration_record.getUnexploredVertex();
exploration_record.explore(starting_vertex);
graph_visitor.setStartingVertex(starting_vertex);
graph_visitor.initialize(graph);
vector<int> chain{starting_vertex};
int old_vertex = starting_vertex;
bool new_chain = false;
while (!graph_visitor.queEmpty()) {
Edge edge = graph_visitor.nextEdge(graph);
vector<int> unexplored_vertex = graph_visitor.getUnexploredVertex(edge);
if (new_chain) {
if (unexplored_vertex.size() == 0) {
old_vertex = edge.getEndPoint1();
chain.push_back(old_vertex);
new_chain = false;
} else {
old_vertex = edge.getOtherEndPoint(unexplored_vertex.at(0));
chain.push_back(old_vertex);
new_chain = false;
}
}
int new_vertex = edge.getOtherEndPoint(old_vertex);
if (unexplored_vertex.size() == 0) {
chain.push_back(new_vertex);
chains.push_back(chain);
chain.clear();
new_chain = true;
} else if (graph.getDegree(new_vertex) == 1) {
chain.push_back(new_vertex);
chains.push_back(chain);
chain.clear();
exploration_record.explore(new_vertex);
new_chain = true;
} else if (graph.getDegree(new_vertex) > 2) {
chain.push_back(new_vertex);
chains.push_back(chain);
chain.clear();
exploration_record.explore(new_vertex);
new_chain = true;
} else if (unexplored_vertex.size() == 1) {
chain.push_back(new_vertex);
old_vertex = new_vertex;
exploration_record.explore(new_vertex);
}
graph_visitor.exec(graph, edge);
}
}
vector<ReducedEdge> reduced_edges;
for (vector<int> chain : chains) {
ReducedEdge reduced_edge(chain);
reduced_edges.push_back(reduced_edge);
}
ReducedGraph reduced_g(reduced_edges);
auto nodes_graph = graph.getNodes();
reduced_g.copyNodes(graph);
auto nodes_reduced_g = reduced_g.getNodes();
return reduced_g;
}
vector<Graph> decoupleIsolatedSubGraphs(Graph graph) {
cout << "Calling decoupleIsolatedSubGraphs" << endl;
list<int> vertices_list = vectorToList_(graph.getVertices());
vector<Graph> subGraphs;
Graph_BF_Visitor graph_visitor_breadth_first;
graph_visitor_breadth_first.setStartingVertex(vertices_list.front());
if (singleNetwork(graph, graph_visitor_breadth_first)) {
cout << "Is considered a single network " << endl;
subGraphs.push_back(graph);
return subGraphs;
}
list<int>::iterator vertices_iterator = vertices_list.begin();
while (vertices_iterator != vertices_list.end()) {
unordered_map<int, GraphNode> sub_graph_nodes;
Graph_BF_Visitor graph_visitor_breadth_first;
graph_visitor_breadth_first.setStartingVertex(*vertices_iterator);
exploreGraph(graph, graph_visitor_breadth_first);
++vertices_iterator;
set<int> sub_graph_explored_vertices =
graph_visitor_breadth_first.getExploredVertices();
set<Edge> sub_graph_edges;
set<int>::iterator sub_graph_vertex_it =
sub_graph_explored_vertices.begin();
// Means it is an isolated node
while (sub_graph_vertex_it != sub_graph_explored_vertices.end()) {
if (*vertices_iterator == *sub_graph_vertex_it) {
++vertices_iterator;
}
vertices_list.remove(*sub_graph_vertex_it);
vector<Edge> sub_graph_neigh_edges =
graph.getNeighEdges(*sub_graph_vertex_it);
for (const Edge sub_graph_edge : sub_graph_neigh_edges) {
cout << "Getting edge " << sub_graph_edge << endl;
sub_graph_edges.insert(sub_graph_edge);
}
cout << "Getting node " << *sub_graph_vertex_it << endl;
sub_graph_nodes[*sub_graph_vertex_it] =
graph.getNode(*sub_graph_vertex_it);
++sub_graph_vertex_it;
}
cout << "End of subgraph " << endl;
vector<Edge> sub_graph_vector_edges = edgeSetToVector_(sub_graph_edges);
Graph graph_temp(sub_graph_vector_edges, sub_graph_nodes);
subGraphs.push_back(graph_temp);
}
return subGraphs;
}
void exploreGraph(Graph& graph, GraphVisitor& graph_visitor) {
if (!graph.vertexExist(graph_visitor.getStartingVertex())) {
string err = "Cannot explore graph starting at vertex " +
to_string(graph_visitor.getStartingVertex()) +
" because it does not exist in the "
"graph. You can change the starting vertex by using the "
"setStartingVertex method of the visitor instance.";
throw invalid_argument(err);
}
// Create a list of all vertices and determine if they have all been
// explored when the visitor que is empty
graph_visitor.initialize(graph);
while (!graph_visitor.queEmpty()) {
Edge edge = graph_visitor.nextEdge(graph);
graph_visitor.exec(graph, edge);
}
}
} // namespace tools
} // namespace votca
<commit_msg>removed cout from graph algorithm files<commit_after>/*
* Copyright 2009-2019 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 writingraph, 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 <list>
#include <votca/tools/graph.h>
#include <votca/tools/graph_bf_visitor.h>
#include <votca/tools/graph_df_visitor.h>
#include <votca/tools/graphalgorithm.h>
#include <votca/tools/graphvisitor.h>
using namespace std;
namespace votca {
namespace tools {
/**********************
* Internal Functions *
**********************/
list<int> vectorToList_(vector<int> values) {
list<int> values_list;
copy(values.begin(), values.end(), back_inserter(values_list));
return values_list;
}
vector<Edge> edgeSetToVector_(set<Edge> edges) {
vector<Edge> edges_vector;
copy(edges.begin(), edges.end(), back_inserter(edges_vector));
return edges_vector;
}
/********************
* Public Functions *
********************/
bool singleNetwork(Graph& graph, GraphVisitor& graph_visitor) {
exploreGraph(graph, graph_visitor);
return graph_visitor.getExploredVertices().size() ==
graph.getVertices().size() &&
graph.getIsolatedNodes().size() == 0;
}
std::set<Edge> exploreBranch(Graph g, int starting_vertex, const Edge& edge) {
// Check if the starting vertex is in the graph
if (!g.vertexExist(starting_vertex)) {
throw invalid_argument(
"Cannot explore a branch of the graph when the "
"exploration is started from a vertex that does not exist within the "
"graph.");
}
if (!g.edgeExist(edge)) {
throw invalid_argument(
"Edge does not exist in the graph so exploration of"
" the graph branch cannot continue");
}
if (!edge.contains(starting_vertex)) {
throw invalid_argument(
"The edge determining which branch to explore does "
"not contain the starting vertex.");
}
set<Edge> branch_edges;
if (edge.getEndPoint1() == edge.getEndPoint2()) {
branch_edges.insert(edge);
return branch_edges;
}
Graph_BF_Visitor gv_breadth_first;
GraphNode gn;
pair<int, GraphNode> pr_gn(starting_vertex, gn);
gv_breadth_first.exploreNode(pr_gn, g);
gv_breadth_first.setStartingVertex(edge.getOtherEndPoint(starting_vertex));
gv_breadth_first.initialize(g);
branch_edges.insert(edge);
while (!gv_breadth_first.queEmpty()) {
Edge ed = gv_breadth_first.nextEdge(g);
branch_edges.insert(ed);
gv_breadth_first.exec(g, ed);
}
vector<Edge> neigh_edges = g.getNeighEdges(starting_vertex);
for (Edge& ed : neigh_edges) {
int neigh_vertex = ed.getOtherEndPoint(starting_vertex);
if (neigh_vertex != starting_vertex) {
if (gv_breadth_first.vertexExplored(neigh_vertex)) {
branch_edges.insert(ed);
}
}
}
return branch_edges;
}
ReducedGraph reduceGraph(Graph graph) {
/****************************
* Internal Function Class
****************************/
/**
* \brief This class is to help keep track of which vertices have and have not
* been explored.
*
* It is only used within the function and hence the encapsulation, it is not
* a public class and is not meant to be.
**/
class ExplorationRecord {
private:
unordered_map<int, std::pair<bool, int>> vertex_explored_;
size_t unexplored_vertex_count_;
public:
ExplorationRecord(unordered_map<int, std::pair<bool, int>> vertex_explored)
: vertex_explored_(vertex_explored),
unexplored_vertex_count_(vertex_explored.size()){};
void explore(int vertex) {
vertex_explored_[vertex].first = true;
--unexplored_vertex_count_;
}
bool unexploredVerticesExist() { return unexplored_vertex_count_ > 0; }
int getUnexploredVertex() {
vector<int> remaining_unexplored;
for (const pair<int, pair<bool, int>>& vertex_record : vertex_explored_) {
bool vertex_explored = vertex_record.second.first;
if (!vertex_explored) {
int degree = vertex_record.second.second;
if (degree > 2) {
return vertex_record.first;
}
remaining_unexplored.push_back(vertex_record.first);
}
}
// Search tips next
for (const int& vertex : remaining_unexplored) {
if (vertex_explored_[vertex].second == 1) {
return vertex;
}
}
// Finally if there are no tips or junctions left we will return a vertex
// of degree 2 if one exists
for (const int& vertex : remaining_unexplored) {
if (!vertex_explored_[vertex].first) return vertex;
}
throw runtime_error(
"You cannot get an unexplored vertex as they have all"
" been explored.");
}
}; // Class ExplorationRecord
unordered_map<int, pair<bool, int>> unexplored_vertices;
vector<int> vertices = graph.getVertices();
for (const int& vertex : vertices) {
unexplored_vertices[vertex] =
pair<bool, int>(false, graph.getDegree(vertex));
}
ExplorationRecord exploration_record(unexplored_vertices);
vector<vector<int>> chains;
while (exploration_record.unexploredVerticesExist()) {
Graph_DF_Visitor graph_visitor;
int starting_vertex = exploration_record.getUnexploredVertex();
exploration_record.explore(starting_vertex);
graph_visitor.setStartingVertex(starting_vertex);
graph_visitor.initialize(graph);
vector<int> chain{starting_vertex};
int old_vertex = starting_vertex;
bool new_chain = false;
while (!graph_visitor.queEmpty()) {
Edge edge = graph_visitor.nextEdge(graph);
vector<int> unexplored_vertex = graph_visitor.getUnexploredVertex(edge);
if (new_chain) {
if (unexplored_vertex.size() == 0) {
old_vertex = edge.getEndPoint1();
chain.push_back(old_vertex);
new_chain = false;
} else {
old_vertex = edge.getOtherEndPoint(unexplored_vertex.at(0));
chain.push_back(old_vertex);
new_chain = false;
}
}
int new_vertex = edge.getOtherEndPoint(old_vertex);
if (unexplored_vertex.size() == 0) {
chain.push_back(new_vertex);
chains.push_back(chain);
chain.clear();
new_chain = true;
} else if (graph.getDegree(new_vertex) == 1) {
chain.push_back(new_vertex);
chains.push_back(chain);
chain.clear();
exploration_record.explore(new_vertex);
new_chain = true;
} else if (graph.getDegree(new_vertex) > 2) {
chain.push_back(new_vertex);
chains.push_back(chain);
chain.clear();
exploration_record.explore(new_vertex);
new_chain = true;
} else if (unexplored_vertex.size() == 1) {
chain.push_back(new_vertex);
old_vertex = new_vertex;
exploration_record.explore(new_vertex);
}
graph_visitor.exec(graph, edge);
}
}
vector<ReducedEdge> reduced_edges;
for (vector<int> chain : chains) {
ReducedEdge reduced_edge(chain);
reduced_edges.push_back(reduced_edge);
}
ReducedGraph reduced_g(reduced_edges);
auto nodes_graph = graph.getNodes();
reduced_g.copyNodes(graph);
auto nodes_reduced_g = reduced_g.getNodes();
return reduced_g;
}
vector<Graph> decoupleIsolatedSubGraphs(Graph graph) {
list<int> vertices_list = vectorToList_(graph.getVertices());
vector<Graph> subGraphs;
Graph_BF_Visitor graph_visitor_breadth_first;
graph_visitor_breadth_first.setStartingVertex(vertices_list.front());
if (singleNetwork(graph, graph_visitor_breadth_first)) {
subGraphs.push_back(graph);
return subGraphs;
}
list<int>::iterator vertices_iterator = vertices_list.begin();
while (vertices_iterator != vertices_list.end()) {
unordered_map<int, GraphNode> sub_graph_nodes;
Graph_BF_Visitor graph_visitor_breadth_first;
graph_visitor_breadth_first.setStartingVertex(*vertices_iterator);
exploreGraph(graph, graph_visitor_breadth_first);
++vertices_iterator;
set<int> sub_graph_explored_vertices =
graph_visitor_breadth_first.getExploredVertices();
set<Edge> sub_graph_edges;
set<int>::iterator sub_graph_vertex_it =
sub_graph_explored_vertices.begin();
// Means it is an isolated node
while (sub_graph_vertex_it != sub_graph_explored_vertices.end()) {
if (*vertices_iterator == *sub_graph_vertex_it) {
++vertices_iterator;
}
vertices_list.remove(*sub_graph_vertex_it);
vector<Edge> sub_graph_neigh_edges =
graph.getNeighEdges(*sub_graph_vertex_it);
for (const Edge sub_graph_edge : sub_graph_neigh_edges) {
sub_graph_edges.insert(sub_graph_edge);
}
sub_graph_nodes[*sub_graph_vertex_it] =
graph.getNode(*sub_graph_vertex_it);
++sub_graph_vertex_it;
}
vector<Edge> sub_graph_vector_edges = edgeSetToVector_(sub_graph_edges);
Graph graph_temp(sub_graph_vector_edges, sub_graph_nodes);
subGraphs.push_back(graph_temp);
}
return subGraphs;
}
void exploreGraph(Graph& graph, GraphVisitor& graph_visitor) {
if (!graph.vertexExist(graph_visitor.getStartingVertex())) {
string err = "Cannot explore graph starting at vertex " +
to_string(graph_visitor.getStartingVertex()) +
" because it does not exist in the "
"graph. You can change the starting vertex by using the "
"setStartingVertex method of the visitor instance.";
throw invalid_argument(err);
}
// Create a list of all vertices and determine if they have all been
// explored when the visitor que is empty
graph_visitor.initialize(graph);
while (!graph_visitor.queEmpty()) {
Edge edge = graph_visitor.nextEdge(graph);
graph_visitor.exec(graph, edge);
}
}
} // namespace tools
} // namespace votca
<|endoftext|> |
<commit_before>#include "data-student.hpp"
using namespace std;
Semester::Semester() {
period = 0;
}
Semester::Semester(int p) {
period = p;
}
void Student::init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
parseMajors(m);
}
Student::Student() {
init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
int startYear = stringToInt(s), endYear = stringToInt(e);
init(n, startYear, endYear, m);
}
Student::Student(string fn) {
ifstream infile;
infile.open(fn.c_str());
}
void Student::parseMajors(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
string str = removeStartingText(*i, " ");
Major m = Major(str);
majors.push_back(m);
}
}
bool Student::hasTakenCourse() {
return false;
}
void Student::addCourse(const Course& c) {
// cout << "Hi! I'm addCourse (not courses!!)!" << endl;
courses.push_back(c);
// cout << courses.at(courses.size()-1) << endl;
}
void Student::addCourses(string str) {
// cout << "Hi! I'm addCourses!" << endl;
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
Course c = Course(*i);
addCourse(c);
}
}
ostream& Student::getData(ostream &os) {
os << name << ", ";
os << "you are majoring in ";
for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
if (i!=majors.end()-1)
os << *i << ", ";
else
os << "and "<< *i;
}
os << ", while taking:" << endl;
for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
os << *i << endl;
return os;
}
void Student::display() {
cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
os << item.getData(os);
return os;
}
<commit_msg>… or two, it seems.<commit_after>#include "data-student.hpp"
using namespace std;
Semester::Semester() {
period = 0;
}
Semester::Semester(int p) {
period = p;
}
void Student::init(string n, int s, int g, string m) {
name = n;
startingYear = s;
gradutationYear = g;
parseMajors(m);
}
Student::Student() {
init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
int startYear = stringToInt(s), endYear = stringToInt(e);
init(n, startYear, endYear, m);
}
Student::Student(string fn) {
ifstream infile;
infile.open(fn.c_str());
}
void Student::parseMajors(string str) {
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
string str = removeStartingText(*i, " ");
Major m = Major(str);
majors.push_back(m);
}
}
bool Student::hasTakenCourse() {
return false;
}
void Student::addCourse(const Course& c) {
// cout << "Hi! I'm addCourse (not courses!!)!" << endl;
courses.push_back(c);
// cout << courses.at(courses.size()-1) << endl;
}
void Student::addCourses(string str) {
// cout << "Hi! I'm addCourses!" << endl;
vector<string> record = split(str, ',');
for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) {
// cout << *i << endl;
Course c = Course(*i);
addCourse(c);
}
}
ostream& Student::getData(ostream &os) {
os << name << ", ";
os << "you are majoring in ";
for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
if (i!=majors.end()-1)
os << *i << ", ";
else
os << "and "<< *i;
}
os << ", while taking:" << endl;
for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
os << *i << endl;
return os;
}
void Student::display() {
cout << *this << endl;
};
ostream& operator<<(ostream& os, Student& item) {
os << item.getData(os);
return os;
}
<|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 <boost/python.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
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));
}
#ifndef TORRENT_NO_DEPRECATE
torrent_handle add_torrent_depr(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);
}
#endif
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;
}
if (params.has_key("storage_mode"))
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
if (params.has_key("paused"))
p.paused = params["paused"];
if (params.has_key("auto_managed"))
p.auto_managed = params["auto_managed"];
if (params.has_key("duplicate_is_error"))
p.duplicate_is_error = params["duplicate_is_error"];
if (params.has_key("seed_mode"))
p.seed_mode = params["seed_mode"];
if (params.has_key("override_resume_data"))
p.override_resume_data = params["override_resume_data"];
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")
.def_readonly("has_incoming_connections", &session_status::has_incoming_connections)
.def_readonly("upload_rate", &session_status::upload_rate)
.def_readonly("download_rate", &session_status::download_rate)
.def_readonly("payload_upload_rate", &session_status::payload_upload_rate)
.def_readonly("payload_download_rate", &session_status::payload_download_rate)
.def_readonly("total_download", &session_status::total_download)
.def_readonly("total_upload", &session_status::total_upload)
.def_readonly("total_payload_download", &session_status::total_payload_download)
.def_readonly("total_payload_upload", &session_status::total_payload_upload)
.def_readonly("num_peers", &session_status::num_peers)
#ifndef TORRENT_DISABLE_DHT
.def_readonly("dht_nodes", &session_status::dht_nodes)
.def_readonly("dht_cache_nodes", &session_status::dht_node_cache)
.def_readonly("dht_torrents", &session_status::dht_torrents)
#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)
;
enum_<session::session_flags_t>("session_flags_t")
.value("add_default_plugins", session::add_default_plugins)
.value("start_default_features", session::start_default_features)
;
class_<session, boost::noncopyable>("session", no_init)
.def(
init<fingerprint, int>((
arg("fingerprint")=fingerprint("LT",0,1,0,0)
, arg("flags")=session::start_default_features | session::add_default_plugins))
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
)
.def("outgoing_ports", &outgoing_ports)
.def("is_listening", allow_threads(&session::is_listening))
.def("listen_port", allow_threads(&session::listen_port))
.def("status", allow_threads(&session::status))
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
)
.def("start_dht", allow_threads(&session::start_dht))
.def("stop_dht", allow_threads(&session::stop_dht))
.def("dht_state", allow_threads(&session::dht_state))
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
.def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())
#endif
.def("add_torrent", &add_torrent)
#ifndef TORRENT_NO_DEPRECATE
.def(
"add_torrent", &add_torrent_depr
, (
arg("resume_data") = entry(),
arg("storage_mode") = storage_mode_sparse,
arg("paused") = false
)
)
#endif
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
)
.def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit))
.def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit))
.def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit))
.def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit))
.def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit))
.def("download_rate_limit", allow_threads(&session::download_rate_limit))
.def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit))
.def("upload_rate_limit", allow_threads(&session::upload_rate_limit))
.def("set_max_uploads", allow_threads(&session::set_max_uploads))
.def("set_max_connections", allow_threads(&session::set_max_connections))
.def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections))
.def("num_connections", allow_threads(&session::num_connections))
.def("set_settings", allow_threads(&session::set_settings))
.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))
.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))
#ifndef TORRENT_NO_DEPRECATE
.def("set_severity_level", allow_threads(&session::set_severity_level))
#endif
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", allow_threads(&session::pop_alert))
.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("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())
.def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())
.def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())
.def("start_upnp", &start_upnp)
.def("stop_upnp", allow_threads(&session::stop_upnp))
.def("start_lsd", allow_threads(&session::start_lsd))
.def("stop_lsd", allow_threads(&session::stop_lsd))
.def("start_natpmp", &start_natpmp)
.def("stop_natpmp", allow_threads(&session::stop_natpmp))
.def("set_ip_filter", allow_threads(&session::set_ip_filter))
.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))
.def("id", allow_threads(&session::id))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<commit_msg>Update and clean-up session.cpp in python bindings<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 <boost/python.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
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));
}
#ifndef TORRENT_NO_DEPRECATE
torrent_handle add_torrent_depr(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);
}
#endif
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;
}
if (params.has_key("storage_mode"))
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
if (params.has_key("paused"))
p.paused = params["paused"];
if (params.has_key("auto_managed"))
p.auto_managed = params["auto_managed"];
if (params.has_key("duplicate_is_error"))
p.duplicate_is_error = params["duplicate_is_error"];
if (params.has_key("seed_mode"))
p.seed_mode = params["seed_mode"];
if (params.has_key("override_resume_data"))
p.override_resume_data = params["override_resume_data"];
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")
.def_readonly("has_incoming_connections", &session_status::has_incoming_connections)
.def_readonly("upload_rate", &session_status::upload_rate)
.def_readonly("download_rate", &session_status::download_rate)
.def_readonly("total_download", &session_status::total_download)
.def_readonly("total_upload", &session_status::total_upload)
.def_readonly("payload_upload_rate", &session_status::payload_upload_rate)
.def_readonly("payload_download_rate", &session_status::payload_download_rate)
.def_readonly("total_payload_download", &session_status::total_payload_download)
.def_readonly("total_payload_upload", &session_status::total_payload_upload)
.def_readonly("ip_overhead_upload_rate", &session_status::ip_overhead_upload_rate)
.def_readonly("ip_overhead_download_rate", &session_status::ip_overhead_download_rate)
.def_readonly("total_ip_overhead_download", &session_status::total_ip_overhead_download)
.def_readonly("total_ip_overhead_upload", &session_status::total_ip_overhead_upload)
.def_readonly("dht_upload_rate", &session_status::dht_upload_rate)
.def_readonly("dht_download_rate", &session_status::dht_download_rate)
.def_readonly("total_dht_download", &session_status::total_dht_download)
.def_readonly("total_dht_upload", &session_status::total_dht_upload)
.def_readonly("tracker_upload_rate", &session_status::tracker_upload_rate)
.def_readonly("tracker_download_rate", &session_status::tracker_download_rate)
.def_readonly("total_tracker_download", &session_status::total_tracker_download)
.def_readonly("total_tracker_upload", &session_status::total_tracker_upload)
.def_readonly("total_redundant_bytes", &session_status::total_redundant_bytes)
.def_readonly("total_failed_bytes", &session_status::total_failed_bytes)
.def_readonly("num_peers", &session_status::num_peers)
.def_readonly("num_unchoked", &session_status::num_unchoked)
.def_readonly("allowed_upload_slots", &session_status::allowed_upload_slots)
.def_readonly("up_bandwidth_queue", &session_status::up_bandwidth_queue)
.def_readonly("down_bandwidth_queue", &session_status::down_bandwidth_queue)
.def_readonly("up_bandwidth_bytes_queue", &session_status::up_bandwidth_bytes_queue)
.def_readonly("down_bandwidth_bytes_queue", &session_status::down_bandwidth_bytes_queue)
.def_readonly("optimistic_unchoke_counter", &session_status::optimistic_unchoke_counter)
.def_readonly("unchoke_counter", &session_status::unchoke_counter)
#ifndef TORRENT_DISABLE_DHT
.def_readonly("dht_nodes", &session_status::dht_nodes)
.def_readonly("dht_cache_nodes", &session_status::dht_node_cache)
.def_readonly("dht_torrents", &session_status::dht_torrents)
.def_readonly("dht_global_nodes", &session_status::dht_global_nodes)
.def_readonly("active_requests", &session_status::active_requests)
#endif
;
class_<dht_lookup>("dht_lookup")
.def_readonly("type", &dht_lookup::type)
.def_readonly("outstanding_requests", &dht_lookup::outstanding_requests)
.def_readonly("timeouts", &dht_lookup::timeouts)
.def_readonly("response", &dht_lookup::responses)
.def_readonly("branch_factor", &dht_lookup::branch_factor)
;
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)
;
enum_<session::session_flags_t>("session_flags_t")
.value("add_default_plugins", session::add_default_plugins)
.value("start_default_features", session::start_default_features)
;
class_<session, boost::noncopyable>("session", no_init)
.def(
init<fingerprint, int>((
arg("fingerprint")=fingerprint("LT",0,1,0,0)
, arg("flags")=session::start_default_features | session::add_default_plugins))
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
)
.def("outgoing_ports", &outgoing_ports)
.def("is_listening", allow_threads(&session::is_listening))
.def("listen_port", allow_threads(&session::listen_port))
.def("status", allow_threads(&session::status))
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
)
.def("start_dht", allow_threads(&session::start_dht))
.def("stop_dht", allow_threads(&session::stop_dht))
.def("dht_state", allow_threads(&session::dht_state))
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
.def("dht_proxy", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())
#endif
.def("add_torrent", &add_torrent)
#ifndef TORRENT_NO_DEPRECATE
.def(
"add_torrent", &add_torrent_depr
, (
arg("resume_data") = entry(),
arg("storage_mode") = storage_mode_sparse,
arg("paused") = false
)
)
#endif
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
)
.def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit))
.def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit))
.def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit))
.def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit))
.def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit))
.def("download_rate_limit", allow_threads(&session::download_rate_limit))
.def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit))
.def("upload_rate_limit", allow_threads(&session::upload_rate_limit))
.def("set_max_uploads", allow_threads(&session::set_max_uploads))
.def("set_max_connections", allow_threads(&session::set_max_connections))
.def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections))
.def("num_connections", allow_threads(&session::num_connections))
.def("set_settings", allow_threads(&session::set_settings))
.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))
.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))
#ifndef TORRENT_NO_DEPRECATE
.def("set_severity_level", allow_threads(&session::set_severity_level))
#endif
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", allow_threads(&session::pop_alert))
.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("peer_proxy", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())
.def("tracker_proxy", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())
.def("web_seed_proxy", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())
.def("start_upnp", &start_upnp)
.def("stop_upnp", allow_threads(&session::stop_upnp))
.def("start_lsd", allow_threads(&session::start_lsd))
.def("stop_lsd", allow_threads(&session::stop_lsd))
.def("start_natpmp", &start_natpmp)
.def("stop_natpmp", allow_threads(&session::stop_natpmp))
.def("set_ip_filter", allow_threads(&session::set_ip_filter))
.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))
.def("id", allow_threads(&session::id))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<|endoftext|> |
<commit_before>#include "aa_controller.h"
#include "animation.h"
#include "p_rect.h"
//#include "stack_cutter.h"
#include <iostream>
#include <string>
std::array<int,3> aa_controller::prompt_for_quadratic_coeffs(bool allow_negatives) {
std::array<int,3> out{};
std::string vars[] = {"a","b","c"};
for (int i = 0; i < 3; ++i) {
std::cout << vars[i] << " = " << std::endl;
std::cin >> out[i];
while (!allow_negatives && out[i] < 0) {
std::cout << "Non-negative values are not permitted." << std::endl;
std::cout << vars[i] << " = " << std::endl;
std::cin >> out[i];
}
}
return out;
}
void aa_controller::animate_quadratic_factorization(std::array<int,3> coeffs) {
int a = std::get<0>(coeffs);
int b = std::get<1>(coeffs);
int c = std::get<2>(coeffs);
animate_quadratic_factorization(a,b,c);
}
void aa_controller::animate_quadratic_factorization(const int a, const int b, const int c) {
// factors ax^2 + bx + c into (a0x + b0)(a1x + b1)
std::tuple<bool,int,int,int,int> f = algebra::quad_factor(a,b,c);
bool is_factorable = std::get<0>(f);
if (!is_factorable) {
std::cout << "not factorable." << std::endl;
return;
}
int a0 = std::get<1>(f);
int b0 = std::get<2>(f);
int a1 = std::get<3>(f);
int b1 = std::get<4>(f);
// set up scene
// 3 p_rects to start
// 1st column: 1x by a x's
// 2nd column: 1x by b 1's
// 3rd column: 1 by c 1's
// first split second column into two sub-columns
// col 2a: 1x wide by a0*b1 1's high
// col 2b: 1x wide by a1*b0 1's high
// split first column into a0 columns, each of which is 1x wide and a1 x's high (group 1)
// split subcolumns 2a and 2b into two groups of columns:
// group 2a: a0 columns, each of which is 1x wide and b1 1's high
// group 2b: a1 columns, each of which is 1x wide and b0 1's high
// split 3rd column into b0 columns, each of which is 1 wide and b1 1's high (group 3)
// lock the groups together
// move group 2a on top of group 1
// rotate group 2b
// move group 3 on top of group 2b
/*
ascii_viewer vwr{};
auto s = std::make_shared<scene>();
auto root = std::make_shared<node>();
s->set_root(root);
view v{};
ascii_renderer r{};
v.rectangle = located<rect,2>(rect(STD_VIEW_WIDTH,STD_VIEW_HEIGHT),point<2>(0,0));
v.scn = std::weak_ptr<scene>(s);
auto animation_ = std::make_shared<animation<wchar_t>>();
animation_->set_animation_speed(3);
length one{"1",1};
length x{"x",2};
std::shared_ptr<p_rect> group1, group2, group3;
group1 = std::make_shared<p_rect>(std::vector<length>(1,x),std::vector<length>(a,x));
group2 = std::make_shared<p_rect>(std::vector<length>(1,x),std::vector<length>(b,one));
group3 = std::make_shared<p_rect>(std::vector<length>(1,one),std::vector<length>(c,one));
root->add_child(group1);
root->add_child(group2);
root->add_child(group3);
group1->set_location(0,0,0);
group2->set_location(group1->width() + p_rect::unit_size,0,0);
group3->set_location(group2->get_location() + point<3>(group2->width() + p_rect::unit_size,0,0));
animation_->append_frame(v.render(r));
stack_cutter sc{v,animation_};
auto group3_p = sc.cut_and_stack(group3,b0);
group3_p->shift(group2->width() + p_rect::unit_size,0,0);
auto group2_p = sc.cut_and_stack(group2,std::set<int>({static_cast<int>(a0 * b1)}));
auto group2_a = group2_p->get_children()[0];
auto group2_b = group2_p->get_children()[1];
group2_a->set_parent(root,true);
group2_b->set_parent(root,true);
vwr.present(*animation_);
*/
}<commit_msg>remove obsolete animation code. add user interface code.<commit_after>#include "aa_controller.h"
#include "animation.h"
#include "p_rect.h"
#include "quad_factor_animator.h"
#include "viewer.h"
#include <iostream>
#include <string>
std::array<int,3> aa_controller::prompt_for_quadratic_coeffs(bool allow_negatives) {
std::array<int,3> out{};
std::string vars[] = {"a","b","c"};
std::cout << "Enter coefficients : ax^2 + bx + c" << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << vars[i] << " = " << std::endl;
std::cin >> out[i];
while (!allow_negatives && out[i] < 0) {
std::cout << "Non-negative values are not permitted." << std::endl;
std::cout << vars[i] << " = " << std::endl;
std::cin >> out[i];
}
}
return out;
}
void aa_controller::animate_quadratic_factorization(std::array<int,3> coeffs) {
int a = std::get<0>(coeffs);
int b = std::get<1>(coeffs);
int c = std::get<2>(coeffs);
animate_quadratic_factorization(a,b,c);
}
void aa_controller::animate_quadratic_factorization(int a, int b, int c) {
auto qfa = quad_factor_animator(a,b,c);
ascii_viewer vwr{};
vwr.present(*qfa.animate());
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: documentacceleratorconfiguration.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-12-08 08:32:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
#define __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
//__________________________________________
// own includes
#ifndef __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
#include <accelerators/acceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_PRESETHANDLER_HXX_
#include <accelerators/presethandler.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/interface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONSTORAGE_HPP_
#include <drafts/com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
//__________________________________________
// other includes
//__________________________________________
// definition
namespace framework
{
//__________________________________________
/**
implements a read/write access to a document
based accelerator configuration.
*/
class DocumentAcceleratorConfiguration : public AcceleratorConfiguration
, public css::lang::XServiceInfo
, public css::lang::XInitialization
// , public dcss::ui::XUIConfigurationStorage
{
//______________________________________
// member
private:
//----------------------------------
/** points to the root storage of the outside document,
where we can read/save our configuration data. */
css::uno::Reference< css::embed::XStorage > m_xDocumentRoot;
//______________________________________
// interface
public:
//----------------------------------
/** initialize this instance and fill the internal cache.
@param xSMGR
reference to an uno service manager, which is used internaly.
*/
DocumentAcceleratorConfiguration(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR);
virtual ~DocumentAcceleratorConfiguration();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XInitialization
virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
// XUIConfigurationStorage
virtual void SAL_CALL setStorage(const css::uno::Reference< css::embed::XStorage >& xStorage)
throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasStorage()
throw(css::uno::RuntimeException);
//______________________________________
// helper
private:
//----------------------------------
/** read all data into the cache. */
void impl_ts_fillCache();
//----------------------------------
/** forget all currently cached data AND(!)
forget all currently used storages. */
void impl_ts_clearCache();
};
} // namespace framework
#endif // __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
<commit_msg>INTEGRATION: CWS removedrafts (1.4.58); FILE MERGED 2005/02/17 12:47:41 cd 1.4.58.1: #i42557# move UNOIDL types from drafts to com<commit_after>/*************************************************************************
*
* $RCSfile: documentacceleratorconfiguration.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-03-01 19:37:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
#define __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
//__________________________________________
// own includes
#ifndef __FRAMEWORK_ACCELERATORS_ACCELERATORCONFIGURATION_HXX_
#include <accelerators/acceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_PRESETHANDLER_HXX_
#include <accelerators/presethandler.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/interface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONSTORAGE_HPP_
#include <com/sun/star/ui/XUIConfigurationStorage.hpp>
#endif
//__________________________________________
// other includes
//__________________________________________
// definition
namespace framework
{
//__________________________________________
/**
implements a read/write access to a document
based accelerator configuration.
*/
class DocumentAcceleratorConfiguration : public AcceleratorConfiguration
, public css::lang::XServiceInfo
, public css::lang::XInitialization
// , public css::ui::XUIConfigurationStorage
{
//______________________________________
// member
private:
//----------------------------------
/** points to the root storage of the outside document,
where we can read/save our configuration data. */
css::uno::Reference< css::embed::XStorage > m_xDocumentRoot;
//______________________________________
// interface
public:
//----------------------------------
/** initialize this instance and fill the internal cache.
@param xSMGR
reference to an uno service manager, which is used internaly.
*/
DocumentAcceleratorConfiguration(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR);
virtual ~DocumentAcceleratorConfiguration();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XInitialization
virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException);
// XUIConfigurationStorage
virtual void SAL_CALL setStorage(const css::uno::Reference< css::embed::XStorage >& xStorage)
throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasStorage()
throw(css::uno::RuntimeException);
//______________________________________
// helper
private:
//----------------------------------
/** read all data into the cache. */
void impl_ts_fillCache();
//----------------------------------
/** forget all currently cached data AND(!)
forget all currently used storages. */
void impl_ts_clearCache();
};
} // namespace framework
#endif // __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
<|endoftext|> |
<commit_before>// Maintainer: Jan Kristian Sto. Domingo [jstod001@ucr.edu]
// exec.cpp for rshell
#include <iostream>
#include <cstring>
#include <string>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
//Notes on function formats:
//execvp(const char *file, char *const argv[])
// tokenCounter function used to determine size of dynamically
// allocated array for use in the execvp function
unsigned tokenCounter(char* a)
{
unsigned count = 0;
char* token;
token = strtok(a, " ;");
while(token != NULL)
{
token = strtok(NULL, " ;");
count++;
}
return count;
}
int main()
{
int PID = fork();
if(PID == 0)
{
//cout << "child process" << endl;
// command prompt
char* username = getlogin();
char hostname[20];
gethostname(hostname, 20);
cout << username << "@" << hostname << "$ ";
string str_input;
getline(cin, str_input);
// output message for test purposes
// cout << "Original string: " << str_input << endl << endl;
char* c_input = new char[str_input.length() + 1];
strcpy(c_input, str_input.c_str());
// output message for test purposes
// cout << "Converted to cstring: " << c_input << endl << endl;
// new cstring now has to be tokenized and placed into a char**
// for the exec vp function
char* tmp = new char[str_input.length() + 1];
strcpy(tmp, c_input);
// tmp protects the original cstring input
// tmp will be used for the tokenCounter function
unsigned token_count = 0;
token_count = tokenCounter(tmp);
char** arg;
arg = new char* [token_count];
// output message for test purposes
// cout << "c_input after tokenCounter: " << c_input << endl;
// the following chunk of code will take each token
// and place it into arg which will then be used as
// a parameter in execvp
unsigned i = 0;
char* ptr;
ptr = strtok(c_input, " ;");
while(ptr != NULL)
{
arg[i] = ptr;
// cout message for test purposes
cout << "arg[" << i << "] = " << arg[i] << endl;
ptr = strtok(NULL, " ;");
i++;
}
//cout << arg[0] << endl;
char exit_key[5] = "exit";
//cout << "arg[0]: " << arg[0] << endl;
//cout << "exit_key: " << exit_key << endl;
//cout << strcmp(arg[0], exit_key) << endl;
if(*arg[0] == *exit_key)
{
//cout << "executing exit(0)" << endl;
exit(0);
}
else
{
execvp(arg[0], arg);
perror(arg[0]);
}
}
else
{
if(PID == -1)
{
perror("fork");
}
int w = wait(0);
if(w == -1)
{
perror("wait");
}
//cout << "parent process" << endl;
}
return 0;
}
<commit_msg>fixed bug where program will exit if executable entered exists and is four characters in length<commit_after>// Maintainer: Jan Kristian Sto. Domingo [jstod001@ucr.edu]
// exec.cpp for rshell
#include <iostream>
#include <cstring>
#include <string>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
//Notes on function formats:
//execvp(const char *file, char *const argv[])
// tokenCounter function used to determine size of dynamically
// allocated array for use in the execvp function
unsigned tokenCounter(char* a)
{
unsigned count = 0;
char* token;
token = strtok(a, " ;");
while(token != NULL)
{
token = strtok(NULL, " ;");
count++;
}
return count;
}
int main()
{
int PID = fork();
if(PID == 0)
{
//cout << "child process" << endl;
// command prompt
char* username = getlogin();
char hostname[20];
gethostname(hostname, 20);
cout << username << "@" << hostname << "$ ";
string str_input;
getline(cin, str_input);
// output message for test purposes
// cout << "Original string: " << str_input << endl << endl;
char* c_input = new char[str_input.length() + 1];
strcpy(c_input, str_input.c_str());
// output message for test purposes
// cout << "Converted to cstring: " << c_input << endl << endl;
// new cstring now has to be tokenized and placed into a char**
// for the exec vp function
char* tmp = new char[str_input.length() + 1];
strcpy(tmp, c_input);
// tmp protects the original cstring input
// tmp will be used for the tokenCounter function
unsigned token_count = 0;
token_count = tokenCounter(tmp);
char** arg;
arg = new char* [token_count];
// output message for test purposes
// cout << "c_input after tokenCounter: " << c_input << endl;
// the following chunk of code will take each token
// and place it into arg which will then be used as
// a parameter in execvp
unsigned i = 0;
char* ptr;
ptr = strtok(c_input, " ;");
while(ptr != NULL)
{
arg[i] = ptr;
// cout message for test purposes
cout << "arg[" << i << "] = " << arg[i] << endl;
ptr = strtok(NULL, " ;");
i++;
}
//cout << arg[0] << endl;
if(string(arg[0]) == "exit")
{
cout << "executing exit(0)" << endl;
exit(0);
}
else
{
cout << "in execvp" << endl;
execvp(arg[0], arg);
perror(arg[0]);
}
}
else
{
if(PID == -1)
{
perror("fork");
}
int w = wait(0);
if(w == -1)
{
perror("wait");
}
//cout << "parent process" << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "L3G.h"
#include <stdexcept>
#define L3G4200D_ADDRESS_SA0_LOW (0xD0 >> 1)
#define L3G4200D_ADDRESS_SA0_HIGH (0xD2 >> 1)
#define L3GD20_ADDRESS_SA0_LOW (0xD4 >> 1)
#define L3GD20_ADDRESS_SA0_HIGH (0xD6 >> 1)
L3G::L3G(const char * i2cDeviceName) : i2c(i2cDeviceName)
{
// Auto-detect address
// try each possible address and stop if reading WHO_AM_I returns the expected response
detectAddress();
}
void L3G::detectAddress()
{
i2c.addressSet(L3G4200D_ADDRESS_SA0_LOW);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD3) return;
i2c.addressSet(L3G4200D_ADDRESS_SA0_HIGH);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD3) return;
i2c.addressSet(L3GD20_ADDRESS_SA0_LOW);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD4) return;
i2c.addressSet(L3GD20_ADDRESS_SA0_HIGH);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD4) return;
throw std::runtime_error("Could not detect gyro.");
}
// Turns on the gyro and places it in normal mode.
void L3G::enableDefault()
{
// Normal power mode, all axes enabled
writeReg(L3G_CTRL_REG1, 0b00001111);
}
void L3G::writeReg(uint8_t reg, uint8_t value)
{
i2c.writeByte(reg, value);
}
uint8_t L3G::readReg(uint8_t reg)
{
return i2c.readByte(reg);
}
void L3G::read()
{
uint8_t block[6];
i2c.readBlock(0x80 | L3G_OUT_X_L, sizeof(block), block);
g[0] = (int16_t)(block[1] << 8 | block[0]);
g[1] = (int16_t)(block[3] << 8 | block[2]);
g[2] = (int16_t)(block[5] << 8 | block[4]);
}
<commit_msg>Removed some comments.<commit_after>#include "L3G.h"
#include <stdexcept>
#define L3G4200D_ADDRESS_SA0_LOW (0xD0 >> 1)
#define L3G4200D_ADDRESS_SA0_HIGH (0xD2 >> 1)
#define L3GD20_ADDRESS_SA0_LOW (0xD4 >> 1)
#define L3GD20_ADDRESS_SA0_HIGH (0xD6 >> 1)
L3G::L3G(const char * i2cDeviceName) : i2c(i2cDeviceName)
{
detectAddress();
}
void L3G::detectAddress()
{
i2c.addressSet(L3G4200D_ADDRESS_SA0_LOW);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD3) return;
i2c.addressSet(L3G4200D_ADDRESS_SA0_HIGH);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD3) return;
i2c.addressSet(L3GD20_ADDRESS_SA0_LOW);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD4) return;
i2c.addressSet(L3GD20_ADDRESS_SA0_HIGH);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD4) return;
throw std::runtime_error("Could not detect gyro.");
}
// Turns on the gyro and places it in normal mode.
void L3G::enableDefault()
{
// Normal power mode, all axes enabled
writeReg(L3G_CTRL_REG1, 0b00001111);
}
void L3G::writeReg(uint8_t reg, uint8_t value)
{
i2c.writeByte(reg, value);
}
uint8_t L3G::readReg(uint8_t reg)
{
return i2c.readByte(reg);
}
void L3G::read()
{
uint8_t block[6];
i2c.readBlock(0x80 | L3G_OUT_X_L, sizeof(block), block);
g[0] = (int16_t)(block[1] << 8 | block[0]);
g[1] = (int16_t)(block[3] << 8 | block[2]);
g[2] = (int16_t)(block[5] << 8 | block[4]);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
namespace fs = boost::filesystem;
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
assert(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
void open(fs::path const& path, int mode)
{
assert(path.is_complete());
close();
#if defined(_WIN32) && defined(UNICODE)
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
m_fd = ::_open(
#else
m_fd = ::open(
#endif
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode)
#ifdef _WIN32
, S_IREAD | S_IWRITE);
#else
, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< strerror(errno);
throw file_error(msg.str());
}
m_open_mode = mode;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
assert(num_bytes > 0);
assert(m_open_mode & mode_in);
assert(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1 || ret == 0)
{
std::stringstream msg;
msg << "read failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
assert(m_open_mode & mode_out);
assert(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type seek(size_type offset, int m)
{
assert(m_open_mode);
assert(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
throw file_error(msg.str());
}
return ret;
}
size_type tell()
{
assert(m_open_mode);
assert(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(boost::filesystem::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
void file::open(boost::filesystem::path const& p, file::open_mode m)
{
m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>reverted last check-in<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
namespace fs = boost::filesystem;
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
assert(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
void open(fs::path const& path, int mode)
{
assert(path.is_complete());
close();
#if defined(_WIN32) && defined(UNICODE)
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
m_fd = ::_open(
#else
m_fd = ::open(
#endif
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode)
#ifdef _WIN32
, S_IREAD | S_IWRITE);
#else
, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< strerror(errno);
throw file_error(msg.str());
}
m_open_mode = mode;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
assert(m_open_mode & mode_in);
assert(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
assert(m_open_mode & mode_out);
assert(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type seek(size_type offset, int m)
{
assert(m_open_mode);
assert(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
throw file_error(msg.str());
}
return ret;
}
size_type tell()
{
assert(m_open_mode);
assert(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(boost::filesystem::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
void file::open(boost::filesystem::path const& p, file::open_mode m)
{
m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <signal.h>
#include <iostream>
#include <folly/Random.h>
#include <folly/String.h>
#include <folly/init/Init.h>
#include <folly/ssl/Init.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/perf/cpp/AsyncLoadHandler2.h>
using std::cout;
using namespace apache::thrift;
DEFINE_int32(port, 1234, "server port");
DEFINE_int64(num_threads, 4, "number of worker threads");
DEFINE_int64(num_queue_threads, 4, "number of task queue threads");
DEFINE_int32(max_conn_pool_size, 0, "maximum size of idle connection pool");
DEFINE_int32(idle_timeout, 0, "idle timeout (in milliseconds)");
DEFINE_int32(task_timeout, 0, "task timeout (in milliseconds)");
DEFINE_int32(
handshake_timeout,
0,
"SSL handshake timeout (in milliseconds). "
"Default is 0, which is to not set a granular timeout for SSL handshakes. "
"Connections that stall during handshakes may still be timed out "
"with --idle_timeout");
DEFINE_int32(max_connections, 0, "DEPRECATED (REMOVE ME)");
DEFINE_int32(max_requests, 0, "max active requests");
DEFINE_string(cert, "", "server SSL certificate file");
DEFINE_string(key, "", "server SSL private key file");
DEFINE_string(client_ca_list, "", "file pointing to a client CA or list");
DEFINE_string(ticket_seeds, "", "server Ticket seeds file");
DEFINE_string(
ecc_curve, "prime256v1", "The ECC curve to use for EC handshakes");
DEFINE_bool(enable_tfo, true, "Enable TFO");
DEFINE_int32(tfo_queue_size, 1000, "TFO queue size");
void setTunables(ThriftServer* server) {
if (FLAGS_idle_timeout > 0) {
server->setIdleTimeout(std::chrono::milliseconds(FLAGS_idle_timeout));
}
if (FLAGS_task_timeout > 0) {
server->setTaskExpireTime(std::chrono::milliseconds(FLAGS_task_timeout));
}
if (FLAGS_handshake_timeout > 0) {
server->setSSLHandshakeTimeout(
std::chrono::milliseconds(FLAGS_handshake_timeout));
}
}
ThriftServer* g_server = nullptr;
[[noreturn]] void sigHandler(int /* signo */) {
g_server->stop();
exit(0);
}
int main(int argc, char* argv[]) {
folly::init(&argc, &argv);
if (argc != 1) {
fprintf(stderr, "error: unhandled arguments:");
for (int n = 1; n < argc; ++n) {
fprintf(stderr, " %s", argv[n]);
}
fprintf(stderr, "\n");
return 1;
}
auto handler = std::make_shared<AsyncLoadHandler2>();
std::shared_ptr<ThriftServer> server;
server.reset(new ThriftServer());
server->setInterface(handler);
server->setPort(FLAGS_port);
server->setNumIOWorkerThreads(FLAGS_num_threads);
server->setNumCPUWorkerThreads(FLAGS_num_queue_threads);
server->setMaxRequests(FLAGS_max_requests);
server->setFastOpenOptions(FLAGS_enable_tfo, FLAGS_tfo_queue_size);
if (FLAGS_cert.length() > 0 && FLAGS_key.length() > 0) {
auto sslContext = std::make_shared<wangle::SSLContextConfig>();
sslContext->setCertificate(FLAGS_cert, FLAGS_key, "");
sslContext->clientCAFile = FLAGS_client_ca_list;
sslContext->eccCurveName = FLAGS_ecc_curve;
server->setSSLConfig(sslContext);
}
if (!FLAGS_ticket_seeds.empty()) {
server->watchTicketPathForChanges(FLAGS_ticket_seeds);
} else {
// Generate random seeds to use for all workers. If no seeds are set, then
// each worker gets its own random seeds, so session resumptions fail across
// workers.
wangle::TLSTicketKeySeeds seeds;
for (auto* seed : {&seeds.oldSeeds, &seeds.currentSeeds, &seeds.newSeeds}) {
auto randomData = folly::Random::secureRandom<uint64_t>();
auto asHex = folly::hexlify(folly::ByteRange(
(const unsigned char*)&randomData, sizeof(uint64_t)));
seed->push_back(std::move(asHex));
}
server->setTicketSeeds(std::move(seeds));
}
// Set tunable server parameters
setTunables(server.get());
g_server = server.get();
signal(SIGINT, sigHandler);
cout << "Serving requests on port " << FLAGS_port << "...\n";
server->serve();
cout << "Exiting normally" << std::endl;
return 0;
}
<commit_msg>Support disabling active requests counter<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <signal.h>
#include <iostream>
#include <folly/Random.h>
#include <folly/String.h>
#include <folly/init/Init.h>
#include <folly/ssl/Init.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/perf/cpp/AsyncLoadHandler2.h>
using std::cout;
using namespace apache::thrift;
DEFINE_int32(port, 1234, "server port");
DEFINE_int64(num_threads, 4, "number of worker threads");
DEFINE_int64(num_queue_threads, 4, "number of task queue threads");
DEFINE_int32(max_conn_pool_size, 0, "maximum size of idle connection pool");
DEFINE_int32(idle_timeout, 0, "idle timeout (in milliseconds)");
DEFINE_int32(task_timeout, 0, "task timeout (in milliseconds)");
DEFINE_int32(
handshake_timeout,
0,
"SSL handshake timeout (in milliseconds). "
"Default is 0, which is to not set a granular timeout for SSL handshakes. "
"Connections that stall during handshakes may still be timed out "
"with --idle_timeout");
DEFINE_int32(max_connections, 0, "DEPRECATED (REMOVE ME)");
DEFINE_int32(
max_requests,
0,
"max active requests, ignored if disable_active_requests_tracking is true");
DEFINE_bool(
disable_active_requests_tracking,
false,
"Disable active request tracking to improve performance");
DEFINE_string(cert, "", "server SSL certificate file");
DEFINE_string(key, "", "server SSL private key file");
DEFINE_string(client_ca_list, "", "file pointing to a client CA or list");
DEFINE_string(ticket_seeds, "", "server Ticket seeds file");
DEFINE_string(
ecc_curve, "prime256v1", "The ECC curve to use for EC handshakes");
DEFINE_bool(enable_tfo, true, "Enable TFO");
DEFINE_int32(tfo_queue_size, 1000, "TFO queue size");
void setTunables(ThriftServer* server) {
if (FLAGS_idle_timeout > 0) {
server->setIdleTimeout(std::chrono::milliseconds(FLAGS_idle_timeout));
}
if (FLAGS_task_timeout > 0) {
server->setTaskExpireTime(std::chrono::milliseconds(FLAGS_task_timeout));
}
if (FLAGS_handshake_timeout > 0) {
server->setSSLHandshakeTimeout(
std::chrono::milliseconds(FLAGS_handshake_timeout));
}
if (FLAGS_disable_active_requests_tracking) {
server->disableActiveRequestsTracking();
}
}
ThriftServer* g_server = nullptr;
[[noreturn]] void sigHandler(int /* signo */) {
g_server->stop();
exit(0);
}
int main(int argc, char* argv[]) {
folly::init(&argc, &argv);
if (argc != 1) {
fprintf(stderr, "error: unhandled arguments:");
for (int n = 1; n < argc; ++n) {
fprintf(stderr, " %s", argv[n]);
}
fprintf(stderr, "\n");
return 1;
}
auto handler = std::make_shared<AsyncLoadHandler2>();
std::shared_ptr<ThriftServer> server;
server.reset(new ThriftServer());
server->setInterface(handler);
server->setPort(FLAGS_port);
server->setNumIOWorkerThreads(FLAGS_num_threads);
server->setNumCPUWorkerThreads(FLAGS_num_queue_threads);
server->setMaxRequests(FLAGS_max_requests);
server->setFastOpenOptions(FLAGS_enable_tfo, FLAGS_tfo_queue_size);
if (FLAGS_cert.length() > 0 && FLAGS_key.length() > 0) {
auto sslContext = std::make_shared<wangle::SSLContextConfig>();
sslContext->setCertificate(FLAGS_cert, FLAGS_key, "");
sslContext->clientCAFile = FLAGS_client_ca_list;
sslContext->eccCurveName = FLAGS_ecc_curve;
server->setSSLConfig(sslContext);
}
if (!FLAGS_ticket_seeds.empty()) {
server->watchTicketPathForChanges(FLAGS_ticket_seeds);
} else {
// Generate random seeds to use for all workers. If no seeds are set, then
// each worker gets its own random seeds, so session resumptions fail across
// workers.
wangle::TLSTicketKeySeeds seeds;
for (auto* seed : {&seeds.oldSeeds, &seeds.currentSeeds, &seeds.newSeeds}) {
auto randomData = folly::Random::secureRandom<uint64_t>();
auto asHex = folly::hexlify(folly::ByteRange(
(const unsigned char*)&randomData, sizeof(uint64_t)));
seed->push_back(std::move(asHex));
}
server->setTicketSeeds(std::move(seeds));
}
// Set tunable server parameters
setTunables(server.get());
g_server = server.get();
signal(SIGINT, sigHandler);
cout << "Serving requests on port " << FLAGS_port << "...\n";
server->serve();
cout << "Exiting normally" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include "Log.h"
namespace i2p {
namespace log {
static Log logger;
/**
* @brief Maps our loglevel to their symbolic name
*/
static const char * g_LogLevelStr[eNumLogLevels] =
{
"error", // eLogError
"warn", // eLogWarn
"info", // eLogInfo
"debug" // eLogDebug
};
/**
* @brief Colorize log output -- array of terminal control sequences
* @note Using ISO 6429 (ANSI) color sequences
*/
#ifdef _WIN32
static const char *LogMsgColors[] = { "", "", "", "", "" };
#else /* UNIX */
static const char *LogMsgColors[] = {
[eLogError] = "\033[1;31m", /* red */
[eLogWarning] = "\033[1;33m", /* yellow */
[eLogInfo] = "\033[1;36m", /* cyan */
[eLogDebug] = "\033[1;34m", /* blue */
[eNumLogLevels] = "\033[0m", /* reset */
};
#endif
#ifndef _WIN32
/**
* @brief Maps our log levels to syslog one
* @return syslog priority LOG_*, as defined in syslog.h
*/
static inline int GetSyslogPrio (enum LogLevel l) {
int priority = LOG_DEBUG;
switch (l) {
case eLogError : priority = LOG_ERR; break;
case eLogWarning : priority = LOG_WARNING; break;
case eLogInfo : priority = LOG_INFO; break;
case eLogDebug : priority = LOG_DEBUG; break;
default : priority = LOG_DEBUG; break;
}
return priority;
}
#endif
Log::Log():
m_Destination(eLogStdout), m_MinLevel(eLogInfo),
m_LogStream (nullptr), m_Logfile(""), m_HasColors(true),
m_IsRunning (false), m_Thread (nullptr)
{
}
Log::~Log ()
{
delete m_Thread;
}
void Log::Start ()
{
if (!m_IsRunning)
{
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&Log::Run, this));
}
}
void Log::Stop ()
{
switch (m_Destination)
{
#ifndef _WIN32
case eLogSyslog :
closelog();
break;
#endif
case eLogFile:
case eLogStream:
if (m_LogStream) m_LogStream->flush();
break;
default:
/* do nothing */
break;
}
m_IsRunning = false;
m_Queue.WakeUp ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
}
void Log::SetLogLevel (const std::string& level) {
if (level == "error") { m_MinLevel = eLogError; }
else if (level == "warn") { m_MinLevel = eLogWarning; }
else if (level == "info") { m_MinLevel = eLogInfo; }
else if (level == "debug") { m_MinLevel = eLogDebug; }
else {
LogPrint(eLogError, "Log: unknown loglevel: ", level);
return;
}
LogPrint(eLogInfo, "Log: min messages level set to ", level);
}
const char * Log::TimeAsString(std::time_t t) {
if (t != m_LastTimestamp) {
strftime(m_LastDateTime, sizeof(m_LastDateTime), "%H:%M:%S", localtime(&t));
m_LastTimestamp = t;
}
return m_LastDateTime;
}
/**
* @note This function better to be run in separate thread due to disk i/o.
* Unfortunately, with current startup process with late fork() this
* will give us nothing but pain. Maybe later. See in NetDb as example.
*/
void Log::Process(std::shared_ptr<LogMsg> msg)
{
if (!msg) return;
std::hash<std::thread::id> hasher;
unsigned short short_tid;
short_tid = (short) (hasher(msg->tid) % 1000);
switch (m_Destination) {
#ifndef _WIN32
case eLogSyslog:
syslog(GetSyslogPrio(msg->level), "[%03u] %s", short_tid, msg->text.c_str());
break;
#endif
case eLogFile:
case eLogStream:
if (m_LogStream)
*m_LogStream << TimeAsString(msg->timestamp)
<< "@" << short_tid
<< "/" << g_LogLevelStr[msg->level]
<< " - " << msg->text << std::endl;
break;
case eLogStdout:
default:
std::cout << TimeAsString(msg->timestamp)
<< "@" << short_tid
<< "/" << LogMsgColors[msg->level] << g_LogLevelStr[msg->level] << LogMsgColors[eNumLogLevels]
<< " - " << msg->text << std::endl;
break;
} // switch
}
void Log::Run ()
{
while (m_IsRunning)
{
std::shared_ptr<LogMsg> msg;
while (msg = m_Queue.Get ())
Process (msg);
if (m_LogStream) m_LogStream->flush();
if (m_IsRunning)
m_Queue.Wait ();
}
}
void Log::Append(std::shared_ptr<i2p::log::LogMsg> & msg)
{
m_Queue.Put(msg);
}
void Log::SendTo (const std::string& path)
{
if (m_LogStream) m_LogStream = nullptr; // close previous
auto flags = std::ofstream::out | std::ofstream::app;
auto os = std::make_shared<std::ofstream> (path, flags);
if (os->is_open ())
{
m_HasColors = false;
m_Logfile = path;
m_Destination = eLogFile;
m_LogStream = os;
return;
}
LogPrint(eLogError, "Log: can't open file ", path);
}
void Log::SendTo (std::shared_ptr<std::ostream> os) {
m_HasColors = false;
m_Destination = eLogStream;
m_LogStream = os;
}
#ifndef _WIN32
void Log::SendTo(const char *name, int facility) {
m_HasColors = false;
m_Destination = eLogSyslog;
m_LogStream = nullptr;
openlog(name, LOG_CONS | LOG_PID, facility);
}
#endif
void Log::Reopen() {
if (m_Destination == eLogFile)
SendTo(m_Logfile);
}
Log & Logger() {
return logger;
}
} // log
} // i2p
<commit_msg>reopen log upon daemon start<commit_after>/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include "Log.h"
namespace i2p {
namespace log {
static Log logger;
/**
* @brief Maps our loglevel to their symbolic name
*/
static const char * g_LogLevelStr[eNumLogLevels] =
{
"error", // eLogError
"warn", // eLogWarn
"info", // eLogInfo
"debug" // eLogDebug
};
/**
* @brief Colorize log output -- array of terminal control sequences
* @note Using ISO 6429 (ANSI) color sequences
*/
#ifdef _WIN32
static const char *LogMsgColors[] = { "", "", "", "", "" };
#else /* UNIX */
static const char *LogMsgColors[] = {
[eLogError] = "\033[1;31m", /* red */
[eLogWarning] = "\033[1;33m", /* yellow */
[eLogInfo] = "\033[1;36m", /* cyan */
[eLogDebug] = "\033[1;34m", /* blue */
[eNumLogLevels] = "\033[0m", /* reset */
};
#endif
#ifndef _WIN32
/**
* @brief Maps our log levels to syslog one
* @return syslog priority LOG_*, as defined in syslog.h
*/
static inline int GetSyslogPrio (enum LogLevel l) {
int priority = LOG_DEBUG;
switch (l) {
case eLogError : priority = LOG_ERR; break;
case eLogWarning : priority = LOG_WARNING; break;
case eLogInfo : priority = LOG_INFO; break;
case eLogDebug : priority = LOG_DEBUG; break;
default : priority = LOG_DEBUG; break;
}
return priority;
}
#endif
Log::Log():
m_Destination(eLogStdout), m_MinLevel(eLogInfo),
m_LogStream (nullptr), m_Logfile(""), m_HasColors(true),
m_IsRunning (false), m_Thread (nullptr)
{
}
Log::~Log ()
{
delete m_Thread;
}
void Log::Start ()
{
if (!m_IsRunning)
{
Reopen ();
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&Log::Run, this));
}
}
void Log::Stop ()
{
switch (m_Destination)
{
#ifndef _WIN32
case eLogSyslog :
closelog();
break;
#endif
case eLogFile:
case eLogStream:
if (m_LogStream) m_LogStream->flush();
break;
default:
/* do nothing */
break;
}
m_IsRunning = false;
m_Queue.WakeUp ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
}
void Log::SetLogLevel (const std::string& level) {
if (level == "error") { m_MinLevel = eLogError; }
else if (level == "warn") { m_MinLevel = eLogWarning; }
else if (level == "info") { m_MinLevel = eLogInfo; }
else if (level == "debug") { m_MinLevel = eLogDebug; }
else {
LogPrint(eLogError, "Log: unknown loglevel: ", level);
return;
}
LogPrint(eLogInfo, "Log: min messages level set to ", level);
}
const char * Log::TimeAsString(std::time_t t) {
if (t != m_LastTimestamp) {
strftime(m_LastDateTime, sizeof(m_LastDateTime), "%H:%M:%S", localtime(&t));
m_LastTimestamp = t;
}
return m_LastDateTime;
}
/**
* @note This function better to be run in separate thread due to disk i/o.
* Unfortunately, with current startup process with late fork() this
* will give us nothing but pain. Maybe later. See in NetDb as example.
*/
void Log::Process(std::shared_ptr<LogMsg> msg)
{
if (!msg) return;
std::hash<std::thread::id> hasher;
unsigned short short_tid;
short_tid = (short) (hasher(msg->tid) % 1000);
switch (m_Destination) {
#ifndef _WIN32
case eLogSyslog:
syslog(GetSyslogPrio(msg->level), "[%03u] %s", short_tid, msg->text.c_str());
break;
#endif
case eLogFile:
case eLogStream:
if (m_LogStream)
*m_LogStream << TimeAsString(msg->timestamp)
<< "@" << short_tid
<< "/" << g_LogLevelStr[msg->level]
<< " - " << msg->text << std::endl;
break;
case eLogStdout:
default:
std::cout << TimeAsString(msg->timestamp)
<< "@" << short_tid
<< "/" << LogMsgColors[msg->level] << g_LogLevelStr[msg->level] << LogMsgColors[eNumLogLevels]
<< " - " << msg->text << std::endl;
break;
} // switch
}
void Log::Run ()
{
while (m_IsRunning)
{
std::shared_ptr<LogMsg> msg;
while (msg = m_Queue.Get ())
Process (msg);
if (m_LogStream) m_LogStream->flush();
if (m_IsRunning)
m_Queue.Wait ();
}
}
void Log::Append(std::shared_ptr<i2p::log::LogMsg> & msg)
{
m_Queue.Put(msg);
}
void Log::SendTo (const std::string& path)
{
if (m_LogStream) m_LogStream = nullptr; // close previous
auto flags = std::ofstream::out | std::ofstream::app;
auto os = std::make_shared<std::ofstream> (path, flags);
if (os->is_open ())
{
m_HasColors = false;
m_Logfile = path;
m_Destination = eLogFile;
m_LogStream = os;
return;
}
LogPrint(eLogError, "Log: can't open file ", path);
}
void Log::SendTo (std::shared_ptr<std::ostream> os) {
m_HasColors = false;
m_Destination = eLogStream;
m_LogStream = os;
}
#ifndef _WIN32
void Log::SendTo(const char *name, int facility) {
m_HasColors = false;
m_Destination = eLogSyslog;
m_LogStream = nullptr;
openlog(name, LOG_CONS | LOG_PID, facility);
}
#endif
void Log::Reopen() {
if (m_Destination == eLogFile)
SendTo(m_Logfile);
}
Log & Logger() {
return logger;
}
} // log
} // i2p
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
// Maximum number of numbers in files.
const int MAX_SIZE = 1024;
// Total quantity of numbers
int N;
// File counter for heap. Initially equals fileNumber and decreases when all number in a file used.
int fileCtr = 0;
// Number of files
int fileNumber;
// Heap for sorting numbers from main file part by part.
double *dmHeap;
/*
* Struct to be used in main heap.
* Moves like a cursor on a specific file.
*/
struct numbFiles{
// Current number in its file.
double x;
// Remaining number in its file.
int counter;
// Index for its file in filesH[]
int No;
};
// Ordering rule for the heap while merging
struct greater1{
bool operator()(const numbFiles& a, numbFiles& b) const{
return a.x > b.x;
}
};
// Ordering rule for the heap while separating
struct greater2{
bool operator()(const double& a, double& b) const{
return a > b;
}
};
double heap_pop(int& array_size){
array_size--;
double value = dmHeap[array_size];
dmHeap[array_size] = 0;
return value;
}
/*
* Reads the numbers to dmHeap[] from the given file part by part.
* Each file has MAX_SIZE numbers (last file has <= MAX_SIZE).
* Writes the sorted version of the heap to a specific file.
* File name is "/tmp/F_"+fileCtr+".txt".
* For example, 3. part will be written in "F_3.txt".
*/
void readnSeparate(string fname){
ifstream finn (fname);
int i, j;
dmHeap = new double[MAX_SIZE];
finn >> N;
while(!finn.eof()){
fileCtr++;
double x;
for(i = 0 ; i < MAX_SIZE ; i++){
finn >> x;
if(finn.eof()){
if(x != dmHeap[i-1]){
dmHeap[i] = x;
i++;
}
break;
}
dmHeap[i] = x;
}
make_heap(&dmHeap[0],&dmHeap[i],greater2());
string fpath = "";
fpath += "/tmp/F_";
fpath += to_string(fileCtr);
fpath += ".txt";
ofstream fout(fpath);
fout << fixed;
fout.precision(6);
while(i){
pop_heap (&dmHeap[0],&dmHeap[i],greater2());
double x = heap_pop(i);
fout << x <<endl;
}
}
delete[] dmHeap;
}
// Deletes the created files in /tmp directory.
void deleteFiles(){
int i, j;
for(i = 1 ; i <= fileNumber ; i++){
string fpath = "";
fpath += "/tmp/F_";
fpath += to_string(i);
fpath += ".txt";
char f_name[fpath.length()];
for(j = 0 ; j < fpath.length() ; j++)
f_name[j] = fpath[j];
const char* file_name = f_name;
remove(file_name);
}
}
int main(int argc, char *argv[]){
int i, j;
readnSeparate(argv[1]);
fileNumber = fileCtr;
numbFiles heapX[fileCtr];
// Cursor for each file. Starts from index 1.
// filesH[i] shows "/tmp/F_"+i+".txt".
ifstream filesH[fileCtr+1];
// Initialization of heapX[]
for(i = 0 ; i < fileCtr ; i++){
heapX[i].No = i+1;
string fpath = "";
fpath += "/tmp/F_";
fpath += to_string(i+1);
fpath += ".txt";
filesH[i+1].open(fpath);
filesH[i+1] >> heapX[i].x;
heapX[i].counter = MAX_SIZE;
}
heapX[fileCtr-1].counter = N - (fileCtr-1)*MAX_SIZE;
make_heap(&heapX[0],&heapX[fileCtr],greater1());
ofstream fout(argv[2]);
fout << fixed;
fout.precision(6);
/*
* Like in our final exam question there are fileNumber files with MAX_SIZE number of double numbers in them.
* The code puts every file's first number into the heap.
* Then pop the min number and write it on the output file.
* If there is still numbers in the poped number's file, then the new number pushed into the heap.
* If there is no number remains in the poped number's file, then the heap's size decreases
* and this procedure continues until there is only one file remains.
* When one file remains, the code attach the remaining numbers on this file to the output file.
*
*/
for(i = 0 ; i < N ; i++){
if(fileCtr == 1){
fout << heapX[0].x <<endl;
filesH[ heapX[0].No ] >> heapX[0].x;
}
else{
pop_heap (&heapX[0],&heapX[fileCtr],greater1());
fout << heapX[fileCtr-1].x<<endl;
heapX[fileCtr-1].counter--;
if(heapX[fileCtr-1].counter > 0){
filesH[ heapX[fileCtr-1].No ] >> heapX[fileCtr-1].x;
push_heap(&heapX[0],&heapX[fileCtr],greater1());
}
else
fileCtr--;
}
}
fileCtr--;
deleteFiles();
return (0-0);
}
<commit_msg>Delete Main.cc<commit_after><|endoftext|> |
<commit_before>#ifndef __STOUT_MULTIHASHMAP_HPP__
#define __STOUT_MULTIHASHMAP_HPP__
#include <utility>
#include <boost/unordered_map.hpp>
#include "hashset.hpp"
// Implementation of a hash multimap via Boost's
// 'unordered_multimap'. The rationale for creating this is that the
// std::multimap implementation is painful to use (requires lots of
// iterator garbage, as well as the use of 'equal_range' which makes
// for cluttered code).
template <typename K, typename V>
class multihashmap : public boost::unordered_multimap<K, V>
{
public:
void put(const K& key, const V& value);
hashset<V> get(const K& key) const;
bool remove(const K& key);
bool remove(const K& key, const V& value);
bool contains(const K& key) const;
bool contains(const K& key, const V& value) const;
};
template <typename K, typename V>
void multihashmap<K, V>::put(const K& key, const V& value)
{
insert(std::pair<K, V>(key, value));
}
template <typename K, typename V>
hashset<V> multihashmap<K, V>::get(const K& key) const
{
hashset<V> values; // Values to return.
std::pair<typename boost::unordered_multimap<K, V>::const_iterator,
typename boost::unordered_multimap<K, V>::const_iterator> range;
range = equal_range(key);
typename boost::unordered_multimap<K, V>::const_iterator i;
for (i = range.first; i != range.second; ++i) {
values.insert((*i).second);
}
return values;
}
template <typename K, typename V>
bool multihashmap<K, V>::remove(const K& key)
{
return erase(key) > 0;
}
template <typename K, typename V>
bool multihashmap<K, V>::remove(const K& key, const V& value)
{
typename boost::unordered_multimap<K, V>::iterator i;
for (i = find(key); i != boost::unordered_multimap<K, V>::end(); ++i) {
if ((*i).second == value) {
erase(i);
return true;
}
}
return false;
}
template <typename K, typename V>
bool multihashmap<K, V>::contains(const K& key) const
{
return count(key) > 0;
}
template <typename K, typename V>
bool multihashmap<K, V>::contains(const K& key, const V& value) const
{
typename boost::unordered_multimap<K, V>::const_iterator i;
for (i = find(key); i != boost::unordered_multimap<K, V>::end(); ++i) {
if ((*i).second == value) {
return true;
}
}
return false;
}
#endif // __STOUT_MULTIHASHMAP_HPP__
<commit_msg>Updated multihashmap to compile with GCC 4.7<commit_after>#ifndef __STOUT_MULTIHASHMAP_HPP__
#define __STOUT_MULTIHASHMAP_HPP__
#include <utility>
#include <boost/unordered_map.hpp>
#include "hashset.hpp"
// Implementation of a hash multimap via Boost's
// 'unordered_multimap'. The rationale for creating this is that the
// std::multimap implementation is painful to use (requires lots of
// iterator garbage, as well as the use of 'equal_range' which makes
// for cluttered code).
template <typename K, typename V>
class multihashmap : public boost::unordered_multimap<K, V>
{
public:
void put(const K& key, const V& value);
hashset<V> get(const K& key) const;
bool remove(const K& key);
bool remove(const K& key, const V& value);
bool contains(const K& key) const;
bool contains(const K& key, const V& value) const;
};
template <typename K, typename V>
void multihashmap<K, V>::put(const K& key, const V& value)
{
boost::unordered_multimap<K, V>::insert(std::pair<K, V>(key, value));
}
template <typename K, typename V>
hashset<V> multihashmap<K, V>::get(const K& key) const
{
hashset<V> values; // Values to return.
std::pair<typename boost::unordered_multimap<K, V>::const_iterator,
typename boost::unordered_multimap<K, V>::const_iterator> range;
range = boost::unordered_multimap<K, V>::equal_range(key);
typename boost::unordered_multimap<K, V>::const_iterator i;
for (i = range.first; i != range.second; ++i) {
values.insert((*i).second);
}
return values;
}
template <typename K, typename V>
bool multihashmap<K, V>::remove(const K& key)
{
return boost::unordered_multimap<K, V>::erase(key) > 0;
}
template <typename K, typename V>
bool multihashmap<K, V>::remove(const K& key, const V& value)
{
typename boost::unordered_multimap<K, V>::iterator i;
for (i = boost::unordered_multimap<K, V>::find(key);
i != boost::unordered_multimap<K, V>::end();
++i) {
if ((*i).second == value) {
boost::unordered_multimap<K, V>::erase(i);
return true;
}
}
return false;
}
template <typename K, typename V>
bool multihashmap<K, V>::contains(const K& key) const
{
return count(key) > 0;
}
template <typename K, typename V>
bool multihashmap<K, V>::contains(const K& key, const V& value) const
{
typename boost::unordered_multimap<K, V>::const_iterator i;
for (i = boost::unordered_multimap<K, V>::find(key);
i != boost::unordered_multimap<K, V>::end();
++i) {
if ((*i).second == value) {
return true;
}
}
return false;
}
#endif // __STOUT_MULTIHASHMAP_HPP__
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2ituple.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:36:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#define _BGFX_TUPLE_B2ITUPLE_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
namespace basegfx
{
/** Base class for all Points/Vectors with two sal_Int32 values
This class provides all methods common to Point
avd Vector classes which are derived from here.
@derive Use this class to implement Points or Vectors
which are based on two sal_Int32 values
*/
class B2ITuple
{
protected:
sal_Int32 mnX;
sal_Int32 mnY;
public:
/** Create a 2D Tuple
The tuple is initialized to (0, 0)
*/
B2ITuple()
: mnX(0),
mnY(0)
{}
/** Create a 2D Tuple
@param fX
This parameter is used to initialize the X-coordinate
of the 2D Tuple.
@param fY
This parameter is used to initialize the Y-coordinate
of the 2D Tuple.
*/
B2ITuple(sal_Int32 fX, sal_Int32 fY)
: mnX( fX ),
mnY( fY )
{}
/** Create a copy of a 2D Tuple
@param rTup
The 2D Tuple which will be copied.
*/
B2ITuple(const B2ITuple& rTup)
: mnX( rTup.mnX ),
mnY( rTup.mnY )
{}
~B2ITuple()
{}
/// Get X-Coordinate of 2D Tuple
sal_Int32 getX() const
{
return mnX;
}
/// Get Y-Coordinate of 2D Tuple
sal_Int32 getY() const
{
return mnY;
}
/// Set X-Coordinate of 2D Tuple
void setX(sal_Int32 fX)
{
mnX = fX;
}
/// Set Y-Coordinate of 2D Tuple
void setY(sal_Int32 fY)
{
mnY = fY;
}
/// Array-access to 2D Tuple
const sal_Int32& operator[] (int nPos) const
{
// Here, normally one if(...) should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; return mnY;
return *((&mnX) + nPos);
}
/// Array-access to 2D Tuple
sal_Int32& operator[] (int nPos)
{
// Here, normally one if(...) should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; return mnY;
return *((&mnX) + nPos);
}
// operators
//////////////////////////////////////////////////////////////////////
B2ITuple& operator+=( const B2ITuple& rTup )
{
mnX += rTup.mnX;
mnY += rTup.mnY;
return *this;
}
B2ITuple& operator-=( const B2ITuple& rTup )
{
mnX -= rTup.mnX;
mnY -= rTup.mnY;
return *this;
}
B2ITuple& operator/=( const B2ITuple& rTup )
{
mnX /= rTup.mnX;
mnY /= rTup.mnY;
return *this;
}
B2ITuple& operator*=( const B2ITuple& rTup )
{
mnX *= rTup.mnX;
mnY *= rTup.mnY;
return *this;
}
B2ITuple& operator*=(sal_Int32 t)
{
mnX *= t;
mnY *= t;
return *this;
}
B2ITuple& operator/=(sal_Int32 t)
{
mnX /= t;
mnY /= t;
return *this;
}
B2ITuple operator-(void) const
{
return B2ITuple(-mnX, -mnY);
}
bool equalZero() const { return mnX == 0 && mnY == 0; }
bool operator==( const B2ITuple& rTup ) const
{
return rTup.mnX == mnX && rTup.mnY == mnY;
}
bool operator!=( const B2ITuple& rTup ) const
{
return !(*this == rTup);
}
B2ITuple& operator=( const B2ITuple& rTup )
{
mnX = rTup.mnX;
mnY = rTup.mnY;
return *this;
}
static const B2ITuple& getEmptyTuple();
};
// external operators
//////////////////////////////////////////////////////////////////////////
class B2DTuple;
B2ITuple minimum(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple maximum(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple absolute(const B2ITuple& rTup);
B2DTuple interpolate(const B2ITuple& rOld1, const B2ITuple& rOld2, double t);
B2DTuple average(const B2ITuple& rOld1, const B2ITuple& rOld2);
B2DTuple average(const B2ITuple& rOld1, const B2ITuple& rOld2, const B2ITuple& rOld3);
B2ITuple operator+(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator-(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator/(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator*(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator*(const B2ITuple& rTup, sal_Int32 t);
B2ITuple operator*(sal_Int32 t, const B2ITuple& rTup);
B2ITuple operator/(const B2ITuple& rTup, sal_Int32 t);
B2ITuple operator/(sal_Int32 t, const B2ITuple& rTup);
} // end of namespace basegfx
#endif /* _BGFX_TUPLE_B2ITUPLE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.5.88); FILE MERGED 2008/04/01 15:01:11 thb 1.5.88.2: #i85898# Stripping all external header guards 2008/03/28 16:05:46 rt 1.5.88.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2ituple.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#define _BGFX_TUPLE_B2ITUPLE_HXX
#include <sal/types.h>
namespace basegfx
{
/** Base class for all Points/Vectors with two sal_Int32 values
This class provides all methods common to Point
avd Vector classes which are derived from here.
@derive Use this class to implement Points or Vectors
which are based on two sal_Int32 values
*/
class B2ITuple
{
protected:
sal_Int32 mnX;
sal_Int32 mnY;
public:
/** Create a 2D Tuple
The tuple is initialized to (0, 0)
*/
B2ITuple()
: mnX(0),
mnY(0)
{}
/** Create a 2D Tuple
@param fX
This parameter is used to initialize the X-coordinate
of the 2D Tuple.
@param fY
This parameter is used to initialize the Y-coordinate
of the 2D Tuple.
*/
B2ITuple(sal_Int32 fX, sal_Int32 fY)
: mnX( fX ),
mnY( fY )
{}
/** Create a copy of a 2D Tuple
@param rTup
The 2D Tuple which will be copied.
*/
B2ITuple(const B2ITuple& rTup)
: mnX( rTup.mnX ),
mnY( rTup.mnY )
{}
~B2ITuple()
{}
/// Get X-Coordinate of 2D Tuple
sal_Int32 getX() const
{
return mnX;
}
/// Get Y-Coordinate of 2D Tuple
sal_Int32 getY() const
{
return mnY;
}
/// Set X-Coordinate of 2D Tuple
void setX(sal_Int32 fX)
{
mnX = fX;
}
/// Set Y-Coordinate of 2D Tuple
void setY(sal_Int32 fY)
{
mnY = fY;
}
/// Array-access to 2D Tuple
const sal_Int32& operator[] (int nPos) const
{
// Here, normally one if(...) should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; return mnY;
return *((&mnX) + nPos);
}
/// Array-access to 2D Tuple
sal_Int32& operator[] (int nPos)
{
// Here, normally one if(...) should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; return mnY;
return *((&mnX) + nPos);
}
// operators
//////////////////////////////////////////////////////////////////////
B2ITuple& operator+=( const B2ITuple& rTup )
{
mnX += rTup.mnX;
mnY += rTup.mnY;
return *this;
}
B2ITuple& operator-=( const B2ITuple& rTup )
{
mnX -= rTup.mnX;
mnY -= rTup.mnY;
return *this;
}
B2ITuple& operator/=( const B2ITuple& rTup )
{
mnX /= rTup.mnX;
mnY /= rTup.mnY;
return *this;
}
B2ITuple& operator*=( const B2ITuple& rTup )
{
mnX *= rTup.mnX;
mnY *= rTup.mnY;
return *this;
}
B2ITuple& operator*=(sal_Int32 t)
{
mnX *= t;
mnY *= t;
return *this;
}
B2ITuple& operator/=(sal_Int32 t)
{
mnX /= t;
mnY /= t;
return *this;
}
B2ITuple operator-(void) const
{
return B2ITuple(-mnX, -mnY);
}
bool equalZero() const { return mnX == 0 && mnY == 0; }
bool operator==( const B2ITuple& rTup ) const
{
return rTup.mnX == mnX && rTup.mnY == mnY;
}
bool operator!=( const B2ITuple& rTup ) const
{
return !(*this == rTup);
}
B2ITuple& operator=( const B2ITuple& rTup )
{
mnX = rTup.mnX;
mnY = rTup.mnY;
return *this;
}
static const B2ITuple& getEmptyTuple();
};
// external operators
//////////////////////////////////////////////////////////////////////////
class B2DTuple;
B2ITuple minimum(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple maximum(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple absolute(const B2ITuple& rTup);
B2DTuple interpolate(const B2ITuple& rOld1, const B2ITuple& rOld2, double t);
B2DTuple average(const B2ITuple& rOld1, const B2ITuple& rOld2);
B2DTuple average(const B2ITuple& rOld1, const B2ITuple& rOld2, const B2ITuple& rOld3);
B2ITuple operator+(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator-(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator/(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator*(const B2ITuple& rTupA, const B2ITuple& rTupB);
B2ITuple operator*(const B2ITuple& rTup, sal_Int32 t);
B2ITuple operator*(sal_Int32 t, const B2ITuple& rTup);
B2ITuple operator/(const B2ITuple& rTup, sal_Int32 t);
B2ITuple operator/(sal_Int32 t, const B2ITuple& rTup);
} // end of namespace basegfx
#endif /* _BGFX_TUPLE_B2ITUPLE_HXX */
<|endoftext|> |
<commit_before>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <exception>
#include <botan/filters.h>
using Botan::byte;
using Botan::u64bit;
#include "common.h"
#include "timer.h"
#include "bench.h"
/* Discard output to reduce overhead */
struct BitBucket : public Botan::Filter
{
void write(const byte[], u32bit) {}
};
Botan::Filter* lookup(const std::string&,
const std::vector<std::string>&,
const std::string& = "All");
namespace {
double bench_filter(std::string name, Botan::Filter* filter,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
Botan::Pipe pipe(filter, new BitBucket);
pipe.start_msg();
byte buf[32 * 1024];
Timer timer(name, sizeof(buf));
rng.randomize(buf, sizeof(buf));
while(timer.seconds() < seconds)
{
timer.start();
pipe.write(buf, sizeof(buf));
timer.stop();
}
pipe.end_msg();
double bytes_per_sec = timer.events() / timer.seconds();
double mbytes_per_sec = bytes_per_sec / (1024.0 * 1024.0);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(2);
if(html)
{
if(name.find("<") != std::string::npos)
name.replace(name.find("<"), 1, "<");
if(name.find(">") != std::string::npos)
name.replace(name.find(">"), 1, ">");
std::cout << " <TR><TH>" << name
<< std::string(25 - name.length(), ' ') << " <TH>";
std::cout.width(6);
std::cout << mbytes_per_sec << std::endl;
}
else
{
std::cout << name << ": " << std::string(25 - name.length(), ' ');
std::cout.width(6);
std::cout << mbytes_per_sec << " Mbytes/sec" << std::endl;
}
return (mbytes_per_sec);
}
double bench(const std::string& name, const std::string& filtername, bool html,
double seconds, u32bit keylen, u32bit ivlen,
Botan::RandomNumberGenerator& rng)
{
std::vector<std::string> params;
Botan::SecureVector<byte> key(keylen);
rng.randomize(key, key.size());
params.push_back(hex_encode(key, key.size()));
//params.push_back(std::string(int(2*keylen), 'A'));
params.push_back(std::string(int(2* ivlen), 'A'));
Botan::Filter* filter = lookup(filtername, params);
if(filter)
return bench_filter(name, filter, rng, html, seconds);
return 0;
}
}
void benchmark(const std::string& what,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
try {
if(html)
{
std::cout << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD "
<< "HTML 4.0 Transitional//EN\">\n"
<< "<HTML>\n\n"
<< "<TITLE>Botan Benchmarks</TITLE>\n\n"
<< "<BODY>\n\n"
<< "<P><TABLE BORDER CELLSPACING=1>\n"
<< "<THEAD>\n"
<< "<TR><TH>Algorithm "
<< "<TH>Mbytes / second\n"
<< "<TBODY>\n";
}
double sum = 0;
u32bit how_many = 0;
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
if(what == "All" || what == algos[j].type)
{
double speed = bench(algos[j].name, algos[j].filtername,
html, seconds, algos[j].keylen,
algos[j].ivlen, rng);
if(speed > .00001) /* log(0) == -inf -> messed up average */
sum += std::log(speed);
how_many++;
}
if(html)
std::cout << "</TABLE>\n\n";
double average = std::exp(sum / static_cast<double>(how_many));
if(what == "All" && html)
std::cout << "\n<P>Overall speed average: " << average
<< "\n\n";
else if(what == "All")
std::cout << "\nOverall speed average: " << average
<< std::endl;
if(html) std::cout << "</BODY></HTML>\n";
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return;
}
}
u32bit bench_algo(const std::string& name,
Botan::RandomNumberGenerator& rng,
double seconds)
{
try {
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
{
if(algos[j].name == name)
{
bench(algos[j].name, algos[j].filtername, false, seconds,
algos[j].keylen, algos[j].ivlen, rng);
return 1;
}
}
return 0;
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return 0;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return 0;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 0;
}
}
<commit_msg>s/Mbyte/MiB/ to be precise about meaning (2^20 bytes/second)<commit_after>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <exception>
#include <botan/filters.h>
using Botan::byte;
using Botan::u64bit;
#include "common.h"
#include "timer.h"
#include "bench.h"
/* Discard output to reduce overhead */
struct BitBucket : public Botan::Filter
{
void write(const byte[], u32bit) {}
};
Botan::Filter* lookup(const std::string&,
const std::vector<std::string>&,
const std::string& = "All");
namespace {
double bench_filter(std::string name, Botan::Filter* filter,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
Botan::Pipe pipe(filter, new BitBucket);
pipe.start_msg();
byte buf[32 * 1024];
Timer timer(name, sizeof(buf));
rng.randomize(buf, sizeof(buf));
while(timer.seconds() < seconds)
{
timer.start();
pipe.write(buf, sizeof(buf));
timer.stop();
}
pipe.end_msg();
double bytes_per_sec = timer.events() / timer.seconds();
double mbytes_per_sec = bytes_per_sec / (1024.0 * 1024.0);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(2);
if(html)
{
if(name.find("<") != std::string::npos)
name.replace(name.find("<"), 1, "<");
if(name.find(">") != std::string::npos)
name.replace(name.find(">"), 1, ">");
std::cout << " <TR><TH>" << name
<< std::string(25 - name.length(), ' ') << " <TH>";
std::cout.width(6);
std::cout << mbytes_per_sec << std::endl;
}
else
{
std::cout << name << ": " << std::string(25 - name.length(), ' ');
std::cout.width(6);
std::cout << mbytes_per_sec << " MiB/sec" << std::endl;
}
return (mbytes_per_sec);
}
double bench(const std::string& name, const std::string& filtername, bool html,
double seconds, u32bit keylen, u32bit ivlen,
Botan::RandomNumberGenerator& rng)
{
std::vector<std::string> params;
Botan::SecureVector<byte> key(keylen);
rng.randomize(key, key.size());
params.push_back(hex_encode(key, key.size()));
//params.push_back(std::string(int(2*keylen), 'A'));
params.push_back(std::string(int(2* ivlen), 'A'));
Botan::Filter* filter = lookup(filtername, params);
if(filter)
return bench_filter(name, filter, rng, html, seconds);
return 0;
}
}
void benchmark(const std::string& what,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
try {
if(html)
{
std::cout << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD "
<< "HTML 4.0 Transitional//EN\">\n"
<< "<HTML>\n\n"
<< "<TITLE>Botan Benchmarks</TITLE>\n\n"
<< "<BODY>\n\n"
<< "<P><TABLE BORDER CELLSPACING=1>\n"
<< "<THEAD>\n"
<< "<TR><TH>Algorithm "
<< "<TH>Mib / second\n"
<< "<TBODY>\n";
}
double sum = 0;
u32bit how_many = 0;
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
if(what == "All" || what == algos[j].type)
{
double speed = bench(algos[j].name, algos[j].filtername,
html, seconds, algos[j].keylen,
algos[j].ivlen, rng);
if(speed > .00001) /* log(0) == -inf -> messed up average */
sum += std::log(speed);
how_many++;
}
if(html)
std::cout << "</TABLE>\n\n";
double average = std::exp(sum / static_cast<double>(how_many));
if(what == "All" && html)
std::cout << "\n<P>Overall speed average: " << average
<< "\n\n";
else if(what == "All")
std::cout << "\nOverall speed average: " << average
<< std::endl;
if(html) std::cout << "</BODY></HTML>\n";
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return;
}
}
u32bit bench_algo(const std::string& name,
Botan::RandomNumberGenerator& rng,
double seconds)
{
try {
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
{
if(algos[j].name == name)
{
bench(algos[j].name, algos[j].filtername, false, seconds,
algos[j].keylen, algos[j].ivlen, rng);
return 1;
}
}
return 0;
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return 0;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return 0;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 0;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/assert.hpp"
#include "libtorrent/puff.hpp"
#include <vector>
#include <string>
namespace
{
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
TORRENT_ASSERT(buf != 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10 || buf == 0) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != 8 || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
// buffer += 2;
}
return total_size - size;
}
// TODO: 2 it would be nice to use proper error handling here
bool inflate_gzip(
char const* in
, int size
, std::vector<char>& buffer
, int maximum_size
, std::string& error)
{
TORRENT_ASSERT(maximum_size > 0);
int header_len = gzip_header(in, size);
if (header_len < 0)
{
error = "invalid gzip header";
return true;
}
// start off with 4 kilobytes and grow
// if needed
boost::uint32_t destlen = 4096;
int ret = 0;
boost::uint32_t srclen = size - header_len;
in += header_len;
do
{
TORRENT_TRY {
buffer.resize(destlen);
} TORRENT_CATCH(std::exception& e) {
error = "out of memory";
return true;
}
ret = puff((unsigned char*)&buffer[0], &destlen, (unsigned char*)in, &srclen);
// if the destination buffer wasn't large enough, double its
// size and try again. Unless it's already at its max, in which
// case we fail
if (ret == 1) // 1: output space exhausted before completing inflate
{
if (destlen == maximum_size)
{
error = "inflated data too big";
return true;
}
destlen *= 2;
if (destlen > maximum_size)
destlen = maximum_size;
}
} while (ret == 1);
if (ret != 0)
{
error = "error while inflating data";
return true;
}
if (destlen > buffer.size())
{
error = "internal gzip error";
return true;
}
buffer.resize(destlen);
return false;
}
}
<commit_msg>fix inflate_gzip export for unit test<commit_after>/*
Copyright (c) 2007-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/assert.hpp"
#include "libtorrent/puff.hpp"
#include <vector>
#include <string>
namespace
{
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
TORRENT_ASSERT(buf != 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10 || buf == 0) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != 8 || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
// buffer += 2;
}
return total_size - size;
}
// TODO: 2 it would be nice to use proper error handling here
TORRENT_EXTRA_EXPORT bool inflate_gzip(
char const* in
, int size
, std::vector<char>& buffer
, int maximum_size
, std::string& error)
{
TORRENT_ASSERT(maximum_size > 0);
int header_len = gzip_header(in, size);
if (header_len < 0)
{
error = "invalid gzip header";
return true;
}
// start off with 4 kilobytes and grow
// if needed
boost::uint32_t destlen = 4096;
int ret = 0;
boost::uint32_t srclen = size - header_len;
in += header_len;
do
{
TORRENT_TRY {
buffer.resize(destlen);
} TORRENT_CATCH(std::exception& e) {
error = "out of memory";
return true;
}
ret = puff((unsigned char*)&buffer[0], &destlen, (unsigned char*)in, &srclen);
// if the destination buffer wasn't large enough, double its
// size and try again. Unless it's already at its max, in which
// case we fail
if (ret == 1) // 1: output space exhausted before completing inflate
{
if (destlen == maximum_size)
{
error = "inflated data too big";
return true;
}
destlen *= 2;
if (destlen > maximum_size)
destlen = maximum_size;
}
} while (ret == 1);
if (ret != 0)
{
error = "error while inflating data";
return true;
}
if (destlen > buffer.size())
{
error = "internal gzip error";
return true;
}
buffer.resize(destlen);
return false;
}
}
<|endoftext|> |
<commit_before>#include "helix-c/helix.h"
#include "helix/nasdaq/nordic_itch.hh"
#include "helix/net.hh"
#include <cassert>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
inline helix_order_book_t wrap(helix::core::order_book* ob)
{
return reinterpret_cast<helix_order_book_t>(ob);
}
inline helix::core::order_book* unwrap(helix_order_book_t ob)
{
return reinterpret_cast<helix::core::order_book*>(ob);
}
inline helix_trade_t wrap(helix::core::trade* ob)
{
return reinterpret_cast<helix_trade_t>(ob);
}
inline helix::core::trade* unwrap(helix_trade_t ob)
{
return reinterpret_cast<helix::core::trade*>(ob);
}
inline helix_protocol_t wrap(helix::core::protocol* proto)
{
return reinterpret_cast<helix_protocol_t>(proto);
}
inline helix::core::protocol* unwrap(helix_protocol_t proto)
{
return reinterpret_cast<helix::core::protocol*>(proto);
}
inline helix_session_t wrap(helix::core::session* session)
{
return reinterpret_cast<helix_session_t>(session);
}
inline helix::core::session* unwrap(helix_session_t session)
{
return reinterpret_cast<helix::core::session*>(session);
}
helix_protocol_t helix_protocol_lookup(const char *name)
{
if (!strcmp(name, "nasdaq-nordic-moldudp-itch") || !strcmp(name, "nasdaq-nordic-soupfile-itch")) {
return wrap(new helix::nasdaq::nordic_itch_protocol{name});
}
return NULL;
}
helix_session_t
helix_session_create(helix_protocol_t proto, const char *symbol, helix_order_book_callback_t ob_callback, helix_trade_callback_t trade_callback, void *data)
{
vector<string> symbols;
symbols.emplace_back(string{symbol});
auto session = unwrap(proto)->new_session(symbols, data);
session->register_callback([session, ob_callback](const helix::core::order_book& ob) {
ob_callback(wrap(session), wrap(const_cast<helix::core::order_book*>(&ob)));
});
session->register_callback([session, trade_callback](const helix::core::trade& trade) {
trade_callback(wrap(session), wrap(const_cast<helix::core::trade*>(&trade)));
});
return wrap(session);
}
void *helix_session_data(helix_session_t session)
{
return unwrap(session)->data();
}
size_t helix_session_process_packet(helix_session_t session, const char* buf, size_t len)
{
return unwrap(session)->process_packet(helix::net::packet_view{buf, len});
}
const char *helix_order_book_symbol(helix_order_book_t ob)
{
return unwrap(ob)->symbol().c_str();
}
uint64_t helix_order_book_timestamp(helix_order_book_t ob)
{
return unwrap(ob)->timestamp();
}
size_t helix_order_book_bid_levels(helix_order_book_t ob)
{
return unwrap(ob)->bid_levels();
}
size_t helix_order_book_ask_levels(helix_order_book_t ob)
{
return unwrap(ob)->ask_levels();
}
uint64_t helix_order_book_bid_price(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->bid_price(level);
}
uint64_t helix_order_book_bid_size(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->bid_size(level);
}
uint64_t helix_order_book_ask_price(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->ask_price(level);
}
uint64_t helix_order_book_ask_size(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->ask_size(level);
}
uint64_t helix_order_book_midprice(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->midprice(level);
}
helix_trading_state_t helix_order_book_state(helix_order_book_t ob)
{
switch (unwrap(ob)->state()) {
case helix::core::trading_state::unknown: return HELIX_TRADING_STATE_UNKNOWN;
case helix::core::trading_state::halted: return HELIX_TRADING_STATE_HALTED;
case helix::core::trading_state::trading: return HELIX_TRADING_STATE_TRADING;
case helix::core::trading_state::auction: return HELIX_TRADING_STATE_AUCTION;
}
assert(0);
}
const char *helix_trade_symbol(helix_trade_t trade)
{
return unwrap(trade)->symbol.c_str();
}
uint64_t helix_trade_timestamp(helix_trade_t trade)
{
return unwrap(trade)->timestamp;
}
uint64_t helix_trade_price(helix_trade_t trade)
{
return unwrap(trade)->price;
}
uint64_t helix_trade_size(helix_trade_t trade)
{
return unwrap(trade)->size;
}
helix_trade_sign_t helix_trade_sign(helix_trade_t trade)
{
switch (unwrap(trade)->sign) {
case helix::core::trade_sign::buyer_initiated: return HELIX_TRADE_SIGN_BUYER_INITIATED;
case helix::core::trade_sign::seller_initiated: return HELIX_TRADE_SIGN_SELLER_INITIATED;
case helix::core::trade_sign::crossing: return HELIX_TRADE_SIGN_CROSSING;
case helix::core::trade_sign::non_displayable: return HELIX_TRADE_SIGN_NON_DISPLAYABLE;
}
assert(0);
}
<commit_msg>helix.cc: Fix formatting issues<commit_after>#include "helix-c/helix.h"
#include "helix/nasdaq/nordic_itch.hh"
#include "helix/net.hh"
#include <cassert>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
inline helix_order_book_t wrap(helix::core::order_book* ob)
{
return reinterpret_cast<helix_order_book_t>(ob);
}
inline helix::core::order_book* unwrap(helix_order_book_t ob)
{
return reinterpret_cast<helix::core::order_book*>(ob);
}
inline helix_trade_t wrap(helix::core::trade* ob)
{
return reinterpret_cast<helix_trade_t>(ob);
}
inline helix::core::trade* unwrap(helix_trade_t ob)
{
return reinterpret_cast<helix::core::trade*>(ob);
}
inline helix_protocol_t wrap(helix::core::protocol* proto)
{
return reinterpret_cast<helix_protocol_t>(proto);
}
inline helix::core::protocol* unwrap(helix_protocol_t proto)
{
return reinterpret_cast<helix::core::protocol*>(proto);
}
inline helix_session_t wrap(helix::core::session* session)
{
return reinterpret_cast<helix_session_t>(session);
}
inline helix::core::session* unwrap(helix_session_t session)
{
return reinterpret_cast<helix::core::session*>(session);
}
helix_protocol_t helix_protocol_lookup(const char *name)
{
if (!strcmp(name, "nasdaq-nordic-moldudp-itch") || !strcmp(name, "nasdaq-nordic-soupfile-itch")) {
return wrap(new helix::nasdaq::nordic_itch_protocol{name});
}
return NULL;
}
helix_session_t
helix_session_create(helix_protocol_t proto, const char *symbol, helix_order_book_callback_t ob_callback, helix_trade_callback_t trade_callback, void *data)
{
vector<string> symbols;
symbols.emplace_back(string{symbol});
auto session = unwrap(proto)->new_session(symbols, data);
session->register_callback([session, ob_callback](const helix::core::order_book& ob) {
ob_callback(wrap(session), wrap(const_cast<helix::core::order_book*>(&ob)));
});
session->register_callback([session, trade_callback](const helix::core::trade& trade) {
trade_callback(wrap(session), wrap(const_cast<helix::core::trade*>(&trade)));
});
return wrap(session);
}
void *helix_session_data(helix_session_t session)
{
return unwrap(session)->data();
}
size_t helix_session_process_packet(helix_session_t session, const char* buf, size_t len)
{
return unwrap(session)->process_packet(helix::net::packet_view{buf, len});
}
const char *helix_order_book_symbol(helix_order_book_t ob)
{
return unwrap(ob)->symbol().c_str();
}
uint64_t helix_order_book_timestamp(helix_order_book_t ob)
{
return unwrap(ob)->timestamp();
}
size_t helix_order_book_bid_levels(helix_order_book_t ob)
{
return unwrap(ob)->bid_levels();
}
size_t helix_order_book_ask_levels(helix_order_book_t ob)
{
return unwrap(ob)->ask_levels();
}
uint64_t helix_order_book_bid_price(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->bid_price(level);
}
uint64_t helix_order_book_bid_size(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->bid_size(level);
}
uint64_t helix_order_book_ask_price(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->ask_price(level);
}
uint64_t helix_order_book_ask_size(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->ask_size(level);
}
uint64_t helix_order_book_midprice(helix_order_book_t ob, size_t level)
{
return unwrap(ob)->midprice(level);
}
helix_trading_state_t helix_order_book_state(helix_order_book_t ob)
{
switch (unwrap(ob)->state()) {
case helix::core::trading_state::unknown: return HELIX_TRADING_STATE_UNKNOWN;
case helix::core::trading_state::halted: return HELIX_TRADING_STATE_HALTED;
case helix::core::trading_state::trading: return HELIX_TRADING_STATE_TRADING;
case helix::core::trading_state::auction: return HELIX_TRADING_STATE_AUCTION;
}
assert(0);
}
const char *helix_trade_symbol(helix_trade_t trade)
{
return unwrap(trade)->symbol.c_str();
}
uint64_t helix_trade_timestamp(helix_trade_t trade)
{
return unwrap(trade)->timestamp;
}
uint64_t helix_trade_price(helix_trade_t trade)
{
return unwrap(trade)->price;
}
uint64_t helix_trade_size(helix_trade_t trade)
{
return unwrap(trade)->size;
}
helix_trade_sign_t helix_trade_sign(helix_trade_t trade)
{
switch (unwrap(trade)->sign) {
case helix::core::trade_sign::buyer_initiated: return HELIX_TRADE_SIGN_BUYER_INITIATED;
case helix::core::trade_sign::seller_initiated: return HELIX_TRADE_SIGN_SELLER_INITIATED;
case helix::core::trade_sign::crossing: return HELIX_TRADE_SIGN_CROSSING;
case helix::core::trade_sign::non_displayable: return HELIX_TRADE_SIGN_NON_DISPLAYABLE;
}
assert(0);
}
<|endoftext|> |
<commit_before>#include "nanocv.h"
#include "tasks/task_dummy.h"
#include <boost/program_options.hpp>
int main(int argc, char *argv[])
{
ncv::init();
using namespace ncv;
// parse the command line
boost::program_options::options_description po_desc("", 160);
po_desc.add_options()("help,h", "test program");
po_desc.add_options()("threads,t",
boost::program_options::value<size_t>()->default_value(1),
"number of threads to use [1, 64], 0 - use all available threads");
po_desc.add_options()("samples,s",
boost::program_options::value<size_t>()->default_value(100000),
"number of samples to use [1000, 100000]");
po_desc.add_options()("forward",
"evaluate the \'forward\' pass (output)");
po_desc.add_options()("backward",
"evaluate the \'backward' pass (gradient)");
boost::program_options::variables_map po_vm;
boost::program_options::store(
boost::program_options::command_line_parser(argc, argv).options(po_desc).run(),
po_vm);
boost::program_options::notify(po_vm);
// check arguments and options
if ( po_vm.empty() ||
po_vm.count("help"))
{
std::cout << po_desc;
return EXIT_FAILURE;
}
const size_t cmd_threads = math::clamp(po_vm["threads"].as<size_t>(), 0, 64);
const size_t cmd_samples = math::clamp(po_vm["samples"].as<size_t>(), 1000, 100 * 1000);
const bool cmd_forward = po_vm.count("forward");
const bool cmd_backward = po_vm.count("backward");
if (!cmd_forward && !cmd_backward)
{
std::cout << po_desc;
return EXIT_FAILURE;
}
dummy_task_t task;
task.set_rows(28);
task.set_cols(28);
task.set_color(color_mode::luma);
task.set_outputs(10);
task.set_folds(1);
task.set_size(cmd_samples * 100);
task.setup();
const size_t cmd_outputs = task.n_outputs();
const string_t lmodel0;
const string_t lmodel1 = lmodel0 + "linear:dims=100;act-snorm;";
const string_t lmodel2 = lmodel1 + "linear:dims=100;act-snorm;";
const string_t lmodel3 = lmodel2 + "linear:dims=100;act-snorm;";
const string_t lmodel4 = lmodel3 + "linear:dims=100;act-snorm;";
const string_t lmodel5 = lmodel4 + "linear:dims=100;act-snorm;";
string_t cmodel;
cmodel = cmodel + "conv:dims=16,rows=6,cols=6,type=full;act-snorm;pool-max;";
cmodel = cmodel + "conv:dims=32,rows=5,cols=5,type=full;act-snorm;pool-max;";
cmodel = cmodel + "conv:dims=64,rows=4,cols=4,type=full;act-snorm;";
string_t rmodel;
rmodel = rmodel + "conv:dims=16,rows=6,cols=6,type=rand;act-snorm;pool-max;";
rmodel = rmodel + "conv:dims=32,rows=5,cols=5,type=rand;act-snorm;pool-max;";
rmodel = rmodel + "conv:dims=64,rows=4,cols=4,type=rand;act-snorm;";
string_t mmodel;
mmodel = mmodel + "conv:dims=16,rows=6,cols=6,type=mask;act-snorm;pool-max;";
mmodel = mmodel + "conv:dims=32,rows=5,cols=5,type=mask;act-snorm;pool-max;";
mmodel = mmodel + "conv:dims=64,rows=4,cols=4,type=mask;act-snorm;";
const string_t outlayer = "linear:dims=" + text::to_string(cmd_outputs) + ";";
strings_t cmd_networks =
{
lmodel0 + outlayer,
lmodel1 + outlayer,
lmodel2 + outlayer,
lmodel3 + outlayer,
lmodel4 + outlayer,
lmodel5 + outlayer,
cmodel + outlayer,
rmodel + outlayer,
mmodel + outlayer
};
const rloss_t loss = loss_manager_t::instance().get("logistic");
assert(loss);
for (const string_t& cmd_network : cmd_networks)
{
log_info() << "<<< running network [" << cmd_network << "] ...";
// create feed-forward network
const rmodel_t model = model_manager_t::instance().get("forward-network", cmd_network);
assert(model);
model->resize(task, true);
// select random samples
samples_t samples;
{
const ncv::timer_t timer;
sampler_t sampler(task);
sampler.setup(sampler_t::stype::uniform, cmd_samples).setup(sampler_t::atype::annotated);
samples = sampler.get();
log_info() << "<<< selected [" << samples.size()
<< "] random samples in " << timer.elapsed() << ".";
}
// simulate parameter loading & saving
{
const ncv::timer_t timer;
vector_t params(model->psize());
const size_t tests = 1024;
for (size_t t = 0; t < tests; t ++)
{
model->save_params(params);
model->load_params(params);
}
log_info() << "<<< loaded & saved " << tests << "x " << model->psize()
<< " parameters in " << timer.elapsed() << ".";
}
// process the samples
if (cmd_forward)
{
accumulator_t ldata(*model, cmd_threads, "l2n-reg", criterion_t::type::value, 0.1);
const ncv::timer_t timer;
ldata.update(task, samples, *loss);
log_info() << "<<< processed [" << ldata.count() << "] forward samples in " << timer.elapsed() << ".";
}
if (cmd_backward)
{
accumulator_t gdata(*model, cmd_threads, "l2n-reg", criterion_t::type::vgrad, 0.1);
const ncv::timer_t timer;
gdata.update(task, samples, *loss);
log_info() << "<<< processed [" << gdata.count() << "] backward samples in " << timer.elapsed() << ".";
}
log_info();
}
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<commit_msg>default number of samples<commit_after>#include "nanocv.h"
#include "tasks/task_dummy.h"
#include <boost/program_options.hpp>
int main(int argc, char *argv[])
{
ncv::init();
using namespace ncv;
// parse the command line
boost::program_options::options_description po_desc("", 160);
po_desc.add_options()("help,h", "test program");
po_desc.add_options()("threads,t",
boost::program_options::value<size_t>()->default_value(1),
"number of threads to use [1, 64], 0 - use all available threads");
po_desc.add_options()("samples,s",
boost::program_options::value<size_t>()->default_value(10000),
"number of samples to use [1000, 100000]");
po_desc.add_options()("forward",
"evaluate the \'forward\' pass (output)");
po_desc.add_options()("backward",
"evaluate the \'backward' pass (gradient)");
boost::program_options::variables_map po_vm;
boost::program_options::store(
boost::program_options::command_line_parser(argc, argv).options(po_desc).run(),
po_vm);
boost::program_options::notify(po_vm);
// check arguments and options
if ( po_vm.empty() ||
po_vm.count("help"))
{
std::cout << po_desc;
return EXIT_FAILURE;
}
const size_t cmd_threads = math::clamp(po_vm["threads"].as<size_t>(), 0, 64);
const size_t cmd_samples = math::clamp(po_vm["samples"].as<size_t>(), 1000, 100 * 1000);
const bool cmd_forward = po_vm.count("forward");
const bool cmd_backward = po_vm.count("backward");
if (!cmd_forward && !cmd_backward)
{
std::cout << po_desc;
return EXIT_FAILURE;
}
dummy_task_t task;
task.set_rows(28);
task.set_cols(28);
task.set_color(color_mode::luma);
task.set_outputs(10);
task.set_folds(1);
task.set_size(cmd_samples * 100);
task.setup();
const size_t cmd_outputs = task.n_outputs();
const string_t lmodel0;
const string_t lmodel1 = lmodel0 + "linear:dims=100;act-snorm;";
const string_t lmodel2 = lmodel1 + "linear:dims=100;act-snorm;";
const string_t lmodel3 = lmodel2 + "linear:dims=100;act-snorm;";
const string_t lmodel4 = lmodel3 + "linear:dims=100;act-snorm;";
const string_t lmodel5 = lmodel4 + "linear:dims=100;act-snorm;";
string_t cmodel;
cmodel = cmodel + "conv:dims=16,rows=6,cols=6,type=full;act-snorm;pool-max;";
cmodel = cmodel + "conv:dims=32,rows=5,cols=5,type=full;act-snorm;pool-max;";
cmodel = cmodel + "conv:dims=64,rows=4,cols=4,type=full;act-snorm;";
string_t rmodel;
rmodel = rmodel + "conv:dims=16,rows=6,cols=6,type=rand;act-snorm;pool-max;";
rmodel = rmodel + "conv:dims=32,rows=5,cols=5,type=rand;act-snorm;pool-max;";
rmodel = rmodel + "conv:dims=64,rows=4,cols=4,type=rand;act-snorm;";
string_t mmodel;
mmodel = mmodel + "conv:dims=16,rows=6,cols=6,type=mask;act-snorm;pool-max;";
mmodel = mmodel + "conv:dims=32,rows=5,cols=5,type=mask;act-snorm;pool-max;";
mmodel = mmodel + "conv:dims=64,rows=4,cols=4,type=mask;act-snorm;";
const string_t outlayer = "linear:dims=" + text::to_string(cmd_outputs) + ";";
strings_t cmd_networks =
{
lmodel0 + outlayer,
lmodel1 + outlayer,
lmodel2 + outlayer,
lmodel3 + outlayer,
lmodel4 + outlayer,
lmodel5 + outlayer,
cmodel + outlayer,
rmodel + outlayer,
mmodel + outlayer
};
const rloss_t loss = loss_manager_t::instance().get("logistic");
assert(loss);
for (const string_t& cmd_network : cmd_networks)
{
log_info() << "<<< running network [" << cmd_network << "] ...";
// create feed-forward network
const rmodel_t model = model_manager_t::instance().get("forward-network", cmd_network);
assert(model);
model->resize(task, true);
// select random samples
samples_t samples;
{
const ncv::timer_t timer;
sampler_t sampler(task);
sampler.setup(sampler_t::stype::uniform, cmd_samples).setup(sampler_t::atype::annotated);
samples = sampler.get();
log_info() << "<<< selected [" << samples.size()
<< "] random samples in " << timer.elapsed() << ".";
}
// simulate parameter loading & saving
{
const ncv::timer_t timer;
vector_t params(model->psize());
const size_t tests = 1024;
for (size_t t = 0; t < tests; t ++)
{
model->save_params(params);
model->load_params(params);
}
log_info() << "<<< loaded & saved " << tests << "x " << model->psize()
<< " parameters in " << timer.elapsed() << ".";
}
// process the samples
if (cmd_forward)
{
accumulator_t ldata(*model, cmd_threads, "l2n-reg", criterion_t::type::value, 0.1);
const ncv::timer_t timer;
ldata.update(task, samples, *loss);
log_info() << "<<< processed [" << ldata.count() << "] forward samples in " << timer.elapsed() << ".";
}
if (cmd_backward)
{
accumulator_t gdata(*model, cmd_threads, "l2n-reg", criterion_t::type::vgrad, 0.1);
const ncv::timer_t timer;
gdata.update(task, samples, *loss);
log_info() << "<<< processed [" << gdata.count() << "] backward samples in " << timer.elapsed() << ".";
}
log_info();
}
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2003 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <gadget/Devices/DriverConfig.h>
#include <algorithm>
#include <boost/concept_check.hpp>
#include <gadget/Util/Debug.h>
#include <gadget/Type/DeviceConstructor.h>
#include <jccl/Config/ConfigElement.h>
#include <vpr/vpr.h>
#include <vpr/System.h>
// Fakespace pinch driver
#include <drivers/Fakespace/PinchGlove/PinchGloveStandalone.h>
// Gadgeteer pinch driver
#include <drivers/Fakespace/PinchGlove/PinchGlove.h>
extern "C"
{
GADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr)
{
new gadget::DeviceConstructor<gadget::PinchGlove>(inputMgr);
}
}
namespace gadget
{
std::string PinchGlove::getElementType()
{
return "pinch_glove";
}
bool PinchGlove::config(jccl::ConfigElementPtr e)
{
Input::config(e);
mPortName = e->getProperty<std::string>("port");
mBaud = e->getProperty<int>("baud");
// This should have been set by Input(c)
vprASSERT(mThread == NULL);
return true;
}
PinchGlove::~PinchGlove ()
{
stopSampling(); // Stop the glove
delete mGlove; // Delete the glove
}
bool PinchGlove::startSampling()
{
if (NULL != mThread)
{
// Already sampling
return 0;
}
else
{
// Create a new PinchGloveStandalone device.
mGlove = new PinchGloveStandalone();
// Formatting so that the [OK] or [FAILED] lines up with the rest.
const int port_width(17);
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "[PinchGlove] Connecting to PinchGlove on port: "
<< std::setiosflags(std::ios::right) << std::setfill(' ')
<< std::setw(port_width) << mPortName << " ";
// Attempt to connect to the PinchGlove.
if(mGlove->connect(mPortName, mBaud).success())
{
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL) << "[ " << clrSetNORM(clrGREEN) << "OK" << clrRESET << " ]"
<< std::endl << vprDEBUG_FLUSH;
}
else
{
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL) << "[ " << clrSetNORM(clrRED) << "FAILED" << clrRESET << " ]"
<< std::endl << vprDEBUG_FLUSH;
return 0;
}
// Create a vector of strings to hold information about PinchGlove.
std::vector<std::string> info(0);
// Query the PinchGlove for its harware information.
if(!mGlove->printHardwareInformation(info).success())
{
return 0;
}
// Time stamps are on by default. (Pinch Glove Manual p. 8)
if(!mGlove->setTimestampsOn(true).success())
{
return 0;
}
// Print out the hardware information.
for(std::vector<std::string>::iterator itr = info.begin() ; itr != info.end() ; ++itr)
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< (*itr) << std::endl << vprDEBUG_FLUSH;
}
mExitFlag = false;
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< "[PinchGlove] Spawning control thread." << std::endl << vprDEBUG_FLUSH;
// Create a functor that points at the sample method.
vpr::ThreadMemberFunctor<PinchGlove>* memberFunctor =
new vpr::ThreadMemberFunctor<PinchGlove>(this, &PinchGlove::controlLoop, NULL);
// Create a new thread to handle the control.
mThread = new vpr::Thread(memberFunctor);
if (!mThread->valid())
{
return 0;
}
else
{
// We want to add an open hand sample first because the pinch glove
// will not return data until there is a pinch. And until then, the
// hand will be open.
std::vector<DigitalData> digital_sample(10, 0);
addDigitalSample(digital_sample);
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< "[PinchGlove] PinchGlove is active " << std::endl
<< vprDEBUG_FLUSH;
return 1;
}
}
}
void PinchGlove::controlLoop(void* nullParam)
{
boost::ignore_unused_variable_warning(nullParam);
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
<< "[PinchGlove] Entered control thread"
<< std::endl << vprDEBUG_FLUSH;
// Looping until we are told to exit.
while ( !mExitFlag )
{
sample();
}
}
bool PinchGlove::sample()
{
// Create a vector of DigitalData's to hold our sample.
std::vector<DigitalData> digital_sample(10);
// Create a vector to retrieve data from the PinchGloveStandalone
// driver with.
std::vector<int> data(10, 0);
// NOTE: The timestamp retrieved from the PinchGlove is not used at this
// time. This is partly because it saturates at 16382 ticks.
// (13.6511206 seconds) (p. 10 PinchGlove Manual)"
int timestamp = 0;
// Get data from PinchGlove;
if(mGlove->sample(data, timestamp).success())
{
// Copy the data into a new digital sample.
std::copy(data.begin(), data.end(), digital_sample.begin());
// Add a new digital sample to the buffer.
addDigitalSample(digital_sample);
std::vector<GloveData> gloveData=getGloveDataFromDigitalData(digital_sample);
addGloveSample(gloveData);
// Debug print.
//for(unsigned int i = 0 ; i < data.size() ; ++i)
//{
// std::cout << (data[i] > 0 ? "1" : "0");
//}
//std::cout << std::endl;
return 1;
}
return 0;
}
void PinchGlove::updateData()
{
swapDigitalBuffers();
swapGloveBuffers();
return;
}
bool PinchGlove::stopSampling()
{
if ( mThread != NULL )
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "[PinchGlove] Stopping PinchGlove." << std::endl << vprDEBUG_FLUSH;
//Signal to thread that it should exit
mExitFlag = true;
mThread->join();
delete mThread;
mThread = NULL;
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "[PinchGlove] PinchGlove stopped." << std::endl << vprDEBUG_FLUSH;
}
return 1;
}
} // namespace gadget
<commit_msg>Bug fxe: possible deadlock because a debug output statement was not calling vprDEBUG_FLUSH to unlock the stream.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2003 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <gadget/Devices/DriverConfig.h>
#include <algorithm>
#include <boost/concept_check.hpp>
#include <gadget/Util/Debug.h>
#include <gadget/Type/DeviceConstructor.h>
#include <jccl/Config/ConfigElement.h>
#include <vpr/vpr.h>
#include <vpr/System.h>
// Fakespace pinch driver
#include <drivers/Fakespace/PinchGlove/PinchGloveStandalone.h>
// Gadgeteer pinch driver
#include <drivers/Fakespace/PinchGlove/PinchGlove.h>
extern "C"
{
GADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr)
{
new gadget::DeviceConstructor<gadget::PinchGlove>(inputMgr);
}
}
namespace gadget
{
std::string PinchGlove::getElementType()
{
return "pinch_glove";
}
bool PinchGlove::config(jccl::ConfigElementPtr e)
{
Input::config(e);
mPortName = e->getProperty<std::string>("port");
mBaud = e->getProperty<int>("baud");
// This should have been set by Input(c)
vprASSERT(mThread == NULL);
return true;
}
PinchGlove::~PinchGlove ()
{
stopSampling(); // Stop the glove
delete mGlove; // Delete the glove
}
bool PinchGlove::startSampling()
{
if (NULL != mThread)
{
// Already sampling
return 0;
}
else
{
// Create a new PinchGloveStandalone device.
mGlove = new PinchGloveStandalone();
// Formatting so that the [OK] or [FAILED] lines up with the rest.
const int port_width(17);
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "[PinchGlove] Connecting to PinchGlove on port: "
<< std::setiosflags(std::ios::right) << std::setfill(' ')
<< std::setw(port_width) << mPortName << " " << vprDEBUG_FLUSH;
// Attempt to connect to the PinchGlove.
if(mGlove->connect(mPortName, mBaud).success())
{
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL) << "[ " << clrSetNORM(clrGREEN) << "OK" << clrRESET << " ]"
<< std::endl << vprDEBUG_FLUSH;
}
else
{
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL) << "[ " << clrSetNORM(clrRED) << "FAILED" << clrRESET << " ]"
<< std::endl << vprDEBUG_FLUSH;
return 0;
}
// Create a vector of strings to hold information about PinchGlove.
std::vector<std::string> info(0);
// Query the PinchGlove for its harware information.
if(!mGlove->printHardwareInformation(info).success())
{
return 0;
}
// Time stamps are on by default. (Pinch Glove Manual p. 8)
if(!mGlove->setTimestampsOn(true).success())
{
return 0;
}
// Print out the hardware information.
for(std::vector<std::string>::iterator itr = info.begin() ; itr != info.end() ; ++itr)
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< (*itr) << std::endl << vprDEBUG_FLUSH;
}
mExitFlag = false;
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< "[PinchGlove] Spawning control thread." << std::endl << vprDEBUG_FLUSH;
// Create a functor that points at the sample method.
vpr::ThreadMemberFunctor<PinchGlove>* memberFunctor =
new vpr::ThreadMemberFunctor<PinchGlove>(this, &PinchGlove::controlLoop, NULL);
// Create a new thread to handle the control.
mThread = new vpr::Thread(memberFunctor);
if (!mThread->valid())
{
return 0;
}
else
{
// We want to add an open hand sample first because the pinch glove
// will not return data until there is a pinch. And until then, the
// hand will be open.
std::vector<DigitalData> digital_sample(10, 0);
addDigitalSample(digital_sample);
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< "[PinchGlove] PinchGlove is active " << std::endl
<< vprDEBUG_FLUSH;
return 1;
}
}
}
void PinchGlove::controlLoop(void* nullParam)
{
boost::ignore_unused_variable_warning(nullParam);
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
<< "[PinchGlove] Entered control thread"
<< std::endl << vprDEBUG_FLUSH;
// Looping until we are told to exit.
while ( !mExitFlag )
{
sample();
}
}
bool PinchGlove::sample()
{
// Create a vector of DigitalData's to hold our sample.
std::vector<DigitalData> digital_sample(10);
// Create a vector to retrieve data from the PinchGloveStandalone
// driver with.
std::vector<int> data(10, 0);
// NOTE: The timestamp retrieved from the PinchGlove is not used at this
// time. This is partly because it saturates at 16382 ticks.
// (13.6511206 seconds) (p. 10 PinchGlove Manual)"
int timestamp = 0;
// Get data from PinchGlove;
if(mGlove->sample(data, timestamp).success())
{
// Copy the data into a new digital sample.
std::copy(data.begin(), data.end(), digital_sample.begin());
// Add a new digital sample to the buffer.
addDigitalSample(digital_sample);
std::vector<GloveData> gloveData=getGloveDataFromDigitalData(digital_sample);
addGloveSample(gloveData);
// Debug print.
//for(unsigned int i = 0 ; i < data.size() ; ++i)
//{
// std::cout << (data[i] > 0 ? "1" : "0");
//}
//std::cout << std::endl;
return 1;
}
return 0;
}
void PinchGlove::updateData()
{
swapDigitalBuffers();
swapGloveBuffers();
return;
}
bool PinchGlove::stopSampling()
{
if ( mThread != NULL )
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "[PinchGlove] Stopping PinchGlove." << std::endl << vprDEBUG_FLUSH;
//Signal to thread that it should exit
mExitFlag = true;
mThread->join();
delete mThread;
mThread = NULL;
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "[PinchGlove] PinchGlove stopped." << std::endl << vprDEBUG_FLUSH;
}
return 1;
}
} // namespace gadget
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CTables.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:35:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_CALC_TABLES_HXX_
#include "calc/CTables.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_TABLE_HXX_
#include "calc/CTable.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CATALOG_HXX_
#include "calc/CCatalog.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::calc;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
namespace starutil = ::com::sun::star::util;
sdbcx::ObjectType OCalcTables::createObject(const ::rtl::OUString& _rName)
{
return new OCalcTable(this,(OCalcConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
_rName,::rtl::OUString::createFromAscii("TABLE"));
}
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.166); FILE MERGED 2006/09/01 17:22:01 kaib 1.9.166.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CTables.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:20:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_CALC_TABLES_HXX_
#include "calc/CTables.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_TABLE_HXX_
#include "calc/CTable.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CATALOG_HXX_
#include "calc/CCatalog.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::calc;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
namespace starutil = ::com::sun::star::util;
sdbcx::ObjectType OCalcTables::createObject(const ::rtl::OUString& _rName)
{
return new OCalcTable(this,(OCalcConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
_rName,::rtl::OUString::createFromAscii("TABLE"));
}
// -------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MTable.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 18:30:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_MOZAB_TABLE_HXX_
#define _CONNECTIVITY_MOZAB_TABLE_HXX_
#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _CONNECTIVITY_MOZAB_BCONNECTION_HXX_
#include "MConnection.hxx"
#endif
namespace connectivity
{
namespace mozab
{
typedef connectivity::sdbcx::OTable OTable_TYPEDEF;
::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp);
class OTable : public OTable_TYPEDEF
{
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
OConnection* m_pConnection;
public:
OTable( sdbcx::OCollection* _pTables, OConnection* _pConnection);
OTable( sdbcx::OCollection* _pTables,
OConnection* _pConnection,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _Type,
const ::rtl::OUString& _Description = ::rtl::OUString(),
const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
const ::rtl::OUString& _CatalogName = ::rtl::OUString()
);
OConnection* getConnection() { return m_pConnection;}
sal_Bool isReadOnly() const { return sal_False; }
virtual void refreshColumns();
::rtl::OUString getTableName() const { return m_Name; }
::rtl::OUString getSchema() const { return m_SchemaName; }
// com::sun::star::lang::XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
};
}
}
#endif // _CONNECTIVITY_MOZAB_TABLE_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.138); FILE MERGED 2005/09/05 17:24:25 rt 1.3.138.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MTable.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:21:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_MOZAB_TABLE_HXX_
#define _CONNECTIVITY_MOZAB_TABLE_HXX_
#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _CONNECTIVITY_MOZAB_BCONNECTION_HXX_
#include "MConnection.hxx"
#endif
namespace connectivity
{
namespace mozab
{
typedef connectivity::sdbcx::OTable OTable_TYPEDEF;
::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp);
class OTable : public OTable_TYPEDEF
{
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
OConnection* m_pConnection;
public:
OTable( sdbcx::OCollection* _pTables, OConnection* _pConnection);
OTable( sdbcx::OCollection* _pTables,
OConnection* _pConnection,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _Type,
const ::rtl::OUString& _Description = ::rtl::OUString(),
const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
const ::rtl::OUString& _CatalogName = ::rtl::OUString()
);
OConnection* getConnection() { return m_pConnection;}
sal_Bool isReadOnly() const { return sal_False; }
virtual void refreshColumns();
::rtl::OUString getTableName() const { return m_Name; }
::rtl::OUString getSchema() const { return m_SchemaName; }
// com::sun::star::lang::XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
};
}
}
#endif // _CONNECTIVITY_MOZAB_TABLE_HXX_
<|endoftext|> |
<commit_before>/*****************************************************************************
* Copyright (C) 2011-2012 Michael Krufky
*
* Author: Michael Krufky <mkrufky@linuxtv.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "output.h"
#include "log.h"
#define dprintf(fmt, arg...) __dprintf(DBG_OUTPUT, fmt, ##arg)
output_stream::output_stream()
: f_kill_thread(false)
, sock(-1)
, ringbuffer()
, stream_method(OUTPUT_STREAM_UDP)
{
dprintf("()");
memset(&ringbuffer, 0, sizeof(ringbuffer));
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE);
}
output_stream::~output_stream()
{
dprintf("()");
stop();
}
#if 1
output_stream::output_stream(const output_stream&)
{
dprintf("(copy)");
memset(&ringbuffer, 0, sizeof(ringbuffer));
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE);
}
output_stream& output_stream::operator= (const output_stream& cSource)
{
dprintf("(operator=)");
if (this == &cSource)
return *this;
memset(&ringbuffer, 0, sizeof(ringbuffer));
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE);
return *this;
}
#endif
//static
void* output_stream::output_stream_thread(void *p_this)
{
return static_cast<output_stream*>(p_this)->output_stream_thread();
}
#define OUTPUT_STREAM_PACKET_SIZE ((stream_method == OUTPUT_STREAM_UDP) ? 188*7 : 188*175)
void* output_stream::output_stream_thread()
{
uint8_t *data = NULL;
int buf_size;
dprintf("()");
/* push data from output_stream buffer to target */
while (!f_kill_thread) {
buf_size = ringbuffer.get_size();
if (buf_size < OUTPUT_STREAM_PACKET_SIZE) {
usleep(50*1000);
continue;
}
buf_size = ringbuffer.read_ptr((void**)&data, OUTPUT_STREAM_PACKET_SIZE);
stream(data, buf_size);
ringbuffer.advance_read_ptr();
}
pthread_exit(NULL);
}
int output_stream::start()
{
dprintf("()");
int ret = pthread_create(&h_thread, NULL, output_stream_thread, this);
if (0 != ret)
perror("pthread_create() failed");
return ret;
}
void output_stream::stop()
{
dprintf("()");
stop_without_wait();
#if 0
while (-1 != sock_fd) {
usleep(20*1000);
}
#endif
return;
}
int output_stream::push(uint8_t* p_data, int size)
{
/* push data into output_stream buffer */
return ringbuffer.write(p_data, size);
}
int output_stream::stream(uint8_t* p_data, int size)
{
int ret = -1;
/* stream data to target */
switch (stream_method) {
case OUTPUT_STREAM_UDP:
ret = sendto(sock, p_data, size, 0, (struct sockaddr*) &ip_addr, sizeof(ip_addr));
break;
case OUTPUT_STREAM_TCP:
while (0 >= ret) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
struct timeval sel_timeout = {0, 10000};
ret = select(sock + 1, NULL, &fds, NULL, &sel_timeout);
if (ret < 0)
perror("error!");
usleep(20*1000);
}
ret = send(sock, p_data, size, 0);
break;
}
return ret;
}
int output_stream::add(char* target)
{
char *ip;
uint16_t port;
bool b_tcp = false;
bool b_udp = false;
dprintf("(-->%s)", target);
if (strstr(target, ":")) {
ip = strtok(target, ":");
if (strstr(ip, "tcp"))
b_tcp = true;
else
if (strstr(ip, "udp"))
b_udp = true;
if ((b_tcp) || (b_udp)) {
ip = strtok(NULL, ":");
if (strstr(ip, "//") == ip)
ip += 2;
}
// else ip = proto;
port = atoi(strtok(NULL, ":"));
} else {
b_tcp = false;
ip = target;
port = 1234;
}
if (sock >= 0)
close(sock);
sock = socket(AF_INET, (b_tcp) ? SOCK_STREAM : SOCK_DGRAM, (b_tcp) ? IPPROTO_TCP : IPPROTO_UDP);
if (sock >= 0) {
int fl = fcntl(sock, F_GETFL, 0);
if (fcntl(sock, F_SETFL, fl | O_NONBLOCK) < 0)
perror("set non-blocking failed");
memset(&ip_addr, 0, sizeof(ip_addr));
ip_addr.sin_family = AF_INET;
ip_addr.sin_port = htons(port);
if (inet_aton(ip, &ip_addr.sin_addr) == 0) {
perror("ip address translation failed");
return -1;
} else
ringbuffer.reset();
if (b_tcp) {
if ((connect(sock, (struct sockaddr *) &ip_addr, sizeof(ip_addr)) < 0) && (errno != EINPROGRESS)) {
perror("failed to connect to server");
return -1;
}
stream_method = OUTPUT_STREAM_TCP;
} else {
stream_method = OUTPUT_STREAM_UDP;
}
} else {
perror("socket failed");
return -1;
}
dprintf("~(-->%s)", target);
return 0;
}
/* ----------------------------------------------------------------- */
output::output()
: f_kill_thread(false)
, ringbuffer()
, num_targets(0)
, options(OUTPUT_NONE)
{
dprintf("()");
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE*2);
memset(&output_streams, 0, sizeof(output_streams));
output_streams.clear();
}
output::~output()
{
dprintf("()");
stop();
output_streams.clear();
}
#if 0
output::output(const output&)
{
dprintf("(copy)");
output_streams.clear();
}
output& output::operator= (const output& cSource)
{
dprintf("(operator=)");
if (this == &cSource)
return *this;
output_streams.clear();
return *this;
}
#endif
//static
void* output::output_thread(void *p_this)
{
return static_cast<output*>(p_this)->output_thread();
}
void* output::output_thread()
{
int buf_size;
uint8_t *data = NULL;
/* push data from main output buffer into output_stream buffers */
while (!f_kill_thread) {
buf_size = ringbuffer.get_size();
//data = NULL;
if (buf_size) {
buf_size = ringbuffer.read_ptr((void**)&data, buf_size);
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.push(data, buf_size);
ringbuffer.advance_read_ptr();
} else {
usleep(50*1000);
}
}
pthread_exit(NULL);
}
int output::start()
{
dprintf("()");
int ret = pthread_create(&h_thread, NULL, output_thread, this);
if (0 != ret)
perror("pthread_create() failed");
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.start();
return ret;
}
void output::stop()
{
dprintf("()");
/* call stop_without_wait() on everybody first before we call stop() on everybody, which is a blocking function */
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.stop_without_wait();
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.stop();
stop_without_wait();
#if 0
while (-1 != sock_fd) {
usleep(20*1000);
}
#endif
return;
}
int output::push(uint8_t* p_data, int size)
{
/* push data into output buffer */
return ringbuffer.write(p_data, size);
}
int output::push(uint8_t* p_data, enum output_options opt)
{
return (((!options) || (!opt)) || (opt & options)) ? push(p_data, 188) : 0;
}
int output::add(char* target)
{
dprintf("(%d->%s)", num_targets, target);
/* push data into output buffer */
int ret = output_streams[num_targets].add(target);
if (ret == 0)
num_targets++;
else
dprintf("failed to add target #%d: %s", num_targets, target);
dprintf("~(%d->%s)", (ret == 0) ? num_targets - 1 : num_targets, target);
return ret;
}
<commit_msg>output: dont allocate buffers unless at least one target has been specified<commit_after>/*****************************************************************************
* Copyright (C) 2011-2012 Michael Krufky
*
* Author: Michael Krufky <mkrufky@linuxtv.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "output.h"
#include "log.h"
#define dprintf(fmt, arg...) __dprintf(DBG_OUTPUT, fmt, ##arg)
output_stream::output_stream()
: f_kill_thread(false)
, sock(-1)
, ringbuffer()
, stream_method(OUTPUT_STREAM_UDP)
{
dprintf("()");
memset(&ringbuffer, 0, sizeof(ringbuffer));
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE);
}
output_stream::~output_stream()
{
dprintf("()");
stop();
}
#if 1
output_stream::output_stream(const output_stream&)
{
dprintf("(copy)");
memset(&ringbuffer, 0, sizeof(ringbuffer));
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE);
}
output_stream& output_stream::operator= (const output_stream& cSource)
{
dprintf("(operator=)");
if (this == &cSource)
return *this;
memset(&ringbuffer, 0, sizeof(ringbuffer));
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE);
return *this;
}
#endif
//static
void* output_stream::output_stream_thread(void *p_this)
{
return static_cast<output_stream*>(p_this)->output_stream_thread();
}
#define OUTPUT_STREAM_PACKET_SIZE ((stream_method == OUTPUT_STREAM_UDP) ? 188*7 : 188*175)
void* output_stream::output_stream_thread()
{
uint8_t *data = NULL;
int buf_size;
dprintf("()");
/* push data from output_stream buffer to target */
while (!f_kill_thread) {
buf_size = ringbuffer.get_size();
if (buf_size < OUTPUT_STREAM_PACKET_SIZE) {
usleep(50*1000);
continue;
}
buf_size = ringbuffer.read_ptr((void**)&data, OUTPUT_STREAM_PACKET_SIZE);
stream(data, buf_size);
ringbuffer.advance_read_ptr();
}
pthread_exit(NULL);
}
int output_stream::start()
{
dprintf("()");
int ret = pthread_create(&h_thread, NULL, output_stream_thread, this);
if (0 != ret)
perror("pthread_create() failed");
return ret;
}
void output_stream::stop()
{
dprintf("()");
stop_without_wait();
#if 0
while (-1 != sock_fd) {
usleep(20*1000);
}
#endif
return;
}
int output_stream::push(uint8_t* p_data, int size)
{
/* push data into output_stream buffer */
return ringbuffer.write(p_data, size);
}
int output_stream::stream(uint8_t* p_data, int size)
{
int ret = -1;
/* stream data to target */
switch (stream_method) {
case OUTPUT_STREAM_UDP:
ret = sendto(sock, p_data, size, 0, (struct sockaddr*) &ip_addr, sizeof(ip_addr));
break;
case OUTPUT_STREAM_TCP:
while (0 >= ret) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
struct timeval sel_timeout = {0, 10000};
ret = select(sock + 1, NULL, &fds, NULL, &sel_timeout);
if (ret < 0)
perror("error!");
usleep(20*1000);
}
ret = send(sock, p_data, size, 0);
break;
}
return ret;
}
int output_stream::add(char* target)
{
char *ip;
uint16_t port;
bool b_tcp = false;
bool b_udp = false;
dprintf("(-->%s)", target);
if (strstr(target, ":")) {
ip = strtok(target, ":");
if (strstr(ip, "tcp"))
b_tcp = true;
else
if (strstr(ip, "udp"))
b_udp = true;
if ((b_tcp) || (b_udp)) {
ip = strtok(NULL, ":");
if (strstr(ip, "//") == ip)
ip += 2;
}
// else ip = proto;
port = atoi(strtok(NULL, ":"));
} else {
b_tcp = false;
ip = target;
port = 1234;
}
if (sock >= 0)
close(sock);
sock = socket(AF_INET, (b_tcp) ? SOCK_STREAM : SOCK_DGRAM, (b_tcp) ? IPPROTO_TCP : IPPROTO_UDP);
if (sock >= 0) {
int fl = fcntl(sock, F_GETFL, 0);
if (fcntl(sock, F_SETFL, fl | O_NONBLOCK) < 0)
perror("set non-blocking failed");
memset(&ip_addr, 0, sizeof(ip_addr));
ip_addr.sin_family = AF_INET;
ip_addr.sin_port = htons(port);
if (inet_aton(ip, &ip_addr.sin_addr) == 0) {
perror("ip address translation failed");
return -1;
} else
ringbuffer.reset();
if (b_tcp) {
if ((connect(sock, (struct sockaddr *) &ip_addr, sizeof(ip_addr)) < 0) && (errno != EINPROGRESS)) {
perror("failed to connect to server");
return -1;
}
stream_method = OUTPUT_STREAM_TCP;
} else {
stream_method = OUTPUT_STREAM_UDP;
}
} else {
perror("socket failed");
return -1;
}
dprintf("~(-->%s)", target);
return 0;
}
/* ----------------------------------------------------------------- */
output::output()
: f_kill_thread(false)
, ringbuffer()
, num_targets(0)
, options(OUTPUT_NONE)
{
dprintf("()");
memset(&output_streams, 0, sizeof(output_streams));
output_streams.clear();
}
output::~output()
{
dprintf("()");
stop();
output_streams.clear();
}
#if 0
output::output(const output&)
{
dprintf("(copy)");
output_streams.clear();
}
output& output::operator= (const output& cSource)
{
dprintf("(operator=)");
if (this == &cSource)
return *this;
output_streams.clear();
return *this;
}
#endif
//static
void* output::output_thread(void *p_this)
{
return static_cast<output*>(p_this)->output_thread();
}
void* output::output_thread()
{
int buf_size;
uint8_t *data = NULL;
/* push data from main output buffer into output_stream buffers */
while (!f_kill_thread) {
buf_size = ringbuffer.get_size();
//data = NULL;
if (buf_size) {
buf_size = ringbuffer.read_ptr((void**)&data, buf_size);
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.push(data, buf_size);
ringbuffer.advance_read_ptr();
} else {
usleep(50*1000);
}
}
pthread_exit(NULL);
}
int output::start()
{
dprintf("()");
int ret = pthread_create(&h_thread, NULL, output_thread, this);
if (0 != ret)
perror("pthread_create() failed");
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.start();
return ret;
}
void output::stop()
{
dprintf("()");
/* call stop_without_wait() on everybody first before we call stop() on everybody, which is a blocking function */
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.stop_without_wait();
for (output_stream_map::iterator iter = output_streams.begin(); iter != output_streams.end(); ++iter)
iter->second.stop();
stop_without_wait();
#if 0
while (-1 != sock_fd) {
usleep(20*1000);
}
#endif
return;
}
int output::push(uint8_t* p_data, int size)
{
/* push data into output buffer */
return ringbuffer.write(p_data, size);
}
int output::push(uint8_t* p_data, enum output_options opt)
{
return (((!options) || (!opt)) || (opt & options)) ? push(p_data, 188) : 0;
}
int output::add(char* target)
{
dprintf("(%d->%s)", num_targets, target);
/* allocates out buffer if and only if we have at least one target */
if (ringbuffer.get_capacity() <= 0)
ringbuffer.set_capacity(OUTPUT_STREAM_BUF_SIZE*2);
/* push data into output buffer */
int ret = output_streams[num_targets].add(target);
if (ret == 0)
num_targets++;
else
dprintf("failed to add target #%d: %s", num_targets, target);
dprintf("~(%d->%s)", (ret == 0) ? num_targets - 1 : num_targets, target);
return ret;
}
<|endoftext|> |
<commit_before>// coding: utf-8
#ifndef TASK_MECHANICS_HPP
# error "Don't include this file directly, use 'task_mechanics.hpp' instead!"
#endif
task::Mechanics::Mechanics(Leds &leds, Buttons &buttons)
: leds(leds), buttons(buttons),
isCalibratedX(false), isCalibratedZ(false),
correctionX(-20), correctionZ(13),
xMotor(&OCR1AL, &TCCR1B, t1_steps), zMotor(&OCR0A, &TCCR0B, t0_steps),
motorTimeout(30000)
{
}
void
task::Mechanics::initialize()
{
// setup CTC mode for Z axis
TCCR0A = (1 << COM0A0) | (1 << WGM01);
TCCR0B = 0;
OCR0A = 0;
TIMSK0 = (1 << OCIE0A);
// setup CTC mode for X axis
TCCR1A = (1 << COM1A0);
TCCR1B = (1 << WGM12);
OCR1A = 0;
TIMSK1 = (1 << OCIE1A);
XZ_Enable::setOutput(xpcc::Gpio::Low);
releaseMotors();
xMotor.initialize();
zMotor.initialize();
}
xpcc::co::Result<bool>
task::Mechanics::calibrateX(void *ctx)
{
CO_BEGIN(ctx);
startMotors();
if (buttons.isX_AxisLimitPressed())
{
xMotor.rotateBy(100, 1000);
CO_WAIT_WHILE(xMotor.isRunning());
}
xMotor.setSpeed(-100);
timeout.restart(18000);
CO_WAIT_UNTIL(buttons.isX_AxisLimitPressed() || timeout.isExpired());
xMotor.stop();
if ( (isCalibratedX = !timeout.isExpired()) )
{
xMotor.rotateBy(correctionX, 200);
CO_WAIT_WHILE(xMotor.isRunning());
leds.resetMechanicalError();
leds.resetBusy();
CO_RETURN(true);
}
leds.setMechanicalError();
leds.resetBusy();
CO_RETURN(false);
CO_END();
}
xpcc::co::Result<bool>
task::Mechanics::calibrateZ(void *ctx)
{
CO_BEGIN(ctx);
startMotors();
zMotor.stop();
if (buttons.isZ_AxisLimitPressed())
{
zMotor.rotateBy(100, 1000);
CO_WAIT_WHILE(zMotor.isRunning());
zMotor.stop();
}
zMotor.setSpeed(-100);
timeout.restart(18000);
CO_WAIT_UNTIL(buttons.isZ_AxisLimitPressed() || timeout.isExpired());
zMotor.stop();
if ( (isCalibratedZ = !timeout.isExpired()) )
{
zMotor.rotateBy(correctionZ, 300);
CO_WAIT_WHILE(zMotor.isRunning());
leds.resetMechanicalError();
leds.resetBusy();
CO_RETURN(true);
}
leds.setMechanicalError();
leds.resetBusy();
CO_RETURN(false);
CO_END();
}
xpcc::co::Result<bool>
task::Mechanics::rotateForward(void *ctx)
{
CO_BEGIN(ctx);
if (!isCalibrated())
CO_RETURN(false);
startMotors();
xMotor.rotateBy(3600, 10000);
CO_WAIT_WHILE(xMotor.isRunning());
zMotor.rotateBy(3600, 10000);
CO_WAIT_WHILE(zMotor.isRunning());
leds.resetBusy();
isCalibratedX = false;
isCalibratedZ = false;
CO_RETURN(true);
CO_END();
}
xpcc::co::Result<bool>
task::Mechanics::rotateBackward(void *ctx)
{
CO_BEGIN(ctx);
startMotors();
zMotor.rotateBy(-3600, 10000);
CO_WAIT_WHILE(zMotor.isRunning());
xMotor.rotateBy(-3600, 10000);
CO_WAIT_WHILE(xMotor.isRunning());
releaseMotors();
CO_RETURN(true);
CO_END();
}
void
task::Mechanics::startMotors()
{
leds.setBusy();
XZ_Enable::set();
motorTimeout.restart(30000);
}
void
task::Mechanics::stopMotors()
{
xMotor.stop();
zMotor.stop();
stopCoroutine();
isCalibratedX = false;
isCalibratedZ = false;
leds.resetBusy();
}
void
task::Mechanics::releaseMotors()
{
stopMotors();
XZ_Enable::reset();
leds.resetMechanicalError();
}
void
task::Mechanics::update()
{
xMotor.update();
zMotor.update();
this->run();
}
bool
task::Mechanics::run()
{
PT_BEGIN();
while(true)
{
if (!xMotor.isRunning() && !zMotor.isRunning() && motorTimeout.isExpired())
{
stopMotors();
XZ_Enable::reset();
}
PT_YIELD();
}
PT_END();
}
<commit_msg>Make mechanics a little faster.<commit_after>// coding: utf-8
#ifndef TASK_MECHANICS_HPP
# error "Don't include this file directly, use 'task_mechanics.hpp' instead!"
#endif
task::Mechanics::Mechanics(Leds &leds, Buttons &buttons)
: leds(leds), buttons(buttons),
isCalibratedX(false), isCalibratedZ(false),
correctionX(-40), correctionZ(15),
xMotor(&OCR1AL, &TCCR1B, t1_steps), zMotor(&OCR0A, &TCCR0B, t0_steps),
motorTimeout(30000)
{
}
void
task::Mechanics::initialize()
{
// setup CTC mode for Z axis
TCCR0A = (1 << COM0A0) | (1 << WGM01);
TCCR0B = 0;
OCR0A = 0;
TIMSK0 = (1 << OCIE0A);
// setup CTC mode for X axis
TCCR1A = (1 << COM1A0);
TCCR1B = (1 << WGM12);
OCR1A = 0;
TIMSK1 = (1 << OCIE1A);
XZ_Enable::setOutput(xpcc::Gpio::Low);
releaseMotors();
xMotor.initialize();
zMotor.initialize();
}
xpcc::co::Result<bool>
task::Mechanics::calibrateX(void *ctx)
{
CO_BEGIN(ctx);
startMotors();
if (buttons.isX_AxisLimitPressed())
{
xMotor.rotateBy(100, 500);
CO_WAIT_WHILE(xMotor.isRunning());
}
xMotor.setSpeed(-100);
timeout.restart(18000);
CO_WAIT_UNTIL(buttons.isX_AxisLimitPressed() || timeout.isExpired());
xMotor.stop();
if ( (isCalibratedX = !timeout.isExpired()) )
{
xMotor.rotateBy(correctionX, 200);
CO_WAIT_WHILE(xMotor.isRunning());
leds.resetMechanicalError();
leds.resetBusy();
CO_RETURN(true);
}
leds.setMechanicalError();
leds.resetBusy();
CO_RETURN(false);
CO_END();
}
xpcc::co::Result<bool>
task::Mechanics::calibrateZ(void *ctx)
{
CO_BEGIN(ctx);
startMotors();
zMotor.stop();
if (buttons.isZ_AxisLimitPressed())
{
zMotor.rotateBy(100, 500);
CO_WAIT_WHILE(zMotor.isRunning());
zMotor.stop();
}
zMotor.setSpeed(-100);
timeout.restart(18000);
CO_WAIT_UNTIL(buttons.isZ_AxisLimitPressed() || timeout.isExpired());
zMotor.stop();
if ( (isCalibratedZ = !timeout.isExpired()) )
{
zMotor.rotateBy(correctionZ, 300);
CO_WAIT_WHILE(zMotor.isRunning());
leds.resetMechanicalError();
leds.resetBusy();
CO_RETURN(true);
}
leds.setMechanicalError();
leds.resetBusy();
CO_RETURN(false);
CO_END();
}
xpcc::co::Result<bool>
task::Mechanics::rotateForward(void *ctx)
{
CO_BEGIN(ctx);
if (!isCalibrated())
CO_RETURN(false);
startMotors();
xMotor.rotateBy(3600, 10000);
CO_WAIT_WHILE(xMotor.isRunning());
zMotor.rotateBy(3600, 10000);
CO_WAIT_WHILE(zMotor.isRunning());
leds.resetBusy();
isCalibratedX = false;
isCalibratedZ = false;
CO_RETURN(true);
CO_END();
}
xpcc::co::Result<bool>
task::Mechanics::rotateBackward(void *ctx)
{
CO_BEGIN(ctx);
startMotors();
zMotor.rotateBy(-3600, 5000);
CO_WAIT_WHILE(zMotor.isRunning());
xMotor.rotateBy(-3600, 5000);
CO_WAIT_WHILE(xMotor.isRunning());
releaseMotors();
CO_RETURN(true);
CO_END();
}
void
task::Mechanics::startMotors()
{
leds.setBusy();
XZ_Enable::set();
motorTimeout.restart(30000);
}
void
task::Mechanics::stopMotors()
{
xMotor.stop();
zMotor.stop();
stopCoroutine();
isCalibratedX = false;
isCalibratedZ = false;
leds.resetBusy();
}
void
task::Mechanics::releaseMotors()
{
stopMotors();
XZ_Enable::reset();
leds.resetMechanicalError();
}
void
task::Mechanics::update()
{
xMotor.update();
zMotor.update();
this->run();
}
bool
task::Mechanics::run()
{
PT_BEGIN();
while(true)
{
if (!xMotor.isRunning() && !zMotor.isRunning() && motorTimeout.isExpired())
{
stopMotors();
XZ_Enable::reset();
}
PT_YIELD();
}
PT_END();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
namespace {
class TestRenderViewContextMenu : public RenderViewContextMenu {
public:
TestRenderViewContextMenu(TabContents* tab_contents, ContextMenuParams params)
: RenderViewContextMenu(tab_contents, params) { }
virtual void PlatformInit() { }
virtual bool GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
bool IsItemPresent(int command_id) {
return menu_model_.GetIndexOfCommandId(command_id) != -1;
}
};
class RegisterProtocolHandlerBrowserTest : public InProcessBrowserTest {
public:
RegisterProtocolHandlerBrowserTest() {
}
TestRenderViewContextMenu* CreateContextMenu(GURL url) {
ContextMenuParams params;
params.media_type = WebKit::WebContextMenuData::MediaTypeNone;
params.link_url = url;
TabContents* tab_contents = browser()->GetSelectedTabContents();
params.page_url = tab_contents->controller().GetActiveEntry()->url();
#if defined(OS_MACOSX)
params.writing_direction_default = 0;
params.writing_direction_left_to_right = 0;
params.writing_direction_right_to_left = 0;
#endif // OS_MACOSX
TestRenderViewContextMenu* menu = new TestRenderViewContextMenu(
browser()->GetSelectedTabContents(), params);
menu->Init();
return menu;
}
};
IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerBrowserTest,
ContextMenuEntryAppearsForHandledUrls) {
scoped_ptr<TestRenderViewContextMenu> menu(
CreateContextMenu(GURL("http://www.google.com/")));
ASSERT_FALSE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKWITH));
ProtocolHandler handler = ProtocolHandler::CreateProtocolHandler(
std::string("web+search"),
GURL("http://www.google.com/%s"),
UTF8ToUTF16(std::string("Test handler")));
ProtocolHandlerRegistry* registry =
browser()->profile()->GetProtocolHandlerRegistry();
GURL url("web+search:testing");
registry->OnAcceptRegisterProtocolHandler(handler);
ASSERT_TRUE(registry->IsHandledProtocol("web+search"));
ASSERT_EQ(registry->GetHandlersFor(url.scheme()).size(), (size_t) 1);
menu.reset(CreateContextMenu(url));
ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKWITH));
}
} // namespace
<commit_msg>Fix formatting nit I forgot to fix during code review.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
namespace {
class TestRenderViewContextMenu : public RenderViewContextMenu {
public:
TestRenderViewContextMenu(TabContents* tab_contents, ContextMenuParams params)
: RenderViewContextMenu(tab_contents, params) { }
virtual void PlatformInit() { }
virtual bool GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
bool IsItemPresent(int command_id) {
return menu_model_.GetIndexOfCommandId(command_id) != -1;
}
};
class RegisterProtocolHandlerBrowserTest : public InProcessBrowserTest {
public:
RegisterProtocolHandlerBrowserTest() { }
TestRenderViewContextMenu* CreateContextMenu(GURL url) {
ContextMenuParams params;
params.media_type = WebKit::WebContextMenuData::MediaTypeNone;
params.link_url = url;
TabContents* tab_contents = browser()->GetSelectedTabContents();
params.page_url = tab_contents->controller().GetActiveEntry()->url();
#if defined(OS_MACOSX)
params.writing_direction_default = 0;
params.writing_direction_left_to_right = 0;
params.writing_direction_right_to_left = 0;
#endif // OS_MACOSX
TestRenderViewContextMenu* menu = new TestRenderViewContextMenu(
browser()->GetSelectedTabContents(), params);
menu->Init();
return menu;
}
};
IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerBrowserTest,
ContextMenuEntryAppearsForHandledUrls) {
scoped_ptr<TestRenderViewContextMenu> menu(
CreateContextMenu(GURL("http://www.google.com/")));
ASSERT_FALSE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKWITH));
ProtocolHandler handler = ProtocolHandler::CreateProtocolHandler(
std::string("web+search"),
GURL("http://www.google.com/%s"),
UTF8ToUTF16(std::string("Test handler")));
ProtocolHandlerRegistry* registry =
browser()->profile()->GetProtocolHandlerRegistry();
GURL url("web+search:testing");
registry->OnAcceptRegisterProtocolHandler(handler);
ASSERT_TRUE(registry->IsHandledProtocol("web+search"));
ASSERT_EQ(registry->GetHandlersFor(url.scheme()).size(), (size_t) 1);
menu.reset(CreateContextMenu(url));
ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKWITH));
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/autofill/password_generation_popup_controller_impl.h"
#include <math.h>
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/autofill/password_generation_popup_observer.h"
#include "chrome/browser/ui/autofill/password_generation_popup_view.h"
#include "chrome/browser/ui/autofill/popup_constants.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/common/url_constants.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/autofill/core/browser/password_generator.h"
#include "components/password_manager/core/browser/password_manager.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/google_chrome_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/text_utils.h"
namespace autofill {
base::WeakPtr<PasswordGenerationPopupControllerImpl>
PasswordGenerationPopupControllerImpl::GetOrCreate(
base::WeakPtr<PasswordGenerationPopupControllerImpl> previous,
const gfx::RectF& bounds,
const PasswordForm& form,
int max_length,
password_manager::PasswordManager* password_manager,
PasswordGenerationPopupObserver* observer,
content::WebContents* web_contents,
gfx::NativeView container_view) {
if (previous.get() &&
previous->element_bounds() == bounds &&
previous->web_contents() == web_contents &&
previous->container_view() == container_view) {
return previous;
}
if (previous.get())
previous->Hide();
PasswordGenerationPopupControllerImpl* controller =
new PasswordGenerationPopupControllerImpl(
bounds,
form,
max_length,
password_manager,
observer,
web_contents,
container_view);
return controller->GetWeakPtr();
}
PasswordGenerationPopupControllerImpl::PasswordGenerationPopupControllerImpl(
const gfx::RectF& bounds,
const PasswordForm& form,
int max_length,
password_manager::PasswordManager* password_manager,
PasswordGenerationPopupObserver* observer,
content::WebContents* web_contents,
gfx::NativeView container_view)
: form_(form),
password_manager_(password_manager),
observer_(observer),
generator_(new PasswordGenerator(max_length)),
controller_common_(bounds, container_view, web_contents),
view_(NULL),
font_list_(ResourceBundle::GetSharedInstance().GetFontList(
ResourceBundle::SmallFont)),
password_selected_(false),
display_password_(false),
weak_ptr_factory_(this) {
controller_common_.SetKeyPressCallback(
base::Bind(&PasswordGenerationPopupControllerImpl::HandleKeyPressEvent,
base::Unretained(this)));
std::vector<base::string16> pieces;
base::SplitStringDontTrim(
l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_PROMPT),
'|', // separator
&pieces);
DCHECK_EQ(3u, pieces.size());
link_range_ = gfx::Range(pieces[0].size(),
pieces[0].size() + pieces[1].size());
help_text_ = JoinString(pieces, base::string16());
}
PasswordGenerationPopupControllerImpl::~PasswordGenerationPopupControllerImpl()
{}
base::WeakPtr<PasswordGenerationPopupControllerImpl>
PasswordGenerationPopupControllerImpl::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
bool PasswordGenerationPopupControllerImpl::HandleKeyPressEvent(
const content::NativeWebKeyboardEvent& event) {
switch (event.windowsKeyCode) {
case ui::VKEY_UP:
case ui::VKEY_DOWN:
PasswordSelected(true);
return true;
case ui::VKEY_ESCAPE:
Hide();
return true;
case ui::VKEY_RETURN:
case ui::VKEY_TAB:
// We suppress tab if the password is selected because we will
// automatically advance focus anyway.
return PossiblyAcceptPassword();
default:
return false;
}
}
bool PasswordGenerationPopupControllerImpl::PossiblyAcceptPassword() {
if (password_selected_) {
PasswordAccepted(); // This will delete |this|.
return true;
}
return false;
}
void PasswordGenerationPopupControllerImpl::PasswordSelected(bool selected) {
if (!display_password_)
return;
password_selected_ = selected;
view_->PasswordSelectionUpdated();
view_->UpdateBoundsAndRedrawPopup();
}
void PasswordGenerationPopupControllerImpl::PasswordAccepted() {
if (!display_password_)
return;
web_contents()->GetRenderViewHost()->Send(
new AutofillMsg_GeneratedPasswordAccepted(
web_contents()->GetRenderViewHost()->GetRoutingID(),
current_password_));
password_manager_->SetFormHasGeneratedPassword(form_);
Hide();
}
int PasswordGenerationPopupControllerImpl::GetDesiredWidth() {
// Minimum width in pixels.
const int minimum_required_width = 300;
// If the width of the field is longer than the minimum, use that instead.
int width = std::max(minimum_required_width,
controller_common_.RoundedElementBounds().width());
if (display_password_) {
// Make sure that the width will always be large enough to display the
// password and suggestion on one line.
width = std::max(width,
gfx::GetStringWidth(current_password_ + SuggestedText(),
font_list_) + 2 * kHorizontalPadding);
}
return width;
}
int PasswordGenerationPopupControllerImpl::GetDesiredHeight(int width) {
// Note that this wrapping isn't exactly what the popup will do. It shouldn't
// line break in the middle of the link, but as long as the link isn't longer
// than given width this shouldn't affect the height calculated here. The
// default width should be wide enough to prevent this from being an issue.
int total_length = gfx::GetStringWidth(HelpText(), font_list_);
int usable_width = width - 2 * kHorizontalPadding;
int text_height =
static_cast<int>(ceil(static_cast<double>(total_length)/usable_width)) *
font_list_.GetFontSize();
int help_section_height = text_height + 2 * kHelpVerticalPadding;
int password_section_height = 0;
if (display_password_) {
password_section_height =
font_list_.GetFontSize() + 2 * kPasswordVerticalPadding;
}
return (2 * kPopupBorderThickness +
help_section_height +
password_section_height);
}
void PasswordGenerationPopupControllerImpl::CalculateBounds() {
int popup_width = GetDesiredWidth();
int popup_height = GetDesiredHeight(popup_width);
popup_bounds_ = controller_common_.GetPopupBounds(popup_height, popup_width);
int sub_view_width = popup_bounds_.width() - 2 * kPopupBorderThickness;
// Calculate the bounds for the rest of the elements given the bounds of
// the popup.
if (display_password_) {
password_bounds_ = gfx::Rect(
kPopupBorderThickness,
kPopupBorderThickness,
sub_view_width,
font_list_.GetFontSize() + 2 * kPasswordVerticalPadding);
divider_bounds_ = gfx::Rect(kPopupBorderThickness,
password_bounds_.bottom(),
sub_view_width,
1 /* divider heigth*/);
} else {
password_bounds_ = gfx::Rect();
divider_bounds_ = gfx::Rect();
}
int help_y = std::max(kPopupBorderThickness, divider_bounds_.bottom());
int help_height =
popup_bounds_.height() - help_y - kPopupBorderThickness;
help_bounds_ = gfx::Rect(
kPopupBorderThickness,
help_y,
sub_view_width,
help_height);
}
void PasswordGenerationPopupControllerImpl::Show(bool display_password) {
display_password_ = display_password;
if (display_password_)
current_password_ = base::ASCIIToUTF16(generator_->Generate());
CalculateBounds();
if (!view_) {
view_ = PasswordGenerationPopupView::Create(this);
view_->Show();
} else {
view_->UpdateBoundsAndRedrawPopup();
}
controller_common_.RegisterKeyPressCallback();
if (observer_)
observer_->OnPopupShown(display_password_);
}
void PasswordGenerationPopupControllerImpl::HideAndDestroy() {
Hide();
}
void PasswordGenerationPopupControllerImpl::Hide() {
controller_common_.RemoveKeyPressCallback();
if (view_)
view_->Hide();
if (observer_)
observer_->OnPopupHidden();
delete this;
}
void PasswordGenerationPopupControllerImpl::ViewDestroyed() {
view_ = NULL;
Hide();
}
void PasswordGenerationPopupControllerImpl::OnSavedPasswordsLinkClicked() {
// TODO(gcasto): Change this to navigate to account central once passwords
// are visible there.
Browser* browser =
chrome::FindBrowserWithWebContents(controller_common_.web_contents());
content::OpenURLParams params(
GURL(chrome::kAutoPasswordGenerationLearnMoreURL), content::Referrer(),
NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false);
browser->OpenURL(params);
}
void PasswordGenerationPopupControllerImpl::SetSelectionAtPoint(
const gfx::Point& point) {
if (password_bounds_.Contains(point))
PasswordSelected(true);
}
bool PasswordGenerationPopupControllerImpl::AcceptSelectedLine() {
if (!password_selected_)
return false;
PasswordAccepted();
return true;
}
void PasswordGenerationPopupControllerImpl::SelectionCleared() {
PasswordSelected(false);
}
gfx::NativeView PasswordGenerationPopupControllerImpl::container_view() {
return controller_common_.container_view();
}
const gfx::FontList& PasswordGenerationPopupControllerImpl::font_list() const {
return font_list_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::popup_bounds() const {
return popup_bounds_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::password_bounds()
const {
return password_bounds_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::divider_bounds()
const {
return divider_bounds_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::help_bounds() const {
return help_bounds_;
}
bool PasswordGenerationPopupControllerImpl::display_password() const {
return display_password_;
}
bool PasswordGenerationPopupControllerImpl::password_selected() const {
return password_selected_;
}
base::string16 PasswordGenerationPopupControllerImpl::password() const {
return current_password_;
}
base::string16 PasswordGenerationPopupControllerImpl::SuggestedText() {
return l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_SUGGESTION);
}
const base::string16& PasswordGenerationPopupControllerImpl::HelpText() {
return help_text_;
}
const gfx::Range& PasswordGenerationPopupControllerImpl::HelpTextLinkRange() {
return link_range_;
}
} // namespace autofill
<commit_msg>Reland 270975: [Mac] Unselect generated password when mouse leaves password bounds.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/autofill/password_generation_popup_controller_impl.h"
#include <math.h>
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/autofill/password_generation_popup_observer.h"
#include "chrome/browser/ui/autofill/password_generation_popup_view.h"
#include "chrome/browser/ui/autofill/popup_constants.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/common/url_constants.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/autofill/core/browser/password_generator.h"
#include "components/password_manager/core/browser/password_manager.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/google_chrome_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/text_utils.h"
namespace autofill {
base::WeakPtr<PasswordGenerationPopupControllerImpl>
PasswordGenerationPopupControllerImpl::GetOrCreate(
base::WeakPtr<PasswordGenerationPopupControllerImpl> previous,
const gfx::RectF& bounds,
const PasswordForm& form,
int max_length,
password_manager::PasswordManager* password_manager,
PasswordGenerationPopupObserver* observer,
content::WebContents* web_contents,
gfx::NativeView container_view) {
if (previous.get() &&
previous->element_bounds() == bounds &&
previous->web_contents() == web_contents &&
previous->container_view() == container_view) {
return previous;
}
if (previous.get())
previous->Hide();
PasswordGenerationPopupControllerImpl* controller =
new PasswordGenerationPopupControllerImpl(
bounds,
form,
max_length,
password_manager,
observer,
web_contents,
container_view);
return controller->GetWeakPtr();
}
PasswordGenerationPopupControllerImpl::PasswordGenerationPopupControllerImpl(
const gfx::RectF& bounds,
const PasswordForm& form,
int max_length,
password_manager::PasswordManager* password_manager,
PasswordGenerationPopupObserver* observer,
content::WebContents* web_contents,
gfx::NativeView container_view)
: form_(form),
password_manager_(password_manager),
observer_(observer),
generator_(new PasswordGenerator(max_length)),
controller_common_(bounds, container_view, web_contents),
view_(NULL),
font_list_(ResourceBundle::GetSharedInstance().GetFontList(
ResourceBundle::SmallFont)),
password_selected_(false),
display_password_(false),
weak_ptr_factory_(this) {
controller_common_.SetKeyPressCallback(
base::Bind(&PasswordGenerationPopupControllerImpl::HandleKeyPressEvent,
base::Unretained(this)));
std::vector<base::string16> pieces;
base::SplitStringDontTrim(
l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_PROMPT),
'|', // separator
&pieces);
DCHECK_EQ(3u, pieces.size());
link_range_ = gfx::Range(pieces[0].size(),
pieces[0].size() + pieces[1].size());
help_text_ = JoinString(pieces, base::string16());
}
PasswordGenerationPopupControllerImpl::~PasswordGenerationPopupControllerImpl()
{}
base::WeakPtr<PasswordGenerationPopupControllerImpl>
PasswordGenerationPopupControllerImpl::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
bool PasswordGenerationPopupControllerImpl::HandleKeyPressEvent(
const content::NativeWebKeyboardEvent& event) {
switch (event.windowsKeyCode) {
case ui::VKEY_UP:
case ui::VKEY_DOWN:
PasswordSelected(true);
return true;
case ui::VKEY_ESCAPE:
Hide();
return true;
case ui::VKEY_RETURN:
case ui::VKEY_TAB:
// We suppress tab if the password is selected because we will
// automatically advance focus anyway.
return PossiblyAcceptPassword();
default:
return false;
}
}
bool PasswordGenerationPopupControllerImpl::PossiblyAcceptPassword() {
if (password_selected_) {
PasswordAccepted(); // This will delete |this|.
return true;
}
return false;
}
void PasswordGenerationPopupControllerImpl::PasswordSelected(bool selected) {
if (!display_password_ || selected == password_selected_)
return;
password_selected_ = selected;
view_->PasswordSelectionUpdated();
view_->UpdateBoundsAndRedrawPopup();
}
void PasswordGenerationPopupControllerImpl::PasswordAccepted() {
if (!display_password_)
return;
web_contents()->GetRenderViewHost()->Send(
new AutofillMsg_GeneratedPasswordAccepted(
web_contents()->GetRenderViewHost()->GetRoutingID(),
current_password_));
password_manager_->SetFormHasGeneratedPassword(form_);
Hide();
}
int PasswordGenerationPopupControllerImpl::GetDesiredWidth() {
// Minimum width in pixels.
const int minimum_required_width = 300;
// If the width of the field is longer than the minimum, use that instead.
int width = std::max(minimum_required_width,
controller_common_.RoundedElementBounds().width());
if (display_password_) {
// Make sure that the width will always be large enough to display the
// password and suggestion on one line.
width = std::max(width,
gfx::GetStringWidth(current_password_ + SuggestedText(),
font_list_) + 2 * kHorizontalPadding);
}
return width;
}
int PasswordGenerationPopupControllerImpl::GetDesiredHeight(int width) {
// Note that this wrapping isn't exactly what the popup will do. It shouldn't
// line break in the middle of the link, but as long as the link isn't longer
// than given width this shouldn't affect the height calculated here. The
// default width should be wide enough to prevent this from being an issue.
int total_length = gfx::GetStringWidth(HelpText(), font_list_);
int usable_width = width - 2 * kHorizontalPadding;
int text_height =
static_cast<int>(ceil(static_cast<double>(total_length)/usable_width)) *
font_list_.GetFontSize();
int help_section_height = text_height + 2 * kHelpVerticalPadding;
int password_section_height = 0;
if (display_password_) {
password_section_height =
font_list_.GetFontSize() + 2 * kPasswordVerticalPadding;
}
return (2 * kPopupBorderThickness +
help_section_height +
password_section_height);
}
void PasswordGenerationPopupControllerImpl::CalculateBounds() {
int popup_width = GetDesiredWidth();
int popup_height = GetDesiredHeight(popup_width);
popup_bounds_ = controller_common_.GetPopupBounds(popup_height, popup_width);
int sub_view_width = popup_bounds_.width() - 2 * kPopupBorderThickness;
// Calculate the bounds for the rest of the elements given the bounds of
// the popup.
if (display_password_) {
password_bounds_ = gfx::Rect(
kPopupBorderThickness,
kPopupBorderThickness,
sub_view_width,
font_list_.GetFontSize() + 2 * kPasswordVerticalPadding);
divider_bounds_ = gfx::Rect(kPopupBorderThickness,
password_bounds_.bottom(),
sub_view_width,
1 /* divider heigth*/);
} else {
password_bounds_ = gfx::Rect();
divider_bounds_ = gfx::Rect();
}
int help_y = std::max(kPopupBorderThickness, divider_bounds_.bottom());
int help_height =
popup_bounds_.height() - help_y - kPopupBorderThickness;
help_bounds_ = gfx::Rect(
kPopupBorderThickness,
help_y,
sub_view_width,
help_height);
}
void PasswordGenerationPopupControllerImpl::Show(bool display_password) {
display_password_ = display_password;
if (display_password_)
current_password_ = base::ASCIIToUTF16(generator_->Generate());
CalculateBounds();
if (!view_) {
view_ = PasswordGenerationPopupView::Create(this);
view_->Show();
} else {
view_->UpdateBoundsAndRedrawPopup();
}
controller_common_.RegisterKeyPressCallback();
if (observer_)
observer_->OnPopupShown(display_password_);
}
void PasswordGenerationPopupControllerImpl::HideAndDestroy() {
Hide();
}
void PasswordGenerationPopupControllerImpl::Hide() {
controller_common_.RemoveKeyPressCallback();
if (view_)
view_->Hide();
if (observer_)
observer_->OnPopupHidden();
delete this;
}
void PasswordGenerationPopupControllerImpl::ViewDestroyed() {
view_ = NULL;
Hide();
}
void PasswordGenerationPopupControllerImpl::OnSavedPasswordsLinkClicked() {
// TODO(gcasto): Change this to navigate to account central once passwords
// are visible there.
Browser* browser =
chrome::FindBrowserWithWebContents(controller_common_.web_contents());
content::OpenURLParams params(
GURL(chrome::kAutoPasswordGenerationLearnMoreURL), content::Referrer(),
NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false);
browser->OpenURL(params);
}
void PasswordGenerationPopupControllerImpl::SetSelectionAtPoint(
const gfx::Point& point) {
PasswordSelected(password_bounds_.Contains(point));
}
bool PasswordGenerationPopupControllerImpl::AcceptSelectedLine() {
if (!password_selected_)
return false;
PasswordAccepted();
return true;
}
void PasswordGenerationPopupControllerImpl::SelectionCleared() {
PasswordSelected(false);
}
gfx::NativeView PasswordGenerationPopupControllerImpl::container_view() {
return controller_common_.container_view();
}
const gfx::FontList& PasswordGenerationPopupControllerImpl::font_list() const {
return font_list_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::popup_bounds() const {
return popup_bounds_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::password_bounds()
const {
return password_bounds_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::divider_bounds()
const {
return divider_bounds_;
}
const gfx::Rect& PasswordGenerationPopupControllerImpl::help_bounds() const {
return help_bounds_;
}
bool PasswordGenerationPopupControllerImpl::display_password() const {
return display_password_;
}
bool PasswordGenerationPopupControllerImpl::password_selected() const {
return password_selected_;
}
base::string16 PasswordGenerationPopupControllerImpl::password() const {
return current_password_;
}
base::string16 PasswordGenerationPopupControllerImpl::SuggestedText() {
return l10n_util::GetStringUTF16(IDS_PASSWORD_GENERATION_SUGGESTION);
}
const base::string16& PasswordGenerationPopupControllerImpl::HelpText() {
return help_text_;
}
const gfx::Range& PasswordGenerationPopupControllerImpl::HelpTextLinkRange() {
return link_range_;
}
} // namespace autofill
<|endoftext|> |
<commit_before>/*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QScriptEngineSlots.h"
static QScriptEngineSlots * s = NULL;
QScriptEngineSlots::QScriptEngineSlots(QObject *parent) : QObject(parent)
{
}
QScriptEngineSlots::~QScriptEngineSlots()
{
}
void QScriptEngineSlots::signalHandlerException( const QScriptValue & exception )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Signals_return_codeblock( object, "signalHandlerException(QScriptValue)" );
if( cb )
{
PHB_ITEM psender = hb_itemPutPtr( NULL, (QObject *) object );
PHB_ITEM pexception = hb_itemPutPtr( NULL, (QScriptValue *) &exception );
hb_vmEvalBlockV( (PHB_ITEM) cb, 2, psender, pexception );
hb_itemRelease( psender );
hb_itemRelease( pexception );
}
}
void QScriptEngineSlots_connect_signal ( const QString & signal, const QString & slot )
{
if( s == NULL )
{
s = new QScriptEngineSlots( QCoreApplication::instance() );
}
hb_retl( Signals_connection_disconnection( s, signal, slot ) );
}
<commit_msg>QtScript: module updated<commit_after>/*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QScriptEngineSlots.h"
static QScriptEngineSlots * s = NULL;
QScriptEngineSlots::QScriptEngineSlots(QObject *parent) : QObject(parent)
{
}
QScriptEngineSlots::~QScriptEngineSlots()
{
}
void QScriptEngineSlots::signalHandlerException( const QScriptValue & exception )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Signals_return_codeblock( object, "signalHandlerException(QScriptValue)" );
if( cb )
{
PHB_ITEM psender = Signals_return_qobject ( object, "QOBJECT" );
PHB_ITEM pexception = Signals_return_object( (void *) &exception, "QSCRIPTVALUE" );
hb_vmEvalBlockV( (PHB_ITEM) cb, 2, psender, pexception );
hb_itemRelease( psender );
hb_itemRelease( pexception );
}
}
void QScriptEngineSlots_connect_signal ( const QString & signal, const QString & slot )
{
if( s == NULL )
{
s = new QScriptEngineSlots( QCoreApplication::instance() );
}
hb_retl( Signals_connection_disconnection( s, signal, slot ) );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: frmsh.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-08-12 13:04:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SWFRMSH_HXX
#define _SWFRMSH_HXX
#include "basesh.hxx"
class SwFrameShell: public SwBaseShell
{
public:
SFX_DECL_INTERFACE(SW_FRAMESHELL);
SwFrameShell(SwView &rView);
virtual ~SwFrameShell();
void Execute(SfxRequest &);
void GetState(SfxItemSet &);
void ExecFrameStyle(SfxRequest& rReq);
void GetLineStyleState(SfxItemSet &rSet);
void StateInsert(SfxItemSet &rSet);
void StateStatusline(SfxItemSet &rSet);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.600); FILE MERGED 2005/09/05 13:45:13 rt 1.3.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmsh.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:16:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SWFRMSH_HXX
#define _SWFRMSH_HXX
#include "basesh.hxx"
class SwFrameShell: public SwBaseShell
{
public:
SFX_DECL_INTERFACE(SW_FRAMESHELL);
SwFrameShell(SwView &rView);
virtual ~SwFrameShell();
void Execute(SfxRequest &);
void GetState(SfxItemSet &);
void ExecFrameStyle(SfxRequest& rReq);
void GetLineStyleState(SfxItemSet &rSet);
void StateInsert(SfxItemSet &rSet);
void StateStatusline(SfxItemSet &rSet);
};
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include "GL/glew.h"
#include "RaZ/Utils/Window.hpp"
namespace Raz {
Window::Window(unsigned int width, unsigned int height, const std::string& name) {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
m_window = glfwCreateWindow(width, height, name.c_str(), nullptr, nullptr);
if (!m_window) {
std::cerr << "Error: Failed to create GLFW Window." << std::endl;
glfwTerminate();
}
glfwMakeContextCurrent(m_window);
glfwSetKeyCallback(m_window, [] (GLFWwindow* window, int key, int scancode, int action, int mode) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
});
glViewport(0, 0, width, height);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
std::cerr << "Error: Failed to initialize GLEW." << std::endl;
}
bool Window::run() const {
if (glfwWindowShouldClose(m_window))
return false;
glfwSwapBuffers(m_window);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwPollEvents();
return true;
}
} // namespace Raz
<commit_msg>[Update] Added GL debug output in Window<commit_after>#include <iostream>
#include "GL/glew.h"
#include "RaZ/Utils/Window.hpp"
namespace Raz {
namespace {
void GLAPIENTRY callbackDebugLog(GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam) {
std::cout << "OpenGL Debug - ";
switch (source) {
case GL_DEBUG_SOURCE_API:
std::cout << "Source:OpenGL\t";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
std::cout << "Source:Windows\t";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
std::cout << "Source:Shader compiler\t";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY:
std::cout << "Source:Third party\t";
break;
case GL_DEBUG_SOURCE_APPLICATION:
std::cout << "Source:Application\t";
break;
case GL_DEBUG_SOURCE_OTHER:
std::cout << "Source:Other\t";
break;
default:
break;
}
switch (type) {
case GL_DEBUG_TYPE_ERROR:
std::cout << "Type:Error\t";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
std::cout << "Type:Deprecated behavior\t";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
std::cout << "Type:Undefined behavior\t";
break;
case GL_DEBUG_TYPE_PORTABILITY:
std::cout << "Type:Portability\t";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
std::cout << "Type:Performance\t";
break;
case GL_DEBUG_TYPE_OTHER:
std::cout << "Type:Other\t";
break;
default:
break;
}
std::cout << "ID:" << id << "\t";
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH:
std::cout << "Severity:High\t";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
std::cout << "Severity:Medium\t";
break;
case GL_DEBUG_SEVERITY_LOW:
std::cout << "Severity:Low\t";
break;
default:
break;
}
std::cout << "Message:" << message << std::endl;
}
} // namespace
Window::Window(unsigned int width, unsigned int height, const std::string& name) {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
m_window = glfwCreateWindow(width, height, name.c_str(), nullptr, nullptr);
if (!m_window) {
std::cerr << "Error: Failed to create GLFW Window." << std::endl;
glfwTerminate();
}
glfwMakeContextCurrent(m_window);
glfwSetKeyCallback(m_window, [] (GLFWwindow* window, int key, int scancode, int action, int mode) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
});
glViewport(0, 0, width, height);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
std::cerr << "Error: Failed to initialize GLEW." << std::endl;
glDebugMessageCallback(&callbackDebugLog, nullptr);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
bool Window::run() const {
if (glfwWindowShouldClose(m_window))
return false;
glfwSwapBuffers(m_window);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwPollEvents();
return true;
}
} // namespace Raz
<|endoftext|> |
<commit_before>#include "MysqlDbConnection.h"
#include <vector>
#include <boost/lexical_cast.hpp>
#include <cstdio>
namespace sf1r {
MysqlDbConnection::MysqlDbConnection()
:PoolSize(16)
{
sqlKeywords_[DbConnection::ATTR_AUTO_INCREMENT] = "AUTO_INCREMENT";
sqlKeywords_[DbConnection::FUNC_LAST_INSERT_ID] = "last_insert_id()";
}
MysqlDbConnection::~MysqlDbConnection()
{
close();
}
void MysqlDbConnection::close()
{
mutex_.acquire_write_lock();
for(std::list<MYSQL*>::iterator it= pool_.begin(); it!=pool_.end(); it++ ) {
mysql_close(*it);
}
pool_.clear();
//release it at last
mysql_library_end();
mutex_.release_write_lock();
}
bool MysqlDbConnection::init(const std::string& str )
{
mysql_library_init(0, NULL, NULL);
std::string host;
std::string portStr;
uint32_t port = 3306;
std::string username;
std::string password;
std::string database("SF1R");
std::string default_charset("utf8");
std::string conn = str;
std::size_t pos = conn.find(":");
if(pos==0 || pos == std::string::npos) return false;
username = conn.substr(0, pos);
conn = conn.substr(pos+1);
pos = conn.find("@");
if(pos == std::string::npos) return false;
password = conn.substr(0, pos);
conn = conn.substr(pos+1);
pos = conn.find(":");
if(pos==0 || pos == std::string::npos) return false;
host = conn.substr(0, pos);
conn = conn.substr(pos+1);
pos = conn.find("/");
if(pos==0) return false;
if(pos == std::string::npos)
{
portStr = conn;
}
else
{
portStr = conn.substr(0, pos);
conn = conn.substr(pos+1);
if (!conn.empty())
database = conn;
}
try
{
port = boost::lexical_cast<uint32_t>(portStr);
}
catch(std::exception& ex)
{
return false;
}
if(host=="localhost") host = "127.0.0.1";
int flags = CLIENT_MULTI_STATEMENTS;
bool ret = true;
mutex_.acquire_write_lock();
for(int i=0; i<PoolSize; i++) {
MYSQL* mysql = mysql_init(NULL);
if (!mysql)
{
std::cerr<<"mysql_init failed"<<std::endl;
return false;
}
mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset.c_str());
if (!mysql_real_connect(mysql, host.c_str(), username.c_str(), password.c_str(), NULL, port, NULL, flags))
{
printf("Couldn't connect mysql : %d:(%s) %s\n", mysql_errno(mysql), mysql_sqlstate(mysql), mysql_error(mysql));
mysql_close(mysql);
return false;
}
mysql_query(mysql, "SET NAMES utf8");
std::string create_db_query = "create database IF NOT EXISTS "+database+" default character set utf8";
if ( mysql_query(mysql, create_db_query.c_str())>0 ) {
printf("Error %u: %s\n", mysql_errno(mysql), mysql_error(mysql));
mysql_close(mysql);
return false;
}
std::string use_db_query = "use "+database;
if ( mysql_query(mysql, use_db_query.c_str())>0 ) {
printf("Error %u: %s\n", mysql_errno(mysql), mysql_error(mysql));
mysql_close(mysql);
return false;
}
pool_.push_back(mysql);
}
mutex_.release_write_lock();
if(!ret) close();
return ret;
}
MYSQL* MysqlDbConnection::getDb()
{
MYSQL* db = NULL;
mutex_.acquire_write_lock();
if(!pool_.empty()) {
db = pool_.front();
pool_.pop_front();
}
mutex_.release_write_lock();
return db;
}
void MysqlDbConnection::putDb(MYSQL* db)
{
mutex_.acquire_write_lock();
pool_.push_back(db);
mutex_.release_write_lock();
}
bool MysqlDbConnection::exec(const std::string & sql, bool omitError)
{
bool ret = true;
MYSQL* db = getDb();
if( db == NULL ) {
std::cerr << "[LogManager] No available connection in pool" << std::endl;
return false;
}
if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) )
{
printf("Error : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
ret = false;
}
putDb(db);
return ret;
}
bool MysqlDbConnection::exec(const std::string & sql,
std::list< std::map<std::string, std::string> > & results,
bool omitError)
{
bool ret = true;
MYSQL* db = getDb();
if( db == NULL ) {
std::cerr << "[LogManager] No available connection in pool" << std::endl;
return false;
}
if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) )
{
printf("Error : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
ret = false;
}
else
{
ret = fetchRows_(db, results);
}
putDb(db);
return ret;
}
bool MysqlDbConnection::fetchRows_(MYSQL* db, std::list< std::map<std::string, std::string> > & rows)
{
bool success = true;
int status = 0;
while (status == 0)
{
MYSQL_RES* result = mysql_store_result(db);
if(result)
{
uint32_t num_cols = mysql_num_fields(result);
std::vector<std::string> col_nums(num_cols);
for(uint32_t i=0;i<num_cols;i++)
{
MYSQL_FIELD* field = mysql_fetch_field_direct(result, i);
col_nums[i] = field->name;
}
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{
std::map<std::string, std::string> map;
for(uint32_t i=0;i<num_cols;i++)
{
map.insert(std::make_pair(col_nums[i], row[i]) );
}
rows.push_back(map);
}
mysql_free_result(result);
}
else
{
if (mysql_field_count(db))
{
printf("Error during store_result : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
success = false;
break;
}
}
// more results? -1 = no, >0 = error, 0 = yes (keep looping)
if ((status = mysql_next_result(db)) > 0)
{
printf("Error during next_result : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
success = false;
break;
}
}
return success;
}
}
<commit_msg>tiny tweak<commit_after>#include "MysqlDbConnection.h"
#include <vector>
#include <boost/lexical_cast.hpp>
#include <cstdio>
namespace sf1r {
MysqlDbConnection::MysqlDbConnection()
:PoolSize(16)
{
sqlKeywords_[DbConnection::ATTR_AUTO_INCREMENT] = "AUTO_INCREMENT";
sqlKeywords_[DbConnection::FUNC_LAST_INSERT_ID] = "last_insert_id()";
}
MysqlDbConnection::~MysqlDbConnection()
{
close();
}
void MysqlDbConnection::close()
{
mutex_.acquire_write_lock();
for(std::list<MYSQL*>::iterator it= pool_.begin(); it!=pool_.end(); it++ ) {
mysql_close(*it);
}
pool_.clear();
//release it at last
mysql_library_end();
mutex_.release_write_lock();
}
bool MysqlDbConnection::init(const std::string& str )
{
mysql_library_init(0, NULL, NULL);
std::string host;
std::string portStr;
uint32_t port = 3306;
std::string username;
std::string password;
std::string database("SF1R");
std::string default_charset("utf8");
std::string conn = str;
std::size_t pos = conn.find(":");
if(pos==0 || pos == std::string::npos) return false;
username = conn.substr(0, pos);
conn = conn.substr(pos+1);
pos = conn.find("@");
if(pos == std::string::npos) return false;
password = conn.substr(0, pos);
conn = conn.substr(pos+1);
pos = conn.find(":");
if(pos==0 || pos == std::string::npos) return false;
host = conn.substr(0, pos);
conn = conn.substr(pos+1);
pos = conn.find("/");
if(pos==0) return false;
if(pos == std::string::npos)
{
portStr = conn;
}
else
{
portStr = conn.substr(0, pos);
conn = conn.substr(pos+1);
if (!conn.empty())
database = conn;
}
try
{
port = boost::lexical_cast<uint32_t>(portStr);
}
catch(std::exception& ex)
{
return false;
}
if(host=="localhost") host = "127.0.0.1";
int flags = CLIENT_MULTI_STATEMENTS;
bool ret = true;
mutex_.acquire_write_lock();
for(int i=0; i<PoolSize; i++) {
MYSQL* mysql = mysql_init(NULL);
if (!mysql)
{
std::cerr<<"mysql_init failed"<<std::endl;
return false;
}
mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset.c_str());
if (!mysql_real_connect(mysql, host.c_str(), username.c_str(), password.c_str(), NULL, port, NULL, flags))
{
fprintf(stderr, "Couldn't connect mysql : %d:(%s) %s\n", mysql_errno(mysql), mysql_sqlstate(mysql), mysql_error(mysql));
mysql_close(mysql);
return false;
}
mysql_query(mysql, "SET NAMES utf8");
std::string create_db_query = "create database IF NOT EXISTS "+database+" default character set utf8";
if ( mysql_query(mysql, create_db_query.c_str())>0 ) {
fprintf(stderr, "Error %u: %s\n", mysql_errno(mysql), mysql_error(mysql));
mysql_close(mysql);
return false;
}
std::string use_db_query = "use "+database;
if ( mysql_query(mysql, use_db_query.c_str())>0 ) {
fprintf(stderr, "Error %u: %s\n", mysql_errno(mysql), mysql_error(mysql));
mysql_close(mysql);
return false;
}
pool_.push_back(mysql);
}
mutex_.release_write_lock();
if(!ret) close();
return ret;
}
MYSQL* MysqlDbConnection::getDb()
{
MYSQL* db = NULL;
mutex_.acquire_write_lock();
if(!pool_.empty()) {
db = pool_.front();
pool_.pop_front();
}
mutex_.release_write_lock();
return db;
}
void MysqlDbConnection::putDb(MYSQL* db)
{
mutex_.acquire_write_lock();
pool_.push_back(db);
mutex_.release_write_lock();
}
bool MysqlDbConnection::exec(const std::string & sql, bool omitError)
{
bool ret = true;
MYSQL* db = getDb();
if( db == NULL ) {
std::cerr << "[LogManager] No available connection in pool" << std::endl;
return false;
}
if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) )
{
fprintf(stderr, "Error : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
ret = false;
}
putDb(db);
return ret;
}
bool MysqlDbConnection::exec(const std::string & sql,
std::list< std::map<std::string, std::string> > & results,
bool omitError)
{
bool ret = true;
MYSQL* db = getDb();
if( db == NULL ) {
std::cerr << "[LogManager] No available connection in pool" << std::endl;
return false;
}
if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) )
{
fprintf(stderr, "Error : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
ret = false;
}
else
{
ret = fetchRows_(db, results);
}
putDb(db);
return ret;
}
bool MysqlDbConnection::fetchRows_(MYSQL* db, std::list< std::map<std::string, std::string> > & rows)
{
bool success = true;
int status = 0;
while (status == 0)
{
MYSQL_RES* result = mysql_store_result(db);
if(result)
{
uint32_t num_cols = mysql_num_fields(result);
std::vector<std::string> col_nums(num_cols);
for(uint32_t i=0;i<num_cols;i++)
{
MYSQL_FIELD* field = mysql_fetch_field_direct(result, i);
col_nums[i] = field->name;
}
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{
std::map<std::string, std::string> map;
for(uint32_t i=0;i<num_cols;i++)
{
map.insert(std::make_pair(col_nums[i], row[i]) );
}
rows.push_back(map);
}
mysql_free_result(result);
}
else
{
if (mysql_field_count(db))
{
fprintf(stderr, "Error during store_result : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
success = false;
break;
}
}
// more results? -1 = no, >0 = error, 0 = yes (keep looping)
if ((status = mysql_next_result(db)) > 0)
{
fprintf(stderr, "Error during next_result : %d:(%s) %s\n", mysql_errno(db), mysql_sqlstate(db), mysql_error(db));
success = false;
break;
}
}
return success;
}
}
<|endoftext|> |
<commit_before>#include "DistributeDriver.h"
#include "MasterManagerBase.h"
#include "DistributeRequestHooker.h"
#include "RequestLog.h"
#include "DistributeTest.hpp"
#include <util/scheduler.h>
#include <util/driver/Reader.h>
#include <util/driver/Writer.h>
#include <util/driver/writers/JsonWriter.h>
#include <util/driver/readers/JsonReader.h>
#include <util/driver/Keys.h>
#include <boost/bind.hpp>
#include <glog/logging.h>
using namespace izenelib::driver;
namespace sf1r
{
DistributeDriver::DistributeDriver()
{
async_task_worker_ = boost::thread(&DistributeDriver::run, this);
// only one write task can exist in distribute system.
asyncWriteTasks_.resize(1);
}
void DistributeDriver::stop()
{
async_task_worker_.interrupt();
async_task_worker_.join();
asyncWriteTasks_.clear();
}
void DistributeDriver::run()
{
try
{
while(true)
{
boost::function<bool()> task;
asyncWriteTasks_.pop(task);
task();
boost::this_thread::interruption_point();
}
}
catch (boost::thread_interrupted&)
{
return;
}
}
void DistributeDriver::init(const RouterPtr& router)
{
router_ = router;
MasterManagerBase::get()->setCallback(boost::bind(&DistributeDriver::on_new_req_available, this));
}
static bool callCronJob(Request::kCallType calltype, const std::string& jobname, const std::string& packed_data)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("cron_" + jobname);
bool ret = izenelib::util::Scheduler::runJobImmediatly(jobname, calltype, calltype == Request::FromLog);
if (!ret)
{
LOG(ERROR) << "start cron job failed." << jobname;
}
else
{
LOG(INFO) << "cron job finished local: " << jobname;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
static bool callHandler(izenelib::driver::Router::handler_ptr handler,
Request::kCallType calltype, const std::string& packed_data,
Request& request)
{
try
{
DistributeRequestHooker::get()->processLocalBegin();
Response response;
response.setSuccess(true);
static Poller tmp_poller;
// prepare request
handler->invoke(request,
response,
tmp_poller);
LOG(INFO) << "write request send in DistributeDriver success.";
return true;
}
catch(const std::exception& e)
{
LOG(ERROR) << "call request handler exception: " << e.what();
throw;
}
return false;
}
static bool callCBWriteHandler(Request::kCallType calltype, const std::string& callback_name,
const DistributeDriver::CBWriteHandlerT& cb_handler)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("callback_" + callback_name);
bool ret = cb_handler(calltype);
if (!ret)
{
LOG(ERROR) << "callback handler failed." << callback_name;
}
else
{
LOG(INFO) << "a callback write request finished :" << callback_name;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
void DistributeDriver::removeCallbackWriteHandler(const std::string& name)
{
// no lock needed because of this will only happen while stopping collection,
// it will be sure there is no any callback write request.
callback_handlers_.erase(name);
LOG(INFO) << "callback handler removed :" << name;
}
bool DistributeDriver::addCallbackWriteHandler(const std::string& name, const CBWriteHandlerT& handler)
{
if (callback_handlers_.find(name) != callback_handlers_.end())
{
LOG(WARNING) << "callback handler already existed";
return false;
}
if (!handler)
{
LOG(WARNING) << "callback NULL handler!";
return false;
}
callback_handlers_[name] = handler;
return true;
}
bool DistributeDriver::handleRequest(const std::string& reqjsondata, const std::string& packed_data, Request::kCallType calltype)
{
static izenelib::driver::JsonReader reader;
Value requestValue;
if(reader.read(reqjsondata, requestValue))
{
if (requestValue.type() != Value::kObjectType)
{
LOG(ERROR) << "read request data type error: Malformed request: require an object as input.";
return false;
}
Request request;
request.assignTmp(requestValue);
izenelib::driver::Router::handler_ptr handler = router_->find(
request.controller(),
request.action()
);
if (!handler)
{
LOG(ERROR) << "Handler not found for the request : " << request.controller() <<
"," << request.action();
return false;
}
if (!ReqLogMgr::isWriteRequest(request.controller(), request.action()))
{
LOG(ERROR) << "=== Wrong, not a write request in DistributeDriver!!";
return false;
}
try
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
DistributeTestSuit::incWriteRequestTimes(request.controller() + "_" + request.action());
DistributeRequestHooker::get()->setHook(calltype, packed_data);
request.setCallType(calltype);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (calltype == Request::FromLog)
{
// redo log must process the request one by one, so sync needed.
return callHandler(handler, calltype, packed_data, request);
}
else
{
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callHandler,
handler, calltype, packed_data, request));
}
}
return true;
}
catch (const std::exception& e)
{
LOG(ERROR) << "process request exception: " << e.what();
}
}
else
{
// malformed request
LOG(WARNING) << "read request data error: " << reader.errorMessages();
}
return false;
}
bool DistributeDriver::handleReqFromLog(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a cron job request in log." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCronJob(Request::FromLog, reqjsondata, packed_data);
}
else if ((ReqLogType)reqtype == Req_Callback)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a callback request in log." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCBWriteHandler(Request::FromLog, reqjsondata, it->second);
}
return handleRequest(reqjsondata, packed_data, Request::FromLog);
}
bool DistributeDriver::handleReqFromPrimary(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
LOG(INFO) << "got a cron job request from primary." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromPrimaryWorker, reqjsondata, packed_data));
}
return true;
}
else if((ReqLogType)reqtype == Req_Callback)
{
LOG(INFO) << "got a callback request in log." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler,
Request::FromPrimaryWorker, reqjsondata, it->second));
}
return true;
}
return handleRequest(reqjsondata, packed_data, Request::FromPrimaryWorker);
}
bool DistributeDriver::pushCallbackWrite(const std::string& name, const std::string& packed_data)
{
LOG(INFO) << "a callback write pushed to queue: " << name;
MasterManagerBase::get()->pushWriteReq(name + "::" + packed_data, "callback");
return true;
}
bool DistributeDriver::on_new_req_available()
{
if (!MasterManagerBase::get()->prepareWriteReq())
{
LOG(WARNING) << "prepare new request failed. maybe some other primary master prepared first. ";
return false;
}
while(true)
{
std::string reqdata;
std::string reqtype;
if(!MasterManagerBase::get()->popWriteReq(reqdata, reqtype))
{
LOG(INFO) << "no more request.";
return false;
}
if(reqtype.empty() && !handleRequest(reqdata, reqdata, Request::FromDistribute) )
{
LOG(WARNING) << "one write request failed to deliver :" << reqdata;
// a write request failed to deliver means the worker did not
// started to handle this request, so the request is ignored, and
// continue to deliver next write request in the queue.
}
else if (reqtype == "cron")
{
LOG(INFO) << "got a cron job request from queue." << reqdata;
DistributeRequestHooker::get()->setHook(Request::FromDistribute, reqdata);
DistributeRequestHooker::get()->hookCurrentReq(reqdata);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromDistribute, reqdata, reqdata));
}
break;
}
else if (reqtype == "callback")
{
LOG(INFO) << "got a callback write request : " << reqdata;
// get the callback name and packed_data.
size_t split_pos = reqdata.find("::");
if (split_pos == std::string::npos)
{
LOG(WARNING) << "callback data invalid.";
continue;
}
std::string callback_name = reqdata.substr(0, split_pos);
std::string packed_data = reqdata.substr(split_pos + 2);
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(callback_name);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << callback_name;
continue;
}
DistributeRequestHooker::get()->setHook(Request::FromOtherShard, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler, Request::FromOtherShard,
callback_name, it->second));
}
break;
}
else
{
// a write request deliver success from master to worker.
// this mean the worker has started to process this request,
// may be not finish writing, so we break here to wait the finished
// event from primary worker.
break;
}
}
return true;
}
}
<commit_msg>tiny fix<commit_after>#include "DistributeDriver.h"
#include "MasterManagerBase.h"
#include "DistributeRequestHooker.h"
#include "RequestLog.h"
#include "DistributeTest.hpp"
#include <util/scheduler.h>
#include <util/driver/Reader.h>
#include <util/driver/Writer.h>
#include <util/driver/writers/JsonWriter.h>
#include <util/driver/readers/JsonReader.h>
#include <util/driver/Keys.h>
#include <boost/bind.hpp>
#include <glog/logging.h>
using namespace izenelib::driver;
namespace sf1r
{
DistributeDriver::DistributeDriver()
{
async_task_worker_ = boost::thread(&DistributeDriver::run, this);
// only one write task can exist in distribute system.
asyncWriteTasks_.resize(1);
}
void DistributeDriver::stop()
{
async_task_worker_.interrupt();
async_task_worker_.join();
asyncWriteTasks_.clear();
}
void DistributeDriver::run()
{
try
{
while(true)
{
boost::function<bool()> task;
asyncWriteTasks_.pop(task);
task();
boost::this_thread::interruption_point();
}
}
catch (boost::thread_interrupted&)
{
return;
}
}
void DistributeDriver::init(const RouterPtr& router)
{
router_ = router;
MasterManagerBase::get()->setCallback(boost::bind(&DistributeDriver::on_new_req_available, this));
}
static bool callCronJob(Request::kCallType calltype, const std::string& jobname, const std::string& packed_data)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("cron_" + jobname);
bool ret = izenelib::util::Scheduler::runJobImmediatly(jobname, calltype, calltype == Request::FromLog);
if (!ret)
{
LOG(ERROR) << "start cron job failed." << jobname;
}
else
{
LOG(INFO) << "cron job finished local: " << jobname;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
static bool callHandler(izenelib::driver::Router::handler_ptr handler,
Request::kCallType calltype, const std::string& packed_data,
Request& request)
{
try
{
DistributeRequestHooker::get()->processLocalBegin();
Response response;
response.setSuccess(true);
static Poller tmp_poller;
// prepare request
handler->invoke(request,
response,
tmp_poller);
LOG(INFO) << "write request send in DistributeDriver success.";
return true;
}
catch(const std::exception& e)
{
LOG(ERROR) << "call request handler exception: " << e.what();
throw;
}
return false;
}
static bool callCBWriteHandler(Request::kCallType calltype, const std::string& callback_name,
const DistributeDriver::CBWriteHandlerT& cb_handler)
{
DistributeRequestHooker::get()->processLocalBegin();
DistributeTestSuit::incWriteRequestTimes("callback_" + callback_name);
bool ret = cb_handler(calltype);
if (!ret)
{
LOG(ERROR) << "callback handler failed." << callback_name;
}
else
{
LOG(INFO) << "a callback write request finished :" << callback_name;
}
DistributeRequestHooker::get()->processLocalFinished(ret);
return ret;
}
void DistributeDriver::removeCallbackWriteHandler(const std::string& name)
{
// no lock needed because of this will only happen while stopping collection,
// it will be sure there is no any callback write request.
callback_handlers_.erase(name);
LOG(INFO) << "callback handler removed :" << name;
}
bool DistributeDriver::addCallbackWriteHandler(const std::string& name, const CBWriteHandlerT& handler)
{
if (callback_handlers_.find(name) != callback_handlers_.end())
{
LOG(WARNING) << "callback handler already existed";
return false;
}
if (!handler)
{
LOG(WARNING) << "callback NULL handler!";
return false;
}
callback_handlers_[name] = handler;
return true;
}
bool DistributeDriver::handleRequest(const std::string& reqjsondata, const std::string& packed_data, Request::kCallType calltype)
{
static izenelib::driver::JsonReader reader;
Value requestValue;
if(reader.read(reqjsondata, requestValue))
{
if (requestValue.type() != Value::kObjectType)
{
LOG(ERROR) << "read request data type error: Malformed request: require an object as input.";
return false;
}
Request request;
request.assignTmp(requestValue);
izenelib::driver::Router::handler_ptr handler = router_->find(
request.controller(),
request.action()
);
if (!handler)
{
LOG(ERROR) << "Handler not found for the request : " << request.controller() <<
"," << request.action();
return false;
}
if (!ReqLogMgr::isWriteRequest(request.controller(), request.action()))
{
LOG(ERROR) << "=== Wrong, not a write request in DistributeDriver!!";
return false;
}
try
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
DistributeTestSuit::incWriteRequestTimes(request.controller() + "_" + request.action());
DistributeRequestHooker::get()->setHook(calltype, packed_data);
request.setCallType(calltype);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (calltype == Request::FromLog)
{
// redo log must process the request one by one, so sync needed.
return callHandler(handler, calltype, packed_data, request);
}
else
{
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callHandler,
handler, calltype, packed_data, request));
}
}
return true;
}
catch (const std::exception& e)
{
LOG(ERROR) << "process request exception: " << e.what();
}
}
else
{
// malformed request
LOG(WARNING) << "read request data error: " << reader.errorMessages();
}
return false;
}
bool DistributeDriver::handleReqFromLog(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a cron job request in log." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCronJob(Request::FromLog, reqjsondata, packed_data);
}
else if ((ReqLogType)reqtype == Req_Callback)
{
if (!asyncWriteTasks_.empty())
{
LOG(ERROR) << "another write task is running in async_task_worker_!!";
return false;
}
LOG(INFO) << "got a callback request in log." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromLog, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
return callCBWriteHandler(Request::FromLog, reqjsondata, it->second);
}
return handleRequest(reqjsondata, packed_data, Request::FromLog);
}
bool DistributeDriver::handleReqFromPrimary(int reqtype, const std::string& reqjsondata, const std::string& packed_data)
{
if ((ReqLogType)reqtype == Req_CronJob)
{
LOG(INFO) << "got a cron job request from primary." << reqjsondata;
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromPrimaryWorker, reqjsondata, packed_data));
}
return true;
}
else if((ReqLogType)reqtype == Req_Callback)
{
LOG(INFO) << "got a callback request from primary." << reqjsondata;
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(reqjsondata);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << reqjsondata;
return false;
}
DistributeRequestHooker::get()->setHook(Request::FromPrimaryWorker, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler,
Request::FromPrimaryWorker, reqjsondata, it->second));
}
return true;
}
return handleRequest(reqjsondata, packed_data, Request::FromPrimaryWorker);
}
bool DistributeDriver::pushCallbackWrite(const std::string& name, const std::string& packed_data)
{
LOG(INFO) << "a callback write pushed to queue: " << name;
MasterManagerBase::get()->pushWriteReq(name + "::" + packed_data, "callback");
return true;
}
bool DistributeDriver::on_new_req_available()
{
if (!MasterManagerBase::get()->prepareWriteReq())
{
LOG(WARNING) << "prepare new request failed. maybe some other primary master prepared first. ";
return false;
}
while(true)
{
std::string reqdata;
std::string reqtype;
if(!MasterManagerBase::get()->popWriteReq(reqdata, reqtype))
{
LOG(INFO) << "no more request.";
return false;
}
if(reqtype.empty() && !handleRequest(reqdata, reqdata, Request::FromDistribute) )
{
LOG(WARNING) << "one write request failed to deliver :" << reqdata;
// a write request failed to deliver means the worker did not
// started to handle this request, so the request is ignored, and
// continue to deliver next write request in the queue.
}
else if (reqtype == "cron")
{
LOG(INFO) << "got a cron job request from queue." << reqdata;
DistributeRequestHooker::get()->setHook(Request::FromDistribute, reqdata);
DistributeRequestHooker::get()->hookCurrentReq(reqdata);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCronJob,
Request::FromDistribute, reqdata, reqdata));
}
break;
}
else if (reqtype == "callback")
{
LOG(INFO) << "got a callback write request : " << reqdata;
// get the callback name and packed_data.
size_t split_pos = reqdata.find("::");
if (split_pos == std::string::npos)
{
LOG(WARNING) << "callback data invalid.";
continue;
}
std::string callback_name = reqdata.substr(0, split_pos);
std::string packed_data = reqdata.substr(split_pos + 2);
std::map<std::string, CBWriteHandlerT>::const_iterator it = callback_handlers_.find(callback_name);
if (it == callback_handlers_.end())
{
LOG(WARNING) << "callback write request not found on the node: " << callback_name;
continue;
}
DistributeRequestHooker::get()->setHook(Request::FromOtherShard, packed_data);
DistributeRequestHooker::get()->hookCurrentReq(packed_data);
if (!async_task_worker_.interruption_requested())
{
asyncWriteTasks_.push(boost::bind(&callCBWriteHandler, Request::FromOtherShard,
callback_name, it->second));
}
break;
}
else
{
// a write request deliver success from master to worker.
// this mean the worker has started to process this request,
// may be not finish writing, so we break here to wait the finished
// event from primary worker.
break;
}
}
return true;
}
}
<|endoftext|> |
<commit_before>#include "QtViewerMapping.h"
#include <gloperate/Camera.h>
#include <gloperate/capabilities/CameraCapability.h>
#include <gloperate/capabilities/AbstractViewportCapability.h>
#include <gloperate/capabilities/AbstractCoordinateProviderCapability.h>
#include <gloperate/input/AbstractEvent.h>
#include <gloperate/input/KeyboardEvent.h>
#include <gloperate/input/MouseEvent.h>
#include <gloperate/navigation/WorldInHandNavigation.h>
#include <gloperate/Painter.h>
using namespace gloperate;
QtViewerMapping::QtViewerMapping()
{
}
QtViewerMapping::~QtViewerMapping()
{
}
void QtViewerMapping::initializeNavigation()
{
if ( m_painter &&
m_painter->supports<CameraCapability>() &&
m_painter->supports<AbstractCoordinateProviderCapability>() &&
m_painter->supports<AbstractViewportCapability>())
{
CameraCapability * cameraCapability = dynamic_cast<CameraCapability*>(m_painter->getCapability<CameraCapability>());
AbstractCoordinateProviderCapability * coordProviderCapability = dynamic_cast<AbstractCoordinateProviderCapability*>(m_painter->getCapability<AbstractCoordinateProviderCapability>());
AbstractViewportCapability * viewportCapability = dynamic_cast<AbstractViewportCapability*>(m_painter->getCapability<AbstractViewportCapability>());
m_navigation.reset(new WorldInHandNavigation(cameraCapability, viewportCapability, coordProviderCapability));
}
}
void QtViewerMapping::processEvent(AbstractEvent * event)
{
if (event->sourceType() == gloperate::SourceType::Keyboard)
{
KeyboardEvent * keyEvent = dynamic_cast<KeyboardEvent*>(event);
if (keyEvent && keyEvent->type() == KeyboardEvent::Type::Press)
{
switch (keyEvent->key())
{
// WASD move camera
case KeyW:
m_navigation->pan(glm::vec3(0, 0, 1));
break;
case KeyA:
m_navigation->pan(glm::vec3(1, 0, 0));
break;
case KeyS:
m_navigation->pan(glm::vec3(0, 0, -1));
break;
case KeyD:
m_navigation->pan(glm::vec3(-1, 0, 0));
break;
// Reset camera position
case KeyR:
m_navigation->reset(true);
break;
// Arrows rotate camera
case KeyUp:
m_navigation->rotate(0.0f, glm::radians(-10.0f));
break;
case KeyLeft:
m_navigation->rotate(glm::radians(10.0f), 0.0f);
break;
case KeyDown:
m_navigation->rotate(0.0f, glm::radians(10.0f));
break;
case KeyRight:
m_navigation->rotate(glm::radians(-10.0f), 0.0f);
break;
default:
break;
}
}
}
// not used right now
else if (event->sourceType() == gloperate::SourceType::Mouse)
{
MouseEvent * mouseEvent = dynamic_cast<MouseEvent*>(event);
if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Press)
{
if (mouseEvent->button() == gloperate::MouseButton1)
{
m_navigation->reset(true);
}
}
}
}
<commit_msg>Use mouse events for panning in mapping<commit_after>#include "QtViewerMapping.h"
#include <gloperate/Camera.h>
#include <gloperate/capabilities/CameraCapability.h>
#include <gloperate/capabilities/AbstractViewportCapability.h>
#include <gloperate/capabilities/AbstractCoordinateProviderCapability.h>
#include <gloperate/input/AbstractEvent.h>
#include <gloperate/input/KeyboardEvent.h>
#include <gloperate/input/MouseEvent.h>
#include <gloperate/navigation/WorldInHandNavigation.h>
#include <gloperate/Painter.h>
using namespace gloperate;
QtViewerMapping::QtViewerMapping()
{
}
QtViewerMapping::~QtViewerMapping()
{
}
void QtViewerMapping::initializeNavigation()
{
if ( m_painter &&
m_painter->supports<CameraCapability>() &&
m_painter->supports<AbstractCoordinateProviderCapability>() &&
m_painter->supports<AbstractViewportCapability>())
{
CameraCapability * cameraCapability = dynamic_cast<CameraCapability*>(m_painter->getCapability<CameraCapability>());
AbstractCoordinateProviderCapability * coordProviderCapability = dynamic_cast<AbstractCoordinateProviderCapability*>(m_painter->getCapability<AbstractCoordinateProviderCapability>());
AbstractViewportCapability * viewportCapability = dynamic_cast<AbstractViewportCapability*>(m_painter->getCapability<AbstractViewportCapability>());
m_navigation.reset(new WorldInHandNavigation(cameraCapability, viewportCapability, coordProviderCapability));
}
}
void QtViewerMapping::processEvent(AbstractEvent * event)
{
if (event->sourceType() == gloperate::SourceType::Keyboard)
{
KeyboardEvent * keyEvent = dynamic_cast<KeyboardEvent*>(event);
if (keyEvent && keyEvent->type() == KeyboardEvent::Type::Press)
{
switch (keyEvent->key())
{
// WASD move camera
case KeyW:
m_navigation->pan(glm::vec3(0, 0, 1));
break;
case KeyA:
m_navigation->pan(glm::vec3(1, 0, 0));
break;
case KeyS:
m_navigation->pan(glm::vec3(0, 0, -1));
break;
case KeyD:
m_navigation->pan(glm::vec3(-1, 0, 0));
break;
// Reset camera position
case KeyR:
m_navigation->reset(true);
break;
// Arrows rotate camera
case KeyUp:
m_navigation->rotate(0.0f, glm::radians(-10.0f));
break;
case KeyLeft:
m_navigation->rotate(glm::radians(10.0f), 0.0f);
break;
case KeyDown:
m_navigation->rotate(0.0f, glm::radians(10.0f));
break;
case KeyRight:
m_navigation->rotate(glm::radians(-10.0f), 0.0f);
break;
default:
break;
}
}
}
else if (event->sourceType() == gloperate::SourceType::Mouse)
{
MouseEvent * mouseEvent = dynamic_cast<MouseEvent*>(event);
if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Press)
{
switch (mouseEvent->button())
{
case MouseButtonMiddle:
m_navigation->reset(true);
break;
case MouseButtonLeft:
m_navigation->panBegin(mouseEvent->pos());
break;
default:
break;
}
}
else if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Move)
{
switch (m_navigation->mode())
{
case WorldInHandNavigation::InteractionMode::PanInteraction:
m_navigation->panProcess(mouseEvent->pos());
default:
break;
}
}
else if (mouseEvent && mouseEvent->type() == MouseEvent::Type::Release)
{
switch (mouseEvent->button())
{
case MouseButtonLeft:
m_navigation->panEnd();
default:
break;
}
}
}
}
<|endoftext|> |
<commit_before>/**
* \file
* Copyright 2018 Jonas Schenke, Matthias Werner
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka 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 alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <alpaka/alpaka.hpp>
//#############################################################################
//! A cheap wrapper around a C-style array in heap memory.
template <typename T, uint64_t size>
struct cheapArray
{
T data[size];
//-----------------------------------------------------------------------------
//! Access operator.
//!
//! \param index The index of the element to be accessed.
//!
//! Returns the requested element per reference.
ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE T &operator[](uint64_t i)
{
return data[i];
}
//-----------------------------------------------------------------------------
//! Access operator.
//!
//! \param index The index of the element to be accessed.
//!
//! Returns the requested element per constant reference.
ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE const T &operator[](uint64_t i) const
{
return data[i];
}
};
//#############################################################################
//! A reduction kernel.
//!
//! \tparam TBlockSize The block size.
//! \tparam T The data type.
//! \tparam TFunc The Functor type for the reduction function.
template <uint32_t TBlockSize, typename T, typename TFunc>
struct ReduceKernel
{
ALPAKA_NO_HOST_ACC_WARNING
//-----------------------------------------------------------------------------
//! The kernel entry point.
//!
//! \tparam TAcc The accelerator environment.
//! \tparam TElem The element type.
//! \tparam TIdx The index type.
//!
//! \param acc The accelerator object.
//! \param source The source memory.
//! \param destination The destination memory.
//! \param n The problem size.
//! \param func The reduction function.
template <typename TAcc, typename TElem, typename TIdx>
ALPAKA_FN_ACC auto operator()(TAcc const &acc,
TElem const *const source,
TElem *destination,
TIdx const &n,
TFunc func) const -> void
{
auto &sdata(
alpaka::block::shared::st::allocVar<cheapArray<T, TBlockSize>,
__COUNTER__>(acc));
const uint32_t blockIndex(
alpaka::idx::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0]);
const uint32_t threadIndex(
alpaka::idx::getIdx<alpaka::Block, alpaka::Threads>(acc)[0]);
const uint32_t gridDimension(
alpaka::workdiv::getWorkDiv<alpaka::Grid, alpaka::Blocks>(acc)[0]);
// equivalent to blockIndex * TBlockSize + threadIndex
const uint32_t linearizedIndex(
alpaka::idx::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0]);
typename GetIterator<T, TElem, TAcc>::Iterator it(
acc, source, linearizedIndex, gridDimension * TBlockSize, n);
T result;
if (threadIndex < n)
result = *(it++); // avoids using the
// neutral element of specific
// --------
// Level 1: grid reduce, reading from global memory
// --------
// reduce per thread with increased ILP by 4x unrolling sum.
// the thread of our block reduces its 4 grid-neighbored threads and
// advances by grid-striding loop (maybe 128bit load improve perf)
while (it + 3 < it.end())
{
result = func(
func(func(result, func(*it, *(it + 1))), *(it + 2)), *(it + 3));
it += 4;
}
// doing the remaining blocks
while (it < it.end())
result = func(result, *(it++));
if (threadIndex < n)
sdata[threadIndex] = result;
alpaka::block::sync::syncBlockThreads(acc);
// --------
// Level 2: block + warp reduce, reading from shared memory
// --------
#pragma unroll
for (uint32_t currentBlockSize = TBlockSize,
currentBlockSizeUp =
(TBlockSize + 1) / 2; // ceil(TBlockSize/2.0)
currentBlockSize > 1;
currentBlockSize = currentBlockSize / 2,
currentBlockSizeUp = (currentBlockSize + 1) /
2) // ceil(currentBlockSize/2.0)
{
bool cond =
threadIndex < currentBlockSizeUp // only first half of block
// is working
&& (threadIndex + currentBlockSizeUp) <
TBlockSize // index for second half must be in bounds
&& (blockIndex * TBlockSize + threadIndex +
currentBlockSizeUp) < n &&
threadIndex <
n; // if elem in second half has been initialized before
if (cond)
sdata[threadIndex] =
func(sdata[threadIndex],
sdata[threadIndex + currentBlockSizeUp]);
alpaka::block::sync::syncBlockThreads(acc);
}
// store block result to gmem
if (threadIndex == 0 && threadIndex < n)
destination[blockIndex] = sdata[0];
}
};
<commit_msg>Used ALPAKA unroll instead of #pragma unroll<commit_after>/**
* \file
* Copyright 2018 Jonas Schenke, Matthias Werner
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka 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 alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <alpaka/alpaka.hpp>
//#############################################################################
//! A cheap wrapper around a C-style array in heap memory.
template <typename T, uint64_t size>
struct cheapArray
{
T data[size];
//-----------------------------------------------------------------------------
//! Access operator.
//!
//! \param index The index of the element to be accessed.
//!
//! Returns the requested element per reference.
ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE T &operator[](uint64_t i)
{
return data[i];
}
//-----------------------------------------------------------------------------
//! Access operator.
//!
//! \param index The index of the element to be accessed.
//!
//! Returns the requested element per constant reference.
ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE const T &operator[](uint64_t i) const
{
return data[i];
}
};
//#############################################################################
//! A reduction kernel.
//!
//! \tparam TBlockSize The block size.
//! \tparam T The data type.
//! \tparam TFunc The Functor type for the reduction function.
template <uint32_t TBlockSize, typename T, typename TFunc>
struct ReduceKernel
{
ALPAKA_NO_HOST_ACC_WARNING
//-----------------------------------------------------------------------------
//! The kernel entry point.
//!
//! \tparam TAcc The accelerator environment.
//! \tparam TElem The element type.
//! \tparam TIdx The index type.
//!
//! \param acc The accelerator object.
//! \param source The source memory.
//! \param destination The destination memory.
//! \param n The problem size.
//! \param func The reduction function.
template <typename TAcc, typename TElem, typename TIdx>
ALPAKA_FN_ACC auto operator()(TAcc const &acc,
TElem const *const source,
TElem *destination,
TIdx const &n,
TFunc func) const -> void
{
auto &sdata(
alpaka::block::shared::st::allocVar<cheapArray<T, TBlockSize>,
__COUNTER__>(acc));
const uint32_t blockIndex(
alpaka::idx::getIdx<alpaka::Grid, alpaka::Blocks>(acc)[0]);
const uint32_t threadIndex(
alpaka::idx::getIdx<alpaka::Block, alpaka::Threads>(acc)[0]);
const uint32_t gridDimension(
alpaka::workdiv::getWorkDiv<alpaka::Grid, alpaka::Blocks>(acc)[0]);
// equivalent to blockIndex * TBlockSize + threadIndex
const uint32_t linearizedIndex(
alpaka::idx::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0]);
typename GetIterator<T, TElem, TAcc>::Iterator it(
acc, source, linearizedIndex, gridDimension * TBlockSize, n);
T result;
if (threadIndex < n)
result = *(it++); // avoids using the
// neutral element of specific
// --------
// Level 1: grid reduce, reading from global memory
// --------
// reduce per thread with increased ILP by 4x unrolling sum.
// the thread of our block reduces its 4 grid-neighbored threads and
// advances by grid-striding loop (maybe 128bit load improve perf)
while (it + 3 < it.end())
{
result = func(
func(func(result, func(*it, *(it + 1))), *(it + 2)), *(it + 3));
it += 4;
}
// doing the remaining blocks
while (it < it.end())
result = func(result, *(it++));
if (threadIndex < n)
sdata[threadIndex] = result;
alpaka::block::sync::syncBlockThreads(acc);
// --------
// Level 2: block + warp reduce, reading from shared memory
// --------
ALPAKA_UNROLL()
for (uint32_t currentBlockSize = TBlockSize,
currentBlockSizeUp =
(TBlockSize + 1) / 2; // ceil(TBlockSize/2.0)
currentBlockSize > 1;
currentBlockSize = currentBlockSize / 2,
currentBlockSizeUp = (currentBlockSize + 1) /
2) // ceil(currentBlockSize/2.0)
{
bool cond =
threadIndex < currentBlockSizeUp // only first half of block
// is working
&& (threadIndex + currentBlockSizeUp) <
TBlockSize // index for second half must be in bounds
&& (blockIndex * TBlockSize + threadIndex +
currentBlockSizeUp) < n &&
threadIndex <
n; // if elem in second half has been initialized before
if (cond)
sdata[threadIndex] =
func(sdata[threadIndex],
sdata[threadIndex + currentBlockSizeUp]);
alpaka::block::sync::syncBlockThreads(acc);
}
// store block result to gmem
if (threadIndex == 0 && threadIndex < n)
destination[blockIndex] = sdata[0];
}
};
<|endoftext|> |
<commit_before>#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/MultiIndexBarrelReader.h>
#include <ir/index_manager/index/IndexBarrelWriter.h>
#include <util/izene_log.h>
#include <util/ThreadModel.h>
using namespace izenelib::ir::indexmanager;
IndexReader::IndexReader(Indexer* pIndex)
:pIndexer_(pIndex)
,pBarrelsInfo_(NULL)
,pBarrelReader_(NULL)
,pDocFilter_(NULL)
,pDocLengthReader_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
Directory* pDirectory = pIndexer_->getDirectory();
if(pDirectory->fileExists(DELETED_DOCS))
{
pDocFilter_ = new BitVector;
pDocFilter_->read(pDirectory, DELETED_DOCS);
}
///todo since only one collection is used within indexmanager, so we only get collectionmeta for one collection to build
///up the DocLengthReader
if(pIndexer_->getIndexManagerConfig()->indexStrategy_.indexDocLength_)
pDocLengthReader_ = new DocLengthReader(
pIndexer_->getCollectionsMeta().begin()->second.getDocumentSchema(),
pIndexer_->getDirectory());
}
IndexReader::~IndexReader()
{
if (pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
flush();
if(pDocFilter_) delete pDocFilter_;
pDocFilter_ = NULL;
if(pDocLengthReader_)
{
delete pDocLengthReader_;
pDocLengthReader_ = NULL;
}
}
void IndexReader::delDocFilter()
{
DVLOG(2) << "=> IndexReader::delDocFilter(), pDocFilter_: " << pDocFilter_;
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
pDocFilter_->clear();
}
DVLOG(2) << "<= IndexReader::delDocFilter()";
}
void IndexReader::flush()
{
if(pDocFilter_)
{
boost::mutex::scoped_lock docFilterLock(docFilterMutex_);
if(pDocFilter_->any())
pDocFilter_->write(pIndexer_->getDirectory(), DELETED_DOCS);
}
}
docid_t IndexReader::maxDoc()
{
return pBarrelsInfo_->maxDocId();
}
size_t IndexReader::docLength(docid_t docId, fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
if (!pDocLengthReader_)
return 0;
return pDocLengthReader_->docLength(docId, fid);
}
double IndexReader::getAveragePropertyLength(fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
if (!pDocLengthReader_)
return 0;
return pDocLengthReader_->averagePropertyLength(fid);
}
bool IndexReader::hasMemBarrelReader()
{
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
if(pBarrelReader_)
return pBarrelReader_->hasMemBarrel();
else
return false;
}
void IndexReader::createBarrelReader()
{
boost::mutex::scoped_lock lock(this->mutex_);
if(pBarrelReader_)
return;
DVLOG(2) << "=> IndexReader::createBarrelReader()";
if(int32_t bc = pBarrelsInfo_->getBarrelCount())
{
DVLOG(2) << "IndexReader::createBarrelReader() => " << bc << " barrels...";
if(bc == 1)
{
boost::mutex::scoped_lock lock(pBarrelsInfo_->getMutex());
pBarrelsInfo_->startIterator();
if(pBarrelsInfo_->hasNext())
{
BarrelInfo* pBarrelInfo = pBarrelsInfo_->next();
if(pBarrelInfo->isSearchable() && pBarrelInfo->getDocCount() > 0)
{
if(IndexBarrelWriter* pBarrelWriter = pBarrelInfo->getWriter())
pBarrelReader_ = pBarrelWriter->inMemoryReader();
else
pBarrelReader_ = new SingleIndexBarrelReader(this, pBarrelInfo);
}
}
}
else if(bc > 1)
pBarrelReader_ = new MultiIndexBarrelReader(this, pBarrelsInfo_);
if(pDocLengthReader_)
pDocLengthReader_->load(pBarrelsInfo_->maxDocId());
}
DVLOG(2) << "<= IndexReader::createBarrelReader()";
}
TermReader* IndexReader::getTermReader(collectionid_t colID)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
pTermReader->setSkipInterval(pIndexer_->getSkipInterval());
pTermReader->setMaxSkipLevel(pIndexer_->getMaxSkipLevel());
if(pDocFilter_)
pTermReader->setDocFilter(pDocFilter_);
return pTermReader->clone();
}
else
return NULL;
}
void IndexReader::reopen()
{
DVLOG(2) << "=> IndexReader::reopen()";
{
boost::mutex::scoped_lock lock(this->mutex_);
if(pBarrelReader_)
{
DVLOG(2) << "IndexReader::reopen() => delete pBarrelReader_: " << pBarrelReader_;
delete pBarrelReader_;
pBarrelReader_ = NULL;
DVLOG(2) << "IndexReader::reopen() <= delete pBarrelReader_";
}
}
createBarrelReader();
DVLOG(2) << "<= IndexReader::reopen(), pBarrelReader_: " << pBarrelReader_;
}
count_t IndexReader::numDocs()
{
return pBarrelsInfo_->getDocCount();
}
void IndexReader::delDocument(collectionid_t colID,docid_t docId)
{
DVLOG(4) << "=> IndexReader::delDocument(), collection id: " << colID << ", doc id: " << docId << " ...";
if(pBarrelsInfo_->deleteDocument(colID, docId))
{
boost::mutex::scoped_lock docFilterLock(docFilterMutex_);
if(!pDocFilter_)
{
// bit 0 is reserved, so that for doc id i, we can access it just using bit i
pDocFilter_ = new BitVector(pBarrelsInfo_->maxDocId() + 1);
}
pDocFilter_->set(docId);
}
DVLOG(4) << "<= IndexReader::delDocument()";
}
freq_t IndexReader::docFreq(collectionid_t colID, Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return 0;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->docFreq(term);
}
return 0;
}
TermInfo* IndexReader::termInfo(collectionid_t colID,Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->termInfo(term);
}
return 0;
}
size_t IndexReader::getDistinctNumTerms(collectionid_t colID, const std::string& property)
{
//collection has been removed, need to rebuild the barrel reader
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pBarrelReader_->getDistinctNumTerms(colID, property);
}
<commit_msg>tiny log<commit_after>#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/MultiIndexBarrelReader.h>
#include <ir/index_manager/index/IndexBarrelWriter.h>
#include <util/izene_log.h>
#include <util/ThreadModel.h>
using namespace izenelib::ir::indexmanager;
IndexReader::IndexReader(Indexer* pIndex)
:pIndexer_(pIndex)
,pBarrelsInfo_(NULL)
,pBarrelReader_(NULL)
,pDocFilter_(NULL)
,pDocLengthReader_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
Directory* pDirectory = pIndexer_->getDirectory();
if(pDirectory->fileExists(DELETED_DOCS))
{
pDocFilter_ = new BitVector;
pDocFilter_->read(pDirectory, DELETED_DOCS);
}
///todo since only one collection is used within indexmanager, so we only get collectionmeta for one collection to build
///up the DocLengthReader
if(pIndexer_->getIndexManagerConfig()->indexStrategy_.indexDocLength_)
pDocLengthReader_ = new DocLengthReader(
pIndexer_->getCollectionsMeta().begin()->second.getDocumentSchema(),
pIndexer_->getDirectory());
}
IndexReader::~IndexReader()
{
if (pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
flush();
if(pDocFilter_) delete pDocFilter_;
pDocFilter_ = NULL;
if(pDocLengthReader_)
{
delete pDocLengthReader_;
pDocLengthReader_ = NULL;
}
}
void IndexReader::delDocFilter()
{
DVLOG(2) << "=> IndexReader::delDocFilter(), pDocFilter_: " << pDocFilter_;
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
pDocFilter_->clear();
}
DVLOG(2) << "<= IndexReader::delDocFilter()";
}
void IndexReader::flush()
{
if(pDocFilter_)
{
boost::mutex::scoped_lock docFilterLock(docFilterMutex_);
if(pDocFilter_->any())
pDocFilter_->write(pIndexer_->getDirectory(), DELETED_DOCS);
}
}
docid_t IndexReader::maxDoc()
{
return pBarrelsInfo_->maxDocId();
}
size_t IndexReader::docLength(docid_t docId, fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
if (!pDocLengthReader_)
return 0;
return pDocLengthReader_->docLength(docId, fid);
}
double IndexReader::getAveragePropertyLength(fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
if (!pDocLengthReader_)
return 0;
return pDocLengthReader_->averagePropertyLength(fid);
}
bool IndexReader::hasMemBarrelReader()
{
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
if(pBarrelReader_)
return pBarrelReader_->hasMemBarrel();
else
return false;
}
void IndexReader::createBarrelReader()
{
boost::mutex::scoped_lock lock(this->mutex_);
if(pBarrelReader_)
return;
DVLOG(2) << "=> IndexReader::createBarrelReader()";
if(int32_t bc = pBarrelsInfo_->getBarrelCount())
{
DVLOG(2) << "IndexReader::createBarrelReader() => " << bc << " barrels...";
if(bc == 1)
{
boost::mutex::scoped_lock lock(pBarrelsInfo_->getMutex());
pBarrelsInfo_->startIterator();
if(pBarrelsInfo_->hasNext())
{
BarrelInfo* pBarrelInfo = pBarrelsInfo_->next();
if(pBarrelInfo->isSearchable() && pBarrelInfo->getDocCount() > 0)
{
if(IndexBarrelWriter* pBarrelWriter = pBarrelInfo->getWriter())
pBarrelReader_ = pBarrelWriter->inMemoryReader();
else
pBarrelReader_ = new SingleIndexBarrelReader(this, pBarrelInfo);
}
}
}
else if(bc > 1)
pBarrelReader_ = new MultiIndexBarrelReader(this, pBarrelsInfo_);
if(pDocLengthReader_)
pDocLengthReader_->load(pBarrelsInfo_->maxDocId());
}
DVLOG(2) << "<= IndexReader::createBarrelReader()";
}
TermReader* IndexReader::getTermReader(collectionid_t colID)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
pTermReader->setSkipInterval(pIndexer_->getSkipInterval());
pTermReader->setMaxSkipLevel(pIndexer_->getMaxSkipLevel());
if(pDocFilter_)
pTermReader->setDocFilter(pDocFilter_);
return pTermReader->clone();
}
else
return NULL;
}
void IndexReader::reopen()
{
DVLOG(2) << "=> IndexReader::reopen()";
{
boost::mutex::scoped_lock lock(this->mutex_);
if(pBarrelReader_)
{
DVLOG(2) << "IndexReader::reopen() => delete pBarrelReader_: " << pBarrelReader_;
delete pBarrelReader_;
pBarrelReader_ = NULL;
DVLOG(2) << "IndexReader::reopen() <= delete pBarrelReader_";
}
}
createBarrelReader();
DVLOG(2) << "<= IndexReader::reopen(), pBarrelReader_: " << pBarrelReader_;
}
count_t IndexReader::numDocs()
{
return pBarrelsInfo_->getDocCount();
}
void IndexReader::delDocument(collectionid_t colID,docid_t docId)
{
DVLOG(4) << "=> IndexReader::delDocument(), collection id: " << colID << ", doc id: " << docId << " ...";
if(pBarrelsInfo_->deleteDocument(colID, docId))
{
boost::mutex::scoped_lock docFilterLock(docFilterMutex_);
if(!pDocFilter_)
{
// bit 0 is reserved, so that for doc id i, we can access it just using bit i
pDocFilter_ = new BitVector(pBarrelsInfo_->maxDocId() + 1);
}
pDocFilter_->set(docId);
}
LOG(WARNING) << "<= IndexReader::delDocument() failed : " << docId;
}
freq_t IndexReader::docFreq(collectionid_t colID, Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return 0;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->docFreq(term);
}
return 0;
}
TermInfo* IndexReader::termInfo(collectionid_t colID,Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->termInfo(term);
}
return 0;
}
size_t IndexReader::getDistinctNumTerms(collectionid_t colID, const std::string& property)
{
//collection has been removed, need to rebuild the barrel reader
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pBarrelReader_->getDistinctNumTerms(colID, property);
}
<|endoftext|> |
<commit_before>#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/MultiIndexBarrelReader.h>
using namespace izenelib::ir::indexmanager;
IndexReader::IndexReader(Indexer* pIndex)
:pIndexer_(pIndex)
,pBarrelsInfo_(NULL)
,pBarrelReader_(NULL)
,pForwardIndexReader_(NULL)
,pDocFilter_(NULL)
,pDocLengthReader_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
Directory* pDirectory = pIndexer_->getDirectory();
if(pDirectory->fileExists(DELETED_DOCS))
{
pDocFilter_ = new BitVector;
pDocFilter_->read(pDirectory, DELETED_DOCS);
}
///todo since only one collection is used within indexmanager, so we only get collectionmeta for one collection to build
///up the DocLengthReader
if(pIndexer_->getIndexManagerConfig()->indexStrategy_.indexDocLength_)
pDocLengthReader_ = new DocLengthReader(pIndexer_->getCollectionsMeta().begin()->second.getDocumentSchema(),
pIndexer_->getDirectory());
}
IndexReader::~IndexReader(void)
{
if (pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
if(pForwardIndexReader_)
delete pForwardIndexReader_;
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
pDocFilter_->write(pIndexer_->getDirectory(), DELETED_DOCS);
delete pDocFilter_;
}
if(pDocLengthReader_) {delete pDocLengthReader_; pDocLengthReader_ = NULL;}
}
void IndexReader::delDocFilter()
{
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
delete pDocFilter_;
pDocFilter_ = NULL;
}
}
docid_t IndexReader::maxDoc()
{
return pBarrelsInfo_->maxDocId();
}
size_t IndexReader::docLength(docid_t docId, fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
return pDocLengthReader_->docLength(docId, fid);
}
double IndexReader::getAveragePropertyLength(fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pDocLengthReader_->averagePropertyLength(fid);
}
void IndexReader::createBarrelReader()
{
boost::mutex::scoped_lock lock(this->mutex_);
if (pBarrelReader_)
return;
// delete pBarrelReader_;
int32_t bc = pBarrelsInfo_->getBarrelCount();
BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel();
if ( (bc > 0) && pLastBarrel)
{
if (pLastBarrel->getDocCount() <= 0)///skip empty barrel
bc--;
pLastBarrel = (*pBarrelsInfo_)[bc - 1];
}
if (bc == 1)
{
if (pLastBarrel && pLastBarrel->getWriter())
pBarrelReader_ = pLastBarrel->getWriter()->inMemoryReader();
else
pBarrelReader_ = new SingleIndexBarrelReader(pIndexer_,pLastBarrel);
}
else if (bc > 1)
{
pBarrelReader_ = new MultiIndexBarrelReader(pIndexer_,pBarrelsInfo_);
}
else
SF1V5_THROW(ERROR_INDEX_COLLAPSE,"the index barrel number is 0.");
if(pDocLengthReader_)
pDocLengthReader_->load(pBarrelsInfo_->maxDocId());
//pIndexer_->setDirty(false);///clear dirty_ flag
}
TermReader* IndexReader::getTermReader(collectionid_t colID)
{
boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
if(!lock.owns_lock())
return NULL;
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
return pTermReader->clone();
else
return NULL;
}
void IndexReader::reopen()
{
//if(pBarrelReader_)
//delete pBarrelReader_;
//pBarrelReader_ = NULL;
/////pBarrelReader_->reopen();
createBarrelReader();
}
ForwardIndexReader* IndexReader::getForwardIndexReader()
{
if(!pForwardIndexReader_)
pForwardIndexReader_ = new ForwardIndexReader(pIndexer_->getDirectory());
return pForwardIndexReader_->clone();
}
count_t IndexReader::numDocs()
{
return pBarrelsInfo_->getDocCount();
}
BarrelInfo* IndexReader::findDocumentInBarrels(collectionid_t colID, docid_t docID)
{
for (int i = pBarrelsInfo_->getBarrelCount() - 1; i >= 0; i--)
{
BarrelInfo* pBarrelInfo = (*pBarrelsInfo_)[i];
if ((pBarrelInfo->baseDocIDMap.find(colID) != pBarrelInfo->baseDocIDMap.end())&&
(pBarrelInfo->baseDocIDMap[colID] <= docID))
return pBarrelInfo;
}
return NULL;
}
void IndexReader::deleteDocumentPhysically(IndexerDocument* pDoc)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock lock(this->mutex_);
pBarrelReader_->deleteDocumentPhysically(pDoc);
DocId uniqueID;
pDoc->getDocId(uniqueID);
BarrelInfo* pBarrelInfo = findDocumentInBarrels(uniqueID.colId, uniqueID.docId);
pBarrelInfo->deleteDocument(uniqueID.docId);
map<IndexerPropertyConfig, IndexerDocumentPropertyType> propertyValueList;
pDoc->getPropertyList(propertyValueList);
for (map<IndexerPropertyConfig, IndexerDocumentPropertyType>::iterator iter = propertyValueList.begin(); iter != propertyValueList.end(); ++iter)
{
if(!iter->first.isIndex())
continue;
if (!iter->first.isForward())
{
pIndexer_->getBTreeIndexer()->remove(uniqueID.colId, iter->first.getPropertyId(), boost::get<PropertyType>(iter->second), uniqueID.docId);
}
}
pIndexer_->setDirty(true);//flush barrelsinfo when Indexer quit
}
void IndexReader::delDocument(collectionid_t colID,docid_t docId)
{
BarrelInfo* pBarrelInfo = findDocumentInBarrels(colID, docId);
if(NULL == pBarrelInfo)
return;
pBarrelInfo->deleteDocument(docId);
if(!pDocFilter_)
{
pDocFilter_ = new BitVector(pBarrelsInfo_->getDocCount() + 1);
}
pDocFilter_->set(docId);
}
freq_t IndexReader::docFreq(collectionid_t colID, Term* term)
{
boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
if(!lock.owns_lock())
return 0;
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->docFreq(term);
}
return 0;
}
TermInfo* IndexReader::termInfo(collectionid_t colID,Term* term)
{
boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
if(!lock.owns_lock())
return NULL;
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->termInfo(term);
}
return 0;
}
size_t IndexReader::getDistinctNumTerms(collectionid_t colID, const std::string& property)
{
//collection has been removed, need to rebuild the barrel reader
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pBarrelReader_->getDistinctNumTerms(colID, property);
}
<commit_msg>remove unnecessary exception<commit_after>#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/MultiIndexBarrelReader.h>
using namespace izenelib::ir::indexmanager;
IndexReader::IndexReader(Indexer* pIndex)
:pIndexer_(pIndex)
,pBarrelsInfo_(NULL)
,pBarrelReader_(NULL)
,pForwardIndexReader_(NULL)
,pDocFilter_(NULL)
,pDocLengthReader_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
Directory* pDirectory = pIndexer_->getDirectory();
if(pDirectory->fileExists(DELETED_DOCS))
{
pDocFilter_ = new BitVector;
pDocFilter_->read(pDirectory, DELETED_DOCS);
}
///todo since only one collection is used within indexmanager, so we only get collectionmeta for one collection to build
///up the DocLengthReader
if(pIndexer_->getIndexManagerConfig()->indexStrategy_.indexDocLength_)
pDocLengthReader_ = new DocLengthReader(pIndexer_->getCollectionsMeta().begin()->second.getDocumentSchema(),
pIndexer_->getDirectory());
}
IndexReader::~IndexReader(void)
{
if (pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
if(pForwardIndexReader_)
delete pForwardIndexReader_;
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
pDocFilter_->write(pIndexer_->getDirectory(), DELETED_DOCS);
delete pDocFilter_;
}
if(pDocLengthReader_) {delete pDocLengthReader_; pDocLengthReader_ = NULL;}
}
void IndexReader::delDocFilter()
{
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
delete pDocFilter_;
pDocFilter_ = NULL;
}
}
docid_t IndexReader::maxDoc()
{
return pBarrelsInfo_->maxDocId();
}
size_t IndexReader::docLength(docid_t docId, fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
return pDocLengthReader_->docLength(docId, fid);
}
double IndexReader::getAveragePropertyLength(fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pDocLengthReader_->averagePropertyLength(fid);
}
void IndexReader::createBarrelReader()
{
boost::mutex::scoped_lock lock(this->mutex_);
if (pBarrelReader_)
return;
// delete pBarrelReader_;
int32_t bc = pBarrelsInfo_->getBarrelCount();
BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel();
if ( (bc > 0) && pLastBarrel)
{
if (pLastBarrel->getDocCount() <= 0)///skip empty barrel
bc--;
pLastBarrel = (*pBarrelsInfo_)[bc - 1];
}
if (bc == 1)
{
if (pLastBarrel && pLastBarrel->getWriter())
pBarrelReader_ = pLastBarrel->getWriter()->inMemoryReader();
else
pBarrelReader_ = new SingleIndexBarrelReader(pIndexer_,pLastBarrel);
}
else if (bc > 1)
{
pBarrelReader_ = new MultiIndexBarrelReader(pIndexer_,pBarrelsInfo_);
}
else
return;
if(pDocLengthReader_)
pDocLengthReader_->load(pBarrelsInfo_->maxDocId());
//pIndexer_->setDirty(false);///clear dirty_ flag
}
TermReader* IndexReader::getTermReader(collectionid_t colID)
{
boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
if(!lock.owns_lock())
return NULL;
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
return pTermReader->clone();
else
return NULL;
}
void IndexReader::reopen()
{
//if(pBarrelReader_)
//delete pBarrelReader_;
//pBarrelReader_ = NULL;
/////pBarrelReader_->reopen();
createBarrelReader();
}
ForwardIndexReader* IndexReader::getForwardIndexReader()
{
if(!pForwardIndexReader_)
pForwardIndexReader_ = new ForwardIndexReader(pIndexer_->getDirectory());
return pForwardIndexReader_->clone();
}
count_t IndexReader::numDocs()
{
return pBarrelsInfo_->getDocCount();
}
BarrelInfo* IndexReader::findDocumentInBarrels(collectionid_t colID, docid_t docID)
{
for (int i = pBarrelsInfo_->getBarrelCount() - 1; i >= 0; i--)
{
BarrelInfo* pBarrelInfo = (*pBarrelsInfo_)[i];
if ((pBarrelInfo->baseDocIDMap.find(colID) != pBarrelInfo->baseDocIDMap.end())&&
(pBarrelInfo->baseDocIDMap[colID] <= docID))
return pBarrelInfo;
}
return NULL;
}
void IndexReader::deleteDocumentPhysically(IndexerDocument* pDoc)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock lock(this->mutex_);
pBarrelReader_->deleteDocumentPhysically(pDoc);
DocId uniqueID;
pDoc->getDocId(uniqueID);
BarrelInfo* pBarrelInfo = findDocumentInBarrels(uniqueID.colId, uniqueID.docId);
pBarrelInfo->deleteDocument(uniqueID.docId);
map<IndexerPropertyConfig, IndexerDocumentPropertyType> propertyValueList;
pDoc->getPropertyList(propertyValueList);
for (map<IndexerPropertyConfig, IndexerDocumentPropertyType>::iterator iter = propertyValueList.begin(); iter != propertyValueList.end(); ++iter)
{
if(!iter->first.isIndex())
continue;
if (!iter->first.isForward())
{
pIndexer_->getBTreeIndexer()->remove(uniqueID.colId, iter->first.getPropertyId(), boost::get<PropertyType>(iter->second), uniqueID.docId);
}
}
pIndexer_->setDirty(true);//flush barrelsinfo when Indexer quit
}
void IndexReader::delDocument(collectionid_t colID,docid_t docId)
{
BarrelInfo* pBarrelInfo = findDocumentInBarrels(colID, docId);
if(NULL == pBarrelInfo)
return;
pBarrelInfo->deleteDocument(docId);
if(!pDocFilter_)
{
pDocFilter_ = new BitVector(pBarrelsInfo_->getDocCount() + 1);
}
pDocFilter_->set(docId);
}
freq_t IndexReader::docFreq(collectionid_t colID, Term* term)
{
boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
if(!lock.owns_lock())
return 0;
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->docFreq(term);
}
return 0;
}
TermInfo* IndexReader::termInfo(collectionid_t colID,Term* term)
{
boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
if(!lock.owns_lock())
return NULL;
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->termInfo(term);
}
return 0;
}
size_t IndexReader::getDistinctNumTerms(collectionid_t colID, const std::string& property)
{
//collection has been removed, need to rebuild the barrel reader
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pBarrelReader_->getDistinctNumTerms(colID, property);
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBitmap.h"
#include "SkShader.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
namespace skiagm {
class Xfermodes2GM : public GM {
public:
Xfermodes2GM() {}
protected:
SkString onShortName() override {
return SkString("xfermodes2");
}
SkISize onISize() override {
return SkISize::Make(455, 475);
}
void onDraw(SkCanvas* canvas) override {
canvas->translate(SkIntToScalar(10), SkIntToScalar(20));
const SkScalar w = SkIntToScalar(kSize);
const SkScalar h = SkIntToScalar(kSize);
SkPaint labelP;
labelP.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&labelP);
labelP.setTextAlign(SkPaint::kCenter_Align);
const int W = 6;
SkScalar x = 0, y = 0;
for (size_t m = 0; m <= SkXfermode::kLastMode; m++) {
SkXfermode::Mode mode = static_cast<SkXfermode::Mode>(m);
SkXfermode* xm = SkXfermode::Create(mode);
SkAutoUnref aur(xm);
canvas->save();
canvas->translate(x, y);
SkPaint p;
p.setAntiAlias(false);
p.setStyle(SkPaint::kFill_Style);
p.setShader(fBG);
SkRect r = SkRect::MakeWH(w, h);
canvas->drawRect(r, p);
canvas->saveLayer(&r, NULL);
p.setShader(fDst);
canvas->drawRect(r, p);
p.setShader(fSrc);
p.setXfermode(xm);
canvas->drawRect(r, p);
canvas->restore();
r.inset(-SK_ScalarHalf, -SK_ScalarHalf);
p.setStyle(SkPaint::kStroke_Style);
p.setShader(NULL);
p.setXfermode(NULL);
canvas->drawRect(r, p);
canvas->restore();
#if 1
canvas->drawText(SkXfermode::ModeName(mode), strlen(SkXfermode::ModeName(mode)),
x + w/2, y - labelP.getTextSize()/2, labelP);
#endif
x += w + SkIntToScalar(10);
if ((m % W) == W - 1) {
x = 0;
y += h + SkIntToScalar(30);
}
}
}
private:
void onOnceBeforeDraw() override {
static const uint32_t kCheckData[] = {
SkPackARGB32(0xFF, 0x40, 0x40, 0x40),
SkPackARGB32(0xFF, 0xD0, 0xD0, 0xD0),
SkPackARGB32(0xFF, 0xD0, 0xD0, 0xD0),
SkPackARGB32(0xFF, 0x40, 0x40, 0x40)
};
SkBitmap bg;
bg.allocN32Pixels(2, 2, true);
memcpy(bg.getPixels(), kCheckData, sizeof(kCheckData));
SkMatrix lm;
lm.setScale(SkIntToScalar(16), SkIntToScalar(16));
fBG.reset(SkShader::CreateBitmapShader(bg,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode,
&lm));
SkBitmap dstBmp;
dstBmp.allocN32Pixels(kSize, kSize);
SkPMColor* pixels = reinterpret_cast<SkPMColor*>(dstBmp.getPixels());
for (int y = 0; y < kSize; ++y) {
int c = y * (1 << kShift);
SkPMColor rowColor = SkPackARGB32(c, c, 0, c/2);
for (int x = 0; x < kSize; ++x) {
pixels[kSize * y + x] = rowColor;
}
}
fSrc.reset(SkShader::CreateBitmapShader(dstBmp,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode));
SkBitmap srcBmp;
srcBmp.allocN32Pixels(kSize, kSize);
pixels = reinterpret_cast<SkPMColor*>(srcBmp.getPixels());
for (int x = 0; x < kSize; ++x) {
int c = x * (1 << kShift);
SkPMColor colColor = SkPackARGB32(c, 0, c, c/2);
for (int y = 0; y < kSize; ++y) {
pixels[kSize * y + x] = colColor;
}
}
fDst.reset(SkShader::CreateBitmapShader(srcBmp,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode));
}
enum {
kShift = 2,
kSize = 256 >> kShift,
};
SkAutoTUnref<SkShader> fBG;
SkAutoTUnref<SkShader> fSrc;
SkAutoTUnref<SkShader> fDst;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new Xfermodes2GM; }
static GMRegistry reg(MyFactory);
}
<commit_msg>Fix variable names in xfermodes2 gm test<commit_after>
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBitmap.h"
#include "SkShader.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
namespace skiagm {
class Xfermodes2GM : public GM {
public:
Xfermodes2GM() {}
protected:
SkString onShortName() override {
return SkString("xfermodes2");
}
SkISize onISize() override {
return SkISize::Make(455, 475);
}
void onDraw(SkCanvas* canvas) override {
canvas->translate(SkIntToScalar(10), SkIntToScalar(20));
const SkScalar w = SkIntToScalar(kSize);
const SkScalar h = SkIntToScalar(kSize);
SkPaint labelP;
labelP.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&labelP);
labelP.setTextAlign(SkPaint::kCenter_Align);
const int W = 6;
SkScalar x = 0, y = 0;
for (size_t m = 0; m <= SkXfermode::kLastMode; m++) {
SkXfermode::Mode mode = static_cast<SkXfermode::Mode>(m);
SkXfermode* xm = SkXfermode::Create(mode);
SkAutoUnref aur(xm);
canvas->save();
canvas->translate(x, y);
SkPaint p;
p.setAntiAlias(false);
p.setStyle(SkPaint::kFill_Style);
p.setShader(fBG);
SkRect r = SkRect::MakeWH(w, h);
canvas->drawRect(r, p);
canvas->saveLayer(&r, NULL);
p.setShader(fDst);
canvas->drawRect(r, p);
p.setShader(fSrc);
p.setXfermode(xm);
canvas->drawRect(r, p);
canvas->restore();
r.inset(-SK_ScalarHalf, -SK_ScalarHalf);
p.setStyle(SkPaint::kStroke_Style);
p.setShader(NULL);
p.setXfermode(NULL);
canvas->drawRect(r, p);
canvas->restore();
#if 1
canvas->drawText(SkXfermode::ModeName(mode), strlen(SkXfermode::ModeName(mode)),
x + w/2, y - labelP.getTextSize()/2, labelP);
#endif
x += w + SkIntToScalar(10);
if ((m % W) == W - 1) {
x = 0;
y += h + SkIntToScalar(30);
}
}
}
private:
void onOnceBeforeDraw() override {
static const uint32_t kCheckData[] = {
SkPackARGB32(0xFF, 0x40, 0x40, 0x40),
SkPackARGB32(0xFF, 0xD0, 0xD0, 0xD0),
SkPackARGB32(0xFF, 0xD0, 0xD0, 0xD0),
SkPackARGB32(0xFF, 0x40, 0x40, 0x40)
};
SkBitmap bg;
bg.allocN32Pixels(2, 2, true);
memcpy(bg.getPixels(), kCheckData, sizeof(kCheckData));
SkMatrix lm;
lm.setScale(SkIntToScalar(16), SkIntToScalar(16));
fBG.reset(SkShader::CreateBitmapShader(bg,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode,
&lm));
SkBitmap srcBmp;
srcBmp.allocN32Pixels(kSize, kSize);
SkPMColor* pixels = reinterpret_cast<SkPMColor*>(srcBmp.getPixels());
for (int y = 0; y < kSize; ++y) {
int c = y * (1 << kShift);
SkPMColor rowColor = SkPackARGB32(c, c, 0, c/2);
for (int x = 0; x < kSize; ++x) {
pixels[kSize * y + x] = rowColor;
}
}
fSrc.reset(SkShader::CreateBitmapShader(srcBmp,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode));
SkBitmap dstBmp;
dstBmp.allocN32Pixels(kSize, kSize);
pixels = reinterpret_cast<SkPMColor*>(dstBmp.getPixels());
for (int x = 0; x < kSize; ++x) {
int c = x * (1 << kShift);
SkPMColor colColor = SkPackARGB32(c, 0, c, c/2);
for (int y = 0; y < kSize; ++y) {
pixels[kSize * y + x] = colColor;
}
}
fDst.reset(SkShader::CreateBitmapShader(dstBmp,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode));
}
enum {
kShift = 2,
kSize = 256 >> kShift,
};
SkAutoTUnref<SkShader> fBG;
SkAutoTUnref<SkShader> fSrc;
SkAutoTUnref<SkShader> fDst;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new Xfermodes2GM; }
static GMRegistry reg(MyFactory);
}
<|endoftext|> |
<commit_before>#include "SQLiteQueryExecutor.h"
#include "Logger.h"
#include "sqlite_orm.h"
#include <sqlite3.h>
#include <memory>
#include <sstream>
#include <string>
namespace comm {
using namespace sqlite_orm;
std::string SQLiteQueryExecutor::sqliteFilePath;
void SQLiteQueryExecutor::migrate() {
sqlite3 *conn;
sqlite3_open(SQLiteQueryExecutor::sqliteFilePath.c_str(), &conn);
char *error;
sqlite3_exec(
conn,
"ALTER TABLE drafts RENAME COLUMN `threadID` TO `key`",
nullptr,
nullptr,
&error);
if (error) {
std::ostringstream stringStream;
stringStream << "Error occurred renaming threadID column in drafts table "
<< "to key: " << error;
Logger::log(stringStream.str());
sqlite3_free(error);
}
sqlite3_close(conn);
}
auto SQLiteQueryExecutor::getStorage() {
static auto storage = make_storage(
SQLiteQueryExecutor::sqliteFilePath,
make_table(
"drafts",
make_column("key", &Draft::key, unique(), primary_key()),
make_column("text", &Draft::text)));
return storage;
}
SQLiteQueryExecutor::SQLiteQueryExecutor() {
this->migrate();
SQLiteQueryExecutor::getStorage().sync_schema(true);
}
std::string SQLiteQueryExecutor::getDraft(std::string key) const {
std::unique_ptr<Draft> draft =
SQLiteQueryExecutor::getStorage().get_pointer<Draft>(key);
return (draft == nullptr) ? "" : draft->text;
}
void SQLiteQueryExecutor::updateDraft(std::string key, std::string text) const {
Draft draft = {key, text};
SQLiteQueryExecutor::getStorage().replace(draft);
}
bool SQLiteQueryExecutor::moveDraft(std::string oldKey, std::string newKey)
const {
std::unique_ptr<Draft> draft =
SQLiteQueryExecutor::getStorage().get_pointer<Draft>(oldKey);
if (draft == nullptr) {
return false;
}
draft->key = newKey;
SQLiteQueryExecutor::getStorage().replace(*draft);
SQLiteQueryExecutor::getStorage().remove<Draft>(oldKey);
return true;
}
std::vector<Draft> SQLiteQueryExecutor::getAllDrafts() const {
return SQLiteQueryExecutor::getStorage().get_all<Draft>();
}
void SQLiteQueryExecutor::removeAllDrafts() const {
SQLiteQueryExecutor::getStorage().remove_all<Draft>();
}
} // namespace comm
<commit_msg>[native] remove `sqlite_orm:sync_schema` usage<commit_after>#include "SQLiteQueryExecutor.h"
#include "Logger.h"
#include "sqlite_orm.h"
#include <sqlite3.h>
#include <memory>
#include <sstream>
#include <string>
namespace comm {
using namespace sqlite_orm;
std::string SQLiteQueryExecutor::sqliteFilePath;
void SQLiteQueryExecutor::migrate() {
sqlite3 *conn;
sqlite3_open(SQLiteQueryExecutor::sqliteFilePath.c_str(), &conn);
char *error;
sqlite3_exec(
conn,
"ALTER TABLE drafts RENAME COLUMN `threadID` TO `key`",
nullptr,
nullptr,
&error);
if (error) {
std::ostringstream stringStream;
stringStream << "Error occurred renaming threadID column in drafts table "
<< "to key: " << error;
Logger::log(stringStream.str());
sqlite3_free(error);
}
sqlite3_close(conn);
}
auto SQLiteQueryExecutor::getStorage() {
static auto storage = make_storage(
SQLiteQueryExecutor::sqliteFilePath,
make_table(
"drafts",
make_column("key", &Draft::key, unique(), primary_key()),
make_column("text", &Draft::text)));
return storage;
}
SQLiteQueryExecutor::SQLiteQueryExecutor() {
this->migrate();
}
std::string SQLiteQueryExecutor::getDraft(std::string key) const {
std::unique_ptr<Draft> draft =
SQLiteQueryExecutor::getStorage().get_pointer<Draft>(key);
return (draft == nullptr) ? "" : draft->text;
}
void SQLiteQueryExecutor::updateDraft(std::string key, std::string text) const {
Draft draft = {key, text};
SQLiteQueryExecutor::getStorage().replace(draft);
}
bool SQLiteQueryExecutor::moveDraft(std::string oldKey, std::string newKey)
const {
std::unique_ptr<Draft> draft =
SQLiteQueryExecutor::getStorage().get_pointer<Draft>(oldKey);
if (draft == nullptr) {
return false;
}
draft->key = newKey;
SQLiteQueryExecutor::getStorage().replace(*draft);
SQLiteQueryExecutor::getStorage().remove<Draft>(oldKey);
return true;
}
std::vector<Draft> SQLiteQueryExecutor::getAllDrafts() const {
return SQLiteQueryExecutor::getStorage().get_all<Draft>();
}
void SQLiteQueryExecutor::removeAllDrafts() const {
SQLiteQueryExecutor::getStorage().remove_all<Draft>();
}
} // namespace comm
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "nanoFramework_hardware_esp32_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Logging::NativeSetLogLevel___STATIC__VOID__STRING__I4,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTimer___STATIC__nanoFrameworkHardwareEsp32EspNativeError__U8,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByPin___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__I4,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByMultiPins___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__nanoFrameworkHardwareEsp32SleepWakeupMode,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTouchPad___STATIC__nanoFrameworkHardwareEsp32EspNativeError,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartLightSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartDeepSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupCause___STATIC__nanoFrameworkHardwareEsp32SleepWakeupCause,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupGpioPin___STATIC__nanoFrameworkHardwareEsp32SleepWakeupGpioPin,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupTouchpad___STATIC__nanoFrameworkHardwareEsp32SleepTouchPad,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerCreate___I4,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerDispose___VOID,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStop___VOID,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartOneShot___VOID__U8,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartPeriodic___VOID__U8,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeGetCurrent___STATIC__U8,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Hardware_Esp32 =
{
"nanoFramework.Hardware.Esp32",
0xF8079179,
method_lookup,
{ 1, 0, 5, 3 }
};
<commit_msg>Update nanoFramework.Hardware.Esp32 version to 1.0.7 ***NO_CI***<commit_after>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "nanoFramework_hardware_esp32_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Logging::NativeSetLogLevel___STATIC__VOID__STRING__I4,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTimer___STATIC__nanoFrameworkHardwareEsp32EspNativeError__U8,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByPin___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__I4,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByMultiPins___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__nanoFrameworkHardwareEsp32SleepWakeupMode,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTouchPad___STATIC__nanoFrameworkHardwareEsp32EspNativeError,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartLightSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartDeepSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupCause___STATIC__nanoFrameworkHardwareEsp32SleepWakeupCause,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupGpioPin___STATIC__nanoFrameworkHardwareEsp32SleepWakeupGpioPin,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupTouchpad___STATIC__nanoFrameworkHardwareEsp32SleepTouchPad,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerCreate___I4,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerDispose___VOID,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStop___VOID,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartOneShot___VOID__U8,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartPeriodic___VOID__U8,
NULL,
Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeGetCurrent___STATIC__U8,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Hardware_Esp32 =
{
"nanoFramework.Hardware.Esp32",
0xF8079179,
method_lookup,
{ 1, 0, 7, 3 }
};
<|endoftext|> |
<commit_before>/**
* @file minimizer_test.cpp
* @brief Minimize Draft code test version
*/
#include "minimizer.h"
#include <SQ_sampler.h>
/**
* @function main
*/
int main( int argc, char* argv[] ) {
// 0. Initialize random seed
std::random_device rd;
std::mt19937 gen( rd() );
std::uniform_real_distribution<> dis(-0.01, 0.015 );
// 1. Sample a SQ (pick any parameters)
SQ_params par;
par.a = 0.5; par.b = 0.35; par.c = 0.2;
par.e1 = 0.8; par.e2 = 0.8;
par.px = 0.1; par.py = 0.9; par.pz = 0.4;
par.ra = 0.5; par.pa = 0.7; par.ya = 0.5;
SQ_sampler sqs;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud( new pcl::PointCloud<pcl::PointXYZ>());
cloud = sqs.sampleSQ_naive( par );
// 1.a. Let's add some error and see how bad it goes (error-related)
for( int i = 0; i < cloud->points.size(); ++i ) {
cloud->points[i].x += dis(gen);
cloud->points[i].y += dis(gen);
cloud->points[i].z += dis(gen);
}
cloud->height = 1;
cloud->width = cloud->points.size();
pcl::io::savePCDFileASCII ("test_pcd.pcd", *cloud);
minimizer mM;
mM.loadPoints( cloud );
mM.visualizePoints();
SQ_params par_in, par_out;
par_in = par;
par_in.a += 0.01;
par_in.c -= 0.02;
par_in.py += 0.03;
par_in.e1 = 0.75;
par_in.e2 = 0.75;
if( mM.minimize(par_in, par_out) ) {
std::cout << "\t SUCCESS!"<< std::endl;
} else {
std::cout << "\t FAILURE!"<< std::endl;
}
return 0;
}
<commit_msg>Tested MATLAB code for J and Hess, it RUN LIKE THE WIND<commit_after>/**
* @file minimizer_test.cpp
* @brief Minimize Draft code test version
*/
#include "minimizer.h"
#include <SQ_sampler.h>
/**
* @function main
*/
int main( int argc, char* argv[] ) {
// 0. Initialize random seed
std::random_device rd;
std::mt19937 gen( rd() );
std::uniform_real_distribution<> dis(-0.01, 0.015 );
// 1. Sample a SQ (pick any parameters)
SQ_params par;
par.a = 0.5; par.b = 0.35; par.c = 0.2;
par.e1 = 0.8; par.e2 = 0.8;
par.px = 0.1; par.py = 0.9; par.pz = 0.4;
par.ra = 0.5; par.pa = 0.7; par.ya = 0.5;
SQ_sampler sqs;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud( new pcl::PointCloud<pcl::PointXYZ>());
cloud = sqs.sampleSQ_naive( par );
// 1.a. Let's add some error and see how bad it goes (error-related)
for( int i = 0; i < cloud->points.size(); ++i ) {
cloud->points[i].x += dis(gen);
cloud->points[i].y += dis(gen);
cloud->points[i].z += dis(gen);
}
cloud->height = 1;
cloud->width = cloud->points.size();
pcl::io::savePCDFileASCII ("test_pcd.pcd", *cloud);
minimizer mM;
mM.loadPoints( cloud );
mM.visualizePoints();
SQ_params par_in, par_out;
par_in = par;
par_in.a += 0.01;
par_in.c -= 0.02;
par_in.py += 0.03;
par_in.e1 = 0.6;
par_in.e2 = 0.6;
if( mM.minimize(par_in, par_out) ) {
std::cout << "\t SUCCESS!"<< std::endl;
} else {
std::cout << "\t FAILURE!"<< std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "languageInfo.h"
using namespace qReal::text;
QList<LanguageInfo> Languages::mUserDefinedLanguages;
QList<LanguageInfo> Languages::knownLanguages()
{
return mUserDefinedLanguages + QList<LanguageInfo>({
// Append here all languages declared in Languages class
c(), russianC(), python(), qtScript(), fSharp()
});
}
void Languages::registerLanguage(const LanguageInfo &language)
{
mUserDefinedLanguages << language;
}
LanguageInfo Languages::pickByExtension(const QString &extension)
{
for (const LanguageInfo &language : knownLanguages()) {
if (language.extension == extension) {
return language;
}
}
return textFileInfo(extension);
}
<commit_msg>*.js added to main open file dialog filters<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "languageInfo.h"
using namespace qReal::text;
QList<LanguageInfo> Languages::mUserDefinedLanguages;
QList<LanguageInfo> Languages::knownLanguages()
{
return mUserDefinedLanguages + QList<LanguageInfo>({
// Append here all languages declared in Languages class
c(), russianC(), python(), qtScript(), javaScript(), fSharp()
});
}
void Languages::registerLanguage(const LanguageInfo &language)
{
mUserDefinedLanguages << language;
}
LanguageInfo Languages::pickByExtension(const QString &extension)
{
for (const LanguageInfo &language : knownLanguages()) {
if (language.extension == extension) {
return language;
}
}
return textFileInfo(extension);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2009, Howard Butler
*
* 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 Martin Isenburg or Iowa Department
* of Natural Resources 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 <pdal/SpatialReference.hpp>
#include <boost/concept_check.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/concept_check.hpp> // ignore_unused_variable_warning
#include <boost/algorithm/string/trim.hpp>
// gdal
#ifdef PDAL_HAVE_GDAL
#include <ogr_spatialref.h>
#include <cpl_conv.h>
#endif
#include <pdal/Utils.hpp>
namespace pdal
{
SpatialReference::SpatialReference()
: m_wkt("")
{
return;
}
SpatialReference::SpatialReference(const std::string& s)
: m_wkt("")
{
this->setFromUserInput(s);
return;
}
SpatialReference::SpatialReference(SpatialReference const& rhs)
: m_wkt(rhs.m_wkt)
{
return;
}
SpatialReference& SpatialReference::operator=(SpatialReference const& rhs)
{
if (&rhs != this)
{
m_wkt = rhs.m_wkt;
}
return *this;
}
SpatialReference::~SpatialReference()
{
return;
}
bool SpatialReference::empty() const
{
return (getWKT() == "");
}
std::string SpatialReference::getWKT(WKTModeFlag mode_flag) const
{
return getWKT(mode_flag, false);
}
/// Fetch the SRS as WKT
std::string SpatialReference::getWKT(WKTModeFlag mode_flag , bool pretty) const
{
#ifndef PDAL_SRS_ENABLED
boost::ignore_unused_variable_warning(mode_flag);
boost::ignore_unused_variable_warning(pretty);
// we don't have a way of making this pretty, or of stripping the compound wrapper.
return m_wkt;
#else
std::string result_wkt = m_wkt;
if ((mode_flag == eHorizontalOnly
&& strstr(result_wkt.c_str(),"COMPD_CS") != NULL)
|| pretty)
{
OGRSpatialReference* poSRS = (OGRSpatialReference*) OSRNewSpatialReference(result_wkt.c_str());
char *pszWKT = NULL;
if (mode_flag == eHorizontalOnly)
poSRS->StripVertical();
if (pretty)
poSRS->exportToPrettyWkt(&pszWKT, FALSE);
else
poSRS->exportToWkt(&pszWKT);
OSRDestroySpatialReference(poSRS);
result_wkt = pszWKT;
CPLFree(pszWKT);
}
return result_wkt;
#endif
}
void SpatialReference::setFromUserInput(std::string const& v)
{
#ifdef PDAL_SRS_ENABLED
char* poWKT = 0;
const char* input = v.c_str();
// OGRSpatialReference* poSRS = (OGRSpatialReference*) OSRNewSpatialReference(NULL);
OGRSpatialReference srs(NULL);
OGRErr err = srs.SetFromUserInput(const_cast<char *>(input));
if (err != OGRERR_NONE)
{
throw std::invalid_argument("could not import coordinate system into OSRSpatialReference SetFromUserInput");
}
srs.exportToWkt(&poWKT);
std::string tmp(poWKT);
CPLFree(poWKT);
setWKT(tmp);
#else
boost::ignore_unused_variable_warning(v);
throw std::runtime_error("GDAL is not available, SpatialReference could not be set from WKT");
#endif
}
void SpatialReference::setWKT(std::string const& v)
{
m_wkt = v;
return;
}
std::string SpatialReference::getProj4() const
{
#ifdef PDAL_SRS_ENABLED
std::string wkt = getWKT(eCompoundOK);
const char* poWKT = wkt.c_str();
OGRSpatialReference srs(NULL);
if (OGRERR_NONE != srs.importFromWkt(const_cast<char **>(&poWKT)))
{
return std::string();
}
char* proj4 = 0;
srs.exportToProj4(&proj4);
std::string tmp(proj4);
CPLFree(proj4);
boost::algorithm::trim(tmp);
return tmp;
#else
// By default or if we have neither GDAL nor proj.4, we can't do squat
return std::string();
#endif
}
void SpatialReference::setProj4(std::string const& v)
{
#ifdef PDAL_SRS_ENABLED
char* poWKT = 0;
const char* poProj4 = v.c_str();
OGRSpatialReference srs(NULL);
if (OGRERR_NONE != srs.importFromProj4(const_cast<char *>(poProj4)))
{
throw std::invalid_argument("could not import proj4 into OSRSpatialReference SetProj4");
}
srs.exportToWkt(&poWKT);
std::string tmp(poWKT);
CPLFree(poWKT);
m_wkt = tmp;
#else
boost::ignore_unused_variable_warning(v);
#endif
return;
}
bool SpatialReference::equals(const SpatialReference& input) const
{
#ifdef PDAL_SRS_ENABLED
OGRSpatialReferenceH current = OSRNewSpatialReference(getWKT(eCompoundOK, false).c_str());
OGRSpatialReferenceH other = OSRNewSpatialReference(input.getWKT(eCompoundOK, false).c_str());
int output = OSRIsSame(current, other);
OSRDestroySpatialReference(current);
OSRDestroySpatialReference(other);
return (output==1);
#else
boost::ignore_unused_variable_warning(input);
throw pdal_error("SpatialReference equality testing not available without GDAL+libgeotiff support");
#endif
}
bool SpatialReference::operator==(const SpatialReference& input) const
{
return this->equals(input);
}
bool SpatialReference::operator!=(const SpatialReference& input) const
{
return !(this->equals(input));
}
const std::string& SpatialReference::getName() const
{
static std::string name("pdal.spatialreference");
return name;
}
bool SpatialReference::isGeographic() const
{
#ifdef PDAL_SRS_ENABLED
OGRSpatialReferenceH current = OSRNewSpatialReference(getWKT(eCompoundOK, false).c_str());
bool geog = static_cast<bool>(OSRIsGeographic(current));
OSRDestroySpatialReference(current);
return geog;
#else
throw std::runtime_error("GDAL is not available, SpatialReference could not determine if isGeographic");
#endif
}
boost::property_tree::ptree SpatialReference::toPTree() const
{
using boost::property_tree::ptree;
ptree srs;
#ifdef PDAL_SRS_ENABLED
srs.put("proj4", getProj4());
srs.put("prettywkt", getWKT(SpatialReference::eHorizontalOnly, true));
srs.put("wkt", getWKT(SpatialReference::eHorizontalOnly, false));
srs.put("compoundwkt", getWKT(eCompoundOK, false));
srs.put("prettycompoundwkt", getWKT(eCompoundOK, true));
#else
std::string message;
if (m_wkt.size() == 0)
{
message = "Reference defined with VLR keys, but GeoTIFF and GDAL support are not available to produce definition";
}
else if (m_wkt.size() > 0)
{
message = "Reference defined with WKT, but GeoTIFF and GDAL support are not available to produce definition";
}
else
{
message = "None";
}
srs.put("proj4", message);
srs.put("prettywkt", message);
srs.put("wkt", message);
srs.put("compoundwkt", message);
srs.put("prettycompoundwkt", message);
srs.put("gtiff", message);
#endif
return srs;
}
void SpatialReference::dump() const
{
std::cout << *this;
}
std::ostream& operator<<(std::ostream& ostr, const SpatialReference& srs)
{
#ifdef PDAL_SRS_ENABLED
std::string wkt = srs.toPTree().get<std::string>("prettycompoundwkt");
ostr << wkt;
return ostr;
#else
boost::ignore_unused_variable_warning(ostr);
boost::ignore_unused_variable_warning(srs);
ostr << "SpatialReference data is not available without GDAL+libgeotiff support";
return ostr;
#endif
}
std::istream& operator>>(std::istream& istr, SpatialReference& srs)
{
#ifdef PDAL_SRS_ENABLED
SpatialReference ref;
std::ostringstream oss;
oss << istr.rdbuf();
std::string wkt = oss.str();
ref.setFromUserInput(wkt.c_str());
srs = ref;
return istr;
#else
boost::ignore_unused_variable_warning(istr);
boost::ignore_unused_variable_warning(srs);
throw pdal_error("SpatialReference io operator>> is not available without GDAL+libgeotiff support");
#endif
}
} // namespace pdal
<commit_msg>silence bool conversion warning<commit_after>/******************************************************************************
* Copyright (c) 2009, Howard Butler
*
* 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 Martin Isenburg or Iowa Department
* of Natural Resources 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 <pdal/SpatialReference.hpp>
#include <boost/concept_check.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/concept_check.hpp> // ignore_unused_variable_warning
#include <boost/algorithm/string/trim.hpp>
// gdal
#ifdef PDAL_HAVE_GDAL
#include <ogr_spatialref.h>
#include <cpl_conv.h>
#endif
#include <pdal/Utils.hpp>
namespace pdal
{
SpatialReference::SpatialReference()
: m_wkt("")
{
return;
}
SpatialReference::SpatialReference(const std::string& s)
: m_wkt("")
{
this->setFromUserInput(s);
return;
}
SpatialReference::SpatialReference(SpatialReference const& rhs)
: m_wkt(rhs.m_wkt)
{
return;
}
SpatialReference& SpatialReference::operator=(SpatialReference const& rhs)
{
if (&rhs != this)
{
m_wkt = rhs.m_wkt;
}
return *this;
}
SpatialReference::~SpatialReference()
{
return;
}
bool SpatialReference::empty() const
{
return (getWKT() == "");
}
std::string SpatialReference::getWKT(WKTModeFlag mode_flag) const
{
return getWKT(mode_flag, false);
}
/// Fetch the SRS as WKT
std::string SpatialReference::getWKT(WKTModeFlag mode_flag , bool pretty) const
{
#ifndef PDAL_SRS_ENABLED
boost::ignore_unused_variable_warning(mode_flag);
boost::ignore_unused_variable_warning(pretty);
// we don't have a way of making this pretty, or of stripping the compound wrapper.
return m_wkt;
#else
std::string result_wkt = m_wkt;
if ((mode_flag == eHorizontalOnly
&& strstr(result_wkt.c_str(),"COMPD_CS") != NULL)
|| pretty)
{
OGRSpatialReference* poSRS = (OGRSpatialReference*) OSRNewSpatialReference(result_wkt.c_str());
char *pszWKT = NULL;
if (mode_flag == eHorizontalOnly)
poSRS->StripVertical();
if (pretty)
poSRS->exportToPrettyWkt(&pszWKT, FALSE);
else
poSRS->exportToWkt(&pszWKT);
OSRDestroySpatialReference(poSRS);
result_wkt = pszWKT;
CPLFree(pszWKT);
}
return result_wkt;
#endif
}
void SpatialReference::setFromUserInput(std::string const& v)
{
#ifdef PDAL_SRS_ENABLED
char* poWKT = 0;
const char* input = v.c_str();
// OGRSpatialReference* poSRS = (OGRSpatialReference*) OSRNewSpatialReference(NULL);
OGRSpatialReference srs(NULL);
OGRErr err = srs.SetFromUserInput(const_cast<char *>(input));
if (err != OGRERR_NONE)
{
throw std::invalid_argument("could not import coordinate system into OSRSpatialReference SetFromUserInput");
}
srs.exportToWkt(&poWKT);
std::string tmp(poWKT);
CPLFree(poWKT);
setWKT(tmp);
#else
boost::ignore_unused_variable_warning(v);
throw std::runtime_error("GDAL is not available, SpatialReference could not be set from WKT");
#endif
}
void SpatialReference::setWKT(std::string const& v)
{
m_wkt = v;
return;
}
std::string SpatialReference::getProj4() const
{
#ifdef PDAL_SRS_ENABLED
std::string wkt = getWKT(eCompoundOK);
const char* poWKT = wkt.c_str();
OGRSpatialReference srs(NULL);
if (OGRERR_NONE != srs.importFromWkt(const_cast<char **>(&poWKT)))
{
return std::string();
}
char* proj4 = 0;
srs.exportToProj4(&proj4);
std::string tmp(proj4);
CPLFree(proj4);
boost::algorithm::trim(tmp);
return tmp;
#else
// By default or if we have neither GDAL nor proj.4, we can't do squat
return std::string();
#endif
}
void SpatialReference::setProj4(std::string const& v)
{
#ifdef PDAL_SRS_ENABLED
char* poWKT = 0;
const char* poProj4 = v.c_str();
OGRSpatialReference srs(NULL);
if (OGRERR_NONE != srs.importFromProj4(const_cast<char *>(poProj4)))
{
throw std::invalid_argument("could not import proj4 into OSRSpatialReference SetProj4");
}
srs.exportToWkt(&poWKT);
std::string tmp(poWKT);
CPLFree(poWKT);
m_wkt = tmp;
#else
boost::ignore_unused_variable_warning(v);
#endif
return;
}
bool SpatialReference::equals(const SpatialReference& input) const
{
#ifdef PDAL_SRS_ENABLED
OGRSpatialReferenceH current = OSRNewSpatialReference(getWKT(eCompoundOK, false).c_str());
OGRSpatialReferenceH other = OSRNewSpatialReference(input.getWKT(eCompoundOK, false).c_str());
int output = OSRIsSame(current, other);
OSRDestroySpatialReference(current);
OSRDestroySpatialReference(other);
return (output==1);
#else
boost::ignore_unused_variable_warning(input);
throw pdal_error("SpatialReference equality testing not available without GDAL+libgeotiff support");
#endif
}
bool SpatialReference::operator==(const SpatialReference& input) const
{
return this->equals(input);
}
bool SpatialReference::operator!=(const SpatialReference& input) const
{
return !(this->equals(input));
}
const std::string& SpatialReference::getName() const
{
static std::string name("pdal.spatialreference");
return name;
}
bool SpatialReference::isGeographic() const
{
#ifdef PDAL_SRS_ENABLED
OGRSpatialReferenceH current = OSRNewSpatialReference(getWKT(eCompoundOK, false).c_str());
int isGeog = OSRIsGeographic(current);
bool output(false);
if (isGeog == 0)
output = false;
else
output = true;
OSRDestroySpatialReference(current);
return output;
#else
throw std::runtime_error("GDAL is not available, SpatialReference could not determine if isGeographic");
#endif
}
boost::property_tree::ptree SpatialReference::toPTree() const
{
using boost::property_tree::ptree;
ptree srs;
#ifdef PDAL_SRS_ENABLED
srs.put("proj4", getProj4());
srs.put("prettywkt", getWKT(SpatialReference::eHorizontalOnly, true));
srs.put("wkt", getWKT(SpatialReference::eHorizontalOnly, false));
srs.put("compoundwkt", getWKT(eCompoundOK, false));
srs.put("prettycompoundwkt", getWKT(eCompoundOK, true));
#else
std::string message;
if (m_wkt.size() == 0)
{
message = "Reference defined with VLR keys, but GeoTIFF and GDAL support are not available to produce definition";
}
else if (m_wkt.size() > 0)
{
message = "Reference defined with WKT, but GeoTIFF and GDAL support are not available to produce definition";
}
else
{
message = "None";
}
srs.put("proj4", message);
srs.put("prettywkt", message);
srs.put("wkt", message);
srs.put("compoundwkt", message);
srs.put("prettycompoundwkt", message);
srs.put("gtiff", message);
#endif
return srs;
}
void SpatialReference::dump() const
{
std::cout << *this;
}
std::ostream& operator<<(std::ostream& ostr, const SpatialReference& srs)
{
#ifdef PDAL_SRS_ENABLED
std::string wkt = srs.toPTree().get<std::string>("prettycompoundwkt");
ostr << wkt;
return ostr;
#else
boost::ignore_unused_variable_warning(ostr);
boost::ignore_unused_variable_warning(srs);
ostr << "SpatialReference data is not available without GDAL+libgeotiff support";
return ostr;
#endif
}
std::istream& operator>>(std::istream& istr, SpatialReference& srs)
{
#ifdef PDAL_SRS_ENABLED
SpatialReference ref;
std::ostringstream oss;
oss << istr.rdbuf();
std::string wkt = oss.str();
ref.setFromUserInput(wkt.c_str());
srs = ref;
return istr;
#else
boost::ignore_unused_variable_warning(istr);
boost::ignore_unused_variable_warning(srs);
throw pdal_error("SpatialReference io operator>> is not available without GDAL+libgeotiff support");
#endif
}
} // namespace pdal
<|endoftext|> |
<commit_before><commit_msg>Wrote tests for Repeater::fire_next(). Tests pass.<commit_after><|endoftext|> |
<commit_before>
#include <cstdio>
#include <thread>
int main(int /*argc*/, char** /*argv*/)
{
printf("test\n");
std::this_thread::sleep_for(std::chrono::seconds(10));
}
<commit_msg>Add basic sound recording scheme and .wav file read/write<commit_after>
#include <cstdio>
#include <thread>
#include <windows.h>
#include <fstream>
#include <cstdlib>
#include <mmsystem.h>
#include <assert.h> // debugging
#include <cstdlib>
int NUM_CHANNELS = 1; // mono audio (stereo would need 2 channels)
int SAMPLES_PER_SEC = 11025;
int BITS_PER_SAMPLE = 8;
#define INP_BUFFER_SIZE SAMPLES_PER_SEC * 10
/* Declare procedures */
void SaveWavFile(char* filename, PWAVEHDR pWaveHdr);
void ReadWavFile(char* filename);
int main(int /*argc*/, char** /*argv*/)
{
printf("test\n");
WAVEHDR waveHdr;
PBYTE buffer;
HWAVEIN hWaveIn;
/* begin sound capture */
buffer = reinterpret_cast<PBYTE>(malloc(INP_BUFFER_SIZE));
if (!buffer)
{
printf("Failed to allocate buffers\n");
return 1;
}
// Open waveform audio for input
WAVEFORMATEX waveform;
waveform.wFormatTag = WAVE_FORMAT_PCM;
waveform.nChannels = NUM_CHANNELS;
waveform.nSamplesPerSec = SAMPLES_PER_SEC;
waveform.nAvgBytesPerSec = SAMPLES_PER_SEC;
waveform.nBlockAlign = 1;
waveform.wBitsPerSample = BITS_PER_SAMPLE;
waveform.cbSize = 0;
MMRESULT result = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveform, NULL, NULL, CALLBACK_WINDOW);
if (result)
{
// todo: properly print this error - WCHAR is unicode garbage
/*
WCHAR fault[256];
waveInGetErrorText(result, fault, 256);
printf("Failed to open waveform input device (fault: %s)", result);
*/
printf("Failed to open waveform input device\n", result);
return 1;
}
// Set up headers and prepare them
waveHdr.lpData = reinterpret_cast<CHAR*>(buffer);
waveHdr.dwBufferLength = INP_BUFFER_SIZE;
waveHdr.dwBytesRecorded = 0;
waveHdr.dwUser = 0;
waveHdr.dwFlags = 0;
waveHdr.dwLoops = 1;
waveHdr.lpNext = NULL;
waveHdr.reserved = 0;
waveInPrepareHeader(hWaveIn, &waveHdr, sizeof(WAVEHDR));
// Insert a wave input buffer
result = waveInAddBuffer(hWaveIn, &waveHdr, sizeof(WAVEHDR));
if (result)
{
printf("Failed to read block from device\n");
return 1;
}
// Commence sampling input
result = waveInStart(hWaveIn);
if (result)
{
printf("Failed to start recording\n");
return 1;
}
// Wait until finished recording
do { } while (waveInUnprepareHeader(hWaveIn, &waveHdr, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
waveInClose(hWaveIn);
SaveWavFile("temp.wav", &waveHdr);
return 0;
}
// Read the temporary wav file
void ReadWavFile(char* filename)
{
// random variables used throughout the function
int length, byte_samp, byte_sec;
bool mono = TRUE;
FILE* file;
// open filepointer readonly
fopen_s(&file, filename, "r");
if (file == NULL)
printf("Wav:: Could not open file: %s", filename);
else
{
// declare a char buff to store some values in
char *buff = new char[5];
buff[4] = '\0';
// read the first 4 bytes
fread((void *)buff, 1, 4, file);
// the first four bytes should be 'RIFF'
if (strcmp((char *)buff, "RIFF") == 0)
{
// read byte 8,9,10 and 11
fseek(file, 4, SEEK_CUR);
fread((void *)buff, 1, 4, file);
// this should read "WAVE"
if (strcmp((char *)buff, "WAVE") == 0)
{
// read byte 12,13,14,15
fread((void *)buff, 1, 4, file);
// this should read "fmt "
if (strcmp((char *)buff, "fmt ") == 0)
{
fseek(file, 20, SEEK_CUR);
// final one read byte 36,37,38,39
fread((void *)buff, 1, 4, file);
if (strcmp((char *)buff, "data") == 0)
{
// Now we know it is a wav file, rewind the stream
rewind(file);
// now is it mono or stereo ?
fseek(file, 22, SEEK_CUR);
fread((void *)buff, 1, 2, file);
// bool isMono = (buff[0] & 0x02 == 0);
// read the sample rate
fread((void *)&SAMPLES_PER_SEC, 1, 4, file);
fread((void *)&byte_sec, 1, 4, file);
byte_samp = 0;
fread((void *)&byte_samp, 1, 2, file);
fread((void *)&BITS_PER_SAMPLE, 1, 2, file);
fseek(file, 4, SEEK_CUR);
fread((void *)&length, 1, 4, file);
}
}
}
}
delete buff;
}
}
void SaveWavFile(char* filename, PWAVEHDR pWaveHdr)
{
std::fstream file(filename, std::fstream::out | std::fstream::binary);
int pcmsize = sizeof(PCMWAVEFORMAT);
int audioFormat = WAVE_FORMAT_PCM;
int subchunk1size = 16;
int byteRate = SAMPLES_PER_SEC * NUM_CHANNELS * BITS_PER_SAMPLE / 8;
int blockAlign = NUM_CHANNELS * BITS_PER_SAMPLE / 8;
int subchunk2size = pWaveHdr->dwBufferLength * NUM_CHANNELS;
int chunksize = (36 + subchunk2size);
// write the wav file per the wav file format
file.seekp(0, std::ios::beg);
file.write("RIFF", 4); // chunk id
file.write((char*)&chunksize, 4); // chunk size (36 + SubChunk2Size))
file.write("WAVE", 4); // format
file.write("fmt ", 4); // subchunk1ID
file.write((char*)&subchunk1size, 4); // subchunk1size (16 for PCM)
file.write((char*)&audioFormat, 2); // AudioFormat (1 for PCM)
file.write((char*)&NUM_CHANNELS, 2); // NumChannels
file.write((char*)&SAMPLES_PER_SEC, 4); // sample rate
file.write((char*)&byteRate, 4); // byte rate (SampleRate * NumChannels * BitsPerSample/8)
file.write((char*)&blockAlign, 2); // block align (NumChannels * BitsPerSample/8)
file.write((char*)&BITS_PER_SAMPLE, 2); // bits per sample
file.write("data", 4); // subchunk2ID
file.write((char*)&subchunk2size, 4); // subchunk2size (NumSamples * NumChannels * BitsPerSample/8)
file.write(pWaveHdr->lpData, pWaveHdr->dwBufferLength); // data
file.close();
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief メニュー・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2019 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <functional>
#include "graphics/widget.hpp"
#include "common/string_utils.hpp"
namespace gui {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief メニュー・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct menu : public widget {
typedef menu value_type;
static const int16_t round_radius = 6; // round radius
static const int16_t item_height = 28; // ITEM height
typedef std::function<void(uint32_t pos, uint32_t num)> SELECT_FUNC_TYPE;
private:
SELECT_FUNC_TYPE select_func_;
vtx::spos item_size_;
uint32_t num_;
uint32_t select_pos_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] loc ロケーション
@param[in] str ボタン文字列
*/
//-----------------------------------------------------------------//
menu(const vtx::srect& loc = vtx::srect(0), const char* str = "") noexcept :
widget(loc, str),
select_func_(), item_size_(0),
num_(utils::str::get_words(str, ',')), select_pos_(num_)
{
if(loc.size.y <= 0) {
at_location().size.y = num_ * item_height;
item_size_.y = item_height;
} else {
item_size_.y = loc.size.y / num_;
}
insert_widget(this);
}
menu(const menu& th) = delete;
menu& operator = (const menu& th) = delete;
//-----------------------------------------------------------------//
/*!
@brief デストラクタ
*/
//-----------------------------------------------------------------//
virtual ~menu() noexcept { remove_widget(this); }
//-----------------------------------------------------------------//
/*!
@brief 型整数を取得
@return 型整数
*/
//-----------------------------------------------------------------//
const char* get_name() const noexcept override { return "Menu"; }
//-----------------------------------------------------------------//
/*!
@brief ID を取得
@return ID
*/
//-----------------------------------------------------------------//
ID get_id() const noexcept override { return ID::MENU; }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void init() noexcept override { }
//-----------------------------------------------------------------//
/*!
@brief タッチ判定を更新
@param[in] pos 判定位置
@param[in] num タッチ数
*/
//-----------------------------------------------------------------//
void update_touch(const vtx::spos& pos, uint16_t num) noexcept override
{
update_touch_def(pos, num, false);
const auto& st = get_touch_state();
if(st.level_) {
select_pos_ = st.relative_.y / item_size_.y;
}
if(st.negative_) {
if(!get_focus()) {
select_pos_ = num_;
}
}
}
//-----------------------------------------------------------------//
/*!
@brief 選択推移
@param[in] inva 無効状態にする場合「true」
*/
//-----------------------------------------------------------------//
void exec_select(bool inva) noexcept override
{
if(select_func_) {
select_func_(select_pos_, num_);
}
}
//-----------------------------------------------------------------//
/*!
@brief 許可・不許可
@param[in] ena 不許可の場合「false」
*/
//-----------------------------------------------------------------//
void enable(bool ena = true) noexcept override
{
if(ena) {
set_state(STATE::ENABLE);
} else {
set_state(STATE::DISABLE);
reset_touch_state();
}
}
//-----------------------------------------------------------------//
/*!
@brief セレクト位置の取得
@return セレクト位置
*/
//-----------------------------------------------------------------//
uint32_t get_select_pos() const noexcept { return select_pos_; }
//-----------------------------------------------------------------//
/*!
@brief セレクト位置の文字取得
@param[in] dst 文字列バッファ
@param[in] len 文字列バッファサイズ
@return セレクト位置
*/
//-----------------------------------------------------------------//
uint32_t get_select_text(char* dst, uint32_t len) const noexcept {
utils::str::get_word(get_title(), select_pos_, dst, len, ',');
return select_pos_;
}
//-----------------------------------------------------------------//
/*!
@brief セレクト関数への参照
@return セレクト関数
*/
//-----------------------------------------------------------------//
SELECT_FUNC_TYPE& at_select_func() noexcept { return select_func_; }
//-----------------------------------------------------------------//
/*!
@brief 描画
*/
//-----------------------------------------------------------------//
template<class RDR>
void draw(RDR& rdr) noexcept
{
auto r = vtx::srect(get_final_position(), get_location().size);
r.size.y /= num_;
for(uint32_t i = 0; i < num_; ++i) {
uint8_t inten = 64;
if(get_touch_state().level_ && select_pos_ == i) {
// rdr.set_fore_color(graphics::def_color::Silver);
inten = 192;
} else {
if(i & 1) {
// rdr.set_fore_color(graphics::def_color::Midgray);
inten = 96;
} else {
// rdr.set_fore_color(graphics::def_color::Gray);
inten = 128;
}
}
graphics::share_color sh(0, 0, 0);
sh.set_color(get_base_color().rgba8, inten);
rdr.set_fore_color(sh);
bool up = false;
bool dn = false;
if(i == 0) up = true;
if(i == (num_ - 1)) dn = true;
rdr.round_box(r, round_radius, up, dn);
char tmp[32];
if(utils::str::get_word(get_title(), i, tmp, sizeof(tmp), ',')) {
auto sz = rdr.at_font().get_text_size(tmp);
rdr.set_fore_color(get_font_color());
rdr.draw_text(r.org + (r.size - sz) / 2, tmp);
}
r.org.y += r.size.y;
}
}
};
}
<commit_msg>Update: title management<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief メニュー・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2019 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <functional>
#include "graphics/widget.hpp"
#include "common/string_utils.hpp"
namespace gui {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief メニュー・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct menu : public widget {
typedef menu value_type;
static const int16_t round_radius = 6; ///< round radius
static const int16_t item_height = 28; ///< ITEM height
static const int16_t check_size = 6; ///< check sign width/height
typedef std::function<void(uint32_t pos, uint32_t num)> SELECT_FUNC_TYPE;
private:
SELECT_FUNC_TYPE select_func_;
vtx::spos item_size_;
uint32_t num_;
uint32_t select_pos_;
bool check_draw_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] loc ロケーション
@param[in] str ボタン文字列
@param[in] chd チェック描画を行わない場合「false」
*/
//-----------------------------------------------------------------//
menu(const vtx::srect& loc = vtx::srect(0), const char* str = "", bool chd = true)
noexcept :
widget(loc, str),
select_func_(), item_size_(0),
num_(utils::str::get_words(str, ',')), select_pos_(0), check_draw_(chd)
{
if(loc.size.y <= 0) {
at_location().size.y = num_ * item_height;
item_size_.y = item_height;
} else {
item_size_.y = loc.size.y / num_;
}
insert_widget(this);
}
menu(const menu& th) = delete;
menu& operator = (const menu& th) = delete;
//-----------------------------------------------------------------//
/*!
@brief デストラクタ
*/
//-----------------------------------------------------------------//
virtual ~menu() noexcept { remove_widget(this); }
//-----------------------------------------------------------------//
/*!
@brief 型整数を取得
@return 型整数
*/
//-----------------------------------------------------------------//
const char* get_name() const noexcept override { return "Menu"; }
//-----------------------------------------------------------------//
/*!
@brief ID を取得
@return ID
*/
//-----------------------------------------------------------------//
ID get_id() const noexcept override { return ID::MENU; }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void init() noexcept override { }
//-----------------------------------------------------------------//
/*!
@brief タッチ判定を更新
@param[in] pos 判定位置
@param[in] num タッチ数
*/
//-----------------------------------------------------------------//
void update_touch(const vtx::spos& pos, uint16_t num) noexcept override
{
update_touch_def(pos, num, false);
const auto& st = get_touch_state();
if(st.level_) {
if(get_focus()) {
auto newpos = st.relative_.y / item_size_.y;
if(newpos >= static_cast<int16_t>(num_)) newpos = num_ - 1;
else if(newpos < 0) newpos = 0;
select_pos_ = newpos;
}
}
// if(st.negative_) {
// if(!get_focus()) {
// select_pos_ = num_;
// }
// }
}
//-----------------------------------------------------------------//
/*!
@brief 選択推移
@param[in] inva 無効状態にする場合「true」
*/
//-----------------------------------------------------------------//
void exec_select(bool inva) noexcept override
{
if(select_func_) {
select_func_(select_pos_, num_);
}
}
//-----------------------------------------------------------------//
/*!
@brief タイトル更新時処理
*/
//-----------------------------------------------------------------//
void update_title() noexcept override
{
num_ = utils::str::get_words(get_title(), ',');
at_location().size.y = num_ * item_size_.y;
if(select_pos_ >= num_) {
select_pos_ = num_ - 1;
}
}
//-----------------------------------------------------------------//
/*!
@brief 許可・不許可
@param[in] ena 不許可の場合「false」
*/
//-----------------------------------------------------------------//
void enable(bool ena = true) noexcept override
{
if(ena) {
set_state(STATE::ENABLE);
} else {
set_state(STATE::DISABLE);
reset_touch_state();
}
}
//-----------------------------------------------------------------//
/*!
@brief アイテム数の取得
@return アイテム数
*/
//-----------------------------------------------------------------//
uint32_t get_item_num() const noexcept { return num_; }
//-----------------------------------------------------------------//
/*!
@brief セレクト位置の取得
@return セレクト位置
*/
//-----------------------------------------------------------------//
uint32_t get_select_pos() const noexcept { return select_pos_; }
//-----------------------------------------------------------------//
/*!
@brief セレクト位置の設定
@param[in] pos セレクト位置
*/
//-----------------------------------------------------------------//
void set_select_pos(uint32_t pos) noexcept { select_pos_ = pos; }
//-----------------------------------------------------------------//
/*!
@brief セレクト位置の文字取得
@param[in] dst 文字列バッファ
@param[in] len 文字列バッファサイズ
@return セレクト位置
*/
//-----------------------------------------------------------------//
uint32_t get_select_text(char* dst, uint32_t len) const noexcept {
utils::str::get_word(get_title(), select_pos_, dst, len, ',');
return select_pos_;
}
//-----------------------------------------------------------------//
/*!
@brief セレクト関数への参照
@return セレクト関数
*/
//-----------------------------------------------------------------//
SELECT_FUNC_TYPE& at_select_func() noexcept { return select_func_; }
//-----------------------------------------------------------------//
/*!
@brief 描画
*/
//-----------------------------------------------------------------//
template<class RDR>
void draw(RDR& rdr) noexcept
{
if(num_ == 0 || get_title() == nullptr) return;
auto r = vtx::srect(get_final_position(), get_location().size);
r.size.y /= num_;
for(uint32_t i = 0; i < num_; ++i) {
uint8_t inten = 64;
if(get_touch_state().level_ && select_pos_ == i) {
inten = 192;
} else {
if(i & 1) {
inten = 96;
} else {
inten = 128;
}
}
graphics::share_color sh(0, 0, 0);
sh.set_color(get_base_color().rgba8, inten);
rdr.set_fore_color(sh);
bool up = false;
bool dn = false;
if(i == 0) up = true;
if(i == (num_ - 1)) dn = true;
rdr.round_box(r, round_radius, up, dn);
if(check_draw_ && i == select_pos_) {
rdr.set_fore_color(get_base_color());
rdr.fill_box(
vtx::srect(r.org.x + check_size, r.org.y + (r.size.y - check_size) / 2,
check_size, check_size));
}
char tmp[32];
if(utils::str::get_word(get_title(), i, tmp, sizeof(tmp), ',')) {
auto sz = rdr.at_font().get_text_size(tmp);
rdr.set_fore_color(get_font_color());
rdr.draw_text(r.org + (r.size - sz) / 2, tmp);
}
r.org.y += r.size.y;
}
}
};
}
<|endoftext|> |
<commit_before>/* This file is part of Zanshin Todo.
Copyright 2008-2010 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "actionlisteditor.h"
#if 0
#include <akonadi/item.h>
#include <akonadi/itemdeletejob.h>
#include <boost/shared_ptr.hpp>
#include <KDE/KCalCore/Todo>
#endif
#include <KDE/Akonadi/EntityTreeView>
#include <KDE/Akonadi/ItemCreateJob>
#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KDebug>
#include <kdescendantsproxymodel.h>
#include <KDE/KIcon>
#include <KDE/KLineEdit>
#include <KDE/KLocale>
#include <KDE/KPassivePopup>
#include <QtCore/QEvent>
#include <QtCore/QTimer>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>
#include <QtGui/QStackedWidget>
#include "actionlistcombobox.h"
#include "actionlistdelegate.h"
#include "actionlisteditorpage.h"
#include "modelstack.h"
#include "todomodel.h"
#if 0
#include "quickselectdialog.h"
#endif
ActionListEditor::ActionListEditor(ModelStack *models,
QItemSelectionModel *projectSelection,
QItemSelectionModel *categoriesSelection,
KActionCollection *ac,
QWidget *parent)
: QWidget(parent),
m_projectSelection(projectSelection),
m_categoriesSelection(categoriesSelection)
{
setLayout(new QVBoxLayout(this));
m_stack = new QStackedWidget(this);
layout()->addWidget(m_stack);
layout()->setContentsMargins(0, 0, 0, 0);
connect(projectSelection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
this, SLOT(onSideBarSelectionChanged(QModelIndex)));
connect(categoriesSelection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
this, SLOT(onSideBarSelectionChanged(QModelIndex)));
createPage(models->treeSelectionModel(projectSelection), models, Zanshin::ProjectMode);
createPage(models->categoriesSelectionModel(categoriesSelection), models, Zanshin::CategoriesMode);
QWidget *bottomBar = new QWidget(this);
layout()->addWidget(bottomBar);
bottomBar->setLayout(new QHBoxLayout(bottomBar));
bottomBar->layout()->setContentsMargins(0, 0, 0, 0);
m_addActionEdit = new KLineEdit(bottomBar);
m_addActionEdit->installEventFilter(this);
bottomBar->layout()->addWidget(m_addActionEdit);
m_addActionEdit->setClickMessage(i18n("Type and press enter to add an action"));
m_addActionEdit->setClearButtonShown(true);
connect(m_addActionEdit, SIGNAL(returnPressed()),
this, SLOT(onAddActionRequested()));
m_comboBox = new ActionListComboBox(bottomBar);
m_comboBox->view()->setTextElideMode(Qt::ElideLeft);
m_comboBox->setMinimumContentsLength(20);
m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
KDescendantsProxyModel *descendantProxyModel = new KDescendantsProxyModel(m_comboBox);
descendantProxyModel->setSourceModel(models->collectionsModel());
descendantProxyModel->setDisplayAncestorData(true);
m_comboBox->setModel(descendantProxyModel);
bottomBar->layout()->addWidget(m_comboBox);
setupActions(ac);
QToolBar *toolBar = new QToolBar(bottomBar);
toolBar->setIconSize(QSize(16, 16));
bottomBar->layout()->addWidget(toolBar);
toolBar->addAction(m_cancelAdd);
m_cancelAdd->setEnabled(false);
updateActions(QModelIndex());
setMode(Zanshin::ProjectMode);
}
void ActionListEditor::setMode(Zanshin::ApplicationMode mode)
{
switch (mode) {
case Zanshin::ProjectMode:
m_stack->setCurrentIndex(0);
onSideBarSelectionChanged(m_projectSelection->currentIndex());
break;
case Zanshin::CategoriesMode:
m_stack->setCurrentIndex(1);
onSideBarSelectionChanged(m_categoriesSelection->currentIndex());
break;
}
}
void ActionListEditor::onSideBarSelectionChanged(const QModelIndex &index)
{
int type = index.data(TodoModel::ItemTypeRole).toInt();
m_comboBox->setVisible(type == TodoModel::Inbox
|| type == TodoModel::Category
|| type == TodoModel::CategoryRoot);
}
void ActionListEditor::createPage(QAbstractItemModel *model, ModelStack *models, Zanshin::ApplicationMode mode)
{
ActionListEditorPage *page = new ActionListEditorPage(model, models, mode, m_stack);
connect(page->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
this, SLOT(updateActions(QModelIndex)));
m_stack->addWidget(page);
}
void ActionListEditor::setupActions(KActionCollection *ac)
{
m_add = ac->addAction("editor_add_action", this, SLOT(focusActionEdit()));
m_add->setText(i18n("New Action"));
m_add->setIcon(KIcon("list-add"));
m_add->setShortcut(Qt::CTRL | Qt::Key_N);
m_cancelAdd = ac->addAction("editor_cancel_action", m_stack, SLOT(setFocus()));
connect(m_cancelAdd, SIGNAL(activated()), m_addActionEdit, SLOT(clear()));
m_cancelAdd->setText(i18n("Cancel New Action"));
m_cancelAdd->setIcon(KIcon("edit-undo"));
m_cancelAdd->setShortcut(Qt::Key_Escape);
m_remove = ac->addAction("editor_remove_action", this, SLOT(onRemoveAction()));
m_remove->setText(i18n("Remove Action"));
m_remove->setIcon(KIcon("list-remove"));
m_remove->setShortcut(Qt::Key_Delete);
m_move = ac->addAction("editor_move_action", this, SLOT(onMoveAction()));
m_move->setText(i18n("Move Action..."));
m_move->setShortcut(Qt::Key_M);
}
void ActionListEditor::updateActions(const QModelIndex &index)
{
if (!index.isValid()) {
m_remove->setEnabled(false);
m_move->setEnabled(false);
} else {
m_remove->setEnabled(true);
m_move->setEnabled(true);
}
}
void ActionListEditor::onAddActionRequested()
{
QString summary = m_addActionEdit->text().trimmed();
m_addActionEdit->setText(QString());
if (summary.isEmpty()) return;
QModelIndex current = currentPage()->selectionModel()->currentIndex();
if (!current.isValid()) {
kWarning() << "Oops, nothing selected in the list!";
return;
}
int type = current.data(TodoModel::ItemTypeRole).toInt();
while (current.isValid() && type==TodoModel::StandardTodo) {
current = current.parent();
type = current.data(TodoModel::ItemTypeRole).toInt();
}
Akonadi::Collection collection;
QString parentUid;
QString category;
switch (type) {
case TodoModel::StandardTodo:
kFatal() << "Can't possibly happen!";
break;
case TodoModel::ProjectTodo:
parentUid = current.data(TodoModel::UidRole).toString();
collection = current.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>();
break;
case TodoModel::Collection:
collection = current.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
break;
case TodoModel::Category:
category = current.data(Qt::EditRole).toString();
// fallthrough
case TodoModel::Inbox:
case TodoModel::CategoryRoot:
QModelIndex collectionIndex = m_comboBox->model()->index( m_comboBox->currentIndex(), 0 );
collection = collectionIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
break;
}
KCalCore::Todo::Ptr todo(new KCalCore::Todo);
todo->setSummary(summary);
if (!parentUid.isEmpty()) {
todo->setRelatedTo(parentUid);
}
if (!category.isEmpty()) {
todo->setCategories(category);
}
Akonadi::Item item;
item.setMimeType("application/x-vnd.akonadi.calendar.todo");
item.setPayload<KCalCore::Todo::Ptr>(todo);
new Akonadi::ItemCreateJob(item, collection);
}
void ActionListEditor::onRemoveAction()
{
#if 0
QModelIndex current = m_view->currentIndex();
if (m_model->rowCount(current)>0) {
return;
}
Akonadi::Item item;
QAbstractItemModel *source = m_model->sourceModel();
TodoFlatModel *flat = dynamic_cast<TodoFlatModel*>(source);
if (flat != 0) {
item = flat->itemForIndex(m_model->mapToSource(current));
}
TodoTreeModel *tree = dynamic_cast<TodoTreeModel*>(source);
if (tree != 0) {
item = tree->itemForIndex(m_model->mapToSource(current));
}
TodoCategoriesModel *categories = dynamic_cast<TodoCategoriesModel*>(source);
if (categories != 0) {
item = categories->itemForIndex(m_model->mapToSource(current));
}
if (!item.isValid()) {
return;
}
new Akonadi::ItemDeleteJob(item, this);
#endif
}
void ActionListEditor::onMoveAction()
{
#if 0
QModelIndex current = m_view->currentIndex();
if (m_model->rowCount(current)>0) {
return;
}
QAbstractItemModel *source = m_model->sourceModel();
QModelIndex movedIndex;
TodoFlatModel *flat = dynamic_cast<TodoFlatModel*>(source);
if (flat != 0) {
movedIndex = m_model->mapToSource(current);
}
TodoTreeModel *tree = dynamic_cast<TodoTreeModel*>(source);
if (tree != 0) {
movedIndex = m_model->mapToSource(current);
}
TodoCategoriesModel *categories = dynamic_cast<TodoCategoriesModel*>(source);
if (categories != 0) {
movedIndex = m_model->mapToSource(current);
}
if (!movedIndex.isValid()) {
return;
}
QuickSelectDialog::Mode mode = QuickSelectDialog::ProjectMode;
if (m_model->mode()==ActionListModel::NoContextMode
|| m_model->mode()==ActionListModel::ContextMode) {
mode = QuickSelectDialog::ContextMode;
}
QuickSelectDialog dlg(this, mode,
QuickSelectDialog::MoveAction);
if (dlg.exec()==QDialog::Accepted) {
QString selectedId = dlg.selectedId();
if (mode==QuickSelectDialog::ProjectMode) {
QModelIndex index = movedIndex.sibling(movedIndex.row(), TodoFlatModel::ParentRemoteId);
source->setData(index, selectedId);
} else {
QModelIndex index = movedIndex.sibling(movedIndex.row(), TodoFlatModel::Categories);
source->setData(index, selectedId);
}
}
#endif
}
void ActionListEditor::focusActionEdit()
{
QPoint pos = m_addActionEdit->geometry().topLeft();
pos = m_addActionEdit->parentWidget()->mapToGlobal(pos);
KPassivePopup *popup = KPassivePopup::message(i18n("Type and press enter to add an action"), m_addActionEdit);
popup->move(pos-QPoint(0, popup->height()));
m_addActionEdit->setFocus();
}
bool ActionListEditor::eventFilter(QObject *watched, QEvent *event)
{
if (watched==m_addActionEdit) {
if (event->type()==QEvent::FocusIn) {
m_cancelAdd->setEnabled(true);
} else if (event->type()==QEvent::FocusOut) {
m_cancelAdd->setEnabled(false);
}
}
return QWidget::eventFilter(watched, event);
}
void ActionListEditor::saveColumnsState(KConfigGroup &config) const
{
page(0)->saveColumnsState(config, "ProjectHeaderState");
page(1)->saveColumnsState(config, "CategoriesHeaderState");
}
void ActionListEditor::restoreColumnsState(const KConfigGroup &config)
{
page(0)->restoreColumnsState(config, "ProjectHeaderState");
page(1)->restoreColumnsState(config, "CategoriesHeaderState");
}
ActionListEditorPage *ActionListEditor::currentPage() const
{
return static_cast<ActionListEditorPage*>(m_stack->currentWidget());
}
ActionListEditorPage *ActionListEditor::page(int idx) const
{
return static_cast<ActionListEditorPage*>(m_stack->widget(idx));
}
void ActionListEditor::hideColumns()
{
for (int i = 0; i < m_stack->count(); ++i) {
ActionListEditorPage *page = static_cast<ActionListEditorPage*>(m_stack->widget(i));
if (page->mode() == Zanshin::ProjectMode) {
page->hideColumn(1);
} else {
page->hideColumn(2);
}
}
}
<commit_msg>Reenable removing standard todos.<commit_after>/* This file is part of Zanshin Todo.
Copyright 2008-2010 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "actionlisteditor.h"
#if 0
#include <akonadi/item.h>
#include <boost/shared_ptr.hpp>
#include <KDE/KCalCore/Todo>
#endif
#include <KDE/Akonadi/EntityTreeView>
#include <KDE/Akonadi/ItemCreateJob>
#include <KDE/Akonadi/ItemDeleteJob>
#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KDebug>
#include <kdescendantsproxymodel.h>
#include <KDE/KIcon>
#include <KDE/KLineEdit>
#include <KDE/KLocale>
#include <KDE/KPassivePopup>
#include <QtCore/QEvent>
#include <QtCore/QTimer>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>
#include <QtGui/QStackedWidget>
#include "actionlistcombobox.h"
#include "actionlistdelegate.h"
#include "actionlisteditorpage.h"
#include "modelstack.h"
#include "todomodel.h"
#if 0
#include "quickselectdialog.h"
#endif
ActionListEditor::ActionListEditor(ModelStack *models,
QItemSelectionModel *projectSelection,
QItemSelectionModel *categoriesSelection,
KActionCollection *ac,
QWidget *parent)
: QWidget(parent),
m_projectSelection(projectSelection),
m_categoriesSelection(categoriesSelection)
{
setLayout(new QVBoxLayout(this));
m_stack = new QStackedWidget(this);
layout()->addWidget(m_stack);
layout()->setContentsMargins(0, 0, 0, 0);
connect(projectSelection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
this, SLOT(onSideBarSelectionChanged(QModelIndex)));
connect(categoriesSelection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
this, SLOT(onSideBarSelectionChanged(QModelIndex)));
createPage(models->treeSelectionModel(projectSelection), models, Zanshin::ProjectMode);
createPage(models->categoriesSelectionModel(categoriesSelection), models, Zanshin::CategoriesMode);
QWidget *bottomBar = new QWidget(this);
layout()->addWidget(bottomBar);
bottomBar->setLayout(new QHBoxLayout(bottomBar));
bottomBar->layout()->setContentsMargins(0, 0, 0, 0);
m_addActionEdit = new KLineEdit(bottomBar);
m_addActionEdit->installEventFilter(this);
bottomBar->layout()->addWidget(m_addActionEdit);
m_addActionEdit->setClickMessage(i18n("Type and press enter to add an action"));
m_addActionEdit->setClearButtonShown(true);
connect(m_addActionEdit, SIGNAL(returnPressed()),
this, SLOT(onAddActionRequested()));
m_comboBox = new ActionListComboBox(bottomBar);
m_comboBox->view()->setTextElideMode(Qt::ElideLeft);
m_comboBox->setMinimumContentsLength(20);
m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
KDescendantsProxyModel *descendantProxyModel = new KDescendantsProxyModel(m_comboBox);
descendantProxyModel->setSourceModel(models->collectionsModel());
descendantProxyModel->setDisplayAncestorData(true);
m_comboBox->setModel(descendantProxyModel);
bottomBar->layout()->addWidget(m_comboBox);
setupActions(ac);
QToolBar *toolBar = new QToolBar(bottomBar);
toolBar->setIconSize(QSize(16, 16));
bottomBar->layout()->addWidget(toolBar);
toolBar->addAction(m_cancelAdd);
m_cancelAdd->setEnabled(false);
updateActions(QModelIndex());
setMode(Zanshin::ProjectMode);
}
void ActionListEditor::setMode(Zanshin::ApplicationMode mode)
{
switch (mode) {
case Zanshin::ProjectMode:
m_stack->setCurrentIndex(0);
onSideBarSelectionChanged(m_projectSelection->currentIndex());
break;
case Zanshin::CategoriesMode:
m_stack->setCurrentIndex(1);
onSideBarSelectionChanged(m_categoriesSelection->currentIndex());
break;
}
}
void ActionListEditor::onSideBarSelectionChanged(const QModelIndex &index)
{
int type = index.data(TodoModel::ItemTypeRole).toInt();
m_comboBox->setVisible(type == TodoModel::Inbox
|| type == TodoModel::Category
|| type == TodoModel::CategoryRoot);
}
void ActionListEditor::createPage(QAbstractItemModel *model, ModelStack *models, Zanshin::ApplicationMode mode)
{
ActionListEditorPage *page = new ActionListEditorPage(model, models, mode, m_stack);
connect(page->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
this, SLOT(updateActions(QModelIndex)));
m_stack->addWidget(page);
}
void ActionListEditor::setupActions(KActionCollection *ac)
{
m_add = ac->addAction("editor_add_action", this, SLOT(focusActionEdit()));
m_add->setText(i18n("New Action"));
m_add->setIcon(KIcon("list-add"));
m_add->setShortcut(Qt::CTRL | Qt::Key_N);
m_cancelAdd = ac->addAction("editor_cancel_action", m_stack, SLOT(setFocus()));
connect(m_cancelAdd, SIGNAL(activated()), m_addActionEdit, SLOT(clear()));
m_cancelAdd->setText(i18n("Cancel New Action"));
m_cancelAdd->setIcon(KIcon("edit-undo"));
m_cancelAdd->setShortcut(Qt::Key_Escape);
m_remove = ac->addAction("editor_remove_action", this, SLOT(onRemoveAction()));
m_remove->setText(i18n("Remove Action"));
m_remove->setIcon(KIcon("list-remove"));
m_remove->setShortcut(Qt::Key_Delete);
m_move = ac->addAction("editor_move_action", this, SLOT(onMoveAction()));
m_move->setText(i18n("Move Action..."));
m_move->setShortcut(Qt::Key_M);
}
void ActionListEditor::updateActions(const QModelIndex &index)
{
int type = index.data(TodoModel::ItemTypeRole).toInt();
m_remove->setEnabled(index.isValid() && (type==TodoModel::StandardTodo));
m_move->setEnabled(index.isValid() && (type==TodoModel::StandardTodo));
}
void ActionListEditor::onAddActionRequested()
{
QString summary = m_addActionEdit->text().trimmed();
m_addActionEdit->setText(QString());
if (summary.isEmpty()) return;
QModelIndex current = currentPage()->selectionModel()->currentIndex();
if (!current.isValid()) {
kWarning() << "Oops, nothing selected in the list!";
return;
}
int type = current.data(TodoModel::ItemTypeRole).toInt();
while (current.isValid() && type==TodoModel::StandardTodo) {
current = current.parent();
type = current.data(TodoModel::ItemTypeRole).toInt();
}
Akonadi::Collection collection;
QString parentUid;
QString category;
switch (type) {
case TodoModel::StandardTodo:
kFatal() << "Can't possibly happen!";
break;
case TodoModel::ProjectTodo:
parentUid = current.data(TodoModel::UidRole).toString();
collection = current.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>();
break;
case TodoModel::Collection:
collection = current.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
break;
case TodoModel::Category:
category = current.data(Qt::EditRole).toString();
// fallthrough
case TodoModel::Inbox:
case TodoModel::CategoryRoot:
QModelIndex collectionIndex = m_comboBox->model()->index( m_comboBox->currentIndex(), 0 );
collection = collectionIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
break;
}
KCalCore::Todo::Ptr todo(new KCalCore::Todo);
todo->setSummary(summary);
if (!parentUid.isEmpty()) {
todo->setRelatedTo(parentUid);
}
if (!category.isEmpty()) {
todo->setCategories(category);
}
Akonadi::Item item;
item.setMimeType("application/x-vnd.akonadi.calendar.todo");
item.setPayload<KCalCore::Todo::Ptr>(todo);
new Akonadi::ItemCreateJob(item, collection);
}
void ActionListEditor::onRemoveAction()
{
QModelIndex current = currentPage()->selectionModel()->currentIndex();
int type = current.data(TodoModel::ItemTypeRole).toInt();
if (!current.isValid() || type!=TodoModel::StandardTodo) {
return;
}
Akonadi::Item item = current.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
if (!item.isValid()) {
return;
}
new Akonadi::ItemDeleteJob(item, this);
}
void ActionListEditor::onMoveAction()
{
#if 0
QModelIndex current = m_view->currentIndex();
if (m_model->rowCount(current)>0) {
return;
}
QAbstractItemModel *source = m_model->sourceModel();
QModelIndex movedIndex;
TodoFlatModel *flat = dynamic_cast<TodoFlatModel*>(source);
if (flat != 0) {
movedIndex = m_model->mapToSource(current);
}
TodoTreeModel *tree = dynamic_cast<TodoTreeModel*>(source);
if (tree != 0) {
movedIndex = m_model->mapToSource(current);
}
TodoCategoriesModel *categories = dynamic_cast<TodoCategoriesModel*>(source);
if (categories != 0) {
movedIndex = m_model->mapToSource(current);
}
if (!movedIndex.isValid()) {
return;
}
QuickSelectDialog::Mode mode = QuickSelectDialog::ProjectMode;
if (m_model->mode()==ActionListModel::NoContextMode
|| m_model->mode()==ActionListModel::ContextMode) {
mode = QuickSelectDialog::ContextMode;
}
QuickSelectDialog dlg(this, mode,
QuickSelectDialog::MoveAction);
if (dlg.exec()==QDialog::Accepted) {
QString selectedId = dlg.selectedId();
if (mode==QuickSelectDialog::ProjectMode) {
QModelIndex index = movedIndex.sibling(movedIndex.row(), TodoFlatModel::ParentRemoteId);
source->setData(index, selectedId);
} else {
QModelIndex index = movedIndex.sibling(movedIndex.row(), TodoFlatModel::Categories);
source->setData(index, selectedId);
}
}
#endif
}
void ActionListEditor::focusActionEdit()
{
QPoint pos = m_addActionEdit->geometry().topLeft();
pos = m_addActionEdit->parentWidget()->mapToGlobal(pos);
KPassivePopup *popup = KPassivePopup::message(i18n("Type and press enter to add an action"), m_addActionEdit);
popup->move(pos-QPoint(0, popup->height()));
m_addActionEdit->setFocus();
}
bool ActionListEditor::eventFilter(QObject *watched, QEvent *event)
{
if (watched==m_addActionEdit) {
if (event->type()==QEvent::FocusIn) {
m_cancelAdd->setEnabled(true);
} else if (event->type()==QEvent::FocusOut) {
m_cancelAdd->setEnabled(false);
}
}
return QWidget::eventFilter(watched, event);
}
void ActionListEditor::saveColumnsState(KConfigGroup &config) const
{
page(0)->saveColumnsState(config, "ProjectHeaderState");
page(1)->saveColumnsState(config, "CategoriesHeaderState");
}
void ActionListEditor::restoreColumnsState(const KConfigGroup &config)
{
page(0)->restoreColumnsState(config, "ProjectHeaderState");
page(1)->restoreColumnsState(config, "CategoriesHeaderState");
}
ActionListEditorPage *ActionListEditor::currentPage() const
{
return static_cast<ActionListEditorPage*>(m_stack->currentWidget());
}
ActionListEditorPage *ActionListEditor::page(int idx) const
{
return static_cast<ActionListEditorPage*>(m_stack->widget(idx));
}
void ActionListEditor::hideColumns()
{
for (int i = 0; i < m_stack->count(); ++i) {
ActionListEditorPage *page = static_cast<ActionListEditorPage*>(m_stack->widget(i));
if (page->mode() == Zanshin::ProjectMode) {
page->hideColumn(1);
} else {
page->hideColumn(2);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2009 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/rubytest/RubyTester.hh"
#include "mem/physical.hh"
#include "mem/ruby/slicc_interface/AbstractController.hh"
#include "mem/ruby/system/RubyPort.hh"
RubyPort::RubyPort(const Params *p)
: MemObject(p)
{
m_version = p->version;
assert(m_version != -1);
physmem = p->physmem;
m_controller = NULL;
m_mandatory_q_ptr = NULL;
m_request_cnt = 0;
pio_port = NULL;
physMemPort = NULL;
}
void
RubyPort::init()
{
assert(m_controller != NULL);
m_mandatory_q_ptr = m_controller->getMandatoryQueue();
}
Port *
RubyPort::getPort(const std::string &if_name, int idx)
{
if (if_name == "port") {
return new M5Port(csprintf("%s-port%d", name(), idx), this);
}
if (if_name == "pio_port") {
// ensure there is only one pio port
assert(pio_port == NULL);
pio_port = new PioPort(csprintf("%s-pio-port%d", name(), idx), this);
return pio_port;
}
if (if_name == "physMemPort") {
// RubyPort should only have one port to physical memory
assert (physMemPort == NULL);
physMemPort = new M5Port(csprintf("%s-physMemPort", name()), this);
return physMemPort;
}
if (if_name == "functional") {
// Calls for the functional port only want to access
// functional memory. Therefore, directly pass these calls
// ports to physmem.
assert(physmem != NULL);
return physmem->getPort(if_name, idx);
}
return NULL;
}
RubyPort::PioPort::PioPort(const std::string &_name,
RubyPort *_port)
: SimpleTimingPort(_name, _port)
{
DPRINTF(Ruby, "creating port to ruby sequencer to cpu %s\n", _name);
ruby_port = _port;
}
RubyPort::M5Port::M5Port(const std::string &_name,
RubyPort *_port)
: SimpleTimingPort(_name, _port)
{
DPRINTF(Ruby, "creating port from ruby sequcner to cpu %s\n", _name);
ruby_port = _port;
}
Tick
RubyPort::PioPort::recvAtomic(PacketPtr pkt)
{
panic("RubyPort::PioPort::recvAtomic() not implemented!\n");
return 0;
}
Tick
RubyPort::M5Port::recvAtomic(PacketPtr pkt)
{
panic("RubyPort::M5Port::recvAtomic() not implemented!\n");
return 0;
}
bool
RubyPort::PioPort::recvTiming(PacketPtr pkt)
{
// In FS mode, ruby memory will receive pio responses from devices
// and it must forward these responses back to the particular CPU.
DPRINTF(MemoryAccess, "Pio response for address %#x\n", pkt->getAddr());
assert(pkt->isResponse());
// First we must retrieve the request port from the sender State
RubyPort::SenderState *senderState =
safe_cast<RubyPort::SenderState *>(pkt->senderState);
M5Port *port = senderState->port;
assert(port != NULL);
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->sendTiming(pkt);
return true;
}
bool
RubyPort::M5Port::recvTiming(PacketPtr pkt)
{
DPRINTF(MemoryAccess,
"Timing access caught for address %#x\n", pkt->getAddr());
//dsm: based on SimpleTimingPort::recvTiming(pkt);
// The received packets should only be M5 requests, which should never
// get nacked. There used to be code to hanldle nacks here, but
// I'm pretty sure it didn't work correctly with the drain code,
// so that would need to be fixed if we ever added it back.
assert(pkt->isRequest());
if (pkt->memInhibitAsserted()) {
warn("memInhibitAsserted???");
// snooper will supply based on copy of packet
// still target's responsibility to delete packet
delete pkt;
return true;
}
// Save the port in the sender state object to be used later to
// route the response
pkt->senderState = new SenderState(this, pkt->senderState);
// Check for pio requests and directly send them to the dedicated
// pio port.
if (!isPhysMemAddress(pkt->getAddr())) {
assert(ruby_port->pio_port != NULL);
DPRINTF(MemoryAccess,
"Request for address 0x%#x is assumed to be a pio request\n",
pkt->getAddr());
return ruby_port->pio_port->sendTiming(pkt);
}
// For DMA and CPU requests, translate them to ruby requests before
// sending them to our assigned ruby port.
RubyRequestType type = RubyRequestType_NULL;
// If valid, copy the pc to the ruby request
Addr pc = 0;
if (pkt->req->hasPC()) {
pc = pkt->req->getPC();
}
if (pkt->isLLSC()) {
if (pkt->isWrite()) {
DPRINTF(MemoryAccess, "Issuing SC\n");
type = RubyRequestType_Locked_Write;
} else {
DPRINTF(MemoryAccess, "Issuing LL\n");
assert(pkt->isRead());
type = RubyRequestType_Locked_Read;
}
} else {
if (pkt->isRead()) {
if (pkt->req->isInstFetch()) {
type = RubyRequestType_IFETCH;
} else {
type = RubyRequestType_LD;
}
} else if (pkt->isWrite()) {
type = RubyRequestType_ST;
} else if (pkt->isReadWrite()) {
// Fix me. This conditional will never be executed
// because isReadWrite() is just an OR of isRead() and
// isWrite(). Furthermore, just because the packet is a
// read/write request does not necessary mean it is a
// read-modify-write atomic operation.
type = RubyRequestType_RMW_Write;
} else {
panic("Unsupported ruby packet type\n");
}
}
RubyRequest ruby_request(pkt->getAddr(), pkt->getPtr<uint8_t>(),
pkt->getSize(), pc, type,
RubyAccessMode_Supervisor, pkt);
// Submit the ruby request
RequestStatus requestStatus = ruby_port->makeRequest(ruby_request);
// If the request successfully issued then we should return true.
// Otherwise, we need to delete the senderStatus we just created and return
// false.
if (requestStatus == RequestStatus_Issued) {
return true;
}
DPRINTF(MemoryAccess,
"Request for address #x did not issue because %s\n",
pkt->getAddr(), RequestStatus_to_string(requestStatus));
SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);
pkt->senderState = senderState->saved;
delete senderState;
return false;
}
void
RubyPort::ruby_hit_callback(PacketPtr pkt)
{
// Retrieve the request port from the sender State
RubyPort::SenderState *senderState =
safe_cast<RubyPort::SenderState *>(pkt->senderState);
M5Port *port = senderState->port;
assert(port != NULL);
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->hitCallback(pkt);
}
void
RubyPort::M5Port::hitCallback(PacketPtr pkt)
{
bool needsResponse = pkt->needsResponse();
//
// All responses except failed SC operations access M5 physical memory
//
bool accessPhysMem = true;
if (pkt->isLLSC()) {
if (pkt->isWrite()) {
if (pkt->req->getExtraData() != 0) {
//
// Successful SC packets convert to normal writes
//
pkt->convertScToWrite();
} else {
//
// Failed SC packets don't access physical memory and thus
// the RubyPort itself must convert it to a response.
//
accessPhysMem = false;
pkt->makeAtomicResponse();
}
} else {
//
// All LL packets convert to normal loads so that M5 PhysMem does
// not lock the blocks.
//
pkt->convertLlToRead();
}
}
DPRINTF(MemoryAccess, "Hit callback needs response %d\n", needsResponse);
if (accessPhysMem) {
ruby_port->physMemPort->sendAtomic(pkt);
}
// turn packet around to go back to requester if response expected
if (needsResponse) {
// sendAtomic() should already have turned packet into
// atomic response
assert(pkt->isResponse());
DPRINTF(MemoryAccess, "Sending packet back over port\n");
sendTiming(pkt);
} else {
delete pkt;
}
DPRINTF(MemoryAccess, "Hit callback done!\n");
}
bool
RubyPort::M5Port::sendTiming(PacketPtr pkt)
{
schedSendTiming(pkt, curTick + 1); //minimum latency, must be > 0
return true;
}
bool
RubyPort::PioPort::sendTiming(PacketPtr pkt)
{
schedSendTiming(pkt, curTick + 1); //minimum latency, must be > 0
return true;
}
bool
RubyPort::M5Port::isPhysMemAddress(Addr addr)
{
AddrRangeList physMemAddrList;
bool snoop = false;
ruby_port->physMemPort->getPeerAddressRanges(physMemAddrList, snoop);
for (AddrRangeIter iter = physMemAddrList.begin();
iter != physMemAddrList.end();
iter++) {
if (addr >= iter->start && addr <= iter->end) {
DPRINTF(MemoryAccess, "Request found in %#llx - %#llx range\n",
iter->start, iter->end);
return true;
}
}
return false;
}
<commit_msg>ruby: Fixed RubyPort sendTiming callbacks<commit_after>/*
* Copyright (c) 2009 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/rubytest/RubyTester.hh"
#include "mem/physical.hh"
#include "mem/ruby/slicc_interface/AbstractController.hh"
#include "mem/ruby/system/RubyPort.hh"
RubyPort::RubyPort(const Params *p)
: MemObject(p)
{
m_version = p->version;
assert(m_version != -1);
physmem = p->physmem;
m_controller = NULL;
m_mandatory_q_ptr = NULL;
m_request_cnt = 0;
pio_port = NULL;
physMemPort = NULL;
}
void
RubyPort::init()
{
assert(m_controller != NULL);
m_mandatory_q_ptr = m_controller->getMandatoryQueue();
}
Port *
RubyPort::getPort(const std::string &if_name, int idx)
{
if (if_name == "port") {
return new M5Port(csprintf("%s-port%d", name(), idx), this);
}
if (if_name == "pio_port") {
// ensure there is only one pio port
assert(pio_port == NULL);
pio_port = new PioPort(csprintf("%s-pio-port%d", name(), idx), this);
return pio_port;
}
if (if_name == "physMemPort") {
// RubyPort should only have one port to physical memory
assert (physMemPort == NULL);
physMemPort = new M5Port(csprintf("%s-physMemPort", name()), this);
return physMemPort;
}
if (if_name == "functional") {
// Calls for the functional port only want to access
// functional memory. Therefore, directly pass these calls
// ports to physmem.
assert(physmem != NULL);
return physmem->getPort(if_name, idx);
}
return NULL;
}
RubyPort::PioPort::PioPort(const std::string &_name,
RubyPort *_port)
: SimpleTimingPort(_name, _port)
{
DPRINTF(Ruby, "creating port to ruby sequencer to cpu %s\n", _name);
ruby_port = _port;
}
RubyPort::M5Port::M5Port(const std::string &_name,
RubyPort *_port)
: SimpleTimingPort(_name, _port)
{
DPRINTF(Ruby, "creating port from ruby sequcner to cpu %s\n", _name);
ruby_port = _port;
}
Tick
RubyPort::PioPort::recvAtomic(PacketPtr pkt)
{
panic("RubyPort::PioPort::recvAtomic() not implemented!\n");
return 0;
}
Tick
RubyPort::M5Port::recvAtomic(PacketPtr pkt)
{
panic("RubyPort::M5Port::recvAtomic() not implemented!\n");
return 0;
}
bool
RubyPort::PioPort::recvTiming(PacketPtr pkt)
{
// In FS mode, ruby memory will receive pio responses from devices
// and it must forward these responses back to the particular CPU.
DPRINTF(MemoryAccess, "Pio response for address %#x\n", pkt->getAddr());
assert(pkt->isResponse());
// First we must retrieve the request port from the sender State
RubyPort::SenderState *senderState =
safe_cast<RubyPort::SenderState *>(pkt->senderState);
M5Port *port = senderState->port;
assert(port != NULL);
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->sendTiming(pkt);
return true;
}
bool
RubyPort::M5Port::recvTiming(PacketPtr pkt)
{
DPRINTF(MemoryAccess,
"Timing access caught for address %#x\n", pkt->getAddr());
//dsm: based on SimpleTimingPort::recvTiming(pkt);
// The received packets should only be M5 requests, which should never
// get nacked. There used to be code to hanldle nacks here, but
// I'm pretty sure it didn't work correctly with the drain code,
// so that would need to be fixed if we ever added it back.
assert(pkt->isRequest());
if (pkt->memInhibitAsserted()) {
warn("memInhibitAsserted???");
// snooper will supply based on copy of packet
// still target's responsibility to delete packet
delete pkt;
return true;
}
// Save the port in the sender state object to be used later to
// route the response
pkt->senderState = new SenderState(this, pkt->senderState);
// Check for pio requests and directly send them to the dedicated
// pio port.
if (!isPhysMemAddress(pkt->getAddr())) {
assert(ruby_port->pio_port != NULL);
DPRINTF(MemoryAccess,
"Request for address 0x%#x is assumed to be a pio request\n",
pkt->getAddr());
return ruby_port->pio_port->sendTiming(pkt);
}
// For DMA and CPU requests, translate them to ruby requests before
// sending them to our assigned ruby port.
RubyRequestType type = RubyRequestType_NULL;
// If valid, copy the pc to the ruby request
Addr pc = 0;
if (pkt->req->hasPC()) {
pc = pkt->req->getPC();
}
if (pkt->isLLSC()) {
if (pkt->isWrite()) {
DPRINTF(MemoryAccess, "Issuing SC\n");
type = RubyRequestType_Locked_Write;
} else {
DPRINTF(MemoryAccess, "Issuing LL\n");
assert(pkt->isRead());
type = RubyRequestType_Locked_Read;
}
} else {
if (pkt->isRead()) {
if (pkt->req->isInstFetch()) {
type = RubyRequestType_IFETCH;
} else {
type = RubyRequestType_LD;
}
} else if (pkt->isWrite()) {
type = RubyRequestType_ST;
} else if (pkt->isReadWrite()) {
// Fix me. This conditional will never be executed
// because isReadWrite() is just an OR of isRead() and
// isWrite(). Furthermore, just because the packet is a
// read/write request does not necessary mean it is a
// read-modify-write atomic operation.
type = RubyRequestType_RMW_Write;
} else {
panic("Unsupported ruby packet type\n");
}
}
RubyRequest ruby_request(pkt->getAddr(), pkt->getPtr<uint8_t>(),
pkt->getSize(), pc, type,
RubyAccessMode_Supervisor, pkt);
// Submit the ruby request
RequestStatus requestStatus = ruby_port->makeRequest(ruby_request);
// If the request successfully issued then we should return true.
// Otherwise, we need to delete the senderStatus we just created and return
// false.
if (requestStatus == RequestStatus_Issued) {
return true;
}
DPRINTF(MemoryAccess,
"Request for address #x did not issue because %s\n",
pkt->getAddr(), RequestStatus_to_string(requestStatus));
SenderState* senderState = safe_cast<SenderState*>(pkt->senderState);
pkt->senderState = senderState->saved;
delete senderState;
return false;
}
void
RubyPort::ruby_hit_callback(PacketPtr pkt)
{
// Retrieve the request port from the sender State
RubyPort::SenderState *senderState =
safe_cast<RubyPort::SenderState *>(pkt->senderState);
M5Port *port = senderState->port;
assert(port != NULL);
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->hitCallback(pkt);
}
void
RubyPort::M5Port::hitCallback(PacketPtr pkt)
{
bool needsResponse = pkt->needsResponse();
//
// All responses except failed SC operations access M5 physical memory
//
bool accessPhysMem = true;
if (pkt->isLLSC()) {
if (pkt->isWrite()) {
if (pkt->req->getExtraData() != 0) {
//
// Successful SC packets convert to normal writes
//
pkt->convertScToWrite();
} else {
//
// Failed SC packets don't access physical memory and thus
// the RubyPort itself must convert it to a response.
//
accessPhysMem = false;
pkt->makeAtomicResponse();
}
} else {
//
// All LL packets convert to normal loads so that M5 PhysMem does
// not lock the blocks.
//
pkt->convertLlToRead();
}
}
DPRINTF(MemoryAccess, "Hit callback needs response %d\n", needsResponse);
if (accessPhysMem) {
ruby_port->physMemPort->sendAtomic(pkt);
}
// turn packet around to go back to requester if response expected
if (needsResponse) {
// sendAtomic() should already have turned packet into
// atomic response
assert(pkt->isResponse());
DPRINTF(MemoryAccess, "Sending packet back over port\n");
sendTiming(pkt);
} else {
delete pkt;
}
DPRINTF(MemoryAccess, "Hit callback done!\n");
}
bool
RubyPort::M5Port::sendTiming(PacketPtr pkt)
{
//minimum latency, must be > 0
schedSendTiming(pkt, curTick + (1 * g_eventQueue_ptr->getClock()));
return true;
}
bool
RubyPort::PioPort::sendTiming(PacketPtr pkt)
{
//minimum latency, must be > 0
schedSendTiming(pkt, curTick + (1 * g_eventQueue_ptr->getClock()));
return true;
}
bool
RubyPort::M5Port::isPhysMemAddress(Addr addr)
{
AddrRangeList physMemAddrList;
bool snoop = false;
ruby_port->physMemPort->getPeerAddressRanges(physMemAddrList, snoop);
for (AddrRangeIter iter = physMemAddrList.begin();
iter != physMemAddrList.end();
iter++) {
if (addr >= iter->start && addr <= iter->end) {
DPRINTF(MemoryAccess, "Request found in %#llx - %#llx range\n",
iter->start, iter->end);
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: SVGTesselator.cpp
created: 1st August 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/svg/SVGTesselator.h"
#include "CEGUI/svg/SVGBasicShape.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/System.h"
#include "CEGUI/Vertex.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
void SVGTesselator::tesselateAndRenderPolyline(const SVGPolyline* polyline,
std::vector<GeometryBuffer*>& geometry_buffers,
const SVGImage::SVGImageRenderSettings& render_settings)
{
CEGUI::GeometryBuffer& geometry_buffer = System::getSingleton().getRenderer()->createGeometryBufferColoured();
geometry_buffers.push_back(&geometry_buffer);
if(render_settings.d_clipArea)
{
geometry_buffer.setClippingActive(true);
geometry_buffer.setClippingRegion(*render_settings.d_clipArea);
}
geometry_buffer.setScale(render_settings.d_scaleFactor);
const CEGUI::Colour& stroke_colour = polyline->d_shapeStyle.d_stroke.d_colour;
const SVGPolyline::PolylinePointsList& points = polyline->d_points;
const float& stroke_width_length_half = polyline->d_shapeStyle.d_strokeWidthLength * 0.5f;
//Draw the line segments TODO Ident: Draw them seamlessly connected with bevels and stuff provided optionally
size_t points_count = points.size();
for (size_t j = 1; j < points_count; ++j)
{
const glm::vec2& prevPos = points.at(j - 1);
const glm::vec2& currentPos = points.at(j);
// Normalize and tilt the 2D direction vector by 90 to get the vector pointing in the offset direction
glm::vec2 offsetVector = currentPos - prevPos;
offsetVector = glm::normalize(offsetVector);
offsetVector = glm::vec2(offsetVector.y, -offsetVector.x) * 0.5f;
CEGUI::ColouredVertex linePositionVertex;
glm::vec2 vertexPosition;
linePositionVertex.colour_val = stroke_colour;
linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(currentPos - offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(prevPos + offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
}
}
//----------------------------------------------------------------------------//
void SVGTesselator::tesselateAndRenderRect(const SVGRect* rect,
std::vector<GeometryBuffer*>& geometry_buffers,
const SVGImage::SVGImageRenderSettings& render_settings)
{
CEGUI::GeometryBuffer& geometry_buffer = System::getSingleton().getRenderer()->createGeometryBufferColoured();
geometry_buffers.push_back(&geometry_buffer);
if(render_settings.d_clipArea)
{
geometry_buffer.setClippingActive(true);
geometry_buffer.setClippingRegion(*render_settings.d_clipArea);
}
geometry_buffer.setScale(render_settings.d_scaleFactor);
const CEGUI::Colour& fill_colour = rect->d_shapeStyle.d_fill.d_colour;
//Draw the rectangle
CEGUI::ColouredVertex rectFillVertex;
glm::vec2 vertexPosition;
rectFillVertex.colour_val = fill_colour;
const float& rectX1 = rect->d_x;
const float& rectY1 = rect->d_y;
const float rectX2 = rect->d_x + rect->d_width;
const float rectY2 = rect->d_y + rect->d_height;
rectFillVertex.position = glm::vec3(rectX1, rectY1, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX1, rectY2, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX2, rectY2, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX2, rectY2, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX1, rectY1, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX2, rectY1, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
}
//----------------------------------------------------------------------------//
}
<commit_msg>MOD: Adapted SVGTesselator for the changed colour type in PaintStyle<commit_after>/***********************************************************************
filename: SVGTesselator.cpp
created: 1st August 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/svg/SVGTesselator.h"
#include "CEGUI/svg/SVGBasicShape.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/System.h"
#include "CEGUI/Vertex.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
void SVGTesselator::tesselateAndRenderPolyline(const SVGPolyline* polyline,
std::vector<GeometryBuffer*>& geometry_buffers,
const SVGImage::SVGImageRenderSettings& render_settings)
{
CEGUI::GeometryBuffer& geometry_buffer = System::getSingleton().getRenderer()->createGeometryBufferColoured();
geometry_buffers.push_back(&geometry_buffer);
if(render_settings.d_clipArea)
{
geometry_buffer.setClippingActive(true);
geometry_buffer.setClippingRegion(*render_settings.d_clipArea);
}
geometry_buffer.setScale(render_settings.d_scaleFactor);
const glm::vec3& strokeColourValues = polyline->d_paintStyle.d_stroke.d_colour;
const CEGUI::Colour stroke_colour(strokeColourValues.x, strokeColourValues.y, strokeColourValues.z, polyline->d_paintStyle.d_strokeOpacity);
const SVGPolyline::PolylinePointsList& points = polyline->d_points;
const float& stroke_width_length_half = polyline->d_paintStyle.d_strokeWidth * 0.5f;
//Draw the line segments TODO Ident: Draw them seamlessly connected with bevels and stuff provided optionally
size_t points_count = points.size();
for (size_t j = 1; j < points_count; ++j)
{
const glm::vec2& prevPos = points.at(j - 1);
const glm::vec2& currentPos = points.at(j);
// Normalize and tilt the 2D direction vector by 90 to get the vector pointing in the offset direction
glm::vec2 offsetVector = currentPos - prevPos;
offsetVector = glm::normalize(offsetVector);
offsetVector = glm::vec2(offsetVector.y, -offsetVector.x) * stroke_width_length_half;
CEGUI::ColouredVertex linePositionVertex;
glm::vec2 vertexPosition;
linePositionVertex.colour_val = stroke_colour;
linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(currentPos - offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
linePositionVertex.position = glm::vec3(prevPos + offsetVector, 0.0f);
geometry_buffer.appendVertex(linePositionVertex);
}
}
//----------------------------------------------------------------------------//
void SVGTesselator::tesselateAndRenderRect(const SVGRect* rect,
std::vector<GeometryBuffer*>& geometry_buffers,
const SVGImage::SVGImageRenderSettings& render_settings)
{
CEGUI::GeometryBuffer& geometry_buffer = System::getSingleton().getRenderer()->createGeometryBufferColoured();
geometry_buffers.push_back(&geometry_buffer);
if(render_settings.d_clipArea)
{
geometry_buffer.setClippingActive(true);
geometry_buffer.setClippingRegion(*render_settings.d_clipArea);
}
geometry_buffer.setScale(render_settings.d_scaleFactor);
const glm::vec3& colourValues = rect->d_paintStyle.d_fill.d_colour;
const CEGUI::Colour fill_colour(colourValues.x, colourValues.y, colourValues.z, rect->d_paintStyle.d_fillOpacity);
//Draw the rectangle
CEGUI::ColouredVertex rectFillVertex;
glm::vec2 vertexPosition;
rectFillVertex.colour_val = fill_colour;
const float& rectX1 = rect->d_x;
const float& rectY1 = rect->d_y;
const float rectX2 = rect->d_x + rect->d_width;
const float rectY2 = rect->d_y + rect->d_height;
rectFillVertex.position = glm::vec3(rectX1, rectY1, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX1, rectY2, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX2, rectY2, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX2, rectY2, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX1, rectY1, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
rectFillVertex.position = glm::vec3(rectX2, rectY1, 0.0f);
geometry_buffer.appendVertex(rectFillVertex);
}
//----------------------------------------------------------------------------//
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <chrono>
using namespace std;
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main ( int argc, char** argv )
{
// 读取argv[1]指定的图像
cv::Mat image;
image = cv::imread ( argv[1] ); //cv::imread函数读取指定路径下的图像
// 判断图像文件是否正确读取
if ( image.data == nullptr ) //数据不存在,可能是文件不存在
{
cerr<<"文件"<<argv[1]<<"不存在."<<endl;
return 0;
}
// 文件顺利读取, 首先输出一些基本信息
cout<<"图像宽为"<<image.cols<<",高为"<<image.rows<<",通道数为"<<image.channels()<<endl;
cv::imshow ( "image", image ); // 用cv::imshow显示图像
cv::waitKey ( 0 ); // 暂停程序,等待一个按键输入
// 判断image的类型
if ( image.type() != CV_8UC1 || image.type() != CV_8UC3 )
{
// 图像类型不符合要求
cout<<"请输入一张彩色图或灰度图."<<endl;
return 0;
}
// 遍历图像, 请注意以下遍历方式亦可使用于随机像素访问
// 使用 std::chrono 来给算法计时
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
for ( size_t y=0; y<image.rows; y++ )
{
for ( size_t x=0; x<image.cols; x++ )
{
// 访问位于 x,y 处的像素
// 用cv::Mat::ptr获得图像的行指针
unsigned char* row_ptr = image.ptr<unsigned char> ( y ); // row_ptr是第y行的头指针
unsigned char* data_ptr = &row_ptr[ x*image.channels() ]; // data_ptr 指向待访问的像素数据
// 输出该像素的每个通道,如果是灰度图就只有一个通道
for ( int c = 0; c != image.channels(); c++ )
{
unsigned char data = data_ptr[c]; // data为I(x,y)第c个通道的值
}
}
}
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>( t2-t1 );
cout<<"遍历图像用时:"<<time_used.count()<<" 秒。"<<endl;
// 关于 cv::Mat 的拷贝
// 直接赋值并不会拷贝数据
cv::Mat image_another = image;
// 修改 image_another 会导致 image 发生变化
image_another ( cv::Rect ( 0,0,100,100 ) ).setTo ( 0 ); // 将左上角100*100的块置零
cv::imshow ( "image", image );
cv::waitKey ( 0 );
// 使用clone函数来拷贝数据
cv::Mat image_clone = image.clone();
image_clone ( cv::Rect ( 0,0,100,100 ) ).setTo ( 255 );
cv::imshow ( "image", image );
cv::imshow ( "image_clone", image_clone );
cv::waitKey ( 0 );
// 对于图像还有很多基本的操作,如剪切,旋转,缩放等,限于篇幅就不一一介绍了,请参看OpenCV官方文档查询每个函数的调用方法.
cv::destroyAllWindows();
return 0;
}
<commit_msg>Update imageBasics.cpp<commit_after>#include <iostream>
#include <chrono>
using namespace std;
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main ( int argc, char** argv )
{
// 读取argv[1]指定的图像
cv::Mat image;
image = cv::imread ( argv[1] ); //cv::imread函数读取指定路径下的图像
// 判断图像文件是否正确读取
if ( image.data == nullptr ) //数据不存在,可能是文件不存在
{
cerr<<"文件"<<argv[1]<<"不存在."<<endl;
return 0;
}
// 文件顺利读取, 首先输出一些基本信息
cout<<"图像宽为"<<image.cols<<",高为"<<image.rows<<",通道数为"<<image.channels()<<endl;
cv::imshow ( "image", image ); // 用cv::imshow显示图像
cv::waitKey ( 0 ); // 暂停程序,等待一个按键输入
// 判断image的类型
if ( image.type() != CV_8UC1 && image.type() != CV_8UC3 )
{
// 图像类型不符合要求
cout<<"请输入一张彩色图或灰度图."<<endl;
return 0;
}
// 遍历图像, 请注意以下遍历方式亦可使用于随机像素访问
// 使用 std::chrono 来给算法计时
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
for ( size_t y=0; y<image.rows; y++ )
{
for ( size_t x=0; x<image.cols; x++ )
{
// 访问位于 x,y 处的像素
// 用cv::Mat::ptr获得图像的行指针
unsigned char* row_ptr = image.ptr<unsigned char> ( y ); // row_ptr是第y行的头指针
unsigned char* data_ptr = &row_ptr[ x*image.channels() ]; // data_ptr 指向待访问的像素数据
// 输出该像素的每个通道,如果是灰度图就只有一个通道
for ( int c = 0; c != image.channels(); c++ )
{
unsigned char data = data_ptr[c]; // data为I(x,y)第c个通道的值
}
}
}
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>( t2-t1 );
cout<<"遍历图像用时:"<<time_used.count()<<" 秒。"<<endl;
// 关于 cv::Mat 的拷贝
// 直接赋值并不会拷贝数据
cv::Mat image_another = image;
// 修改 image_another 会导致 image 发生变化
image_another ( cv::Rect ( 0,0,100,100 ) ).setTo ( 0 ); // 将左上角100*100的块置零
cv::imshow ( "image", image );
cv::waitKey ( 0 );
// 使用clone函数来拷贝数据
cv::Mat image_clone = image.clone();
image_clone ( cv::Rect ( 0,0,100,100 ) ).setTo ( 255 );
cv::imshow ( "image", image );
cv::imshow ( "image_clone", image_clone );
cv::waitKey ( 0 );
// 对于图像还有很多基本的操作,如剪切,旋转,缩放等,限于篇幅就不一一介绍了,请参看OpenCV官方文档查询每个函数的调用方法.
cv::destroyAllWindows();
return 0;
}
<|endoftext|> |
<commit_before>#if !defined(_WIN32)
// This file will only be compiled with clang into llvm bitcode
// Generated bitcode will likely get inline for performance.
#include <atomic>
#include <cmath>
#include <type_traits>
#define STRUCT_FIELD(S, F) \
extern "C" decltype(S::F) S##_get_##F(S *s) { return s->F; } \
extern "C" decltype(S::F) *S##_get_ptr_##F(S *s) { return &(s->F); } \
extern "C" void S##_set_##F(S *s, decltype(S::F) f) { s->F = f; }
#define STRUCT_FIELD_ARRAY(S, F) \
extern "C" std::remove_all_extents_t<decltype(S::F)> S##_get_##F(S *s, \
int i) { \
return s->F[i]; \
} \
extern "C" void S##_set_##F(S *s, int i, \
std::remove_all_extents_t<decltype(S::F)> f) { \
s->F[i] = f; \
}
using int8 = int8_t;
using int16 = int16_t;
using int32 = int32_t;
using int64 = int64_t;
using uint8 = uint8_t;
using uint16 = uint16_t;
using uint32 = uint32_t;
using uint64 = uint64_t;
using float32 = float;
using float64 = double;
using i8 = int8;
using i32 = int32;
using f32 = float32;
using f64 = float64;
// TODO: DRY. merge this with taichi_core
constexpr int taichi_max_num_indices = 4;
constexpr int taichi_max_num_args = 8;
constexpr int taichi_max_num_snodes = 1024;
using uint8 = uint8_t;
using Ptr = uint8 *;
using ContextArgType = long long;
extern "C" {
void vprintf(Ptr format, Ptr arg);
i32 printf(const char *, ...);
#define DEFINE_UNARY_REAL_FUNC(F) \
f32 F##_f32(f32 x) { return std::F(x); } \
f64 F##_f64(f64 x) { return std::F(x); }
// sin and cos are already included in llvm intrinsics
DEFINE_UNARY_REAL_FUNC(exp)
DEFINE_UNARY_REAL_FUNC(log)
DEFINE_UNARY_REAL_FUNC(tan)
DEFINE_UNARY_REAL_FUNC(tanh)
DEFINE_UNARY_REAL_FUNC(abs)
int abs_i32(int a) {
if (a > 0) {
return a;
} else {
return -a;
}
}
int max_i32(int a, int b) { return a > b ? a : b; }
int min_i32(int a, int b) { return a < b ? a : b; }
int32 logic_not_i32(int32 a) { return !a; }
float32 sgn_f32(float32 a) {
float32 b;
if (a > 0)
b = 1;
else if (a < 0)
b = -1;
else
b = 0;
return b;
}
float64 sgn_f64(float64 a) {
float32 b;
if (a > 0)
b = 1;
else if (a < 0)
b = -1;
else
b = 0;
return b;
}
f32 __nv_sgnf(f32 x) { return sgn_f32(x); }
f64 __nv_sgn(f64 x) { return sgn_f64(x); }
struct PhysicalCoordinates {
int val[taichi_max_num_indices];
};
STRUCT_FIELD_ARRAY(PhysicalCoordinates, val);
struct Context {
void *buffer;
ContextArgType args[taichi_max_num_args];
void *leaves;
int num_leaves;
void *cpu_profiler;
Ptr runtime;
};
STRUCT_FIELD_ARRAY(Context, args);
STRUCT_FIELD(Context, runtime);
STRUCT_FIELD(Context, buffer);
#include "atomic.h"
// These structures are accessible by both the LLVM backend and this C++ runtime
// file here (for building complex runtime functions in C++)
// These structs contain some "template parameters"
// Common Attributes
struct StructMeta {
int snode_id;
std::size_t element_size;
int max_num_elements;
Ptr (*lookup_element)(Ptr, Ptr, int i);
Ptr (*from_parent_element)(Ptr);
bool (*is_active)(Ptr, Ptr, int i);
int (*get_num_elements)(Ptr, Ptr);
void (*refine_coordinates)(PhysicalCoordinates *inp_coord,
PhysicalCoordinates *refined_coord, int index);
Context *context;
};
STRUCT_FIELD(StructMeta, snode_id)
STRUCT_FIELD(StructMeta, element_size)
STRUCT_FIELD(StructMeta, max_num_elements)
STRUCT_FIELD(StructMeta, get_num_elements);
STRUCT_FIELD(StructMeta, lookup_element);
STRUCT_FIELD(StructMeta, from_parent_element);
STRUCT_FIELD(StructMeta, refine_coordinates);
STRUCT_FIELD(StructMeta, is_active);
STRUCT_FIELD(StructMeta, context);
void *taichi_allocate_aligned(std::size_t size, int alignment);
void *taichi_allocate(std::size_t size) {
return taichi_allocate_aligned(size, 1);
}
void ___stubs___() {
printf("");
vprintf(nullptr, nullptr);
taichi_allocate(1);
taichi_allocate_aligned(1, 1);
}
struct Element {
uint8 *element;
int loop_bounds[2];
PhysicalCoordinates pcoord;
};
STRUCT_FIELD(Element, element);
STRUCT_FIELD(Element, pcoord);
STRUCT_FIELD_ARRAY(Element, loop_bounds);
struct ElementList {
Element *elements;
int head;
int tail;
};
void ElementList_initialize(ElementList *element_list) {
element_list->elements = (Element *)taichi_allocate(1024 * 1024 * 1024);
element_list->tail = 0;
}
void ElementList_insert(ElementList *element_list, Element *element) {
element_list->elements[element_list->tail] = *element;
element_list->tail++;
}
void ElementList_clear(ElementList *element_list) { element_list->tail = 0; }
struct NodeAllocator {
Ptr pool;
std::size_t node_size;
int tail;
};
void NodeAllocator_initialize(NodeAllocator *node_allocator,
std::size_t node_size) {
node_allocator->pool = (Ptr)taichi_allocate_aligned(1024 * 1024 * 1024, 4096);
node_allocator->node_size = node_size;
node_allocator->tail = 0;
}
Ptr NodeAllocator_allocate(NodeAllocator *node_allocator) {
int p = atomic_add_i32(&node_allocator->tail, 1);
return node_allocator->pool + node_allocator->node_size * p;
}
// Is "runtime" a correct name, even if it is created after the data layout is
// materialized?
struct Runtime {
ElementList *element_lists[taichi_max_num_snodes];
NodeAllocator *node_allocators[taichi_max_num_snodes];
Ptr ambient_elements[taichi_max_num_snodes];
};
STRUCT_FIELD_ARRAY(Runtime, element_lists);
STRUCT_FIELD_ARRAY(Runtime, node_allocators);
Ptr Runtime_initialize(Runtime **runtime_ptr, int num_snodes,
uint64_t root_size, int root_id) {
*runtime_ptr = (Runtime *)taichi_allocate(sizeof(Runtime));
Runtime *runtime = *runtime_ptr;
printf("Initializing runtime with %d elements\n", num_snodes);
for (int i = 0; i < num_snodes; i++) {
runtime->element_lists[i] =
(ElementList *)taichi_allocate(sizeof(ElementList));
ElementList_initialize(runtime->element_lists[i]);
runtime->node_allocators[i] =
(NodeAllocator *)taichi_allocate(sizeof(NodeAllocator));
}
// Assuming num_snodes - 1 is the root
auto root_ptr = taichi_allocate_aligned(root_size, 4096);
Element elem;
elem.loop_bounds[0] = 0;
elem.loop_bounds[1] = 1;
elem.element = (Ptr)root_ptr;
for (int i = 0; i < taichi_max_num_indices; i++) {
elem.pcoord.val[i] = 0;
}
ElementList_insert(runtime->element_lists[root_id], &elem);
printf("Runtime initialized.\n");
return (Ptr)root_ptr;
}
void Runtime_allocate_ambient(Runtime *runtime, int snode_id) {
runtime->ambient_elements[snode_id] =
NodeAllocator_allocate(runtime->node_allocators[snode_id]);
}
// "Element", "component" are different concepts
// ultimately all function calls here will be inlined
void element_listgen(Runtime *runtime, StructMeta *parent, StructMeta *child) {
auto parent_list = runtime->element_lists[parent->snode_id];
int num_parent_elements = parent_list->tail;
auto child_list = runtime->element_lists[child->snode_id];
child_list->head = 0;
child_list->tail = 0;
for (int i = 0; i < num_parent_elements; i++) {
auto element = parent_list->elements[i];
auto ch_component = child->from_parent_element(element.element);
int ch_num_elements = child->get_num_elements((Ptr)child, ch_component);
for (int j = 0; j < ch_num_elements; j++) {
if (child->is_active((Ptr)child, ch_component, j)) {
auto ch_element = child->lookup_element((Ptr)child, element.element, j);
Element elem;
elem.element = ch_element;
elem.loop_bounds[0] = 0;
elem.loop_bounds[1] = child->get_num_elements((Ptr)child, ch_element);
PhysicalCoordinates refined_coord;
child->refine_coordinates(&element.pcoord, &refined_coord, j);
elem.pcoord = refined_coord;
ElementList_insert(child_list, &elem);
}
}
}
}
int32 thread_idx() { return 0; }
int32 block_idx() { return 0; }
int32 block_dim() { return 0; }
int32 grid_dim() { return 0; }
void block_barrier() {}
void for_each_block(Context *context, int snode_id, int element_size,
int element_split,
void (*task)(Context *, Element *, int, int)) {
auto list = ((Runtime *)context->runtime)->element_lists[snode_id];
auto list_tail = list->tail;
#if ARCH_cuda
int i = block_idx();
const auto part_size = element_size / element_split;
while (true) {
int element_id = i / element_split;
if (element_id >= list_tail)
break;
auto part_id = i % element_split;
auto lower = part_size * part_id;
auto upper = part_size * (part_id + 1);
task(context, &list->elements[element_id], lower, upper);
i += grid_dim();
}
#else
for (int i = 0; i < list_tail; i++) {
task(context, &list->elements[i], 0, element_size);
}
#endif
}
#include "node_dense.h"
#include "node_pointer.h"
#include "node_root.h"
}
#endif
<commit_msg>update runtime for windows build<commit_after>#if !defined(TC_INCLUDED)
// This file will only be compiled with clang into llvm bitcode
// Generated bitcode will likely get inline for performance.
#include <atomic>
#include <cmath>
#include <type_traits>
#define STRUCT_FIELD(S, F) \
extern "C" decltype(S::F) S##_get_##F(S *s) { return s->F; } \
extern "C" decltype(S::F) *S##_get_ptr_##F(S *s) { return &(s->F); } \
extern "C" void S##_set_##F(S *s, decltype(S::F) f) { s->F = f; }
#define STRUCT_FIELD_ARRAY(S, F) \
extern "C" std::remove_all_extents_t<decltype(S::F)> S##_get_##F(S *s, \
int i) { \
return s->F[i]; \
} \
extern "C" void S##_set_##F(S *s, int i, \
std::remove_all_extents_t<decltype(S::F)> f) { \
s->F[i] = f; \
}
using int8 = int8_t;
using int16 = int16_t;
using int32 = int32_t;
using int64 = int64_t;
using uint8 = uint8_t;
using uint16 = uint16_t;
using uint32 = uint32_t;
using uint64 = uint64_t;
using float32 = float;
using float64 = double;
using i8 = int8;
using i32 = int32;
using f32 = float32;
using f64 = float64;
// TODO: DRY. merge this with taichi_core
constexpr int taichi_max_num_indices = 4;
constexpr int taichi_max_num_args = 8;
constexpr int taichi_max_num_snodes = 1024;
using uint8 = uint8_t;
using Ptr = uint8 *;
using ContextArgType = long long;
extern "C" {
#if ARCH_cuda
void vprintf(Ptr format, Ptr arg);
#endif
i32 printf(const char *, ...);
#define DEFINE_UNARY_REAL_FUNC(F) \
f32 F##_f32(f32 x) { return std::F(x); } \
f64 F##_f64(f64 x) { return std::F(x); }
// sin and cos are already included in llvm intrinsics
DEFINE_UNARY_REAL_FUNC(exp)
DEFINE_UNARY_REAL_FUNC(log)
DEFINE_UNARY_REAL_FUNC(tan)
DEFINE_UNARY_REAL_FUNC(tanh)
DEFINE_UNARY_REAL_FUNC(abs)
int abs_i32(int a) {
if (a > 0) {
return a;
} else {
return -a;
}
}
int max_i32(int a, int b) { return a > b ? a : b; }
int min_i32(int a, int b) { return a < b ? a : b; }
int32 logic_not_i32(int32 a) { return !a; }
float32 sgn_f32(float32 a) {
float32 b;
if (a > 0)
b = 1;
else if (a < 0)
b = -1;
else
b = 0;
return b;
}
float64 sgn_f64(float64 a) {
float32 b;
if (a > 0)
b = 1;
else if (a < 0)
b = -1;
else
b = 0;
return b;
}
f32 __nv_sgnf(f32 x) { return sgn_f32(x); }
f64 __nv_sgn(f64 x) { return sgn_f64(x); }
struct PhysicalCoordinates {
int val[taichi_max_num_indices];
};
STRUCT_FIELD_ARRAY(PhysicalCoordinates, val);
struct Context {
void *buffer;
ContextArgType args[taichi_max_num_args];
void *leaves;
int num_leaves;
void *cpu_profiler;
Ptr runtime;
};
STRUCT_FIELD_ARRAY(Context, args);
STRUCT_FIELD(Context, runtime);
STRUCT_FIELD(Context, buffer);
#include "atomic.h"
// These structures are accessible by both the LLVM backend and this C++ runtime
// file here (for building complex runtime functions in C++)
// These structs contain some "template parameters"
// Common Attributes
struct StructMeta {
int snode_id;
std::size_t element_size;
int max_num_elements;
Ptr (*lookup_element)(Ptr, Ptr, int i);
Ptr (*from_parent_element)(Ptr);
bool (*is_active)(Ptr, Ptr, int i);
int (*get_num_elements)(Ptr, Ptr);
void (*refine_coordinates)(PhysicalCoordinates *inp_coord,
PhysicalCoordinates *refined_coord, int index);
Context *context;
};
STRUCT_FIELD(StructMeta, snode_id)
STRUCT_FIELD(StructMeta, element_size)
STRUCT_FIELD(StructMeta, max_num_elements)
STRUCT_FIELD(StructMeta, get_num_elements);
STRUCT_FIELD(StructMeta, lookup_element);
STRUCT_FIELD(StructMeta, from_parent_element);
STRUCT_FIELD(StructMeta, refine_coordinates);
STRUCT_FIELD(StructMeta, is_active);
STRUCT_FIELD(StructMeta, context);
void *taichi_allocate_aligned(std::size_t size, int alignment);
void *taichi_allocate(std::size_t size) {
return taichi_allocate_aligned(size, 1);
}
void ___stubs___() {
printf("");
#if ARCH_cuda
vprintf(nullptr, nullptr);
#endif
taichi_allocate(1);
taichi_allocate_aligned(1, 1);
}
struct Element {
uint8 *element;
int loop_bounds[2];
PhysicalCoordinates pcoord;
};
STRUCT_FIELD(Element, element);
STRUCT_FIELD(Element, pcoord);
STRUCT_FIELD_ARRAY(Element, loop_bounds);
struct ElementList {
Element *elements;
int head;
int tail;
};
void ElementList_initialize(ElementList *element_list) {
element_list->elements = (Element *)taichi_allocate(1024 * 1024 * 1024);
element_list->tail = 0;
}
void ElementList_insert(ElementList *element_list, Element *element) {
element_list->elements[element_list->tail] = *element;
element_list->tail++;
}
void ElementList_clear(ElementList *element_list) { element_list->tail = 0; }
struct NodeAllocator {
Ptr pool;
std::size_t node_size;
int tail;
};
void NodeAllocator_initialize(NodeAllocator *node_allocator,
std::size_t node_size) {
node_allocator->pool = (Ptr)taichi_allocate_aligned(1024 * 1024 * 1024, 4096);
node_allocator->node_size = node_size;
node_allocator->tail = 0;
}
Ptr NodeAllocator_allocate(NodeAllocator *node_allocator) {
int p = atomic_add_i32(&node_allocator->tail, 1);
return node_allocator->pool + node_allocator->node_size * p;
}
// Is "runtime" a correct name, even if it is created after the data layout is
// materialized?
struct Runtime {
ElementList *element_lists[taichi_max_num_snodes];
NodeAllocator *node_allocators[taichi_max_num_snodes];
Ptr ambient_elements[taichi_max_num_snodes];
};
STRUCT_FIELD_ARRAY(Runtime, element_lists);
STRUCT_FIELD_ARRAY(Runtime, node_allocators);
Ptr Runtime_initialize(Runtime **runtime_ptr, int num_snodes,
uint64_t root_size, int root_id) {
*runtime_ptr = (Runtime *)taichi_allocate(sizeof(Runtime));
Runtime *runtime = *runtime_ptr;
printf("Initializing runtime with %d elements\n", num_snodes);
for (int i = 0; i < num_snodes; i++) {
runtime->element_lists[i] =
(ElementList *)taichi_allocate(sizeof(ElementList));
ElementList_initialize(runtime->element_lists[i]);
runtime->node_allocators[i] =
(NodeAllocator *)taichi_allocate(sizeof(NodeAllocator));
}
// Assuming num_snodes - 1 is the root
auto root_ptr = taichi_allocate_aligned(root_size, 4096);
Element elem;
elem.loop_bounds[0] = 0;
elem.loop_bounds[1] = 1;
elem.element = (Ptr)root_ptr;
for (int i = 0; i < taichi_max_num_indices; i++) {
elem.pcoord.val[i] = 0;
}
ElementList_insert(runtime->element_lists[root_id], &elem);
printf("Runtime initialized.\n");
return (Ptr)root_ptr;
}
void Runtime_allocate_ambient(Runtime *runtime, int snode_id) {
runtime->ambient_elements[snode_id] =
NodeAllocator_allocate(runtime->node_allocators[snode_id]);
}
// "Element", "component" are different concepts
// ultimately all function calls here will be inlined
void element_listgen(Runtime *runtime, StructMeta *parent, StructMeta *child) {
auto parent_list = runtime->element_lists[parent->snode_id];
int num_parent_elements = parent_list->tail;
auto child_list = runtime->element_lists[child->snode_id];
child_list->head = 0;
child_list->tail = 0;
for (int i = 0; i < num_parent_elements; i++) {
auto element = parent_list->elements[i];
auto ch_component = child->from_parent_element(element.element);
int ch_num_elements = child->get_num_elements((Ptr)child, ch_component);
for (int j = 0; j < ch_num_elements; j++) {
if (child->is_active((Ptr)child, ch_component, j)) {
auto ch_element = child->lookup_element((Ptr)child, element.element, j);
Element elem;
elem.element = ch_element;
elem.loop_bounds[0] = 0;
elem.loop_bounds[1] = child->get_num_elements((Ptr)child, ch_element);
PhysicalCoordinates refined_coord;
child->refine_coordinates(&element.pcoord, &refined_coord, j);
elem.pcoord = refined_coord;
ElementList_insert(child_list, &elem);
}
}
}
}
int32 thread_idx() { return 0; }
int32 block_idx() { return 0; }
int32 block_dim() { return 0; }
int32 grid_dim() { return 0; }
void block_barrier() {}
void for_each_block(Context *context, int snode_id, int element_size,
int element_split,
void (*task)(Context *, Element *, int, int)) {
auto list = ((Runtime *)context->runtime)->element_lists[snode_id];
auto list_tail = list->tail;
#if ARCH_cuda
int i = block_idx();
const auto part_size = element_size / element_split;
while (true) {
int element_id = i / element_split;
if (element_id >= list_tail)
break;
auto part_id = i % element_split;
auto lower = part_size * part_id;
auto upper = part_size * (part_id + 1);
task(context, &list->elements[element_id], lower, upper);
i += grid_dim();
}
#else
for (int i = 0; i < list_tail; i++) {
task(context, &list->elements[i], 0, element_size);
}
#endif
}
#include "node_dense.h"
#include "node_pointer.h"
#include "node_root.h"
}
#endif
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "AuthManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
time_t AuthManager::_time_out;
const char * AuthManager::auth_driver_name = "auth_exe";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * authm_action_loop(void *arg)
{
AuthManager * authm;
if ( arg == 0 )
{
return 0;
}
authm = static_cast<AuthManager *>(arg);
NebulaLog::log("AuM",Log::INFO,"Authorization Manager started.");
authm->am.loop(authm->timer_period,0);
NebulaLog::log("AuM",Log::INFO,"Authorization Manager stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int AuthManager::start()
{
int rc;
pthread_attr_t pattr;
rc = MadManager::start();
if ( rc != 0 )
{
return -1;
}
NebulaLog::log("AuM",Log::INFO,"Starting Auth Manager...");
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create(&authm_thread,&pattr,authm_action_loop,(void *) this);
return rc;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::trigger(Actions action, AuthRequest * request)
{
string aname;
switch (action)
{
case AUTHENTICATE:
aname = "AUTHENTICATE";
break;
case AUTHORIZE:
aname = "AUTHORIZE";
break;
case FINALIZE:
aname = ACTION_FINALIZE;
break;
default:
return;
}
am.trigger(aname,request);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::do_action(const string &action, void * arg)
{
AuthRequest * request;
request = static_cast<AuthRequest *>(arg);
if (action == "AUTHENTICATE" && request != 0)
{
authenticate_action(request);
}
else if (action == "AUTHORIZE" && request != 0)
{
authorize_action(request);
}
else if (action == ACTION_TIMER)
{
timer_action();
}
else if (action == ACTION_FINALIZE)
{
NebulaLog::log("AuM",Log::INFO,"Stopping Authorization Manager...");
MadManager::stop();
}
else
{
ostringstream oss;
oss << "Unknown action name: " << action;
NebulaLog::log("AuM", Log::ERROR, oss);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::authenticate_action(AuthRequest * ar)
{
const AuthManagerDriver * authm_md;
// ------------------------------------------------------------------------
// Get the driver
// ------------------------------------------------------------------------
authm_md = get();
if (authm_md == 0)
{
goto error_driver;
}
// ------------------------------------------------------------------------
// Queue the request
// ------------------------------------------------------------------------
ar->id = add_request(ar);
// ------------------------------------------------------------------------
// Make the request to the driver
// ---- --------------------------------------------------------------------
authm_md->authenticate(ar->id,
ar->uid,
ar->username,
ar->password,
ar->session);
return;
error_driver:
ar->result = false;
ar->message = "Could not find Authorization driver";
ar->notify();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::authorize_action(AuthRequest * ar)
{
const AuthManagerDriver * authm_md;
string auths;
// ------------------------------------------------------------------------
// Get the driver
// ------------------------------------------------------------------------
authm_md = get();
if (authm_md == 0)
{
goto error_driver;
}
// ------------------------------------------------------------------------
// Queue the request
// ------------------------------------------------------------------------
ar->id = add_request(ar);
// ------------------------------------------------------------------------
// Make the request to the driver
// ------------------------------------------------------------------------
auths = ar->get_auths();
authm_md->authorize(ar->id, ar->uid, auths);
return;
error_driver:
ar->result = false;
ar->message = "Could not find Authorization driver";
ar->notify();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::timer_action()
{
map<int,AuthRequest *>::iterator it;
time_t the_time = time(0);
lock();
for (it=auth_requests.begin();it!=auth_requests.end();it++)
{
if (the_time > it->second->time_out)
{
AuthRequest * ar = it->second;
auth_requests.erase(it);
ar->result = false;
ar->timeout = true;
ar->message.clear();
ar->notify();
}
}
unlock();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AuthManager::add_request(AuthRequest *ar)
{
static int auth_id = 0;
int id;
lock();
id = auth_id++;
auth_requests.insert(auth_requests.end(),make_pair(id,ar));
unlock();
return id;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
AuthRequest * AuthManager::get_request(int id)
{
AuthRequest * ar = 0;
map<int,AuthRequest *>::iterator it;
ostringstream oss;
lock();
it=auth_requests.find(id);
if ( it != auth_requests.end())
{
ar = it->second;
auth_requests.erase(it);
}
unlock();
return ar;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::notify_request(int auth_id,bool result,const string& message)
{
AuthRequest * ar;
ar = get_request(auth_id);
if ( ar == 0 )
{
return;
}
ar->result = result;
ar->message= message;
ar->notify();
}
/* ************************************************************************** */
/* MAD Loading */
/* ************************************************************************** */
void AuthManager::load_mads(int uid)
{
ostringstream oss;
const VectorAttribute * vattr;
int rc;
string name;
AuthManagerDriver * authm_driver = 0;
oss << "Loading Auth. Manager driver.";
NebulaLog::log("AuM",Log::INFO,oss);
vattr = static_cast<const VectorAttribute *>(mad_conf[0]);
if ( vattr == 0 )
{
NebulaLog::log("AuM",Log::ERROR,"Failed to load Auth. Manager driver.");
return;
}
VectorAttribute auth_conf("AUTH_MAD",vattr->value());
auth_conf.replace("NAME",auth_driver_name);
authm_driver = new AuthManagerDriver(uid,auth_conf.value(),(uid!=0),this);
rc = add(authm_driver);
if ( rc == 0 )
{
oss.str("");
oss << "\tAuth Manager loaded";
NebulaLog::log("AuM",Log::INFO,oss);
}
}
<commit_msg>feature #203: Default message for timeouts<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "AuthManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
time_t AuthManager::_time_out;
const char * AuthManager::auth_driver_name = "auth_exe";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * authm_action_loop(void *arg)
{
AuthManager * authm;
if ( arg == 0 )
{
return 0;
}
authm = static_cast<AuthManager *>(arg);
NebulaLog::log("AuM",Log::INFO,"Authorization Manager started.");
authm->am.loop(authm->timer_period,0);
NebulaLog::log("AuM",Log::INFO,"Authorization Manager stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int AuthManager::start()
{
int rc;
pthread_attr_t pattr;
rc = MadManager::start();
if ( rc != 0 )
{
return -1;
}
NebulaLog::log("AuM",Log::INFO,"Starting Auth Manager...");
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create(&authm_thread,&pattr,authm_action_loop,(void *) this);
return rc;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::trigger(Actions action, AuthRequest * request)
{
string aname;
switch (action)
{
case AUTHENTICATE:
aname = "AUTHENTICATE";
break;
case AUTHORIZE:
aname = "AUTHORIZE";
break;
case FINALIZE:
aname = ACTION_FINALIZE;
break;
default:
return;
}
am.trigger(aname,request);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::do_action(const string &action, void * arg)
{
AuthRequest * request;
request = static_cast<AuthRequest *>(arg);
if (action == "AUTHENTICATE" && request != 0)
{
authenticate_action(request);
}
else if (action == "AUTHORIZE" && request != 0)
{
authorize_action(request);
}
else if (action == ACTION_TIMER)
{
timer_action();
}
else if (action == ACTION_FINALIZE)
{
NebulaLog::log("AuM",Log::INFO,"Stopping Authorization Manager...");
MadManager::stop();
}
else
{
ostringstream oss;
oss << "Unknown action name: " << action;
NebulaLog::log("AuM", Log::ERROR, oss);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::authenticate_action(AuthRequest * ar)
{
const AuthManagerDriver * authm_md;
// ------------------------------------------------------------------------
// Get the driver
// ------------------------------------------------------------------------
authm_md = get();
if (authm_md == 0)
{
goto error_driver;
}
// ------------------------------------------------------------------------
// Queue the request
// ------------------------------------------------------------------------
ar->id = add_request(ar);
// ------------------------------------------------------------------------
// Make the request to the driver
// ---- --------------------------------------------------------------------
authm_md->authenticate(ar->id,
ar->uid,
ar->username,
ar->password,
ar->session);
return;
error_driver:
ar->result = false;
ar->message = "Could not find Authorization driver";
ar->notify();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::authorize_action(AuthRequest * ar)
{
const AuthManagerDriver * authm_md;
string auths;
// ------------------------------------------------------------------------
// Get the driver
// ------------------------------------------------------------------------
authm_md = get();
if (authm_md == 0)
{
goto error_driver;
}
// ------------------------------------------------------------------------
// Queue the request
// ------------------------------------------------------------------------
ar->id = add_request(ar);
// ------------------------------------------------------------------------
// Make the request to the driver
// ------------------------------------------------------------------------
auths = ar->get_auths();
authm_md->authorize(ar->id, ar->uid, auths);
return;
error_driver:
ar->result = false;
ar->message = "Could not find Authorization driver";
ar->notify();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::timer_action()
{
map<int,AuthRequest *>::iterator it;
time_t the_time = time(0);
lock();
for (it=auth_requests.begin();it!=auth_requests.end();it++)
{
if (the_time > it->second->time_out)
{
AuthRequest * ar = it->second;
auth_requests.erase(it);
ar->result = false;
ar->timeout = true;
ar->message = "Auth request timeout";
ar->notify();
}
}
unlock();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AuthManager::add_request(AuthRequest *ar)
{
static int auth_id = 0;
int id;
lock();
id = auth_id++;
auth_requests.insert(auth_requests.end(),make_pair(id,ar));
unlock();
return id;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
AuthRequest * AuthManager::get_request(int id)
{
AuthRequest * ar = 0;
map<int,AuthRequest *>::iterator it;
ostringstream oss;
lock();
it=auth_requests.find(id);
if ( it != auth_requests.end())
{
ar = it->second;
auth_requests.erase(it);
}
unlock();
return ar;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AuthManager::notify_request(int auth_id,bool result,const string& message)
{
AuthRequest * ar;
ar = get_request(auth_id);
if ( ar == 0 )
{
return;
}
ar->result = result;
ar->message= message;
ar->notify();
}
/* ************************************************************************** */
/* MAD Loading */
/* ************************************************************************** */
void AuthManager::load_mads(int uid)
{
ostringstream oss;
const VectorAttribute * vattr;
int rc;
string name;
AuthManagerDriver * authm_driver = 0;
oss << "Loading Auth. Manager driver.";
NebulaLog::log("AuM",Log::INFO,oss);
vattr = static_cast<const VectorAttribute *>(mad_conf[0]);
if ( vattr == 0 )
{
NebulaLog::log("AuM",Log::ERROR,"Failed to load Auth. Manager driver.");
return;
}
VectorAttribute auth_conf("AUTH_MAD",vattr->value());
auth_conf.replace("NAME",auth_driver_name);
authm_driver = new AuthManagerDriver(uid,auth_conf.value(),(uid!=0),this);
rc = add(authm_driver);
if ( rc == 0 )
{
oss.str("");
oss << "\tAuth Manager loaded";
NebulaLog::log("AuM",Log::INFO,oss);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <asyncio/common.hpp>
#include <deque>
#include <queue>
BEGIN_ASYNCIO_NAMESPACE;
template <class T> class ExtendedQueue : public std::queue<T> {
public:
template <class V> bool erase(V &&elem) {
for (auto i = this->c.begin(); i != this->c.end(); i++) {
if (*i == elem) {
this->c.erase(i);
return true;
}
}
return false;
}
};
END_ASYNCIO_NAMESPACE;<commit_msg>using a set to avoid O(N^2) complexity in UVAsyncTimerService::processTimer()<commit_after>#pragma once
#include <asyncio/common.hpp>
#include <deque>
#include <exception>
#include <queue>
#include <unordered_set>
BEGIN_ASYNCIO_NAMESPACE;
template <class T> class ExtendedQueue : public std::queue<T> {
public: // optimized me when needed
template <class V> bool erase(V &&elem) {
if (_set.erase(elem) == 0) {
return false;
}
for (auto i = this->c.begin(); i != this->c.end(); i++) {
if (*i == elem) {
this->c.erase(i);
break;
}
}
return true;
}
template <class V> void push(V &&v) {
auto pair = _set.insert(v);
if (pair.second) {
std::queue<T>::push(v);
} else {
throw std::logic_error("duplicate elements detected!");
}
}
void pop() {
_set.erase(this->front());
std::queue<T>::pop();
}
private:
std::unordered_set<T> _set;
};
END_ASYNCIO_NAMESPACE;<|endoftext|> |
<commit_before>#include <Io.h>
#include <Windows.h>
#include <Winbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <osg/Notify>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>
using namespace osg;
using namespace osgDB;
#define FILEUTILS_MAX_PATH_LENGTH 2048
char *PathDelimitor = ";";
static const char *s_default_file_path = ".;";
static const char *s_default_dso_path = "C:/Windows/System/;";
static char *s_filePath = ".;";
#define F_OK 4
static bool s_filePathInitialized = false;
void osgDB::initFilePath( void )
{
char *ptr;
if( (ptr = getenv( "OSGFILEPATH" )) )
{
notify(DEBUG_INFO) << "osgDB::Init("<<ptr<<")"<<std::endl;
setFilePath( ptr );
}
else
{
notify(DEBUG_INFO) << "osgDB::Init(NULL)"<<std::endl;
}
s_filePathInitialized = true;
}
void osgDB::setFilePath( const char *_path )
{
char buff[FILEUTILS_MAX_PATH_LENGTH];
notify(DEBUG_INFO) << "In osgDB::setFilePath("<<_path<<")"<<std::endl;
buff[0] = 0;
if( s_filePath != s_default_file_path )
{
strcpy( buff, s_filePath );
}
strcat( buff, PathDelimitor );
strcat( buff, _path );
s_filePath = strdup( buff );
s_filePathInitialized = true;
}
const char* osgDB::getFilePath()
{
return s_filePath;
}
char *osgDB::findFileInPath( const char *_file, const char * filePath )
{
char pathbuff[FILEUTILS_MAX_PATH_LENGTH];
char *tptr, *tmppath;
char *path = 0L;
notify(DEBUG_INFO) << "FindFileInPath() : trying " << _file << " ...\n";
if( access( _file, F_OK ) == 0 )
{
return strdup(_file);
}
tptr = strdup( filePath );
tmppath = strtok( tptr, PathDelimitor );
do
{
sprintf( pathbuff, "%s/%s", tmppath, _file );
notify(DEBUG_INFO) << "FindFileInPath() : trying " << pathbuff << " ...\n";
if( access( pathbuff, F_OK ) == 0 ) break;
} while( (tmppath = strtok( 0, PathDelimitor )) );
if( tmppath != (char *)0L )
path = strdup( pathbuff );
::free(tptr);
if (path) notify( DEBUG_INFO ) << "FindFileInPath() : returning " << path << std::endl;
else notify( DEBUG_INFO ) << "FindFileInPath() : returning NULL" << std::endl;
return path;
}
char *osgDB::findFile( const char *file )
{
if (!file) return NULL;
if (!s_filePathInitialized) initFilePath();
char* newFileName = findFileInPath( file, s_filePath );
if (newFileName) return newFileName;
// need to check here to see if file has a path on it.
// now strip the file of an previous path if one exists.
std::string simpleFileName = getSimpleFileName(file);
newFileName = findFileInPath( simpleFileName.c_str(), s_filePath );
return newFileName;
}
/*
Order of precedence for
Under UNIX.
./
OSG_LD_LIBRARY_PATH
s_default_dso_path
LD_LIBRARY*_PATH
Under Windows
./
OSG_LD_LIBRARY_PATH
s_default_dso_path
PATH
*/
char *osgDB::findDSO( const char *name )
{
if ((ptr = getenv( "PATH" )))
{
notify(DEBUG_INFO) << "PATH = "<<ptr<<std::endl;
strcat( path, PathDelimitor );
strcat( path, ptr );
}
// check existance of dso assembled direct paths.
char* fileFound = NULL;
fileFound = findFileInPath( name , path );
if (fileFound) return fileFound;
// failed with direct paths,
// now try prepending the filename with "osgPlugins/"
char* prependosgPlugins = osgNew char[strlen(name)+12];
strcpy(prependosgPlugins,"osgPlugins/");
strcat(prependosgPlugins,name);
fileFound = findFileInPath( prependosgPlugins , path );
osgDelete [] prependosgPlugins;
return fileFound;
}
std::string osgDB::findFileInDirectory(const std::string& fileName,const std::string& dirName,bool caseInsensitive)
{
bool needFollowingBackslash = false;
bool needDirectoryName = true;
osgDB::DirectoryContents dc;
if (dirName.empty())
{
dc = osgDB::getDirectoryContents(".");
needFollowingBackslash = false;
needDirectoryName = false;
}
else if (dirName=="." || dirName=="./" || dirName==".\\")
{
dc = osgDB::getDirectoryContents(".");
needFollowingBackslash = false;
needDirectoryName = false;
}
else
{
dc = osgDB::getDirectoryContents(dirName);
char lastChar = dirName[dirName.size()-1];
if (lastChar=='/') needFollowingBackslash = false;
else if (lastChar=='\\') needFollowingBackslash = false;
else needFollowingBackslash = true;
needDirectoryName = true;
}
for(osgDB::DirectoryContents::iterator itr=dc.begin();
itr!=dc.end();
++itr)
{
if ((caseInsensitive && osgDB::equalCaseInsensitive(fileName,*itr)) ||
(fileName==*itr))
{
if (!needDirectoryName) return *itr;
else if (needFollowingBackslash) return dirName+'/'+*itr;
else return dirName+*itr;
}
}
return "";
}
#include <io.h>
#include <direct.h>
osgDB::DirectoryContents osgDB::getDirectoryContents(const std::string& dirName)
{
osgDB::DirectoryContents contents;
WIN32_FIND_DATA data;
HANDLE handle = FindFirstFile((dirName + "\\*").c_str(), &data);
if (handle != INVALID_HANDLE_VALUE)
{
do
{
contents.push_back(data.cFileName);
}
while (FindNextFile(handle, &data) != 0);
FindClose(handle);
}
return contents;
}
<commit_msg>Fixed compilation problem associated wirh moving FileUtils source out into seperate files.<commit_after>#include <Io.h>
#include <Windows.h>
#include <Winbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <osg/Notify>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>
using namespace osg;
using namespace osgDB;
#define FILEUTILS_MAX_PATH_LENGTH 2048
char *PathDelimitor = ";";
static const char *s_default_file_path = ".;";
static const char *s_default_dso_path = "C:/Windows/System/;";
static char *s_filePath = ".;";
#define F_OK 4
static bool s_filePathInitialized = false;
void osgDB::initFilePath( void )
{
char *ptr;
if( (ptr = getenv( "OSGFILEPATH" )) )
{
notify(DEBUG_INFO) << "osgDB::Init("<<ptr<<")"<<std::endl;
setFilePath( ptr );
}
else
{
notify(DEBUG_INFO) << "osgDB::Init(NULL)"<<std::endl;
}
s_filePathInitialized = true;
}
void osgDB::setFilePath( const char *_path )
{
char buff[FILEUTILS_MAX_PATH_LENGTH];
notify(DEBUG_INFO) << "In osgDB::setFilePath("<<_path<<")"<<std::endl;
buff[0] = 0;
if( s_filePath != s_default_file_path )
{
strcpy( buff, s_filePath );
}
strcat( buff, PathDelimitor );
strcat( buff, _path );
s_filePath = strdup( buff );
s_filePathInitialized = true;
}
const char* osgDB::getFilePath()
{
return s_filePath;
}
char *osgDB::findFileInPath( const char *_file, const char * filePath )
{
char pathbuff[FILEUTILS_MAX_PATH_LENGTH];
char *tptr, *tmppath;
char *path = 0L;
notify(DEBUG_INFO) << "FindFileInPath() : trying " << _file << " ...\n";
if( access( _file, F_OK ) == 0 )
{
return strdup(_file);
}
tptr = strdup( filePath );
tmppath = strtok( tptr, PathDelimitor );
do
{
sprintf( pathbuff, "%s/%s", tmppath, _file );
notify(DEBUG_INFO) << "FindFileInPath() : trying " << pathbuff << " ...\n";
if( access( pathbuff, F_OK ) == 0 ) break;
} while( (tmppath = strtok( 0, PathDelimitor )) );
if( tmppath != (char *)0L )
path = strdup( pathbuff );
::free(tptr);
if (path) notify( DEBUG_INFO ) << "FindFileInPath() : returning " << path << std::endl;
else notify( DEBUG_INFO ) << "FindFileInPath() : returning NULL" << std::endl;
return path;
}
char *osgDB::findFile( const char *file )
{
if (!file) return NULL;
if (!s_filePathInitialized) initFilePath();
char* newFileName = findFileInPath( file, s_filePath );
if (newFileName) return newFileName;
// need to check here to see if file has a path on it.
// now strip the file of an previous path if one exists.
std::string simpleFileName = getSimpleFileName(file);
newFileName = findFileInPath( simpleFileName.c_str(), s_filePath );
return newFileName;
}
/*
Order of precedence for
Under UNIX.
./
OSG_LD_LIBRARY_PATH
s_default_dso_path
LD_LIBRARY*_PATH
Under Windows
./
OSG_LD_LIBRARY_PATH
s_default_dso_path
PATH
*/
char *osgDB::findDSO( const char *name )
{
char path[FILEUTILS_MAX_PATH_LENGTH];
char *ptr;
strcpy( path, "./" );
if((ptr = getenv( "OSG_LD_LIBRARY_PATH" )))
{
strcat( path, PathDelimitor );
strcat( path, ptr );
}
strcat( path, PathDelimitor );
strcat( path, s_default_dso_path );
if ((ptr = getenv( "PATH" )))
{
notify(DEBUG_INFO) << "PATH = "<<ptr<<std::endl;
strcat( path, PathDelimitor );
strcat( path, ptr );
}
// check existance of dso assembled direct paths.
char* fileFound = NULL;
fileFound = findFileInPath( name , path );
if (fileFound) return fileFound;
// failed with direct paths,
// now try prepending the filename with "osgPlugins/"
char* prependosgPlugins = osgNew char[strlen(name)+12];
strcpy(prependosgPlugins,"osgPlugins/");
strcat(prependosgPlugins,name);
fileFound = findFileInPath( prependosgPlugins , path );
osgDelete [] prependosgPlugins;
return fileFound;
}
std::string osgDB::findFileInDirectory(const std::string& fileName,const std::string& dirName,bool caseInsensitive)
{
bool needFollowingBackslash = false;
bool needDirectoryName = true;
osgDB::DirectoryContents dc;
if (dirName.empty())
{
dc = osgDB::getDirectoryContents(".");
needFollowingBackslash = false;
needDirectoryName = false;
}
else if (dirName=="." || dirName=="./" || dirName==".\\")
{
dc = osgDB::getDirectoryContents(".");
needFollowingBackslash = false;
needDirectoryName = false;
}
else
{
dc = osgDB::getDirectoryContents(dirName);
char lastChar = dirName[dirName.size()-1];
if (lastChar=='/') needFollowingBackslash = false;
else if (lastChar=='\\') needFollowingBackslash = false;
else needFollowingBackslash = true;
needDirectoryName = true;
}
for(osgDB::DirectoryContents::iterator itr=dc.begin();
itr!=dc.end();
++itr)
{
if ((caseInsensitive && osgDB::equalCaseInsensitive(fileName,*itr)) ||
(fileName==*itr))
{
if (!needDirectoryName) return *itr;
else if (needFollowingBackslash) return dirName+'/'+*itr;
else return dirName+*itr;
}
}
return "";
}
#include <io.h>
#include <direct.h>
osgDB::DirectoryContents osgDB::getDirectoryContents(const std::string& dirName)
{
osgDB::DirectoryContents contents;
WIN32_FIND_DATA data;
HANDLE handle = FindFirstFile((dirName + "\\*").c_str(), &data);
if (handle != INVALID_HANDLE_VALUE)
{
do
{
contents.push_back(data.cFileName);
}
while (FindNextFile(handle, &data) != 0);
FindClose(handle);
}
return contents;
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osgShadow/ShadowTexture>
#include <osgShadow/ShadowedScene>
#include <osg/Notify>
#include <osg/io_utils>
using namespace osgShadow;
class CameraCullCallback : public osg::NodeCallback
{
public:
CameraCullCallback(ShadowTexture* st):
_shadowTexture(st)
{
}
virtual void operator()(osg::Node*, osg::NodeVisitor* nv)
{
unsigned int traversalMask = nv->getTraversalMask();
nv->setTraversalMask( traversalMask &
_shadowTexture->getShadowedScene()->getCastsShadowTraversalMask() );
_shadowTexture->getShadowedScene()->osg::Group::traverse(*nv);
nv->setTraversalMask( traversalMask );
}
protected:
ShadowTexture* _shadowTexture;
};
ShadowTexture::ShadowTexture():
_textureUnit(1)
{
osg::notify(osg::NOTICE)<<"Warning: osgShadow::ShadowTexture technique is in development."<<std::endl;
}
ShadowTexture::ShadowTexture(const ShadowTexture& copy, const osg::CopyOp& copyop):
ShadowTechnique(copy,copyop),
_textureUnit(copy._textureUnit)
{
}
void ShadowTexture::init()
{
if (!_shadowedScene) return;
unsigned int tex_width = 512;
unsigned int tex_height = 512;
_texture = new osg::Texture2D;
_texture->setTextureSize(tex_width, tex_height);
_texture->setInternalFormat(GL_RGB);
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
_texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
// set up the render to texture camera.
{
// create the camera
_camera = new osg::Camera;
_camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
_camera->setCullCallback(new CameraCullCallback(this));
// set viewport
_camera->setViewport(0,0,tex_width,tex_height);
// set the camera to render before the main camera.
_camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer object where supported.
//_camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
_camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW);
// attach the texture and use it as the color buffer.
_camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());
_material = new osg::Material;
_material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
_material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
_material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
_material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
osg::StateSet* stateset = _camera->getOrCreateStateSet();
stateset->setAttribute(_material.get(),osg::StateAttribute::OVERRIDE);
}
{
_stateset = new osg::StateSet;
_stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
}
_dirty = false;
}
void ShadowTexture::update(osg::NodeVisitor& nv)
{
_shadowedScene->osg::Group::traverse(nv);
}
void ShadowTexture::cull(osgUtil::CullVisitor& cv)
{
// record the traversal mask on entry so we can reapply it later.
unsigned int traversalMask = cv.getTraversalMask();
osgUtil::RenderStage* orig_rs = cv.getRenderStage();
// do traversal of shadow casting scene which does not need to be decorated by the shadow texture
{
cv.setTraversalMask( traversalMask &
getShadowedScene()->getCastsShadowTraversalMask() );
_shadowedScene->osg::Group::traverse(cv);
}
// do traversal of shadow recieving scene which does need to be decorated by the shadow texture
{
cv.pushStateSet(_stateset.get());
cv.setTraversalMask( traversalMask &
getShadowedScene()->getRecievesShadowTraversalMask() );
_shadowedScene->osg::Group::traverse(cv);
cv.popStateSet();
}
// need to compute view frustum for RTT camera.
// 1) get the light position
// 2) get the center and extents of the view frustum
const osg::Light* selectLight = 0;
osg::Vec4 lightpos;
osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList();
for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin();
itr != aml.end();
++itr)
{
const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
if (light)
{
osg::RefMatrix* matrix = itr->second.get();
if (matrix) lightpos = light->getPosition() * (*matrix);
else lightpos = light->getPosition();
selectLight = light;
}
}
if (selectLight)
{
osg::notify(osg::NOTICE)<<"Selected light "<<lightpos<<std::endl;
// do RTT camera traversal
_camera->accept(cv);
}
// reapply the original traversal mask
cv.setTraversalMask( traversalMask );
}
void ShadowTexture::cleanSceneGraph()
{
}
<commit_msg>Added basic set up of the RTT camera.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osgShadow/ShadowTexture>
#include <osgShadow/ShadowedScene>
#include <osg/Notify>
#include <osg/ComputeBoundsVisitor>
#include <osg/io_utils>
using namespace osgShadow;
class CameraCullCallback : public osg::NodeCallback
{
public:
CameraCullCallback(ShadowTexture* st):
_shadowTexture(st)
{
}
virtual void operator()(osg::Node*, osg::NodeVisitor* nv)
{
_shadowTexture->getShadowedScene()->osg::Group::traverse(*nv);
}
protected:
ShadowTexture* _shadowTexture;
};
ShadowTexture::ShadowTexture():
_textureUnit(1)
{
osg::notify(osg::NOTICE)<<"Warning: osgShadow::ShadowTexture technique is in development."<<std::endl;
}
ShadowTexture::ShadowTexture(const ShadowTexture& copy, const osg::CopyOp& copyop):
ShadowTechnique(copy,copyop),
_textureUnit(copy._textureUnit)
{
}
void ShadowTexture::init()
{
if (!_shadowedScene) return;
unsigned int tex_width = 512;
unsigned int tex_height = 512;
_texture = new osg::Texture2D;
_texture->setTextureSize(tex_width, tex_height);
_texture->setInternalFormat(GL_RGB);
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
_texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
// set up the render to texture camera.
{
// create the camera
_camera = new osg::Camera;
_camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
_camera->setCullCallback(new CameraCullCallback(this));
// set viewport
_camera->setViewport(0,0,tex_width,tex_height);
// set the camera to render before the main camera.
_camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer object where supported.
//_camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
_camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW);
// attach the texture and use it as the color buffer.
_camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());
_material = new osg::Material;
_material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
_material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
_material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
_material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
osg::StateSet* stateset = _camera->getOrCreateStateSet();
stateset->setAttribute(_material.get(),osg::StateAttribute::OVERRIDE);
}
{
_stateset = new osg::StateSet;
_stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
_stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
_texgen = new osg::TexGen;
}
_dirty = false;
}
void ShadowTexture::update(osg::NodeVisitor& nv)
{
_shadowedScene->osg::Group::traverse(nv);
}
void ShadowTexture::cull(osgUtil::CullVisitor& cv)
{
// record the traversal mask on entry so we can reapply it later.
unsigned int traversalMask = cv.getTraversalMask();
osgUtil::RenderStage* orig_rs = cv.getRenderStage();
// do traversal of shadow casting scene which does not need to be decorated by the shadow texture
{
cv.setTraversalMask( traversalMask &
getShadowedScene()->getCastsShadowTraversalMask() );
_shadowedScene->osg::Group::traverse(cv);
}
// do traversal of shadow recieving scene which does need to be decorated by the shadow texture
{
cv.pushStateSet(_stateset.get());
cv.setTraversalMask( traversalMask &
getShadowedScene()->getRecievesShadowTraversalMask() );
_shadowedScene->osg::Group::traverse(cv);
cv.popStateSet();
}
// need to compute view frustum for RTT camera.
// 1) get the light position
// 2) get the center and extents of the view frustum
const osg::Light* selectLight = 0;
osg::Vec4 lightpos;
osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList();
for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin();
itr != aml.end();
++itr)
{
const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
if (light)
{
osg::RefMatrix* matrix = itr->second.get();
if (matrix) lightpos = light->getPosition() * (*matrix);
else lightpos = light->getPosition();
selectLight = light;
}
}
osg::Matrix eyeToWorld;
eyeToWorld.invert(cv.getModelViewMatrix());
lightpos = lightpos * eyeToWorld;
if (selectLight)
{
// get the bounds of the model.
osg::ComputeBoundsVisitor cbbv(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);
cbbv.setTraversalMask(getShadowedScene()->getCastsShadowTraversalMask());
_shadowedScene->osg::Group::traverse(cbbv);
osg::BoundingBox bb = cbbv.getBoundingBox();
if (lightpos[3]!=0.0)
{
osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z());
float centerDistance = (position-bb.center()).length();
float znear = centerDistance-bb.radius();
float zfar = centerDistance+bb.radius();
float zNearRatio = 0.001f;
if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
float top = (bb.radius()/centerDistance)*znear;
float right = top;
_camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
_camera->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar);
_camera->setViewMatrixAsLookAt(position,bb.center(),osg::Vec3(0.0f,1.0f,0.0f));
// compute the matrix which takes a vertex from local coords into tex coords
// will use this later to specify osg::TexGen..
osg::Matrix MVPT = _camera->getViewMatrix() *
_camera->getProjectionMatrix() *
osg::Matrix::translate(1.0,1.0,1.0) *
osg::Matrix::scale(0.5f,0.5f,0.5f);
_texgen->setMode(osg::TexGen::EYE_LINEAR);
_texgen->setPlanesFromMatrix(MVPT);
}
cv.setTraversalMask( traversalMask &
getShadowedScene()->getCastsShadowTraversalMask() );
// do RTT camera traversal
_camera->accept(cv);
}
// reapply the original traversal mask
cv.setTraversalMask( traversalMask );
}
void ShadowTexture::cleanSceneGraph()
{
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include "RouterPredicates.h"
#include "RouterTransforms.h"
#include "ImagingRouter.h"
#include "VRPNAnalogRouter.h"
#include "VRPNButtonRouter.h"
#include "VRPNTrackerRouter.h"
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Transform/JSONTransformVisitor.h>
#include <osvr/Transform/ChangeOfBasis.h>
#include <osvr/Common/CreateDevice.h>
#include <osvr/Common/SystemComponent.h>
#include <osvr/Common/RoutingKeys.h>
#include <osvr/Client/display_json.h>
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
// Standard includes
#include <cstring>
namespace osvr {
namespace client {
RouterEntry::~RouterEntry() {}
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OSVR_ClientContextObject(appId), m_host(host) {
std::string sysDeviceName =
std::string(common::SystemComponent::deviceName()) + "@" + m_host;
/// Get connection, forcing a re-open for improved thread-safety.
m_conn =
vrpn_get_connection_by_name(sysDeviceName.c_str(), nullptr, nullptr,
nullptr, nullptr, nullptr, true);
m_conn->removeReference(); // Remove extra reference.
/// Create the system client device.
m_systemDevice = common::createClientDevice(sysDeviceName, m_conn);
m_systemComponent =
m_systemDevice->addComponent(common::SystemComponent::create());
m_systemComponent->registerRoutesHandler(
&VRPNContext::m_handleRoutingMessage, static_cast<void *>(this));
setParameter("/display",
std::string(display_json, sizeof(display_json)));
}
VRPNContext::~VRPNContext() {}
int VRPNContext::m_handleRoutingMessage(void *userdata,
vrpn_HANDLERPARAM p) {
VRPNContext *self = static_cast<VRPNContext *>(userdata);
common::RouteContainer newDirectives(
std::string(p.buffer, p.payload_len));
self->m_replaceRoutes(newDirectives);
return 0;
}
void
VRPNContext::m_replaceRoutes(common::RouteContainer const &newDirectives) {
OSVR_DEV_VERBOSE("Replacing routing directives: had "
<< m_routingDirectives.size() << ", received "
<< newDirectives.size());
m_routers.clear();
m_routingDirectives = newDirectives;
Json::Reader reader;
for (auto const &routeString : newDirectives.getRouteList()) {
Json::Value route;
if (!reader.parse(routeString, route)) {
OSVR_DEV_VERBOSE("Got a bad route!");
continue;
}
std::string dest =
route[common::routing_keys::destination()].asString();
Json::Value src = route[common::routing_keys::source()];
if (src.isString()) {
m_handleStringRouteEntry(dest, src.asString());
} else {
m_handleTrackerRouteEntry(dest, src);
}
}
#define OSVR_HYDRA_BUTTON(SENSOR, NAME) \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SensorPredicate(SENSOR)); \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SensorPredicate(SENSOR + 8))
OSVR_HYDRA_BUTTON(0, "middle");
OSVR_HYDRA_BUTTON(1, "1");
OSVR_HYDRA_BUTTON(2, "2");
OSVR_HYDRA_BUTTON(3, "3");
OSVR_HYDRA_BUTTON(4, "4");
OSVR_HYDRA_BUTTON(5, "bumper");
OSVR_HYDRA_BUTTON(6, "joystick/button");
#undef OSVR_HYDRA_BUTTON
#define OSVR_HYDRA_ANALOG(SENSOR, NAME) \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SENSOR); \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SENSOR + 3)
OSVR_HYDRA_ANALOG(0, "joystick/x");
OSVR_HYDRA_ANALOG(1, "joystick/y");
OSVR_HYDRA_ANALOG(2, "trigger");
#undef OSVR_HYDRA_ANALOG
OSVR_DEV_VERBOSE("Now have " << m_routers.size() << " routes.");
}
static const char SENSOR_KEY[] = "sensor";
static const char TRACKER_KEY[] = "tracker";
void VRPNContext::m_handleTrackerRouteEntry(std::string const &dest,
Json::Value src) {
boost::optional<int> sensor;
transform::JSONTransformVisitor xformParse(src);
Json::Value srcLeaf = xformParse.getLeaf();
std::string srcDevice = srcLeaf[TRACKER_KEY].asString();
// OSVR_DEV_VERBOSE("Source device: " << srcDevice);
srcDevice.erase(begin(srcDevice)); // remove leading slash
if (srcLeaf.isMember(SENSOR_KEY)) {
sensor = srcLeaf[SENSOR_KEY].asInt();
}
m_addTrackerRouter(srcDevice.c_str(), dest.c_str(), sensor,
xformParse.getTransform());
}
static const char IMAGING_NAME[] = "imaging";
void VRPNContext::m_handleStringRouteEntry(std::string const &dest,
std::string src) {
std::vector<std::string> components;
/// @todo replace literal with getPathSeparator
boost::algorithm::split(components, src,
boost::algorithm::is_any_of("/"));
if (!components.empty()) {
if (components.front().empty()) {
components.erase(begin(components));
}
}
if (components.size() < 4) {
OSVR_DEV_VERBOSE("Could not parse source for route, skipping: "
<< src << " => " << dest);
return;
}
std::string deviceName =
components[0] + "/" + components[1] + "@" + m_host;
std::reverse(begin(components), end(components));
components.pop_back();
components.pop_back();
std::string interfaceType = components.back();
components.pop_back();
if (interfaceType == IMAGING_NAME) {
OSVR_DEV_VERBOSE("Adding imaging route for " << dest);
m_routers.emplace_back(
new ImagingRouter(this, m_conn, deviceName, components, dest));
} else {
OSVR_DEV_VERBOSE(
"Could not handle route message for interface type "
<< interfaceType << ", skipping: " << src << " => " << dest);
}
}
void VRPNContext::m_sendRoute(std::string const &route) {
m_systemComponent->sendClientRouteUpdate(route);
}
void VRPNContext::m_update() {
// mainloop the VRPN connection.
m_conn->mainloop();
// Mainloop the system device
m_systemDevice->update();
// Process each of the routers.
for (auto const &p : m_routers) {
(*p)();
}
}
void VRPNContext::m_addAnalogRouter(const char *src, const char *dest,
int channel) {
OSVR_DEV_VERBOSE("Adding analog route for " << dest);
m_routers.emplace_back(
new VRPNAnalogRouter<SensorPredicate, NullTransform>(
this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest,
SensorPredicate(channel), NullTransform(), channel));
}
template <typename Predicate>
void VRPNContext::m_addButtonRouter(const char *src, const char *dest,
Predicate pred) {
OSVR_DEV_VERBOSE("Adding button route for " << dest);
m_routers.emplace_back(new VRPNButtonRouter<Predicate>(
this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest, pred));
}
void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
boost::optional<int> sensor,
transform::Transform const &xform) {
OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
std::string source(src);
if (std::string::npos != source.find('@')) {
// We found an @ - so this is a device we need a new connection for.
m_routers.emplace_back(
new VRPNTrackerRouter(this, nullptr, src, sensor, dest, xform));
} else {
// No @: assume to be at the same location as the context.
m_routers.emplace_back(new VRPNTrackerRouter(
this, m_conn.get(), (src + ("@" + m_host)).c_str(), sensor,
dest, xform));
}
}
} // namespace client
} // namespace osvr<commit_msg>Update after sending route.<commit_after>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include "RouterPredicates.h"
#include "RouterTransforms.h"
#include "ImagingRouter.h"
#include "VRPNAnalogRouter.h"
#include "VRPNButtonRouter.h"
#include "VRPNTrackerRouter.h"
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Transform/JSONTransformVisitor.h>
#include <osvr/Transform/ChangeOfBasis.h>
#include <osvr/Common/CreateDevice.h>
#include <osvr/Common/SystemComponent.h>
#include <osvr/Common/RoutingKeys.h>
#include <osvr/Client/display_json.h>
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
// Standard includes
#include <cstring>
namespace osvr {
namespace client {
RouterEntry::~RouterEntry() {}
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OSVR_ClientContextObject(appId), m_host(host) {
std::string sysDeviceName =
std::string(common::SystemComponent::deviceName()) + "@" + m_host;
/// Get connection, forcing a re-open for improved thread-safety.
m_conn =
vrpn_get_connection_by_name(sysDeviceName.c_str(), nullptr, nullptr,
nullptr, nullptr, nullptr, true);
m_conn->removeReference(); // Remove extra reference.
/// Create the system client device.
m_systemDevice = common::createClientDevice(sysDeviceName, m_conn);
m_systemComponent =
m_systemDevice->addComponent(common::SystemComponent::create());
m_systemComponent->registerRoutesHandler(
&VRPNContext::m_handleRoutingMessage, static_cast<void *>(this));
setParameter("/display",
std::string(display_json, sizeof(display_json)));
}
VRPNContext::~VRPNContext() {}
int VRPNContext::m_handleRoutingMessage(void *userdata,
vrpn_HANDLERPARAM p) {
VRPNContext *self = static_cast<VRPNContext *>(userdata);
common::RouteContainer newDirectives(
std::string(p.buffer, p.payload_len));
self->m_replaceRoutes(newDirectives);
return 0;
}
void
VRPNContext::m_replaceRoutes(common::RouteContainer const &newDirectives) {
OSVR_DEV_VERBOSE("Replacing routing directives: had "
<< m_routingDirectives.size() << ", received "
<< newDirectives.size());
m_routers.clear();
m_routingDirectives = newDirectives;
Json::Reader reader;
for (auto const &routeString : newDirectives.getRouteList()) {
Json::Value route;
if (!reader.parse(routeString, route)) {
OSVR_DEV_VERBOSE("Got a bad route!");
continue;
}
std::string dest =
route[common::routing_keys::destination()].asString();
Json::Value src = route[common::routing_keys::source()];
if (src.isString()) {
m_handleStringRouteEntry(dest, src.asString());
} else {
m_handleTrackerRouteEntry(dest, src);
}
}
#define OSVR_HYDRA_BUTTON(SENSOR, NAME) \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SensorPredicate(SENSOR)); \
m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SensorPredicate(SENSOR + 8))
OSVR_HYDRA_BUTTON(0, "middle");
OSVR_HYDRA_BUTTON(1, "1");
OSVR_HYDRA_BUTTON(2, "2");
OSVR_HYDRA_BUTTON(3, "3");
OSVR_HYDRA_BUTTON(4, "4");
OSVR_HYDRA_BUTTON(5, "bumper");
OSVR_HYDRA_BUTTON(6, "joystick/button");
#undef OSVR_HYDRA_BUTTON
#define OSVR_HYDRA_ANALOG(SENSOR, NAME) \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/left/" NAME, SENSOR); \
m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \
"/controller/right/" NAME, SENSOR + 3)
OSVR_HYDRA_ANALOG(0, "joystick/x");
OSVR_HYDRA_ANALOG(1, "joystick/y");
OSVR_HYDRA_ANALOG(2, "trigger");
#undef OSVR_HYDRA_ANALOG
OSVR_DEV_VERBOSE("Now have " << m_routers.size() << " routes.");
}
static const char SENSOR_KEY[] = "sensor";
static const char TRACKER_KEY[] = "tracker";
void VRPNContext::m_handleTrackerRouteEntry(std::string const &dest,
Json::Value src) {
boost::optional<int> sensor;
transform::JSONTransformVisitor xformParse(src);
Json::Value srcLeaf = xformParse.getLeaf();
std::string srcDevice = srcLeaf[TRACKER_KEY].asString();
// OSVR_DEV_VERBOSE("Source device: " << srcDevice);
srcDevice.erase(begin(srcDevice)); // remove leading slash
if (srcLeaf.isMember(SENSOR_KEY)) {
sensor = srcLeaf[SENSOR_KEY].asInt();
}
m_addTrackerRouter(srcDevice.c_str(), dest.c_str(), sensor,
xformParse.getTransform());
}
static const char IMAGING_NAME[] = "imaging";
void VRPNContext::m_handleStringRouteEntry(std::string const &dest,
std::string src) {
std::vector<std::string> components;
/// @todo replace literal with getPathSeparator
boost::algorithm::split(components, src,
boost::algorithm::is_any_of("/"));
if (!components.empty()) {
if (components.front().empty()) {
components.erase(begin(components));
}
}
if (components.size() < 4) {
OSVR_DEV_VERBOSE("Could not parse source for route, skipping: "
<< src << " => " << dest);
return;
}
std::string deviceName =
components[0] + "/" + components[1] + "@" + m_host;
std::reverse(begin(components), end(components));
components.pop_back();
components.pop_back();
std::string interfaceType = components.back();
components.pop_back();
if (interfaceType == IMAGING_NAME) {
OSVR_DEV_VERBOSE("Adding imaging route for " << dest);
m_routers.emplace_back(
new ImagingRouter(this, m_conn, deviceName, components, dest));
} else {
OSVR_DEV_VERBOSE(
"Could not handle route message for interface type "
<< interfaceType << ", skipping: " << src << " => " << dest);
}
}
void VRPNContext::m_sendRoute(std::string const &route) {
m_systemComponent->sendClientRouteUpdate(route);
m_update();
}
void VRPNContext::m_update() {
// mainloop the VRPN connection.
m_conn->mainloop();
// Mainloop the system device
m_systemDevice->update();
// Process each of the routers.
for (auto const &p : m_routers) {
(*p)();
}
}
void VRPNContext::m_addAnalogRouter(const char *src, const char *dest,
int channel) {
OSVR_DEV_VERBOSE("Adding analog route for " << dest);
m_routers.emplace_back(
new VRPNAnalogRouter<SensorPredicate, NullTransform>(
this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest,
SensorPredicate(channel), NullTransform(), channel));
}
template <typename Predicate>
void VRPNContext::m_addButtonRouter(const char *src, const char *dest,
Predicate pred) {
OSVR_DEV_VERBOSE("Adding button route for " << dest);
m_routers.emplace_back(new VRPNButtonRouter<Predicate>(
this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest, pred));
}
void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
boost::optional<int> sensor,
transform::Transform const &xform) {
OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
std::string source(src);
if (std::string::npos != source.find('@')) {
// We found an @ - so this is a device we need a new connection for.
m_routers.emplace_back(
new VRPNTrackerRouter(this, nullptr, src, sensor, dest, xform));
} else {
// No @: assume to be at the same location as the context.
m_routers.emplace_back(new VRPNTrackerRouter(
this, m_conn.get(), (src + ("@" + m_host)).c_str(), sensor,
dest, xform));
}
}
} // namespace client
} // namespace osvr<|endoftext|> |
<commit_before>/*
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: ubi
* @Last Modified time: 2017-07-09 16:41:17
*/
#include "FTDebouncer.h"
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() : _debounceDelay(40) {
}
FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
}
FTDebouncer::~FTDebouncer() {
}
/* METHODS */
void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState, PinMode pullUpMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = pinNr;
debounceItem->restState = restState;
if (_firstDebounceItem == nullptr) {
_firstDebounceItem = debounceItem;
} else {
_lastDebounceItem->nextItem = debounceItem;
}
_lastDebounceItem = debounceItem;
pinMode(pinNr, static_cast<uint8_t>(pullUpMode));
++_debouncedItemsCount;
}
void FTDebouncer::init() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::run() {
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
debounceItem = debounceItem->nextItem;
}
this->debouncePins();
this->checkStateChange();
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->currentState != debounceItem->previousState) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
if (debounceItem->previousState == debounceItem->currentState) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
}
debounceItem->previousState = debounceItem->currentState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::checkStateChange() {
DebounceItem *debounceItem = _firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == !debounceItem->restState) {
pinActivated(debounceItem->pinNumber);
}
if (debounceItem->currentDebouncedState == debounceItem->restState) {
pinDeactivated(debounceItem->pinNumber);
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
debounceItem = debounceItem->nextItem;
}
}
uint8_t FTDebouncer::getPinCount(){
return _debouncedItemsCount;
}
<commit_msg>Use for instead of while loop to simplify code<commit_after>/*
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: ubi
* @Last Modified time: 2017-07-09 16:41:17
*/
#include "FTDebouncer.h"
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() : _debounceDelay(40) {
}
FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
}
FTDebouncer::~FTDebouncer() {
}
/* METHODS */
void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState, PinMode pullUpMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = pinNr;
debounceItem->restState = restState;
if (_firstDebounceItem == nullptr) {
_firstDebounceItem = debounceItem;
} else {
_lastDebounceItem->nextItem = debounceItem;
}
_lastDebounceItem = debounceItem;
pinMode(pinNr, static_cast<uint8_t>(pullUpMode));
++_debouncedItemsCount;
}
void FTDebouncer::init() {
unsigned long currentMilliseconds = millis();
for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
}
}
void FTDebouncer::run() {
for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
}
this->debouncePins();
this->checkStateChange();
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if (debounceItem->currentState != debounceItem->previousState) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
if (debounceItem->previousState == debounceItem->currentState) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
}
debounceItem->previousState = debounceItem->currentState;
}
}
void FTDebouncer::checkStateChange() {
for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == !debounceItem->restState) {
pinActivated(debounceItem->pinNumber);
}
if (debounceItem->currentDebouncedState == debounceItem->restState) {
pinDeactivated(debounceItem->pinNumber);
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
}
}
uint8_t FTDebouncer::getPinCount(){
return _debouncedItemsCount;
}
<|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 "webkit/tools/test_shell/test_shell_request_context.h"
#include "build/build_config.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "net/base/cert_verifier.h"
#include "net/base/default_server_bound_cert_store.h"
#include "net/base/host_resolver.h"
#include "net/base/server_bound_cert_service.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/cookies/cookie_monster.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "webkit/blob/blob_storage_controller.h"
#include "webkit/blob/blob_url_request_job_factory.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_url_request_job_factory.h"
#include "webkit/tools/test_shell/simple_file_system.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/user_agent/user_agent.h"
class TestShellHttpUserAgentSettings : public net::HttpUserAgentSettings {
public:
TestShellHttpUserAgentSettings() {}
virtual ~TestShellHttpUserAgentSettings() {}
// hard-code A-L and A-C for test shells
virtual std::string GetAcceptLanguage() const OVERRIDE {
return "en-us,en";
}
virtual std::string GetAcceptCharset() const OVERRIDE {
return "iso-8859-1,*,utf-8";
}
virtual std::string GetUserAgent(const GURL& url) const OVERRIDE {
return webkit_glue::GetUserAgent(url);
}
private:
DISALLOW_COPY_AND_ASSIGN(TestShellHttpUserAgentSettings);
};
TestShellRequestContext::TestShellRequestContext()
: ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
Init(base::FilePath(), net::HttpCache::NORMAL, false);
}
TestShellRequestContext::TestShellRequestContext(
const base::FilePath& cache_path,
net::HttpCache::Mode cache_mode,
bool no_proxy)
: ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
Init(cache_path, cache_mode, no_proxy);
}
void TestShellRequestContext::Init(
const base::FilePath& cache_path,
net::HttpCache::Mode cache_mode,
bool no_proxy) {
storage_.set_cookie_store(new net::CookieMonster(NULL, NULL));
storage_.set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_.set_http_user_agent_settings(new TestShellHttpUserAgentSettings);
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// Use no proxy to avoid ProxyConfigServiceLinux.
// Enabling use of the ProxyConfigServiceLinux requires:
// -Calling from a thread with a TYPE_UI MessageLoop,
// -If at all possible, passing in a pointer to the IO thread's MessageLoop,
// -Keep in mind that proxy auto configuration is also
// non-functional on linux in this context because of v8 threading
// issues.
// TODO(port): rename "linux" to some nonspecific unix.
scoped_ptr<net::ProxyConfigService> proxy_config_service(
new net::ProxyConfigServiceFixed(net::ProxyConfig()));
#else
// Use the system proxy settings.
scoped_ptr<net::ProxyConfigService> proxy_config_service(
net::ProxyService::CreateSystemProxyConfigService(
base::ThreadTaskRunnerHandle::Get(), NULL));
#endif
storage_.set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
storage_.set_cert_verifier(net::CertVerifier::CreateDefault());
storage_.set_proxy_service(net::ProxyService::CreateUsingSystemProxyResolver(
proxy_config_service.release(), 0, NULL));
storage_.set_ssl_config_service(
new net::SSLConfigServiceDefaults);
storage_.set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver()));
storage_.set_http_server_properties(
new net::HttpServerPropertiesImpl);
net::HttpCache::DefaultBackend* backend = new net::HttpCache::DefaultBackend(
cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
cache_path, 0, SimpleResourceLoaderBridge::GetCacheThread());
net::HttpNetworkSession::Params network_session_params;
network_session_params.host_resolver = host_resolver();
network_session_params.cert_verifier = cert_verifier();
network_session_params.server_bound_cert_service =
server_bound_cert_service();
network_session_params.proxy_service = proxy_service();
network_session_params.ssl_config_service = ssl_config_service();
network_session_params.http_auth_handler_factory =
http_auth_handler_factory();
network_session_params.http_server_properties = http_server_properties();
network_session_params.host_resolver = host_resolver();
net::HttpCache* cache = new net::HttpCache(
network_session_params, backend);
cache->set_mode(cache_mode);
storage_.set_http_transaction_factory(cache);
storage_.set_ftp_transaction_factory(
new net::FtpNetworkLayer(host_resolver()));
blob_storage_controller_.reset(new webkit_blob::BlobStorageController());
file_system_context_ = static_cast<SimpleFileSystem*>(
WebKit::Platform::current()->fileSystem())->file_system_context();
net::URLRequestJobFactoryImpl* job_factory =
new net::URLRequestJobFactoryImpl();
job_factory->SetProtocolHandler(
"blob",
new webkit_blob::BlobProtocolHandler(
blob_storage_controller_.get(),
file_system_context_,
SimpleResourceLoaderBridge::GetIoThread()));
job_factory->SetProtocolHandler(
"filesystem",
fileapi::CreateFileSystemProtocolHandler(file_system_context_.get()));
storage_.set_job_factory(job_factory);
}
TestShellRequestContext::~TestShellRequestContext() {
}
<commit_msg>Turn off the network proxy for mac and win in DRT<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 "webkit/tools/test_shell/test_shell_request_context.h"
#include "build/build_config.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "net/base/cert_verifier.h"
#include "net/base/default_server_bound_cert_store.h"
#include "net/base/host_resolver.h"
#include "net/base/server_bound_cert_service.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/cookies/cookie_monster.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "webkit/blob/blob_storage_controller.h"
#include "webkit/blob/blob_url_request_job_factory.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_url_request_job_factory.h"
#include "webkit/tools/test_shell/simple_file_system.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/user_agent/user_agent.h"
class TestShellHttpUserAgentSettings : public net::HttpUserAgentSettings {
public:
TestShellHttpUserAgentSettings() {}
virtual ~TestShellHttpUserAgentSettings() {}
// hard-code A-L and A-C for test shells
virtual std::string GetAcceptLanguage() const OVERRIDE {
return "en-us,en";
}
virtual std::string GetAcceptCharset() const OVERRIDE {
return "iso-8859-1,*,utf-8";
}
virtual std::string GetUserAgent(const GURL& url) const OVERRIDE {
return webkit_glue::GetUserAgent(url);
}
private:
DISALLOW_COPY_AND_ASSIGN(TestShellHttpUserAgentSettings);
};
TestShellRequestContext::TestShellRequestContext()
: ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
Init(base::FilePath(), net::HttpCache::NORMAL, false);
}
TestShellRequestContext::TestShellRequestContext(
const base::FilePath& cache_path,
net::HttpCache::Mode cache_mode,
bool no_proxy)
: ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
Init(cache_path, cache_mode, no_proxy);
}
void TestShellRequestContext::Init(
const base::FilePath& cache_path,
net::HttpCache::Mode cache_mode,
bool no_proxy) {
storage_.set_cookie_store(new net::CookieMonster(NULL, NULL));
storage_.set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_.set_http_user_agent_settings(new TestShellHttpUserAgentSettings);
// Use no proxy; it's not needed for testing and just breaks things.
scoped_ptr<net::ProxyConfigService> proxy_config_service(
new net::ProxyConfigServiceFixed(net::ProxyConfig()));
storage_.set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
storage_.set_cert_verifier(net::CertVerifier::CreateDefault());
storage_.set_proxy_service(net::ProxyService::CreateUsingSystemProxyResolver(
proxy_config_service.release(), 0, NULL));
storage_.set_ssl_config_service(
new net::SSLConfigServiceDefaults);
storage_.set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver()));
storage_.set_http_server_properties(
new net::HttpServerPropertiesImpl);
net::HttpCache::DefaultBackend* backend = new net::HttpCache::DefaultBackend(
cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
cache_path, 0, SimpleResourceLoaderBridge::GetCacheThread());
net::HttpNetworkSession::Params network_session_params;
network_session_params.host_resolver = host_resolver();
network_session_params.cert_verifier = cert_verifier();
network_session_params.server_bound_cert_service =
server_bound_cert_service();
network_session_params.proxy_service = proxy_service();
network_session_params.ssl_config_service = ssl_config_service();
network_session_params.http_auth_handler_factory =
http_auth_handler_factory();
network_session_params.http_server_properties = http_server_properties();
network_session_params.host_resolver = host_resolver();
net::HttpCache* cache = new net::HttpCache(
network_session_params, backend);
cache->set_mode(cache_mode);
storage_.set_http_transaction_factory(cache);
storage_.set_ftp_transaction_factory(
new net::FtpNetworkLayer(host_resolver()));
blob_storage_controller_.reset(new webkit_blob::BlobStorageController());
file_system_context_ = static_cast<SimpleFileSystem*>(
WebKit::Platform::current()->fileSystem())->file_system_context();
net::URLRequestJobFactoryImpl* job_factory =
new net::URLRequestJobFactoryImpl();
job_factory->SetProtocolHandler(
"blob",
new webkit_blob::BlobProtocolHandler(
blob_storage_controller_.get(),
file_system_context_,
SimpleResourceLoaderBridge::GetIoThread()));
job_factory->SetProtocolHandler(
"filesystem",
fileapi::CreateFileSystemProtocolHandler(file_system_context_.get()));
storage_.set_job_factory(job_factory);
}
TestShellRequestContext::~TestShellRequestContext() {
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_thread.h"
// Friendly names for the well-known threads.
static const char* chrome_thread_names[ChromeThread::ID_COUNT] = {
"", // UI (name assembled in browser_main.cc).
"Chrome_DBThread", // DB
"Chrome_WebKitThread", // WEBKIT
"Chrome_FileThread", // FILE
"Chrome_IOThread", // IO
#if defined(OS_LINUX)
"Chrome_Background_X11Thread", // BACKGROUND_X11
#endif
};
Lock ChromeThread::lock_;
ChromeThread* ChromeThread::chrome_threads_[ID_COUNT];
ChromeThread::ChromeThread(ChromeThread::ID identifier)
: Thread(chrome_thread_names[identifier]),
identifier_(identifier) {
Initialize();
}
ChromeThread::ChromeThread(ID identifier, MessageLoop* message_loop)
: Thread(message_loop->thread_name().c_str()),
identifier_(identifier) {
set_message_loop(message_loop);
Initialize();
}
void ChromeThread::Initialize() {
AutoLock lock(lock_);
DCHECK(identifier_ >= 0 && identifier_ < ID_COUNT);
DCHECK(chrome_threads_[identifier_] == NULL);
chrome_threads_[identifier_] = this;
}
ChromeThread::~ChromeThread() {
AutoLock lock(lock_);
chrome_threads_[identifier_] = NULL;
#ifndef NDEBUG
// Double check that the threads are ordererd correctly in the enumeration.
for (int i = identifier_ + 1; i < ID_COUNT; ++i) {
DCHECK(!chrome_threads_[i]) <<
"Threads must be listed in the reverse order that they die";
}
#endif
}
// static
bool ChromeThread::CurrentlyOn(ID identifier) {
AutoLock lock(lock_);
DCHECK(identifier >= 0 && identifier < ID_COUNT);
return chrome_threads_[identifier] &&
chrome_threads_[identifier]->message_loop() == MessageLoop::current();
}
// static
bool ChromeThread::PostTask(ID identifier,
const tracked_objects::Location& from_here,
Task* task) {
return PostTaskHelper(identifier, from_here, task, 0, true);
}
// static
bool ChromeThread::PostDelayedTask(ID identifier,
const tracked_objects::Location& from_here,
Task* task,
int64 delay_ms) {
return PostTaskHelper(identifier, from_here, task, delay_ms, true);
}
// static
bool ChromeThread::PostNonNestableTask(
ID identifier,
const tracked_objects::Location& from_here,
Task* task) {
return PostTaskHelper(identifier, from_here, task, 0, false);
}
// static
bool ChromeThread::PostNonNestableDelayedTask(
ID identifier,
const tracked_objects::Location& from_here,
Task* task,
int64 delay_ms) {
return PostTaskHelper(identifier, from_here, task, delay_ms, false);
}
// static
bool ChromeThread::GetCurrentThreadIdentifier(ID* identifier) {
MessageLoop* cur_message_loop = MessageLoop::current();
for (int i = 0; i < ID_COUNT; ++i) {
if (chrome_threads_[i] &&
chrome_threads_[i]->message_loop() == cur_message_loop) {
*identifier = chrome_threads_[i]->identifier_;
return true;
}
}
return false;
}
// static
bool ChromeThread::PostTaskHelper(
ID identifier,
const tracked_objects::Location& from_here,
Task* task,
int64 delay_ms,
bool nestable) {
DCHECK(identifier >= 0 && identifier < ID_COUNT);
// Optimization: to avoid unnecessary locks, we listed the ID enumeration in
// order of lifetime. So no need to lock if we know that the other thread
// outlives this one.
// Note: since the array is so small, ok to loop instead of creating a map,
// which would require a lock because std::map isn't thread safe, defeating
// the whole purpose of this optimization.
ID current_thread;
bool guaranteed_to_outlive_target_thread =
GetCurrentThreadIdentifier(¤t_thread) &&
current_thread >= identifier;
if (!guaranteed_to_outlive_target_thread)
lock_.Acquire();
MessageLoop* message_loop = chrome_threads_[identifier] ?
chrome_threads_[identifier]->message_loop() : NULL;
if (message_loop) {
if (nestable) {
message_loop->PostDelayedTask(from_here, task, delay_ms);
} else {
message_loop->PostNonNestableDelayedTask(from_here, task, delay_ms);
}
} else {
delete task;
}
if (!guaranteed_to_outlive_target_thread)
lock_.Release();
return !!message_loop;
}
<commit_msg>Stop each ChromeThread before nulling out the entry in chrome_threads_. This allows DCHECKs that the code is running on the correct thread to succeed.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_thread.h"
// Friendly names for the well-known threads.
static const char* chrome_thread_names[ChromeThread::ID_COUNT] = {
"", // UI (name assembled in browser_main.cc).
"Chrome_DBThread", // DB
"Chrome_WebKitThread", // WEBKIT
"Chrome_FileThread", // FILE
"Chrome_IOThread", // IO
#if defined(OS_LINUX)
"Chrome_Background_X11Thread", // BACKGROUND_X11
#endif
};
Lock ChromeThread::lock_;
ChromeThread* ChromeThread::chrome_threads_[ID_COUNT];
ChromeThread::ChromeThread(ChromeThread::ID identifier)
: Thread(chrome_thread_names[identifier]),
identifier_(identifier) {
Initialize();
}
ChromeThread::ChromeThread(ID identifier, MessageLoop* message_loop)
: Thread(message_loop->thread_name().c_str()),
identifier_(identifier) {
set_message_loop(message_loop);
Initialize();
}
void ChromeThread::Initialize() {
AutoLock lock(lock_);
DCHECK(identifier_ >= 0 && identifier_ < ID_COUNT);
DCHECK(chrome_threads_[identifier_] == NULL);
chrome_threads_[identifier_] = this;
}
ChromeThread::~ChromeThread() {
// Stop the thread here, instead of the parent's class destructor. This is so
// that if there are pending tasks that run, code that checks that it's on the
// correct ChromeThread succeeds.
Stop();
AutoLock lock(lock_);
chrome_threads_[identifier_] = NULL;
#ifndef NDEBUG
// Double check that the threads are ordererd correctly in the enumeration.
for (int i = identifier_ + 1; i < ID_COUNT; ++i) {
DCHECK(!chrome_threads_[i]) <<
"Threads must be listed in the reverse order that they die";
}
#endif
}
// static
bool ChromeThread::CurrentlyOn(ID identifier) {
AutoLock lock(lock_);
DCHECK(identifier >= 0 && identifier < ID_COUNT);
return chrome_threads_[identifier] &&
chrome_threads_[identifier]->message_loop() == MessageLoop::current();
}
// static
bool ChromeThread::PostTask(ID identifier,
const tracked_objects::Location& from_here,
Task* task) {
return PostTaskHelper(identifier, from_here, task, 0, true);
}
// static
bool ChromeThread::PostDelayedTask(ID identifier,
const tracked_objects::Location& from_here,
Task* task,
int64 delay_ms) {
return PostTaskHelper(identifier, from_here, task, delay_ms, true);
}
// static
bool ChromeThread::PostNonNestableTask(
ID identifier,
const tracked_objects::Location& from_here,
Task* task) {
return PostTaskHelper(identifier, from_here, task, 0, false);
}
// static
bool ChromeThread::PostNonNestableDelayedTask(
ID identifier,
const tracked_objects::Location& from_here,
Task* task,
int64 delay_ms) {
return PostTaskHelper(identifier, from_here, task, delay_ms, false);
}
// static
bool ChromeThread::GetCurrentThreadIdentifier(ID* identifier) {
MessageLoop* cur_message_loop = MessageLoop::current();
for (int i = 0; i < ID_COUNT; ++i) {
if (chrome_threads_[i] &&
chrome_threads_[i]->message_loop() == cur_message_loop) {
*identifier = chrome_threads_[i]->identifier_;
return true;
}
}
return false;
}
// static
bool ChromeThread::PostTaskHelper(
ID identifier,
const tracked_objects::Location& from_here,
Task* task,
int64 delay_ms,
bool nestable) {
DCHECK(identifier >= 0 && identifier < ID_COUNT);
// Optimization: to avoid unnecessary locks, we listed the ID enumeration in
// order of lifetime. So no need to lock if we know that the other thread
// outlives this one.
// Note: since the array is so small, ok to loop instead of creating a map,
// which would require a lock because std::map isn't thread safe, defeating
// the whole purpose of this optimization.
ID current_thread;
bool guaranteed_to_outlive_target_thread =
GetCurrentThreadIdentifier(¤t_thread) &&
current_thread >= identifier;
if (!guaranteed_to_outlive_target_thread)
lock_.Acquire();
MessageLoop* message_loop = chrome_threads_[identifier] ?
chrome_threads_[identifier]->message_loop() : NULL;
if (message_loop) {
if (nestable) {
message_loop->PostDelayedTask(from_here, task, delay_ms);
} else {
message_loop->PostNonNestableDelayedTask(from_here, task, delay_ms);
}
} else {
delete task;
}
if (!guaranteed_to_outlive_target_thread)
lock_.Release();
return !!message_loop;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_util.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:04:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "pyuno_impl.hxx"
#include <time.h>
#include <osl/thread.h>
#include <typelib/typedescription.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/time.h>
#include <com/sun/star/beans/XMaterialHolder.hpp>
using rtl::OUStringToOString;
using rtl::OUString;
using rtl::OString;
using rtl::OStringBuffer;
using rtl::OUStringBuffer;
using com::sun::star::uno::TypeDescription;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::TypeClass;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::XComponentContext;
using com::sun::star::lang::XSingleServiceFactory;
using com::sun::star::script::XTypeConverter;
using com::sun::star::beans::XMaterialHolder;
#define USTR_ASCII(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )
namespace pyuno
{
PyRef ustring2PyUnicode( const OUString & str )
{
PyRef ret;
#if Py_UNICODE_SIZE == 2
ret = PyRef( PyUnicode_FromUnicode( str.getStr(), str.getLength() ), SAL_NO_ACQUIRE );
#else
OString sUtf8(OUStringToOString(str, RTL_TEXTENCODING_UTF8));
ret = PyRef( PyUnicode_DecodeUTF8( sUtf8.getStr(), sUtf8.getLength(), NULL) , SAL_NO_ACQUIRE );
#endif
return ret;
}
PyRef ustring2PyString( const OUString &str )
{
OString o = OUStringToOString( str, osl_getThreadTextEncoding() );
return PyRef( PyString_FromString( o.getStr() ), SAL_NO_ACQUIRE );
}
OUString pyString2ustring( PyObject *pystr )
{
OUString ret;
if( PyUnicode_Check( pystr ) )
{
#if Py_UNICODE_SIZE == 2
ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );
#else
PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);
ret = OUString(PyString_AsString(pUtf8), PyString_Size(pUtf8), RTL_TEXTENCODING_UTF8);
Py_DECREF(pUtf8);
#endif
}
else
{
char *name = PyString_AsString(pystr );
ret = OUString( name, strlen(name), osl_getThreadTextEncoding() );
}
return ret;
}
PyRef getObjectFromUnoModule( const Runtime &runtime, const char * func )
throw ( RuntimeException )
{
PyRef object(PyDict_GetItemString( runtime.getImpl()->cargo->getUnoModule().get(), (char*)func ) );
if( !object.is() )
{
OUStringBuffer buf;
buf.appendAscii( "couldn't find core function " );
buf.appendAscii( func );
throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
}
return object;
}
//------------------------------------------------------------------------------------
// Logging
//------------------------------------------------------------------------------------
bool isLog( RuntimeCargo * cargo, sal_Int32 loglevel )
{
return cargo && cargo->logFile && loglevel <= cargo->logLevel;
}
void log( RuntimeCargo * cargo, sal_Int32 level, const rtl::OUString &logString )
{
log( cargo, level, OUStringToOString( logString, osl_getThreadTextEncoding() ).getStr() );
}
void log( RuntimeCargo * cargo, sal_Int32 level, const char *str )
{
if( isLog( cargo, level ) )
{
static const char *strLevel[] = { "NONE", "CALL", "ARGS" };
TimeValue systemTime;
TimeValue localTime;
oslDateTime localDateTime;
osl_getSystemTime( &systemTime );
osl_getLocalTimeFromSystemTime( &systemTime, &localTime );
osl_getDateTimeFromTimeValue( &localTime, &localDateTime );
fprintf( cargo->logFile,
"%4i-%02i-%02i %02i:%02i:%02i,%03i [%s,tid %i]: %s\n",
localDateTime.Year,
localDateTime.Month,
localDateTime.Day,
localDateTime.Hours,
localDateTime.Minutes,
localDateTime.Seconds,
localDateTime.NanoSeconds/1000000,
strLevel[level],
(sal_Int32) osl_getThreadIdentifier( 0),
str );
}
}
namespace {
void appendPointer(rtl::OUStringBuffer & buffer, void * pointer) {
buffer.append(
sal::static_int_cast< sal_Int64 >(
reinterpret_cast< sal_IntPtr >(pointer)),
16);
}
}
void logException( RuntimeCargo *cargo, const char *intro,
void * ptr, const rtl::OUString &aFunctionName,
const void * data, const com::sun::star::uno::Type & type )
{
if( isLog( cargo, LogLevel::CALL ) )
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( intro );
appendPointer(buf, ptr);
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
buf.append( aFunctionName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " = " ) );
buf.append(
val2str( data, type.getTypeLibType(), VAL2STR_MODE_SHALLOW ) );
log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}
}
void logReply(
RuntimeCargo *cargo,
const char *intro,
void * ptr,
const rtl::OUString & aFunctionName,
const Any &returnValue,
const Sequence< Any > & aParams )
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( intro );
appendPointer(buf, ptr);
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
buf.append( aFunctionName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("()=") );
if( isLog( cargo, LogLevel::ARGS ) )
{
buf.append(
val2str( returnValue.getValue(), returnValue.getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
for( int i = 0; i < aParams.getLength() ; i ++ )
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", " ) );
buf.append(
val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
}
}
log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}
void logCall( RuntimeCargo *cargo, const char *intro,
void * ptr, const rtl::OUString & aFunctionName,
const Sequence< Any > & aParams )
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( intro );
appendPointer(buf, ptr);
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
buf.append( aFunctionName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("(") );
if( isLog( cargo, LogLevel::ARGS ) )
{
for( int i = 0; i < aParams.getLength() ; i ++ )
{
if( i > 0 )
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", " ) );
buf.append(
val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
}
}
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(")") );
log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}
}
<commit_msg>INTEGRATION: CWS warningfixes02 (1.6.2); FILE MERGED 2006/06/30 12:16:38 sb 1.6.2.1: #i66577# Made the code compile (warning-free) on a unxlngi6.pro GCC 4.1.1 Linux box.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_util.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-07-19 16:42:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "pyuno_impl.hxx"
#include <time.h>
#include <osl/thread.h>
#include <typelib/typedescription.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/time.h>
#include <com/sun/star/beans/XMaterialHolder.hpp>
using rtl::OUStringToOString;
using rtl::OUString;
using rtl::OString;
using rtl::OStringBuffer;
using rtl::OUStringBuffer;
using com::sun::star::uno::TypeDescription;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::TypeClass;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::XComponentContext;
using com::sun::star::lang::XSingleServiceFactory;
using com::sun::star::script::XTypeConverter;
using com::sun::star::beans::XMaterialHolder;
#define USTR_ASCII(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )
namespace pyuno
{
PyRef ustring2PyUnicode( const OUString & str )
{
PyRef ret;
#if Py_UNICODE_SIZE == 2
ret = PyRef( PyUnicode_FromUnicode( str.getStr(), str.getLength() ), SAL_NO_ACQUIRE );
#else
OString sUtf8(OUStringToOString(str, RTL_TEXTENCODING_UTF8));
ret = PyRef( PyUnicode_DecodeUTF8( sUtf8.getStr(), sUtf8.getLength(), NULL) , SAL_NO_ACQUIRE );
#endif
return ret;
}
PyRef ustring2PyString( const OUString &str )
{
OString o = OUStringToOString( str, osl_getThreadTextEncoding() );
return PyRef( PyString_FromString( o.getStr() ), SAL_NO_ACQUIRE );
}
OUString pyString2ustring( PyObject *pystr )
{
OUString ret;
if( PyUnicode_Check( pystr ) )
{
#if Py_UNICODE_SIZE == 2
ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );
#else
PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);
ret = OUString(PyString_AsString(pUtf8), PyString_Size(pUtf8), RTL_TEXTENCODING_UTF8);
Py_DECREF(pUtf8);
#endif
}
else
{
char *name = PyString_AsString(pystr );
ret = OUString( name, strlen(name), osl_getThreadTextEncoding() );
}
return ret;
}
PyRef getObjectFromUnoModule( const Runtime &runtime, const char * func )
throw ( RuntimeException )
{
PyRef object(PyDict_GetItemString( runtime.getImpl()->cargo->getUnoModule().get(), (char*)func ) );
if( !object.is() )
{
OUStringBuffer buf;
buf.appendAscii( "couldn't find core function " );
buf.appendAscii( func );
throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
}
return object;
}
//------------------------------------------------------------------------------------
// Logging
//------------------------------------------------------------------------------------
bool isLog( RuntimeCargo * cargo, sal_Int32 loglevel )
{
return cargo && cargo->logFile && loglevel <= cargo->logLevel;
}
void log( RuntimeCargo * cargo, sal_Int32 level, const rtl::OUString &logString )
{
log( cargo, level, OUStringToOString( logString, osl_getThreadTextEncoding() ).getStr() );
}
void log( RuntimeCargo * cargo, sal_Int32 level, const char *str )
{
if( isLog( cargo, level ) )
{
static const char *strLevel[] = { "NONE", "CALL", "ARGS" };
TimeValue systemTime;
TimeValue localTime;
oslDateTime localDateTime;
osl_getSystemTime( &systemTime );
osl_getLocalTimeFromSystemTime( &systemTime, &localTime );
osl_getDateTimeFromTimeValue( &localTime, &localDateTime );
fprintf( cargo->logFile,
"%4i-%02i-%02i %02i:%02i:%02i,%03lu [%s,tid %ld]: %s\n",
localDateTime.Year,
localDateTime.Month,
localDateTime.Day,
localDateTime.Hours,
localDateTime.Minutes,
localDateTime.Seconds,
sal::static_int_cast< unsigned long >(
localDateTime.NanoSeconds/1000000),
strLevel[level],
sal::static_int_cast< long >(
(sal_Int32) osl_getThreadIdentifier( 0)),
str );
}
}
namespace {
void appendPointer(rtl::OUStringBuffer & buffer, void * pointer) {
buffer.append(
sal::static_int_cast< sal_Int64 >(
reinterpret_cast< sal_IntPtr >(pointer)),
16);
}
}
void logException( RuntimeCargo *cargo, const char *intro,
void * ptr, const rtl::OUString &aFunctionName,
const void * data, const com::sun::star::uno::Type & type )
{
if( isLog( cargo, LogLevel::CALL ) )
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( intro );
appendPointer(buf, ptr);
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
buf.append( aFunctionName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " = " ) );
buf.append(
val2str( data, type.getTypeLibType(), VAL2STR_MODE_SHALLOW ) );
log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}
}
void logReply(
RuntimeCargo *cargo,
const char *intro,
void * ptr,
const rtl::OUString & aFunctionName,
const Any &returnValue,
const Sequence< Any > & aParams )
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( intro );
appendPointer(buf, ptr);
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
buf.append( aFunctionName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("()=") );
if( isLog( cargo, LogLevel::ARGS ) )
{
buf.append(
val2str( returnValue.getValue(), returnValue.getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
for( int i = 0; i < aParams.getLength() ; i ++ )
{
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", " ) );
buf.append(
val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
}
}
log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}
void logCall( RuntimeCargo *cargo, const char *intro,
void * ptr, const rtl::OUString & aFunctionName,
const Sequence< Any > & aParams )
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( intro );
appendPointer(buf, ptr);
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("].") );
buf.append( aFunctionName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("(") );
if( isLog( cargo, LogLevel::ARGS ) )
{
for( int i = 0; i < aParams.getLength() ; i ++ )
{
if( i > 0 )
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", " ) );
buf.append(
val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );
}
}
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(")") );
log( cargo,LogLevel::CALL, buf.makeStringAndClear() );
}
}
<|endoftext|> |
<commit_before><commit_msg>Write the kmail account type correctly for KDE 4 KMail. <commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/bind.hpp>
#include "libtorrent/socket.hpp"
#include "libtorrent/enum_net.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent
{
bool is_local(address const& a)
{
if (a.is_v6()) return a.to_v6().is_link_local();
address_v4 a4 = a.to_v4();
unsigned long ip = a4.to_ulong();
return ((ip & 0xff000000) == 0x0a000000
|| (ip & 0xfff00000) == 0xac100000
|| (ip & 0xffff0000) == 0xc0a80000);
}
bool is_loopback(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::loopback();
else
return addr.to_v6() == address_v6::loopback();
}
bool is_multicast(address const& addr)
{
if (addr.is_v4())
return addr.to_v4().is_multicast();
else
return addr.to_v6().is_multicast();
}
bool is_any(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::any();
else
return addr.to_v6() == address_v6::any();
}
address guess_local_address(asio::io_service& ios)
{
// make a best guess of the interface we're using and its IP
asio::error_code ec;
std::vector<address> const& interfaces = enum_net_interfaces(ios, ec);
address ret = address_v4::any();
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
address const& a = *i;
if (is_loopback(a)
|| is_multicast(a)
|| is_any(a)) continue;
// prefer a v4 address, but return a v6 if
// there are no v4
if (a.is_v4()) return a;
if (ret != address_v4::any())
ret = a;
}
return ret;
}
broadcast_socket::broadcast_socket(asio::io_service& ios
, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler
, bool loopback)
: m_multicast_endpoint(multicast_endpoint)
, m_on_receive(handler)
{
TORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));
using namespace asio::ip::multicast;
asio::error_code ec;
std::vector<address> interfaces = enum_net_interfaces(ios, ec);
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
// only broadcast to IPv4 addresses that are not local
if (!is_local(*i)) continue;
// only multicast on compatible networks
if (i->is_v4() != multicast_endpoint.address().is_v4()) continue;
// ignore any loopback interface
if (is_loopback(*i)) continue;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
if (i->is_v4())
{
s->open(udp::v4(), ec);
if (ec) continue;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) continue;
s->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec);
if (ec) continue;
s->set_option(join_group(multicast_endpoint.address()), ec);
if (ec) continue;
s->set_option(outbound_interface(i->to_v4()), ec);
if (ec) continue;
}
else
{
s->open(udp::v6(), ec);
if (ec) continue;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) continue;
s->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec);
if (ec) continue;
s->set_option(join_group(multicast_endpoint.address()), ec);
if (ec) continue;
// s->set_option(outbound_interface(i->to_v6()), ec);
// if (ec) continue;
}
s->set_option(hops(255), ec);
if (ec) continue;
s->set_option(enable_loopback(loopback), ec);
if (ec) continue;
m_sockets.push_back(socket_entry(s));
socket_entry& se = m_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
#ifndef NDEBUG
// std::cerr << "broadcast socket [ if: " << i->to_v4().to_string()
// << " group: " << multicast_endpoint.address() << " ]" << std::endl;
#endif
}
open_unicast_socket(ios, address_v4::any());
open_unicast_socket(ios, address_v6::any());
}
void broadcast_socket::open_unicast_socket(io_service& ios, address const& addr)
{
asio::error_code ec;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
s->open(addr.is_v4() ? udp::v4() : udp::v6(), ec);
if (ec) return;
s->bind(udp::endpoint(addr, 0), ec);
if (ec) return;
m_unicast_sockets.push_back(socket_entry(s));
socket_entry& se = m_unicast_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
}
void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec)
{
for (std::list<socket_entry>::iterator i = m_unicast_sockets.begin()
, end(m_unicast_sockets.end()); i != end; ++i)
{
if (!i->socket) continue;
asio::error_code e;
i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);
#ifndef NDEBUG
// std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << " to: " << m_multicast_endpoint << std::endl;
#endif
if (e)
{
i->socket->close(e);
i->socket.reset();
}
}
for (std::list<socket_entry>::iterator i = m_sockets.begin()
, end(m_sockets.end()); i != end; ++i)
{
if (!i->socket) continue;
asio::error_code e;
i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);
#ifndef NDEBUG
// std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << " to: " << m_multicast_endpoint << std::endl;
#endif
if (e)
{
i->socket->close(e);
i->socket.reset();
}
}
}
void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred)
{
if (ec || bytes_transferred == 0 || !m_on_receive) return;
m_on_receive(s->remote, s->buffer, bytes_transferred);
if (!s->socket) return;
s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))
, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));
}
void broadcast_socket::close()
{
std::for_each(m_sockets.begin(), m_sockets.end(), bind(&socket_entry::close, _1));
std::for_each(m_unicast_sockets.begin(), m_unicast_sockets.end(), bind(&socket_entry::close, _1));
m_on_receive.clear();
}
}
<commit_msg>broadcast socket updates (better upnp support)<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/bind.hpp>
#include "libtorrent/socket.hpp"
#include "libtorrent/enum_net.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent
{
bool is_local(address const& a)
{
if (a.is_v6()) return a.to_v6().is_link_local();
address_v4 a4 = a.to_v4();
unsigned long ip = a4.to_ulong();
return ((ip & 0xff000000) == 0x0a000000
|| (ip & 0xfff00000) == 0xac100000
|| (ip & 0xffff0000) == 0xc0a80000);
}
bool is_loopback(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::loopback();
else
return addr.to_v6() == address_v6::loopback();
}
bool is_multicast(address const& addr)
{
if (addr.is_v4())
return addr.to_v4().is_multicast();
else
return addr.to_v6().is_multicast();
}
bool is_any(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::any();
else
return addr.to_v6() == address_v6::any();
}
address guess_local_address(asio::io_service& ios)
{
// make a best guess of the interface we're using and its IP
asio::error_code ec;
std::vector<address> const& interfaces = enum_net_interfaces(ios, ec);
address ret = address_v4::any();
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
address const& a = *i;
if (is_loopback(a)
|| is_multicast(a)
|| is_any(a)) continue;
// prefer a v4 address, but return a v6 if
// there are no v4
if (a.is_v4()) return a;
if (ret != address_v4::any())
ret = a;
}
return ret;
}
broadcast_socket::broadcast_socket(asio::io_service& ios
, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler
, bool loopback)
: m_multicast_endpoint(multicast_endpoint)
, m_on_receive(handler)
{
TORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));
using namespace asio::ip::multicast;
asio::error_code ec;
std::vector<address> interfaces = enum_net_interfaces(ios, ec);
if (multicast_endpoint.address().is_v4())
open_multicast_socket(ios, address_v4::any(), loopback);
else
open_multicast_socket(ios, address_v6::any(), loopback);
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
// only broadcast to IPv4 addresses that are not local
if (!is_local(*i)) continue;
// only multicast on compatible networks
if (i->is_v4() != multicast_endpoint.address().is_v4()) continue;
// ignore any loopback interface
if (is_loopback(*i)) continue;
#ifndef NDEBUG
// std::cerr << "broadcast socket [ if: " << i->to_v4().to_string()
// << " group: " << multicast_endpoint.address() << " ]" << std::endl;
#endif
open_unicast_socket(ios, *i);
}
}
void broadcast_socket::open_multicast_socket(io_service& ios
, address const& addr, bool loopback)
{
using namespace asio::ip::multicast;
asio::error_code ec;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
if (addr.is_v4())
s->open(udp::v4(), ec);
else
s->open(udp::v6(), ec);
if (ec) return;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) return;
s->bind(udp::endpoint(addr, m_multicast_endpoint.port()), ec);
if (ec) return;
s->set_option(join_group(m_multicast_endpoint.address()), ec);
if (ec) return;
s->set_option(hops(255), ec);
if (ec) return;
s->set_option(enable_loopback(loopback), ec);
if (ec) return;
m_sockets.push_back(socket_entry(s));
socket_entry& se = m_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
}
void broadcast_socket::open_unicast_socket(io_service& ios, address const& addr)
{
using namespace asio::ip::multicast;
asio::error_code ec;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
s->open(addr.is_v4() ? udp::v4() : udp::v6(), ec);
if (ec) return;
s->bind(udp::endpoint(addr, 0), ec);
if (ec) return;
if (addr.is_v4())
s->set_option(outbound_interface(addr.to_v4()), ec);
if (ec) return;
m_unicast_sockets.push_back(socket_entry(s));
socket_entry& se = m_unicast_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
}
void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec)
{
for (std::list<socket_entry>::iterator i = m_unicast_sockets.begin()
, end(m_unicast_sockets.end()); i != end; ++i)
{
if (!i->socket) continue;
asio::error_code e;
i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);
#ifndef NDEBUG
// std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << " to: " << m_multicast_endpoint << std::endl;
#endif
if (e)
{
i->socket->close(e);
i->socket.reset();
}
}
}
void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred)
{
if (ec || bytes_transferred == 0 || !m_on_receive) return;
m_on_receive(s->remote, s->buffer, bytes_transferred);
if (!s->socket) return;
s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))
, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));
}
void broadcast_socket::close()
{
std::for_each(m_sockets.begin(), m_sockets.end(), bind(&socket_entry::close, _1));
std::for_each(m_unicast_sockets.begin(), m_unicast_sockets.end(), bind(&socket_entry::close, _1));
m_on_receive.clear();
}
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <mist/json.h>
#include <mist/dtsc.h>
#include <mist/procs.h>
#include <mist/timing.h>
namespace Info {
int getInfo(int argc, char* argv[]) {
if (argc < 2){
fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
return 1;
}
DTSC::File F(argv[1]);
JSON::Value fileSpecs = F.getMeta();
if( !fileSpecs ) {
char ** cmd = (char**)malloc(3*sizeof(char*));
cmd[0] = (char*)"ffprobe";
cmd[1] = argv[1];
cmd[2] = NULL;
int outFD = -1;
Util::Procs::StartPiped("FFProbe", cmd, 0, 0, &outFD);
while( Util::Procs::isActive("FFProbe")){ Util::sleep(100); }
FILE * outFile = fdopen( outFD, "r" );
char * fileBuf = 0;
size_t fileBufLen = 0;
while ( !(feof(outFile) || ferror(outFile)) && (getline(&fileBuf, &fileBufLen, outFile) != -1)){
std::string line = fileBuf;
if (line.find("Input") != std::string::npos){
std::string tmp = line.substr(line.find(", ") + 2);
fileSpecs["format"] = tmp.substr(0, tmp.find(","));
}
if (line.find("Duration") != std::string::npos){
std::string tmp = line.substr(line.find(": ", line.find("Duration")) + 2);
tmp = tmp.substr(0, tmp.find(","));
int length = (((atoi(tmp.substr(0,2).c_str()) * 60) + atoi(tmp.substr(3,2).c_str())) * 60) + atoi(tmp.substr(6,2).c_str());
fileSpecs["length"] = length;
length *= 100;
length += atoi(tmp.substr(9,2).c_str());
fileSpecs["lastms"] = length * 10;
}
if (line.find("bitrate") != std::string::npos ){
std::string tmp = line.substr(line.find(": ", line.find("bitrate")) + 2);
fileSpecs["bps"] = atoi(tmp.substr(0, tmp.find(" ")).c_str()) * 128;
}
if (line.find("Stream") != std::string::npos ){
std::string tmp = line.substr(line.find(" ", line.find("Stream")) + 1);
int strmIdx = fileSpecs["streams"].size();
int curPos = 0;
curPos = tmp.find(": ", curPos) + 2;
fileSpecs["streams"][strmIdx]["type"] = tmp.substr(curPos, tmp.find(":", curPos) - curPos);
curPos = tmp.find(":", curPos) + 2;
fileSpecs["streams"][strmIdx]["codec"] = tmp.substr(curPos, tmp.find_first_of(", ", curPos) - curPos);
curPos = tmp.find(",", curPos) + 2;
if (fileSpecs["streams"][strmIdx]["type"] == "Video"){
fileSpecs["streams"][strmIdx]["encoding"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["width"] = atoi(tmp.substr(curPos, tmp.find("x", curPos) - curPos).c_str());
curPos = tmp.find("x", curPos) + 1;
fileSpecs["streams"][strmIdx]["height"] = atoi(tmp.substr(curPos, tmp.find(",", curPos) - curPos).c_str());
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["bps"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 128;
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["fpks"] = (int)(atof(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 1000);
fileSpecs["streams"][strmIdx].removeMember( "type" );
fileSpecs["video"] = fileSpecs["streams"][strmIdx];
}else if (fileSpecs["streams"][strmIdx]["type"] == "Audio"){
fileSpecs["streams"][strmIdx]["samplerate"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str());
curPos = tmp.find(",", curPos) + 2;
if (tmp.substr(curPos, tmp.find(",", curPos) - curPos) == "stereo"){
fileSpecs["streams"][strmIdx]["channels"] = 2;
}else if (tmp.substr(curPos, tmp.find(",", curPos) - curPos) == "mono"){
fileSpecs["streams"][strmIdx]["channels"] = 1;
}else{
fileSpecs["streams"][strmIdx]["channels"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
}
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["samplewidth"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["bps"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 128;
fileSpecs["streams"][strmIdx].removeMember( "type" );
fileSpecs["audio"] = fileSpecs["streams"][strmIdx];
}
}
}
fclose( outFile );
fileSpecs.removeMember( "streams" );
} else {
fileSpecs["format"] = "dtsc";
}
if (fileSpecs.isMember("video")){
fileSpecs["video"].removeMember("init");
}
if (fileSpecs.isMember("audio")){
fileSpecs["audio"].removeMember("init");
}
fileSpecs.removeMember("keybpos");
fileSpecs.removeMember("keytime");
printf( "%s", fileSpecs.toString().c_str() );
return 0;
}
}
int main(int argc, char* argv[]) {
return Info::getInfo(argc, argv);
}
<commit_msg>Updated MistInfo to support dtsc2<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <mist/json.h>
#include <mist/dtsc.h>
#include <mist/procs.h>
#include <mist/timing.h>
namespace Info {
int getInfo(int argc, char* argv[]) {
if (argc < 2){
fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
return 1;
}
DTSC::File F(argv[1]);
JSON::Value fileSpecs = F.getMeta();
if( !fileSpecs ) {
char ** cmd = (char**)malloc(3*sizeof(char*));
cmd[0] = (char*)"ffprobe";
cmd[1] = argv[1];
cmd[2] = NULL;
int outFD = -1;
Util::Procs::StartPiped("FFProbe", cmd, 0, 0, &outFD);
while( Util::Procs::isActive("FFProbe")){ Util::sleep(100); }
FILE * outFile = fdopen( outFD, "r" );
char * fileBuf = 0;
size_t fileBufLen = 0;
while ( !(feof(outFile) || ferror(outFile)) && (getline(&fileBuf, &fileBufLen, outFile) != -1)){
std::string line = fileBuf;
if (line.find("Input") != std::string::npos){
std::string tmp = line.substr(line.find(", ") + 2);
fileSpecs["format"] = tmp.substr(0, tmp.find(","));
}
if (line.find("Duration") != std::string::npos){
std::string tmp = line.substr(line.find(": ", line.find("Duration")) + 2);
tmp = tmp.substr(0, tmp.find(","));
int length = (((atoi(tmp.substr(0,2).c_str()) * 60) + atoi(tmp.substr(3,2).c_str())) * 60) + atoi(tmp.substr(6,2).c_str());
fileSpecs["length"] = length;
length *= 100;
length += atoi(tmp.substr(9,2).c_str());
fileSpecs["lastms"] = length * 10;
}
if (line.find("bitrate") != std::string::npos ){
std::string tmp = line.substr(line.find(": ", line.find("bitrate")) + 2);
fileSpecs["bps"] = atoi(tmp.substr(0, tmp.find(" ")).c_str()) * 128;
}
if (line.find("Stream") != std::string::npos ){
std::string tmp = line.substr(line.find(" ", line.find("Stream")) + 1);
int strmIdx = fileSpecs["streams"].size();
int curPos = 0;
curPos = tmp.find(": ", curPos) + 2;
fileSpecs["streams"][strmIdx]["type"] = tmp.substr(curPos, tmp.find(":", curPos) - curPos);
curPos = tmp.find(":", curPos) + 2;
fileSpecs["streams"][strmIdx]["codec"] = tmp.substr(curPos, tmp.find_first_of(", ", curPos) - curPos);
curPos = tmp.find(",", curPos) + 2;
if (fileSpecs["streams"][strmIdx]["type"] == "Video"){
fileSpecs["streams"][strmIdx]["encoding"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["width"] = atoi(tmp.substr(curPos, tmp.find("x", curPos) - curPos).c_str());
curPos = tmp.find("x", curPos) + 1;
fileSpecs["streams"][strmIdx]["height"] = atoi(tmp.substr(curPos, tmp.find(",", curPos) - curPos).c_str());
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["bps"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 128;
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["fpks"] = (int)(atof(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 1000);
fileSpecs["streams"][strmIdx].removeMember( "type" );
fileSpecs["video"] = fileSpecs["streams"][strmIdx];
}else if (fileSpecs["streams"][strmIdx]["type"] == "Audio"){
fileSpecs["streams"][strmIdx]["samplerate"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str());
curPos = tmp.find(",", curPos) + 2;
if (tmp.substr(curPos, tmp.find(",", curPos) - curPos) == "stereo"){
fileSpecs["streams"][strmIdx]["channels"] = 2;
}else if (tmp.substr(curPos, tmp.find(",", curPos) - curPos) == "mono"){
fileSpecs["streams"][strmIdx]["channels"] = 1;
}else{
fileSpecs["streams"][strmIdx]["channels"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
}
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["samplewidth"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
curPos = tmp.find(",", curPos) + 2;
fileSpecs["streams"][strmIdx]["bps"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 128;
fileSpecs["streams"][strmIdx].removeMember( "type" );
fileSpecs["audio"] = fileSpecs["streams"][strmIdx];
}
}
}
fclose( outFile );
fileSpecs.removeMember( "streams" );
} else {
fileSpecs["format"] = "dtsc";
JSON::Value tracks = fileSpecs["tracks"];
for(JSON::ObjIter trackIt = tracks.ObjBegin(); trackIt != tracks.ObjEnd(); trackIt++){
if (fileSpecs["tracks"][trackIt->first].isMember("init")){
fileSpecs["tracks"][trackIt->first].removeMember("init");
}
if (fileSpecs["tracks"][trackIt->first].isMember("frags")){
fileSpecs["tracks"][trackIt->first].removeMember("frags");
}
if (fileSpecs["tracks"][trackIt->first].isMember("keys")){
fileSpecs["tracks"][trackIt->first].removeMember("keys");
}
}
}
if (fileSpecs.isMember("video")){
fileSpecs["video"].removeMember("init");
}
if (fileSpecs.isMember("audio")){
fileSpecs["audio"].removeMember("init");
}
printf( "%s", fileSpecs.toString().c_str() );
return 0;
}
}
int main(int argc, char* argv[]) {
return Info::getInfo(argc, argv);
}
<|endoftext|> |
<commit_before>#include "openmit/model/ffm.h"
#include "openmit/tools/dstruct/sarray.h"
namespace mit {
/////////////////////////////////////////////////////////////
// ffm model complemention for parameter server framework
/////////////////////////////////////////////////////////////
PSFFM::~PSFFM() {}
PSFFM* PSFFM::Get(const mit::KWArgs& kwargs) {
return new PSFFM(kwargs);
}
/*
// single thread
void PSFFM::Pull(ps::KVPairs<mit_float>& response, mit::entry_map_type* weight) {
size_t keys_size = response.keys.size();
CHECK(keys_size > 0);
CHECK_EQ(keys_size, response.extras.size()); // store field id
response.lens.resize(keys_size);
// intercept
CHECK_EQ(response.keys[0], 0);
if (weight->find(0) == weight->end()) {
weight->insert(std::make_pair(0, mit::Entry::Create(
model_param_, entry_meta_.get(), random_.get(), 0)));
}
response.vals.push_back((*weight)[0]->Get());
response.lens[0] = 1;
// feature
for (auto i = 1u; i < keys_size; ++i) {
ps::Key key = response.keys[i];
if (weight->find(key) == weight->end()) {
auto fid = response.extras[i];
CHECK(fid > 0) << "fid = 0";
auto* entry = mit::Entry::Create(model_param_, entry_meta_.get(), random_.get(), fid);
weight->insert(std::make_pair(key, entry));
}
auto* entry = (*weight)[key];
ps::SArray<mit_float> entry_data(entry->Data(), entry->Size());
response.vals.append(entry_data);
response.lens[i] = entry->Size();
}
}
*/
void PSFFM::Pull(ps::KVPairs<mit_float>& response, mit::entry_map_type* weight) {
size_t keys_size = response.keys.size();
CHECK(keys_size > 0);
CHECK_EQ(keys_size, response.extras.size()); // store field id
response.lens.resize(keys_size);
// intercept
CHECK_EQ(response.keys[0], 0);
if (weight->find(0) == weight->end()) {
weight->insert(std::make_pair(0, mit::Entry::Create(
model_param_, entry_meta_.get(), random_.get(), 0)));
}
response.vals.push_back((*weight)[0]->Get());
response.lens[0] = 1;
// feature (multi-thread)
auto nthread = cli_param_.num_thread; CHECK(nthread > 0);
std::vector<mit::SArray<mit_float>* > vals_thread(nthread);
for (auto i = 0u; i < nthread; ++i) {
vals_thread[i] = new mit::SArray<mit_float>();
}
int chunksize = (keys_size - 1) / nthread;
if ((keys_size - 1) % nthread != 0) chunksize += 1;
#pragma omp parallel for num_threads(nthread) schedule(static, chunksize)
for (auto i = 1u; i < keys_size; ++i) {
ps::Key key = response.keys[i];
mit::Entry* entry = nullptr;
if (weight->find(key) == weight->end()) {
auto fid = response.extras[i]; CHECK(fid > 0);
entry = mit::Entry::Create(model_param_, entry_meta_.get(), random_.get(), fid);
CHECK_NOTNULL(entry);
#pragma omp critical
{
std::lock_guard<std::mutex> lk(mu_);
weight->insert(std::make_pair(key, entry));
}
} else {
entry = (*weight)[key];
}
CHECK_NOTNULL(entry); CHECK(entry->Size() > 0);
vals_thread[omp_get_thread_num()]->append(entry->Data(), entry->Size());
response.lens[i] = entry->Size();
}
// merge multi-thread result
for (auto i = 0u; i < nthread; ++i) {
ps::SArray<mit_float> thread_data(vals_thread[i]->data(), vals_thread[i]->size());
response.vals.append(thread_data);
if (vals_thread[i]) { // free memory
vals_thread[i]->clear();
delete vals_thread[i]; vals_thread[i] = NULL;
}
}
/*
// feature (multi-thread)
auto nthread = cli_param_.num_thread; CHECK(nthread > 0);
std::vector<std::vector<mit_float>* > vals_thread(nthread);
for (auto i = 0u; i < nthread; ++i) {
vals_thread[i] = new std::vector<mit_float>();
}
int chunksize = (keys_size - 1) / nthread;
if ((keys_size - 1) % nthread != 0) chunksize += 1;
#pragma omp parallel for num_threads(nthread) schedule(static, chunksize)
for (auto i = 1u; i < keys_size; ++i) {
ps::Key key = response.keys[i];
mit::Entry* entry = nullptr;
if (weight->find(key) == weight->end()) {
auto fid = response.extras[i]; CHECK(fid > 0);
entry = mit::Entry::Create(model_param_, entry_meta_.get(), random_.get(), fid);
CHECK_NOTNULL(entry);
#pragma omp critical
{
std::lock_guard<std::mutex> lk(mu_);
weight->insert(std::make_pair(key, entry));
}
} else {
entry = (*weight)[key];
}
CHECK_NOTNULL(entry); CHECK(entry->Size() > 0);
for (auto idx = 0u; idx < entry->Size(); ++idx) {
vals_thread[omp_get_thread_num()]->push_back(entry->Get(idx));
}
response.lens[i] = entry->Size();
}
// merge multi-thread result
for (auto i = 0u; i < nthread; ++i) {
ps::SArray<mit_float> sarray(vals_thread[i]->data(), vals_thread[i]->size());
response.vals.append(sarray);
if (vals_thread[i]) { // free memory
vals_thread[i]->clear();
delete vals_thread[i]; vals_thread[i] = NULL;
}
}
*/
}
void PSFFM::Update(const ps::SArray<mit_uint>& keys,
const ps::SArray<mit_float>& vals,
const ps::SArray<int>& lens,
mit::entry_map_type* weight) {
auto keys_size = keys.size();
auto offset = 0u;
for (auto i = 0u; i < keys_size; ++i) {
auto key = keys[i];
if (weight->find(key) == weight->end()) {
LOG(FATAL) << key << " not in model structure";
}
// update_w (1-order linear item)
auto w = (*weight)[key]->Get(0);
auto g = vals[offset++];
optimizer_->Update(key, 0, g, w, (*weight)[key]);
(*weight)[key]->Set(0, w);
// update_v (2-order cross item)
if (lens[i] == 1) continue;
for (int k = 1; k < lens[i]; ++k) {
auto v = (*weight)[key]->Get(k);
auto g = vals[offset++];
optimizer_v_->Update(key, k, g, v, (*weight)[key]);
(*weight)[key]->Set(k, v);
}
}
CHECK_EQ(offset, vals.size()) << "offset not match vals.size for model update";
} // PSFFM::Update
void PSFFM::Gradient(const dmlc::Row<mit_uint>& row,
const std::vector<mit_float>& weights,
mit::key2offset_type& key2offset,
std::vector<mit_float>* grads,
const mit_float& loss_grad) {
auto instweight = row.get_weight();
// 0-order intercept
if (! cli_param_.is_contain_intercept) {
auto offset0 = key2offset[0].first;
(*grads)[offset0] += loss_grad * 1 * instweight;
}
// 1-order linear item
#pragma omp parallel for num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length; ++i) {
mit_uint key = row.index[i];
CHECK(key2offset.find(key) != key2offset.end()) << key << " not in key2offset";
auto offset = key2offset[key].first;
auto xi = row.get_value(i);
(*grads)[offset] += loss_grad * xi * instweight;
}
// 2-order cross item
#pragma omp parallel for num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length - 1; ++i) {
auto fi = row.field[i];
auto keyi = row.index[i];
auto xi = row.get_value(i);
// fi not in fields_map
if (! entry_meta_->CombineInfo(fi)) continue;
for (auto j = i + 1; j < row.length; ++j) {
auto fj = row.field[j];
if (fi == fj) continue; // not cross when same field
if (! entry_meta_->CombineInfo(fj)) continue;
auto keyj = row.index[j];
auto xj = row.get_value(j);
auto vifj_index = entry_meta_->FieldIndex(fi, fj);
if (vifj_index == -1) continue;
auto vifj_offset = key2offset[keyi].first + (1 + vifj_index * model_param_.embedding_size);
auto vjfi_index = entry_meta_->FieldIndex(fj, fi);
if (vjfi_index == -1) continue;
auto vjfi_offset = key2offset[keyj].first + (1 + vjfi_index * model_param_.embedding_size);
// vifj * vjfi * xi * xj
// SSE Accelerated ? const initialize for sse
for (auto k = 0u; k < model_param_.embedding_size; ++k) {
(*grads)[vifj_offset+k] += loss_grad * (weights[vjfi_offset+k] * xi * xj) * instweight;
(*grads)[vjfi_offset+k] += loss_grad * (weights[vifj_offset+k] * xi * xj) * instweight;
}
}
}
}
mit_float PSFFM::Predict(const dmlc::Row<mit_uint>& row,
const std::vector<mit_float>& weights,
mit::key2offset_type& key2offset,
bool norm) {
auto wTx = Linear(row, weights, key2offset);
wTx += Cross(row, weights, key2offset);
if (norm) return mit::math::sigmoid(wTx);
return wTx;
}
mit_float PSFFM::Linear(const dmlc::Row<mit_uint>& row,
const std::vector<mit_float>& weights,
mit::key2offset_type& key2offset) {
mit_float wTx = 0.0f;
// intercept
if (! cli_param_.is_contain_intercept) {
wTx += weights[key2offset[0].first];
}
#pragma omp parallel for reduction(+:wTx) num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length; ++i) {
auto key = row.index[i];
CHECK(key2offset.find(key) != key2offset.end()) << key << " not in key2offset";
auto offseti = key2offset[key].first;
wTx += weights[offseti] * row.get_value(i);
}
return wTx;
}
mit_float PSFFM::Cross(const dmlc::Row<mit_uint>& row, const std::vector<mit_float>& weights, mit::key2offset_type& key2offset) {
const mit_float* pweights = weights.data();
size_t weights_size = weights.size();
mit_float cross = 0.0f;
#pragma omp parallel for reduction(+:cross) num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length - 1; ++i) {
auto fi = row.field[i];
auto keyi = row.index[i];
auto xi = row.get_value(i);
// fi not in fields_map
if (! entry_meta_->CombineInfo(fi)) continue;
for (auto j = i + 1; j < row.length; ++j) {
auto fj = row.field[j];
if (fi == fj) continue; // not cross when same field
if (! entry_meta_->CombineInfo(fj)) continue;
auto keyj = row.index[j];
auto xj = row.get_value(j);
auto vifj_index = entry_meta_->FieldIndex(fi, fj);
auto vjfi_index = entry_meta_->FieldIndex(fj, fi);
if (vifj_index == -1 || vifj_index == -1) continue;
auto vifj_offset = key2offset[keyi].first + (1 + vifj_index * model_param_.embedding_size);
auto vjfi_offset = key2offset[keyj].first + (1 + vjfi_index * model_param_.embedding_size);
CHECK(vifj_offset + model_param_.embedding_size < weights_size);
CHECK(vjfi_offset + model_param_.embedding_size < weights_size);
// sse acceleration
auto inprod = InProdWithSSE(pweights + vifj_offset, pweights + vjfi_offset);
cross += inprod * xi * xj;
/*
auto inprod = 0.0f;
for (auto k = 0u; k < model_param_.embedding_size; ++k) {
inprod += weights[vifj_offset+k] * weights[vjfi_offset+k];
}
cross += inprod * xi * xj;
*/
}
}
return cross;
}
float PSFFM::InProdWithSSE(const float* p1, const float* p2) {
float sum = 0.0f;
__m128 inprod = _mm_setzero_ps();
if (blocksize > 0) {
for (auto offset = 0u; offset < blocksize; offset += 4) {
__m128 v1 = _mm_loadu_ps(p1 + offset);
__m128 v2 = _mm_loadu_ps(p2 + offset);
inprod = _mm_add_ps(inprod, _mm_mul_ps(v1, v2));
}
inprod = _mm_hadd_ps(inprod, inprod);
inprod = _mm_hadd_ps(inprod, inprod);
float v;
_mm_store_ss(&v, inprod);
sum += v;
}
if (remainder > 0) {
for (auto i = 0u; i < remainder; ++i) {
sum += p1[blocksize + i] * p2[blocksize + i];
}
}
return sum;
} // PSFFM::InProdWithSSE
/////////////////////////////////////////////////////////////
// ffm model complemention for mpi or local
/////////////////////////////////////////////////////////////
FFM::~FFM() {}
FFM* FFM::Get(const mit::KWArgs& kwargs) {
return new FFM(kwargs);
}
void FFM::Gradient(const dmlc::Row<mit_uint>& row, const mit_float& pred, mit::SArray<mit_float>* grad) {
// TODO
} // FFM::Gradient
mit_float FFM::Predict(const dmlc::Row<mit_uint>& row, const mit::SArray<mit_float>& weight, bool norm) {
// TODO
return 0.0f;
} // FFM::Predict
} // namespace mit
<commit_msg>update<commit_after>#include "openmit/model/ffm.h"
#include "openmit/tools/dstruct/sarray.h"
namespace mit {
/////////////////////////////////////////////////////////////
// ffm model complemention for parameter server framework
/////////////////////////////////////////////////////////////
PSFFM::~PSFFM() {}
PSFFM* PSFFM::Get(const mit::KWArgs& kwargs) {
return new PSFFM(kwargs);
}
/*
// single thread
void PSFFM::Pull(ps::KVPairs<mit_float>& response, mit::entry_map_type* weight) {
size_t keys_size = response.keys.size();
CHECK(keys_size > 0);
CHECK_EQ(keys_size, response.extras.size()); // store field id
response.lens.resize(keys_size);
// intercept
CHECK_EQ(response.keys[0], 0);
if (weight->find(0) == weight->end()) {
weight->insert(std::make_pair(0, mit::Entry::Create(
model_param_, entry_meta_.get(), random_.get(), 0)));
}
response.vals.push_back((*weight)[0]->Get());
response.lens[0] = 1;
// feature
for (auto i = 1u; i < keys_size; ++i) {
ps::Key key = response.keys[i];
if (weight->find(key) == weight->end()) {
auto fid = response.extras[i];
CHECK(fid > 0) << "fid = 0";
auto* entry = mit::Entry::Create(model_param_, entry_meta_.get(), random_.get(), fid);
weight->insert(std::make_pair(key, entry));
}
auto* entry = (*weight)[key];
ps::SArray<mit_float> entry_data(entry->Data(), entry->Size());
response.vals.append(entry_data);
response.lens[i] = entry->Size();
}
}
*/
void PSFFM::Pull(ps::KVPairs<mit_float>& response, mit::entry_map_type* weight) {
size_t keys_size = response.keys.size();
CHECK(keys_size > 0);
CHECK_EQ(keys_size, response.extras.size()); // store field id
response.lens.resize(keys_size);
// intercept
CHECK_EQ(response.keys[0], 0);
if (weight->find(0) == weight->end()) {
weight->insert(std::make_pair(0, mit::Entry::Create(
model_param_, entry_meta_.get(), random_.get(), 0)));
}
response.vals.push_back((*weight)[0]->Get());
response.lens[0] = 1;
// feature (multi-thread)
auto nthread = cli_param_.num_thread; CHECK(nthread > 0);
std::vector<std::vector<mit_float>* > vals_thread(nthread);
for (auto i = 0u; i < nthread; ++i) {
vals_thread[i] = new std::vector<mit_float>();
}
int chunksize = (keys_size - 1) / nthread;
if ((keys_size - 1) % nthread != 0) chunksize += 1;
#pragma omp parallel for num_threads(nthread) schedule(static, chunksize)
for (auto i = 1u; i < keys_size; ++i) {
ps::Key key = response.keys[i];
mit::Entry* entry = nullptr;
if (weight->find(key) == weight->end()) {
auto fid = response.extras[i]; CHECK(fid > 0);
entry = mit::Entry::Create(model_param_, entry_meta_.get(), random_.get(), fid);
CHECK_NOTNULL(entry);
#pragma omp critical
{
std::lock_guard<std::mutex> lk(mu_);
weight->insert(std::make_pair(key, entry));
}
} else {
entry = (*weight)[key];
}
CHECK_NOTNULL(entry); CHECK(entry->Size() > 0);
if (entry->Size() > 10) {
vals_thread[omp_get_thread_num()]->insert(
vals_thread[omp_get_thread_num()]->end(), entry->Data(), entry->Size());
} else {
for (auto idx = 0u; idx < entry->Size(); ++idx) {
vals_thread[omp_get_thread_num()]->push_back(entry->Get(idx));
}
}
response.lens[i] = entry->Size();
}
// merge multi-thread result
for (auto i = 0u; i < nthread; ++i) {
ps::SArray<mit_float> sarray(vals_thread[i]->data(), vals_thread[i]->size());
response.vals.append(sarray);
if (vals_thread[i]) { // free memory
vals_thread[i]->clear();
delete vals_thread[i]; vals_thread[i] = NULL;
}
}
}
void PSFFM::Update(const ps::SArray<mit_uint>& keys,
const ps::SArray<mit_float>& vals,
const ps::SArray<int>& lens,
mit::entry_map_type* weight) {
auto keys_size = keys.size();
auto offset = 0u;
for (auto i = 0u; i < keys_size; ++i) {
auto key = keys[i];
if (weight->find(key) == weight->end()) {
LOG(FATAL) << key << " not in model structure";
}
// update_w (1-order linear item)
auto w = (*weight)[key]->Get(0);
auto g = vals[offset++];
optimizer_->Update(key, 0, g, w, (*weight)[key]);
(*weight)[key]->Set(0, w);
// update_v (2-order cross item)
if (lens[i] == 1) continue;
for (int k = 1; k < lens[i]; ++k) {
auto v = (*weight)[key]->Get(k);
auto g = vals[offset++];
optimizer_v_->Update(key, k, g, v, (*weight)[key]);
(*weight)[key]->Set(k, v);
}
}
CHECK_EQ(offset, vals.size()) << "offset not match vals.size for model update";
} // PSFFM::Update
void PSFFM::Gradient(const dmlc::Row<mit_uint>& row,
const std::vector<mit_float>& weights,
mit::key2offset_type& key2offset,
std::vector<mit_float>* grads,
const mit_float& loss_grad) {
auto instweight = row.get_weight();
// 0-order intercept
if (! cli_param_.is_contain_intercept) {
auto offset0 = key2offset[0].first;
(*grads)[offset0] += loss_grad * 1 * instweight;
}
// 1-order linear item
#pragma omp parallel for num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length; ++i) {
mit_uint key = row.index[i];
CHECK(key2offset.find(key) != key2offset.end()) << key << " not in key2offset";
auto offset = key2offset[key].first;
auto xi = row.get_value(i);
(*grads)[offset] += loss_grad * xi * instweight;
}
// 2-order cross item
#pragma omp parallel for num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length - 1; ++i) {
auto fi = row.field[i];
auto keyi = row.index[i];
auto xi = row.get_value(i);
// fi not in fields_map
if (! entry_meta_->CombineInfo(fi)) continue;
for (auto j = i + 1; j < row.length; ++j) {
auto fj = row.field[j];
if (fi == fj) continue; // not cross when same field
if (! entry_meta_->CombineInfo(fj)) continue;
auto keyj = row.index[j];
auto xj = row.get_value(j);
auto vifj_index = entry_meta_->FieldIndex(fi, fj);
if (vifj_index == -1) continue;
auto vifj_offset = key2offset[keyi].first + (1 + vifj_index * model_param_.embedding_size);
auto vjfi_index = entry_meta_->FieldIndex(fj, fi);
if (vjfi_index == -1) continue;
auto vjfi_offset = key2offset[keyj].first + (1 + vjfi_index * model_param_.embedding_size);
// vifj * vjfi * xi * xj
// SSE Accelerated ? const initialize for sse
for (auto k = 0u; k < model_param_.embedding_size; ++k) {
(*grads)[vifj_offset+k] += loss_grad * (weights[vjfi_offset+k] * xi * xj) * instweight;
(*grads)[vjfi_offset+k] += loss_grad * (weights[vifj_offset+k] * xi * xj) * instweight;
}
}
}
}
mit_float PSFFM::Predict(const dmlc::Row<mit_uint>& row,
const std::vector<mit_float>& weights,
mit::key2offset_type& key2offset,
bool norm) {
auto wTx = Linear(row, weights, key2offset);
wTx += Cross(row, weights, key2offset);
if (norm) return mit::math::sigmoid(wTx);
return wTx;
}
mit_float PSFFM::Linear(const dmlc::Row<mit_uint>& row,
const std::vector<mit_float>& weights,
mit::key2offset_type& key2offset) {
mit_float wTx = 0.0f;
// intercept
if (! cli_param_.is_contain_intercept) {
wTx += weights[key2offset[0].first];
}
#pragma omp parallel for reduction(+:wTx) num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length; ++i) {
auto key = row.index[i];
CHECK(key2offset.find(key) != key2offset.end()) << key << " not in key2offset";
auto offseti = key2offset[key].first;
wTx += weights[offseti] * row.get_value(i);
}
return wTx;
}
mit_float PSFFM::Cross(const dmlc::Row<mit_uint>& row, const std::vector<mit_float>& weights, mit::key2offset_type& key2offset) {
const mit_float* pweights = weights.data();
size_t weights_size = weights.size();
mit_float cross = 0.0f;
#pragma omp parallel for reduction(+:cross) num_threads(cli_param_.num_thread)
for (auto i = 0u; i < row.length - 1; ++i) {
auto fi = row.field[i];
auto keyi = row.index[i];
auto xi = row.get_value(i);
// fi not in fields_map
if (! entry_meta_->CombineInfo(fi)) continue;
for (auto j = i + 1; j < row.length; ++j) {
auto fj = row.field[j];
if (fi == fj) continue; // not cross when same field
if (! entry_meta_->CombineInfo(fj)) continue;
auto keyj = row.index[j];
auto xj = row.get_value(j);
auto vifj_index = entry_meta_->FieldIndex(fi, fj);
auto vjfi_index = entry_meta_->FieldIndex(fj, fi);
if (vifj_index == -1 || vifj_index == -1) continue;
auto vifj_offset = key2offset[keyi].first + (1 + vifj_index * model_param_.embedding_size);
auto vjfi_offset = key2offset[keyj].first + (1 + vjfi_index * model_param_.embedding_size);
CHECK(vifj_offset + model_param_.embedding_size < weights_size);
CHECK(vjfi_offset + model_param_.embedding_size < weights_size);
// sse acceleration
auto inprod = InProdWithSSE(pweights + vifj_offset, pweights + vjfi_offset);
cross += inprod * xi * xj;
/*
auto inprod = 0.0f;
for (auto k = 0u; k < model_param_.embedding_size; ++k) {
inprod += weights[vifj_offset+k] * weights[vjfi_offset+k];
}
cross += inprod * xi * xj;
*/
}
}
return cross;
}
float PSFFM::InProdWithSSE(const float* p1, const float* p2) {
float sum = 0.0f;
__m128 inprod = _mm_setzero_ps();
if (blocksize > 0) {
for (auto offset = 0u; offset < blocksize; offset += 4) {
__m128 v1 = _mm_loadu_ps(p1 + offset);
__m128 v2 = _mm_loadu_ps(p2 + offset);
inprod = _mm_add_ps(inprod, _mm_mul_ps(v1, v2));
}
inprod = _mm_hadd_ps(inprod, inprod);
inprod = _mm_hadd_ps(inprod, inprod);
float v;
_mm_store_ss(&v, inprod);
sum += v;
}
if (remainder > 0) {
for (auto i = 0u; i < remainder; ++i) {
sum += p1[blocksize + i] * p2[blocksize + i];
}
}
return sum;
} // PSFFM::InProdWithSSE
/////////////////////////////////////////////////////////////
// ffm model complemention for mpi or local
/////////////////////////////////////////////////////////////
FFM::~FFM() {}
FFM* FFM::Get(const mit::KWArgs& kwargs) {
return new FFM(kwargs);
}
void FFM::Gradient(const dmlc::Row<mit_uint>& row, const mit_float& pred, mit::SArray<mit_float>* grad) {
// TODO
} // FFM::Gradient
mit_float FFM::Predict(const dmlc::Row<mit_uint>& row, const mit::SArray<mit_float>& weight, bool norm) {
// TODO
return 0.0f;
} // FFM::Predict
} // namespace mit
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <gtest/gtest.h>
#include "joynr/BrokerUrl.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/Message.h"
#include "joynr/MessagingSettings.h"
#include "joynr/MutableMessage.h"
#include "joynr/Settings.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "libjoynrclustercontroller/mqtt/MqttSender.h"
#include "tests/mock/MockMosquittoConnection.h"
using namespace ::testing;
namespace joynr
{
class MqttSenderTest : public testing::Test
{
public:
MqttSenderTest() : mqttAddress("brokerUri", "clientId"), mockMosquittoConnection(), mqttSender()
{
}
protected:
void createMqttSender(std::string testSettingsFileNameMqtt)
{
Settings testSettings(testSettingsFileNameMqtt);
MessagingSettings messagingSettings(testSettings);
const ClusterControllerSettings ccSettings(testSettings);
BrokerUrl brokerUrl("testBrokerUrl");
std::chrono::seconds mqttKeepAliveTimeSeconds(1);
std::chrono::seconds mqttReconnectDelayTimeSeconds(1);
std::chrono::seconds mqttReconnectMaxDelayTimeSeconds(1);
bool isMqttExponentialBackoffEnabled(false);
const std::string clientId("testClientId");
mockMosquittoConnection =
std::make_shared<MockMosquittoConnection>(ccSettings,
brokerUrl,
mqttKeepAliveTimeSeconds,
mqttReconnectDelayTimeSeconds,
mqttReconnectMaxDelayTimeSeconds,
isMqttExponentialBackoffEnabled,
clientId);
mqttSender = std::make_shared<MqttSender>(mockMosquittoConnection, messagingSettings);
ON_CALL(*mockMosquittoConnection, isSubscribedToChannelTopic()).WillByDefault(Return(true));
ON_CALL(*mockMosquittoConnection, getMqttQos()).WillByDefault(Return(0));
ON_CALL(*mockMosquittoConnection, getMqttPrio()).WillByDefault(Return("low"));
}
ADD_LOGGER(MqttSenderTest)
joynr::system::RoutingTypes::MqttAddress mqttAddress;
std::shared_ptr<MockMosquittoConnection> mockMosquittoConnection;
std::shared_ptr<MqttSender> mqttSender;
};
TEST_F(MqttSenderTest, messagePublishedToCorrectTopic)
{
const std::string expectedTopic = mqttAddress.getTopic() + "/low";
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings");
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_REQUEST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testRecipient");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
Eq(expectedTopic),
Eq(0),
_,
_,
_,
_));
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
});
}
TEST_F(MqttSenderTest, messagePublishedWithMsgTtlSecAlwaysRoundedUp)
{
const TimePoint now = TimePoint::now();
const std::uint32_t expectedRoundedMsgTtlSec = 61;
auto onFailure = [] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
};
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings");
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_REQUEST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testRecipient");
mutableMessage.setPayload("shortMessage");
mutableMessage.setExpiryDate(now + std::chrono::milliseconds(60700)); // 60,7 sec will be rounded to 61 sec
std::shared_ptr<joynr::ImmutableMessage> immutableMessage1 =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
_,
_,
_,
Eq(expectedRoundedMsgTtlSec),
_,
_));
mqttSender->sendMessage(mqttAddress, immutableMessage1, onFailure);
auto relativeTtl1 = immutableMessage1->getExpiryDate().relativeFromNow().count();
ASSERT_TRUE(relativeTtl1 % 1000 > 600 && relativeTtl1 % 1000 < 800);
// Second message with different expiry date
mutableMessage.setExpiryDate(now + std::chrono::milliseconds(60200)); // 60,2 sec will be rounded to 61 sec
std::shared_ptr<joynr::ImmutableMessage> immutableMessage2 =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
_,
_,
_,
Eq(expectedRoundedMsgTtlSec),
_,
_));
mqttSender->sendMessage(mqttAddress, immutableMessage2, onFailure);
auto relativeTtl2 = immutableMessage2->getExpiryDate().relativeFromNow().count();
ASSERT_TRUE(relativeTtl2 % 1000 > 100 && relativeTtl2 % 1000 < 300);
}
TEST_F(MqttSenderTest, messagePublishedWithMsgTtlSecGreaterThanMaxIntervalAlwaysSetToMaxInterval)
{
const TimePoint now = TimePoint::now();
const std::uint32_t MESSAGE_EXPIRY_MAX_INTERVAL = std::numeric_limits<std::uint32_t>::max();
const std::uint32_t expectedMaxMsgTtlSec = MESSAGE_EXPIRY_MAX_INTERVAL;
auto onFailure = [] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
};
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings");
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_REQUEST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testRecipient");
mutableMessage.setPayload("shortMessage");
mutableMessage.setExpiryDate(now + std::chrono::seconds(MESSAGE_EXPIRY_MAX_INTERVAL) +
std::chrono::seconds(6));
std::shared_ptr<joynr::ImmutableMessage> immutableMessage1 =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
_,
_,
_,
Eq(expectedMaxMsgTtlSec),
_,
_)).Times(2);
mqttSender->sendMessage(mqttAddress, immutableMessage1, onFailure);
mutableMessage.setExpiryDate(TimePoint::fromAbsoluteMs(-1000));
std::shared_ptr<joynr::ImmutableMessage> immutableMessage2 =
mutableMessage.getImmutableMessage();
mqttSender->sendMessage(mqttAddress, immutableMessage2, onFailure);
}
TEST_F(MqttSenderTest, multicastMessagePublishedToCorrectTopic)
{
const std::string expectedTopic = mqttAddress.getTopic();
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings");
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_MULTICAST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testMulticastId");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
Eq(expectedTopic),
Eq(0),
_,
_,
_,
_));
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
});
}
TEST_F(MqttSenderTest, TestWithEnabledMessageSizeCheck)
{
MutableMessage mutableMessage;
bool gotExpectedExceptionType;
bool gotCalled;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits1.settings");
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_MULTICAST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testMulticastId");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
gotCalled = false;
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[&gotCalled](
const exceptions::JoynrRuntimeException& exception) {
gotCalled = true;
try {
const joynr::exceptions::JoynrMessageNotSentException& messageNotSentException =
dynamic_cast<const joynr::exceptions::JoynrMessageNotSentException&>(exception);
std::ignore = messageNotSentException;
} catch (std::bad_cast& bc) {
// fallthrough
}
});
EXPECT_FALSE(gotCalled);
std::string longMessagePayload(1000, 'x');
mutableMessage.setPayload(longMessagePayload);
immutableMessage = mutableMessage.getImmutableMessage();
gotExpectedExceptionType = false;
gotCalled = false;
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[&gotCalled, &gotExpectedExceptionType](
const exceptions::JoynrRuntimeException& exception) {
gotCalled = true;
try {
const joynr::exceptions::JoynrMessageNotSentException& messageNotSentException =
dynamic_cast<const joynr::exceptions::JoynrMessageNotSentException&>(exception);
gotExpectedExceptionType = true;
std::ignore = messageNotSentException;
} catch (std::bad_cast& bc) {
// fallthrough
}
});
EXPECT_TRUE(gotCalled);
EXPECT_TRUE(gotExpectedExceptionType);
}
TEST_F(MqttSenderTest, TestWithDisabledMessageSizeCheck)
{
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings");
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_MULTICAST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testMulticastId");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
bool gotCalled = false;
mqttSender->sendMessage(
mqttAddress,
immutableMessage,
[&gotCalled](const exceptions::JoynrRuntimeException&) { gotCalled = true; });
EXPECT_FALSE(gotCalled);
std::string longMessagePayload(1000, 'x');
mutableMessage.setPayload(longMessagePayload);
immutableMessage = mutableMessage.getImmutableMessage();
gotCalled = false;
mqttSender->sendMessage(
mqttAddress,
immutableMessage,
[&gotCalled](const exceptions::JoynrRuntimeException&) { gotCalled = true; });
EXPECT_FALSE(gotCalled);
}
} // namespace joynr
<commit_msg>[C++] Adjusted MqttSenderTest which now gets maximum packet size from Mock<commit_after>/*
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <gtest/gtest.h>
#include "joynr/BrokerUrl.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/Message.h"
#include "joynr/MessagingSettings.h"
#include "joynr/MutableMessage.h"
#include "joynr/Settings.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "libjoynrclustercontroller/mqtt/MqttSender.h"
#include "tests/mock/MockMosquittoConnection.h"
using namespace ::testing;
namespace joynr
{
class MqttSenderTest : public testing::Test
{
public:
MqttSenderTest() : mqttAddress("brokerUri", "clientId"), mockMosquittoConnection(), mqttSender()
{
}
protected:
void createMqttSender(std::string testSettingsFileNameMqtt, std::uint32_t maximumPacketSize)
{
Settings testSettings(testSettingsFileNameMqtt);
MessagingSettings messagingSettings(testSettings);
const ClusterControllerSettings ccSettings(testSettings);
BrokerUrl brokerUrl("testBrokerUrl");
std::chrono::seconds mqttKeepAliveTimeSeconds(1);
std::chrono::seconds mqttReconnectDelayTimeSeconds(1);
std::chrono::seconds mqttReconnectMaxDelayTimeSeconds(1);
bool isMqttExponentialBackoffEnabled(false);
const std::string clientId("testClientId");
mockMosquittoConnection =
std::make_shared<MockMosquittoConnection>(ccSettings,
brokerUrl,
mqttKeepAliveTimeSeconds,
mqttReconnectDelayTimeSeconds,
mqttReconnectMaxDelayTimeSeconds,
isMqttExponentialBackoffEnabled,
clientId);
mqttSender = std::make_shared<MqttSender>(mockMosquittoConnection, messagingSettings);
ON_CALL(*mockMosquittoConnection, isSubscribedToChannelTopic()).WillByDefault(Return(true));
ON_CALL(*mockMosquittoConnection, getMqttQos()).WillByDefault(Return(0));
ON_CALL(*mockMosquittoConnection, getMqttPrio()).WillByDefault(Return("low"));
ON_CALL(*mockMosquittoConnection, getMqttMaximumPacketSize()).WillByDefault(Return(maximumPacketSize));
}
ADD_LOGGER(MqttSenderTest)
joynr::system::RoutingTypes::MqttAddress mqttAddress;
std::shared_ptr<MockMosquittoConnection> mockMosquittoConnection;
std::shared_ptr<MqttSender> mqttSender;
const std::uint32_t noMqttMessagePacketSize = 0;
};
TEST_F(MqttSenderTest, messagePublishedToCorrectTopic)
{
const std::string expectedTopic = mqttAddress.getTopic() + "/low";
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings", MqttSenderTest::noMqttMessagePacketSize);
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_REQUEST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testRecipient");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
Eq(expectedTopic),
Eq(0),
_,
_,
_,
_));
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
});
}
TEST_F(MqttSenderTest, messagePublishedWithMsgTtlSecAlwaysRoundedUp)
{
const TimePoint now = TimePoint::now();
const std::uint32_t expectedRoundedMsgTtlSec = 61;
auto onFailure = [] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
};
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings", MqttSenderTest::noMqttMessagePacketSize);
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_REQUEST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testRecipient");
mutableMessage.setPayload("shortMessage");
mutableMessage.setExpiryDate(now + std::chrono::milliseconds(60700)); // 60,7 sec will be rounded to 61 sec
std::shared_ptr<joynr::ImmutableMessage> immutableMessage1 =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
_,
_,
_,
Eq(expectedRoundedMsgTtlSec),
_,
_));
mqttSender->sendMessage(mqttAddress, immutableMessage1, onFailure);
auto relativeTtl1 = immutableMessage1->getExpiryDate().relativeFromNow().count();
ASSERT_TRUE(relativeTtl1 % 1000 > 600 && relativeTtl1 % 1000 < 800);
// Second message with different expiry date
mutableMessage.setExpiryDate(now + std::chrono::milliseconds(60200)); // 60,2 sec will be rounded to 61 sec
std::shared_ptr<joynr::ImmutableMessage> immutableMessage2 =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
_,
_,
_,
Eq(expectedRoundedMsgTtlSec),
_,
_));
mqttSender->sendMessage(mqttAddress, immutableMessage2, onFailure);
auto relativeTtl2 = immutableMessage2->getExpiryDate().relativeFromNow().count();
ASSERT_TRUE(relativeTtl2 % 1000 > 100 && relativeTtl2 % 1000 < 300);
}
TEST_F(MqttSenderTest, messagePublishedWithMsgTtlSecGreaterThanMaxIntervalAlwaysSetToMaxInterval)
{
const TimePoint now = TimePoint::now();
const std::uint32_t MESSAGE_EXPIRY_MAX_INTERVAL = std::numeric_limits<std::uint32_t>::max();
const std::uint32_t expectedMaxMsgTtlSec = MESSAGE_EXPIRY_MAX_INTERVAL;
auto onFailure = [] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
};
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings", MqttSenderTest::noMqttMessagePacketSize);
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_REQUEST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testRecipient");
mutableMessage.setPayload("shortMessage");
mutableMessage.setExpiryDate(now + std::chrono::seconds(MESSAGE_EXPIRY_MAX_INTERVAL) +
std::chrono::seconds(6));
std::shared_ptr<joynr::ImmutableMessage> immutableMessage1 =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
_,
_,
_,
Eq(expectedMaxMsgTtlSec),
_,
_)).Times(2);
mqttSender->sendMessage(mqttAddress, immutableMessage1, onFailure);
mutableMessage.setExpiryDate(TimePoint::fromAbsoluteMs(-1000));
std::shared_ptr<joynr::ImmutableMessage> immutableMessage2 =
mutableMessage.getImmutableMessage();
mqttSender->sendMessage(mqttAddress, immutableMessage2, onFailure);
}
TEST_F(MqttSenderTest, multicastMessagePublishedToCorrectTopic)
{
const std::string expectedTopic = mqttAddress.getTopic();
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings", MqttSenderTest::noMqttMessagePacketSize);
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_MULTICAST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testMulticastId");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
EXPECT_CALL(*mockMosquittoConnection, publishMessage(
Eq(expectedTopic),
Eq(0),
_,
_,
_,
_));
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[] (const exceptions::JoynrRuntimeException& exception) {
FAIL() << "sendMessage failed: " << exception.getMessage();
});
}
TEST_F(MqttSenderTest, TestWithEnabledMessageSizeCheck)
{
MutableMessage mutableMessage;
bool gotExpectedExceptionType;
bool gotCalled;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits1.settings", 900);
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_MULTICAST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testMulticastId");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
gotCalled = false;
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[&gotCalled](
const exceptions::JoynrRuntimeException& exception) {
gotCalled = true;
try {
const joynr::exceptions::JoynrMessageNotSentException& messageNotSentException =
dynamic_cast<const joynr::exceptions::JoynrMessageNotSentException&>(exception);
std::ignore = messageNotSentException;
} catch (std::bad_cast& bc) {
// fallthrough
}
});
EXPECT_FALSE(gotCalled);
std::string longMessagePayload(1000, 'x');
mutableMessage.setPayload(longMessagePayload);
immutableMessage = mutableMessage.getImmutableMessage();
gotExpectedExceptionType = false;
gotCalled = false;
mqttSender->sendMessage(mqttAddress,
immutableMessage,
[&gotCalled, &gotExpectedExceptionType](
const exceptions::JoynrRuntimeException& exception) {
gotCalled = true;
try {
const joynr::exceptions::JoynrMessageNotSentException& messageNotSentException =
dynamic_cast<const joynr::exceptions::JoynrMessageNotSentException&>(exception);
gotExpectedExceptionType = true;
std::ignore = messageNotSentException;
} catch (std::bad_cast& bc) {
// fallthrough
}
});
EXPECT_TRUE(gotCalled);
EXPECT_TRUE(gotExpectedExceptionType);
}
TEST_F(MqttSenderTest, TestWithDisabledMessageSizeCheck)
{
MutableMessage mutableMessage;
createMqttSender("test-resources/MqttSenderTestWithMaxMessageSizeLimits2.settings", 0);
mutableMessage.setType(joynr::Message::VALUE_MESSAGE_TYPE_MULTICAST());
mutableMessage.setSender("testSender");
mutableMessage.setRecipient("testMulticastId");
mutableMessage.setPayload("shortMessage");
std::shared_ptr<joynr::ImmutableMessage> immutableMessage =
mutableMessage.getImmutableMessage();
bool gotCalled = false;
mqttSender->sendMessage(
mqttAddress,
immutableMessage,
[&gotCalled](const exceptions::JoynrRuntimeException&) { gotCalled = true; });
EXPECT_FALSE(gotCalled);
std::string longMessagePayload(1000, 'x');
mutableMessage.setPayload(longMessagePayload);
immutableMessage = mutableMessage.getImmutableMessage();
gotCalled = false;
mqttSender->sendMessage(
mqttAddress,
immutableMessage,
[&gotCalled](const exceptions::JoynrRuntimeException&) { gotCalled = true; });
EXPECT_FALSE(gotCalled);
}
} // namespace joynr
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: certificatecontainer.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-11-07 10:05:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "precompiled_xmlsecurity.hxx"
#include <certificatecontainer.hxx>
#ifndef _SAL_CONFIG_H_
#include <sal/config.h>
#endif
using namespace ::com::sun::star::uno;
sal_Bool
CertificateContainer::searchMap( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name, Map &_certMap )
{
Map::iterator p = _certMap.find(url);
::sal_Bool ret = sal_False;
while( p != _certMap.end() )
{
ret = (sal_Bool) (*p).second.equals(certificate_name);
if( ret )
break;
p++;
}
return ret;
}
// -------------------------------------------------------------------
sal_Bool
CertificateContainer::isTemporaryCertificate ( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name )
throw(::com::sun::star::uno::RuntimeException)
{
return searchMap( url, certificate_name, certMap);
}
// -------------------------------------------------------------------
sal_Bool
CertificateContainer::isCertificateTrust ( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name )
throw(::com::sun::star::uno::RuntimeException)
{
return searchMap( url, certificate_name, certTrustMap);
}
// -------------------------------------------------------------------
sal_Bool
CertificateContainer::addCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name, ::sal_Bool trust )
throw(::com::sun::star::uno::RuntimeException)
{
certMap.insert( Map::value_type( url, certificate_name ) );
//remember that the cert is trusted
if (trust)
certTrustMap.insert( Map::value_type( url, certificate_name ) );
return true;
}
//-------------------------------------------------------------------------
::security::CertificateContainerStatus
CertificateContainer::hasCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name ) throw(::com::sun::star::uno::RuntimeException)
{
if ( isTemporaryCertificate( url, certificate_name ) )
{
if ( isCertificateTrust( url, certificate_name ) )
return security::CertificateContainerStatus( security::CertificateContainerStatus_TRUSTED );
else
return security::CertificateContainerStatus_UNTRUSTED;
} else
{
return security::CertificateContainerStatus_NOCERT;
}
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL
CertificateContainer::getImplementationName( )
throw(::com::sun::star::uno::RuntimeException)
{
return impl_getStaticImplementationName();
}
//-------------------------------------------------------------------------
sal_Bool SAL_CALL
CertificateContainer::supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException)
{
if ( ServiceName.compareToAscii("com.sun.star.security.CertificateContainer") == 0 )
return sal_True;
else
return sal_False;
}
//-------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL
CertificateContainer::getSupportedServiceNames( )
throw(::com::sun::star::uno::RuntimeException)
{
return impl_getStaticSupportedServiceNames();
}
//-------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL
CertificateContainer::impl_getStaticSupportedServiceNames( )
throw(::com::sun::star::uno::RuntimeException)
{
Sequence< ::rtl::OUString > aRet(1);
*aRet.getArray() = ::rtl::OUString::createFromAscii("com.sun.star.security.CertificateContainer");
return aRet;
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL
CertificateContainer::impl_getStaticImplementationName()
throw(::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.security.CertificateContainer");
}
//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL CertificateContainer::impl_createInstance( const Reference< XMultiServiceFactory >& xServiceManager )
throw( RuntimeException )
{
return Reference< XInterface >( *new CertificateContainer( xServiceManager ) );
}
//-------------------------------------------------------------------------
Reference< XSingleServiceFactory > SAL_CALL
CertificateContainer::impl_createFactory( const Reference< XMultiServiceFactory >& ServiceManager )
throw(RuntimeException)
{
Reference< XSingleServiceFactory > xReturn( ::cppu::createOneInstanceFactory( ServiceManager,
CertificateContainer::impl_getStaticImplementationName(),
CertificateContainer::impl_createInstance,
CertificateContainer::impl_getStaticSupportedServiceNames()));
return xReturn;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.2.36); FILE MERGED 2008/04/01 16:10:53 thb 1.2.36.2: #i85898# Stripping all external header guards 2008/03/31 16:30:56 rt 1.2.36.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: certificatecontainer.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_xmlsecurity.hxx"
#include <certificatecontainer.hxx>
#include <sal/config.h>
using namespace ::com::sun::star::uno;
sal_Bool
CertificateContainer::searchMap( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name, Map &_certMap )
{
Map::iterator p = _certMap.find(url);
::sal_Bool ret = sal_False;
while( p != _certMap.end() )
{
ret = (sal_Bool) (*p).second.equals(certificate_name);
if( ret )
break;
p++;
}
return ret;
}
// -------------------------------------------------------------------
sal_Bool
CertificateContainer::isTemporaryCertificate ( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name )
throw(::com::sun::star::uno::RuntimeException)
{
return searchMap( url, certificate_name, certMap);
}
// -------------------------------------------------------------------
sal_Bool
CertificateContainer::isCertificateTrust ( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name )
throw(::com::sun::star::uno::RuntimeException)
{
return searchMap( url, certificate_name, certTrustMap);
}
// -------------------------------------------------------------------
sal_Bool
CertificateContainer::addCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name, ::sal_Bool trust )
throw(::com::sun::star::uno::RuntimeException)
{
certMap.insert( Map::value_type( url, certificate_name ) );
//remember that the cert is trusted
if (trust)
certTrustMap.insert( Map::value_type( url, certificate_name ) );
return true;
}
//-------------------------------------------------------------------------
::security::CertificateContainerStatus
CertificateContainer::hasCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name ) throw(::com::sun::star::uno::RuntimeException)
{
if ( isTemporaryCertificate( url, certificate_name ) )
{
if ( isCertificateTrust( url, certificate_name ) )
return security::CertificateContainerStatus( security::CertificateContainerStatus_TRUSTED );
else
return security::CertificateContainerStatus_UNTRUSTED;
} else
{
return security::CertificateContainerStatus_NOCERT;
}
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL
CertificateContainer::getImplementationName( )
throw(::com::sun::star::uno::RuntimeException)
{
return impl_getStaticImplementationName();
}
//-------------------------------------------------------------------------
sal_Bool SAL_CALL
CertificateContainer::supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException)
{
if ( ServiceName.compareToAscii("com.sun.star.security.CertificateContainer") == 0 )
return sal_True;
else
return sal_False;
}
//-------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL
CertificateContainer::getSupportedServiceNames( )
throw(::com::sun::star::uno::RuntimeException)
{
return impl_getStaticSupportedServiceNames();
}
//-------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL
CertificateContainer::impl_getStaticSupportedServiceNames( )
throw(::com::sun::star::uno::RuntimeException)
{
Sequence< ::rtl::OUString > aRet(1);
*aRet.getArray() = ::rtl::OUString::createFromAscii("com.sun.star.security.CertificateContainer");
return aRet;
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL
CertificateContainer::impl_getStaticImplementationName()
throw(::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.security.CertificateContainer");
}
//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL CertificateContainer::impl_createInstance( const Reference< XMultiServiceFactory >& xServiceManager )
throw( RuntimeException )
{
return Reference< XInterface >( *new CertificateContainer( xServiceManager ) );
}
//-------------------------------------------------------------------------
Reference< XSingleServiceFactory > SAL_CALL
CertificateContainer::impl_createFactory( const Reference< XMultiServiceFactory >& ServiceManager )
throw(RuntimeException)
{
Reference< XSingleServiceFactory > xReturn( ::cppu::createOneInstanceFactory( ServiceManager,
CertificateContainer::impl_getStaticImplementationName(),
CertificateContainer::impl_createInstance,
CertificateContainer::impl_getStaticSupportedServiceNames()));
return xReturn;
}
<|endoftext|> |
<commit_before><commit_msg>Add a file I forgot in the last change.<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.