text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <geometry_msgs/PointStamped.h>
#include <string>
#include <math.h>
#include <vector>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("octomap_full", 10, &ArtificialPotentialField::obstacleCallback, this)),
goal_sub_(node.subscribe("clicked_point", 10, &ArtificialPotentialField::goalCallback, this))
{
collision_map_.header.stamp = ros::Time(0);
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
if(collision_map_.header.stamp != ros::Time(0)){
std::vector<dmath::Vector3D> obstacles_lc;
std::string map_frame = collision_map_.header.frame_id;
octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));
octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
geometry_msgs::PointStamped p_in, p_out;
p_in.header.frame_id = map_frame;
p_in.point.x = it.getX();
p_in.point.y = it.getY();
p_in.point.z = it.getZ();
try{
tf_listener_.transformPoint(base_link_, p_in, p_out);
dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);
if(magnitude(obs) < 500){
obstacles_lc.push_back(obs);
}
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
}
}
dmath::Vector3D Fs;
//for(int i=0; i < obstacles_lc.size(); i++){
// Fs += get_potential_force(obstacles_lc[i], 0, 1.0, 1.0, 1.5);
//}
dmath::Vector3D g = goal_lc_;
Fs += get_potential_force(g, 200, 0, 1.5, 1);
dmath::Vector3D vel = Fs * force;
cmd.linear.x = vel.y;
cmd.linear.y = vel.x;
cmd.linear.z = vel.z;
cmd_pub_.publish(cmd);
}
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
collision_map_ = *obs_msg;
}
void goalCallback(const geometry_msgs::PointStamped &goal_msg){
geometry_msgs::PointStamped g_lc;
try{
tf_listener_.transformPoint(base_link_, goal_msg, g_lc);
goal_lc_ = dmath::Vector3D(g_lc.point.x, g_lc.point.y, g_lc.point.z);
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
goal_lc_ = dmath::Vector3D();
}
}
octomap_msgs::Octomap collision_map_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_, goal_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
dmath::Vector3D goal_lc_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<commit_msg>Add debug code<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <geometry_msgs/PointStamped.h>
#include <string>
#include <math.h>
#include <vector>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("octomap_full", 10, &ArtificialPotentialField::obstacleCallback, this)),
goal_sub_(node.subscribe("clicked_point", 10, &ArtificialPotentialField::goalCallback, this))
{
collision_map_.header.stamp = ros::Time(0);
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
if(collision_map_.header.stamp != ros::Time(0)){
std::vector<dmath::Vector3D> obstacles_lc;
std::string map_frame = collision_map_.header.frame_id;
octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));
octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
geometry_msgs::PointStamped p_in, p_out;
p_in.header.frame_id = map_frame;
p_in.point.x = it.getX();
p_in.point.y = it.getY();
p_in.point.z = it.getZ();
try{
tf_listener_.transformPoint(base_link_, p_in, p_out);
dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);
if(magnitude(obs) < 500){
obstacles_lc.push_back(obs);
}
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
}
}
dmath::Vector3D Fs;
//for(int i=0; i < obstacles_lc.size(); i++){
// Fs += get_potential_force(obstacles_lc[i], 0, 1.0, 1.0, 1.5);
//}
dmath::Vector3D g = goal_lc_;
Fs += get_potential_force(g, 200, 0, 1.5, 1);
dmath::Vector3D vel = Fs * force;
cmd.linear.x = vel.x;
//cmd.linear.y = vel.x;
//cmd.linear.z = vel.z;
cmd_pub_.publish(cmd);
}
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
collision_map_ = *obs_msg;
}
void goalCallback(const geometry_msgs::PointStamped &goal_msg){
geometry_msgs::PointStamped g_lc;
try{
tf_listener_.transformPoint(base_link_, goal_msg, g_lc);
goal_lc_ = dmath::Vector3D(g_lc.point.x, g_lc.point.y, g_lc.point.z);
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
goal_lc_ = dmath::Vector3D();
}
}
octomap_msgs::Octomap collision_map_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_, goal_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
dmath::Vector3D goal_lc_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<|endoftext|>
|
<commit_before>//
// recursion.cpp
// DS
//
// Created by Rahul Goel on 7/26/17.
// Copyright © 2017 Rahul Goel. All rights reserved.
//
#include "recursion.hpp"
//As Its not suggestable to return local variable outside the function So use this array in case you need to return Array or list of elements
static int *arrayTmp;
int recursion_SumOfNumbersFromList(int *arr, int size){
if (size <= 0){
return arr[size];
}else{
return arr[size] + recursion_SumOfNumbersFromList(arr,size - 1);
}
}
int recursion_SumOfNNaturalNumbers(int upto){
if (upto <= 0){
return 0;
}else{
return upto + recursion_SumOfNNaturalNumbers(upto - 1);
}
}
int recursion_numberOfChars( char *str){
if (*str == '\0'){
return 0;
}
else{
return 1 + recursion_numberOfChars(str + 1);
}
}
void recursion_reverseOfString(char *str, int index){
if (str[index] == '\0'){
return ;
}else{
recursion_reverseOfString(str, ++index);
printf("%c",str[index]);
}
}
int recursion_power(int number, int power){
if (power <= 0){
return 1;
}else{
return number*recursion_power(number, power-1);
}
}
int* recursion_getAllWordsFromSentence(char *str,char *ptr){
//In case sentence ends
if (*str == '\0'){
return arrayTmp;
}else{
//In case of Sapce
if (*str == ' '){
}
return recursion_getAllWordsFromSentence(str + 1,ptr);
}
return arrayTmp;
}
<commit_msg>changes for recursion added<commit_after>//
// recursion.cpp
// DS
//
// Created by Rahul Goel on 7/26/17.
// Copyright © 2017 Rahul Goel. All rights reserved.
//
#include "recursion.hpp"
//As Its not suggestable to return local variable outside the function So use this array in case you need to return Array or list of elements
static int *arrayTmp;
int recursion_SumOfNumbersFromList(int *arr, int size){
if (size <= 0){
return arr[size];
}else{
return arr[size] + recursion_SumOfNumbersFromList(arr,size - 1);
}
}
int recursion_SumOfNNaturalNumbers(int upto){
if (upto <= 0){
return 0;
}else{
return upto + recursion_SumOfNNaturalNumbers(upto - 1);
}
}
int recursion_numberOfChars( char *str){
if (*str == '\0'){
return 0;
}
else{
return 1 + recursion_numberOfChars(str + 1);
}
}
void recursion_reverseOfString(char *str, int index){
if (str[index] == '\0'){
return ;
}else{
recursion_reverseOfString(str, ++index);
printf("%c",str[index]);
}
}
int recursion_power(int number, int power){
if (power <= 0){ //In Case pow(number,0) = 1
return 1;
}else{
return number*recursion_power(number, power-1);
}
}
int* recursion_getAllWordsFromSentence(char *str,char *ptr){
//In case sentence ends
if (*str == '\0'){
return arrayTmp;
}else{
//In case of Space
if (*str == ' '){
}
return recursion_getAllWordsFromSentence(str ,ptr+1);
}
return arrayTmp;
}
void reverseWordAndAddItToArray(char *str,int length){
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 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 <fuzzer/FuzzedDataProvider.h>
#include <vector>
#include <aconf.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <png.h>
#include "gmem.h"
#include "gmempp.h"
#include "parseargs.h"
#include "GString.h"
#include "gfile.h"
#include "GlobalParams.h"
#include "Object.h"
#include "PDFDoc.h"
#include "SplashBitmap.h"
#include "Splash.h"
#include "SplashOutputDev.h"
#include "Stream.h"
#include "config.h"
#include "JBIG2Stream.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
FuzzedDataProvider fdp (data, size);
double hdpi = fdp.ConsumeFloatingPoint<double>();
double vdpi = fdp.ConsumeFloatingPoint<double>();
int rotate = fdp.ConsumeIntegral<int>();
bool useMediaBox = fdp.ConsumeBool();
bool crop = fdp.ConsumeBool();
bool printing = fdp.ConsumeBool();
std::vector<char> payload = fdp.ConsumeRemainingBytes<char>();
Object xpdf_obj;
xpdf_obj.initNull();
BaseStream *stream = new MemStream(payload.data(), 0, payload.size(), &xpdf_obj);
Object info, xfa;
Object *acroForm;
globalParams = new GlobalParams(NULL);
globalParams->setErrQuiet(1);
globalParams->setupBaseFonts(NULL);
char yes[] = "yes";
globalParams->setEnableFreeType(yes); // Yes, it's a string and not a bool.
globalParams->setErrQuiet(1);
PDFDoc *doc = NULL;
try {
PDFDoc doc(stream);
if (doc.isOk() == gTrue)
{
doc.getNumPages();
doc.getOutline();
doc.getStructTreeRoot();
doc.getXRef();
doc.okToPrint(gTrue);
doc.okToCopy(gTrue);
doc.okToChange(gTrue);
doc.okToAddNotes(gTrue);
doc.isLinearized();
doc.getPDFVersion();
GString *metadata;
if ((metadata = doc.readMetadata())) {
(void)metadata->getCString();
}
delete metadata;
Object info;
doc.getDocInfo(&info);
if (info.isDict()) {
info.getDict();
}
info.free();
if ((acroForm = doc.getCatalog()->getAcroForm())->isDict()) {
acroForm->dictLookup("XFA", &xfa);
xfa.free();
}
for (size_t i = 0; i < doc.getNumPages(); i++) {
doc.getLinks(i);
auto page = doc.getCatalog()->getPage(i);
if (!page->isOk()) {
continue;
}
page->getResourceDict();
page->getMetadata();
page->getResourceDict();
}
SplashColor paperColor = {0xff, 0xff, 0xff};
SplashOutputDev *splashOut = new SplashOutputDev(splashModeRGB8, 1, gFalse, paperColor);
splashOut->setNoComposite(gTrue);
splashOut->startDoc(doc.getXRef());
for (size_t i = 0; i <= doc.getNumPages(); ++i) {
doc.displayPage(splashOut, i, hdpi, vdpi, rotate, useMediaBox, crop, printing);
}
(void)splashOut->getBitmap();
delete splashOut;
Object globals;
BaseStream *base_str = doc.getBaseStream();
if (base_str) {
JBIG2Stream *str = new JBIG2Stream(base_str, &globals);
str->reset();
delete str;
}
globals.free();
}
} catch (...) {
}
delete globalParams;
return 0;
}
<commit_msg>Fuzz JBIG2 code by checking on each object in PDF file (#7508)<commit_after>/* Copyright 2020 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 <fuzzer/FuzzedDataProvider.h>
#include <vector>
#include <aconf.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <png.h>
#include "gmem.h"
#include "gmempp.h"
#include "parseargs.h"
#include "GString.h"
#include "gfile.h"
#include "GlobalParams.h"
#include "Object.h"
#include "PDFDoc.h"
#include "SplashBitmap.h"
#include "Splash.h"
#include "SplashOutputDev.h"
#include "Stream.h"
#include "config.h"
#include "JBIG2Stream.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
FuzzedDataProvider fdp (data, size);
double hdpi = fdp.ConsumeFloatingPoint<double>();
double vdpi = fdp.ConsumeFloatingPoint<double>();
int rotate = fdp.ConsumeIntegral<int>();
bool useMediaBox = fdp.ConsumeBool();
bool crop = fdp.ConsumeBool();
bool printing = fdp.ConsumeBool();
std::vector<char> payload = fdp.ConsumeRemainingBytes<char>();
Object xpdf_obj;
xpdf_obj.initNull();
BaseStream *stream = new MemStream(payload.data(), 0, payload.size(), &xpdf_obj);
Object info, xfa;
Object *acroForm;
globalParams = new GlobalParams(NULL);
globalParams->setErrQuiet(1);
globalParams->setupBaseFonts(NULL);
char yes[] = "yes";
globalParams->setEnableFreeType(yes); // Yes, it's a string and not a bool.
globalParams->setErrQuiet(1);
PDFDoc *doc = NULL;
try {
PDFDoc doc(stream);
if (doc.isOk() == gTrue)
{
doc.getNumPages();
doc.getOutline();
doc.getStructTreeRoot();
doc.getXRef();
doc.okToPrint(gTrue);
doc.okToCopy(gTrue);
doc.okToChange(gTrue);
doc.okToAddNotes(gTrue);
doc.isLinearized();
doc.getPDFVersion();
GString *metadata;
if ((metadata = doc.readMetadata())) {
(void)metadata->getCString();
}
delete metadata;
Object info;
doc.getDocInfo(&info);
if (info.isDict()) {
info.getDict();
}
info.free();
if ((acroForm = doc.getCatalog()->getAcroForm())->isDict()) {
acroForm->dictLookup("XFA", &xfa);
xfa.free();
}
for (size_t i = 0; i < doc.getNumPages(); i++) {
doc.getLinks(i);
auto page = doc.getCatalog()->getPage(i);
if (!page->isOk()) {
continue;
}
page->getResourceDict();
page->getMetadata();
page->getResourceDict();
}
SplashColor paperColor = {0xff, 0xff, 0xff};
SplashOutputDev *splashOut = new SplashOutputDev(splashModeRGB8, 1, gFalse, paperColor);
splashOut->setNoComposite(gTrue);
splashOut->startDoc(doc.getXRef());
for (size_t i = 0; i <= doc.getNumPages(); ++i) {
doc.displayPage(splashOut, i, hdpi, vdpi, rotate, useMediaBox, crop, printing);
}
(void)splashOut->getBitmap();
delete splashOut;
XRef *xref = doc.getXRef();
int objNums = xref->getNumObjects();
Object currentObj;
for (int i = 0; i < objNums; ++i) {
if (xref->fetch(i, 0, ¤tObj)->isStream()){
currentObj.getStream()->reset();
}
}
currentObj.free();
}
} catch (...) {
}
delete globalParams;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/common/automation_messages.h"
#include "chrome_frame/cfproxy_private.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
using testing::_;
using testing::DoAll;
using testing::NotNull;
using testing::Return;
using testing::StrictMock;
using testing::InvokeWithoutArgs;
using testing::WithoutArgs;
using testing::CreateFunctor;
using testing::StrEq;
using testing::Eq;
// There is not much to test here since CFProxy is pretty dumb.
struct MockFactory : public ChromeProxyFactory {
MOCK_METHOD0(CreateProxy, ChromeProxy*());
};
struct MockChromeProxyDelegate : public ChromeProxyDelegate {
MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message& message));
MOCK_METHOD1(Connected, void(ChromeProxy* proxy));
MOCK_METHOD2(PeerLost, void(ChromeProxy*, enum DisconnectReason reason));
MOCK_METHOD0(Disconnected, void());
MOCK_METHOD0(tab_handle, int());
MOCK_METHOD5(Completed_CreateTab, void(bool success, HWND chrome_wnd,
HWND tab_window, int tab_handle, int session_id));
MOCK_METHOD5(Completed_ConnectToTab, void(bool success, HWND chrome_window,
HWND tab_window, int tab_handle, int session_id));
MOCK_METHOD2(Completed_Navigate, void(bool success,
enum AutomationMsg_NavigationResponseValues res));
// Network requests from Chrome.
MOCK_METHOD2(Network_Start, void(int request_id,
const AutomationURLRequest& request_info));
MOCK_METHOD2(Network_Read, void(int request_id, int bytes_to_read));
MOCK_METHOD2(Network_End, void(int request_id,
const net::URLRequestStatus& s));
MOCK_METHOD1(Network_DownloadInHost, void(int request_id));
MOCK_METHOD2(GetCookies, void(const GURL& url, int cookie_id));
MOCK_METHOD2(SetCookie, void(const GURL& url, const std::string& cookie));
// Navigation progress notifications.
MOCK_METHOD2(NavigationStateChanged, void(int flags,
const NavigationInfo& nav_info));
MOCK_METHOD1(UpdateTargetUrl, void(const std::wstring& url));
MOCK_METHOD2(NavigationFailed, void(int error_code, const GURL& gurl));
MOCK_METHOD1(DidNavigate, void(const NavigationInfo& navigation_info));
MOCK_METHOD1(TabLoaded, void(const GURL& url));
//
MOCK_METHOD3(OpenURL, void(const GURL& url_to_open, const GURL& referrer,
int open_disposition));
MOCK_METHOD1(GoToHistoryOffset, void(int offset));
MOCK_METHOD3(MessageToHost, void(const std::string& message,
const std::string& origin, const std::string& target));
// Misc. UI.
MOCK_METHOD1(HandleAccelerator, void(const MSG& accel_message));
MOCK_METHOD3(HandleContextMenu, void(HANDLE menu_handle, int align_flags,
const MiniContextMenuParams& params));
MOCK_METHOD1(TabbedOut, void(bool reverse));
//
MOCK_METHOD0(TabClosed, void());
MOCK_METHOD1(AttachTab, void(const AttachExternalTabParams& attach_params));
};
struct MockSender : public IPC::Message::Sender {
MOCK_METHOD1(Send, bool(IPC::Message* m));
};
struct MockCFProxyTraits : public CFProxyTraits {
MOCK_METHOD2(DoCreateChannel, IPC::Message::Sender*(const std::string& id,
IPC::Channel::Listener* l));
MOCK_METHOD1(CloseChannel, void(IPC::Message::Sender* s));
MOCK_METHOD1(LaunchApp, bool(const std::wstring& cmd_line));
// Forward the CreateChannel to DoCreateChannel, but save the ipc_thread
// and the listener (i.e. proxy implementation of Channel::Listener)
virtual IPC::Message::Sender* CreateChannel(const std::string& id,
IPC::Channel::Listener* l) {
ipc_loop = MessageLoop::current();
listener = l;
return this->DoCreateChannel(id, l);
}
// Simulate some activity in the IPC thread.
// You may find API_FIRE_XXXX macros (see below) handy instead.
void FireConnect(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(
FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelConnected,
base::Unretained(listener), 0),
t.InMilliseconds());
}
void FireError(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(
FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelError,
base::Unretained(listener)),
t.InMilliseconds());
}
void FireMessage(const IPC::Message& m, base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(
FROM_HERE,
base::Bind(
base::IgnoreResult(&IPC::Channel::Listener::OnMessageReceived),
base::Unretained(listener), m),
t.InMilliseconds());
}
MockCFProxyTraits() : ipc_loop(NULL) {}
MockSender sender;
private:
MessageLoop* ipc_loop;
IPC::Channel::Listener* listener;
};
// Handy macros when we want so simulate something on the IPC thread.
#define API_FIRE_CONNECT(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireConnect, t))
#define API_FIRE_ERROR(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireError, t))
#define API_FIRE_MESSAGE(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireMessage, t))
TEST(ChromeProxy, DelegateAddRemove) {
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory; // to be destroyed before other mocks
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Disconnected());
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(4);
factory.GetProxy(&delegate, params);
factory.ReleaseProxy(&delegate, params.profile);
}
// Not very useful test. Just for illustration. :)
TEST(ChromeProxy, SharedProxy) {
base::WaitableEvent done1(false, false);
base::WaitableEvent done2(false, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate1;
StrictMock<MockChromeProxyDelegate> delegate2;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(
API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(150)),
Return(true)));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate1, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate2, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate1, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done1, &base::WaitableEvent::Signal));
EXPECT_CALL(delegate2, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done2, &base::WaitableEvent::Signal));
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(4);
factory.GetProxy(&delegate1, params);
params.timeout = base::TimeDelta::FromSeconds(2);
factory.GetProxy(&delegate2, params);
EXPECT_TRUE(done1.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_TRUE(done2.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate2, Disconnected());
EXPECT_CALL(delegate1, Disconnected());
factory.ReleaseProxy(&delegate2, params.profile);
factory.ReleaseProxy(&delegate1, params.profile);
}
TEST(ChromeProxy, LaunchTimeout) {
base::WaitableEvent done(true, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, PeerLost(_,
ChromeProxyDelegate::CHROME_EXE_LAUNCH_TIMEOUT))
.WillOnce(InvokeWithoutArgs(&done, &base::WaitableEvent::Signal));
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromMilliseconds(300);
factory.GetProxy(&delegate, params);
EXPECT_TRUE(done.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
TEST(ChromeProxy, LaunchChrome) {
base::WaitableEvent connected(false, false);
StrictMock<MockChromeProxyDelegate> delegate;
ChromeProxyFactory factory;
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(10);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Connected(NotNull()))
.WillOnce(InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal));
factory.GetProxy(&delegate, params);
EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
// Test that a channel error results in Completed_XYZ(false, ) called if
// the synchronious XYZ message has been sent.
TEST(ChromeProxy, ChannelError) {
base::WaitableEvent connected(false, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromMilliseconds(300);
testing::InSequence s;
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(
API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(10)),
Return(true)));
EXPECT_CALL(delegate, Connected(proxy))
.WillOnce(DoAll(
InvokeWithoutArgs(CreateFunctor(proxy, &ChromeProxy::ConnectTab,
&delegate, HWND(6), 512)),
InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal)));
EXPECT_CALL(api.sender, Send(_));
EXPECT_CALL(delegate, Completed_ConnectToTab(false, _, _, _, _));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, PeerLost(_, ChromeProxyDelegate::CHANNEL_ERROR));
factory.GetProxy(&delegate, params);
EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));
// Simulate a channel error.
api.FireError(base::TimeDelta::FromMilliseconds(0));
// Expectations when the Proxy is destroyed.
EXPECT_CALL(delegate, tab_handle()).WillOnce(Return(0));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
///////////////////////////////////////////////////////////////////////////////
namespace {
template <typename M, typename A>
inline IPC::Message* CreateReply(M* m, const A& a) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a);
}
return r;
}
template <typename M, typename A, typename B>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b);
}
return r;
}
template <typename M, typename A, typename B, typename C>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b, c);
}
return r;
}
template <typename M, typename A, typename B, typename C, typename D>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c,
const D& d) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b, c, d);
}
return r;
}} // namespace
TEST(SyncMsgSender, Deserialize) {
// Note the ipc thread is not actually needed, but we try to be close
// to real-world conditions - that SyncMsgSender works from multiple threads.
base::Thread ipc("ipc");
ipc.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));
StrictMock<MockChromeProxyDelegate> d1;
TabsMap tab2delegate;
SyncMsgSender queue(&tab2delegate);
const int kTabHandle = 6;
const int kSessionId = 8;
// Create a sync message and its reply.
AutomationMsg_CreateExternalTab m(ExternalTabSettings(), 0, 0, 0, 0);
scoped_ptr<IPC::Message> r(CreateReply(&m, (HWND)1, (HWND)2, kTabHandle,
kSessionId));
queue.QueueSyncMessage(&m, &d1, NULL);
testing::InSequence s;
EXPECT_CALL(d1, Completed_CreateTab(true, (HWND)1, (HWND)2, kTabHandle,
kSessionId));
// Execute replies in a worker thread.
ipc.message_loop()->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&SyncMsgSender::OnReplyReceived),
base::Unretained(&queue), r.get()));
ipc.Stop();
// Expect that tab 6 has been associated with the delegate.
EXPECT_EQ(&d1, tab2delegate[6]);
}
TEST(SyncMsgSender, OnChannelClosed) {
// TODO(stoyan): implement.
}
<commit_msg>Scrub CFProxy tests properly.<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 <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/common/automation_messages.h"
#include "chrome_frame/cfproxy_private.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/test_scrubber.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
using testing::_;
using testing::DoAll;
using testing::NotNull;
using testing::Return;
using testing::StrictMock;
using testing::InvokeWithoutArgs;
using testing::WithoutArgs;
using testing::CreateFunctor;
using testing::StrEq;
using testing::Eq;
// There is not much to test here since CFProxy is pretty dumb.
struct MockFactory : public ChromeProxyFactory {
MOCK_METHOD0(CreateProxy, ChromeProxy*());
};
struct MockChromeProxyDelegate : public ChromeProxyDelegate {
MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message& message));
MOCK_METHOD1(Connected, void(ChromeProxy* proxy));
MOCK_METHOD2(PeerLost, void(ChromeProxy*, enum DisconnectReason reason));
MOCK_METHOD0(Disconnected, void());
MOCK_METHOD0(tab_handle, int());
MOCK_METHOD5(Completed_CreateTab, void(bool success, HWND chrome_wnd,
HWND tab_window, int tab_handle, int session_id));
MOCK_METHOD5(Completed_ConnectToTab, void(bool success, HWND chrome_window,
HWND tab_window, int tab_handle, int session_id));
MOCK_METHOD2(Completed_Navigate, void(bool success,
enum AutomationMsg_NavigationResponseValues res));
// Network requests from Chrome.
MOCK_METHOD2(Network_Start, void(int request_id,
const AutomationURLRequest& request_info));
MOCK_METHOD2(Network_Read, void(int request_id, int bytes_to_read));
MOCK_METHOD2(Network_End, void(int request_id,
const net::URLRequestStatus& s));
MOCK_METHOD1(Network_DownloadInHost, void(int request_id));
MOCK_METHOD2(GetCookies, void(const GURL& url, int cookie_id));
MOCK_METHOD2(SetCookie, void(const GURL& url, const std::string& cookie));
// Navigation progress notifications.
MOCK_METHOD2(NavigationStateChanged, void(int flags,
const NavigationInfo& nav_info));
MOCK_METHOD1(UpdateTargetUrl, void(const std::wstring& url));
MOCK_METHOD2(NavigationFailed, void(int error_code, const GURL& gurl));
MOCK_METHOD1(DidNavigate, void(const NavigationInfo& navigation_info));
MOCK_METHOD1(TabLoaded, void(const GURL& url));
//
MOCK_METHOD3(OpenURL, void(const GURL& url_to_open, const GURL& referrer,
int open_disposition));
MOCK_METHOD1(GoToHistoryOffset, void(int offset));
MOCK_METHOD3(MessageToHost, void(const std::string& message,
const std::string& origin, const std::string& target));
// Misc. UI.
MOCK_METHOD1(HandleAccelerator, void(const MSG& accel_message));
MOCK_METHOD3(HandleContextMenu, void(HANDLE menu_handle, int align_flags,
const MiniContextMenuParams& params));
MOCK_METHOD1(TabbedOut, void(bool reverse));
//
MOCK_METHOD0(TabClosed, void());
MOCK_METHOD1(AttachTab, void(const AttachExternalTabParams& attach_params));
};
struct MockSender : public IPC::Message::Sender {
MOCK_METHOD1(Send, bool(IPC::Message* m));
};
struct MockCFProxyTraits : public CFProxyTraits {
MOCK_METHOD2(DoCreateChannel, IPC::Message::Sender*(const std::string& id,
IPC::Channel::Listener* l));
MOCK_METHOD1(CloseChannel, void(IPC::Message::Sender* s));
MOCK_METHOD1(LaunchApp, bool(const std::wstring& cmd_line));
// Forward the CreateChannel to DoCreateChannel, but save the ipc_thread
// and the listener (i.e. proxy implementation of Channel::Listener)
virtual IPC::Message::Sender* CreateChannel(const std::string& id,
IPC::Channel::Listener* l) {
ipc_loop = MessageLoop::current();
listener = l;
return this->DoCreateChannel(id, l);
}
// Simulate some activity in the IPC thread.
// You may find API_FIRE_XXXX macros (see below) handy instead.
void FireConnect(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(
FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelConnected,
base::Unretained(listener), 0),
t.InMilliseconds());
}
void FireError(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(
FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelError,
base::Unretained(listener)),
t.InMilliseconds());
}
void FireMessage(const IPC::Message& m, base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(
FROM_HERE,
base::Bind(
base::IgnoreResult(&IPC::Channel::Listener::OnMessageReceived),
base::Unretained(listener), m),
t.InMilliseconds());
}
MockCFProxyTraits() : ipc_loop(NULL) {}
MockSender sender;
private:
MessageLoop* ipc_loop;
IPC::Channel::Listener* listener;
};
// Handy macros when we want so simulate something on the IPC thread.
#define API_FIRE_CONNECT(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireConnect, t))
#define API_FIRE_ERROR(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireError, t))
#define API_FIRE_MESSAGE(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireMessage, t))
class ChromeProxyTest : public ::testing::Test {
protected:
virtual void SetUp() OVERRIDE {
chrome_frame_test::OverrideDataDirectoryForThisTest(
chrome_frame_test::GetProfilePath(L"").value());
params_.profile = "Adam N. Epilinter";
params_.timeout = base::TimeDelta::FromSeconds(4);
}
ProxyParams params_;
};
TEST_F(ChromeProxyTest, DelegateAddRemove) {
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory; // to be destroyed before other mocks
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Disconnected());
factory.GetProxy(&delegate, params_);
factory.ReleaseProxy(&delegate, params_.profile);
}
// Not very useful test. Just for illustration. :)
TEST_F(ChromeProxyTest, SharedProxy) {
base::WaitableEvent done1(false, false);
base::WaitableEvent done2(false, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate1;
StrictMock<MockChromeProxyDelegate> delegate2;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(
API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(150)),
Return(true)));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate1, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate2, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate1, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done1, &base::WaitableEvent::Signal));
EXPECT_CALL(delegate2, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done2, &base::WaitableEvent::Signal));
factory.GetProxy(&delegate1, params_);
params_.timeout = base::TimeDelta::FromSeconds(2);
factory.GetProxy(&delegate2, params_);
EXPECT_TRUE(done1.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_TRUE(done2.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate2, Disconnected());
EXPECT_CALL(delegate1, Disconnected());
factory.ReleaseProxy(&delegate2, params_.profile);
factory.ReleaseProxy(&delegate1, params_.profile);
}
TEST_F(ChromeProxyTest, LaunchTimeout) {
base::WaitableEvent done(true, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, PeerLost(_,
ChromeProxyDelegate::CHROME_EXE_LAUNCH_TIMEOUT))
.WillOnce(InvokeWithoutArgs(&done, &base::WaitableEvent::Signal));
params_.timeout = base::TimeDelta::FromMilliseconds(300);
factory.GetProxy(&delegate, params_);
EXPECT_TRUE(done.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params_.profile);
}
TEST_F(ChromeProxyTest, LaunchChrome) {
base::WaitableEvent connected(false, false);
StrictMock<MockChromeProxyDelegate> delegate;
ChromeProxyFactory factory;
params_.timeout = base::TimeDelta::FromSeconds(10);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Connected(NotNull()))
.WillOnce(InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal));
factory.GetProxy(&delegate, params_);
EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params_.profile);
}
// Test that a channel error results in Completed_XYZ(false, ) called if
// the synchronious XYZ message has been sent.
TEST_F(ChromeProxyTest, ChannelError) {
base::WaitableEvent connected(false, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
params_.timeout = base::TimeDelta::FromMilliseconds(300);
testing::InSequence s;
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(
API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(10)),
Return(true)));
EXPECT_CALL(delegate, Connected(proxy))
.WillOnce(DoAll(
InvokeWithoutArgs(CreateFunctor(proxy, &ChromeProxy::ConnectTab,
&delegate, HWND(6), 512)),
InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal)));
EXPECT_CALL(api.sender, Send(_));
EXPECT_CALL(delegate, Completed_ConnectToTab(false, _, _, _, _));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, PeerLost(_, ChromeProxyDelegate::CHANNEL_ERROR));
factory.GetProxy(&delegate, params_);
EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));
// Simulate a channel error.
api.FireError(base::TimeDelta::FromMilliseconds(0));
// Expectations when the Proxy is destroyed.
EXPECT_CALL(delegate, tab_handle()).WillOnce(Return(0));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params_.profile);
}
///////////////////////////////////////////////////////////////////////////////
namespace {
template <typename M, typename A>
inline IPC::Message* CreateReply(M* m, const A& a) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a);
}
return r;
}
template <typename M, typename A, typename B>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b);
}
return r;
}
template <typename M, typename A, typename B, typename C>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b, c);
}
return r;
}
template <typename M, typename A, typename B, typename C, typename D>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c,
const D& d) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b, c, d);
}
return r;
}} // namespace
TEST(SyncMsgSender, Deserialize) {
// Note the ipc thread is not actually needed, but we try to be close
// to real-world conditions - that SyncMsgSender works from multiple threads.
base::Thread ipc("ipc");
ipc.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));
StrictMock<MockChromeProxyDelegate> d1;
TabsMap tab2delegate;
SyncMsgSender queue(&tab2delegate);
const int kTabHandle = 6;
const int kSessionId = 8;
// Create a sync message and its reply.
AutomationMsg_CreateExternalTab m(ExternalTabSettings(), 0, 0, 0, 0);
scoped_ptr<IPC::Message> r(CreateReply(&m, (HWND)1, (HWND)2, kTabHandle,
kSessionId));
queue.QueueSyncMessage(&m, &d1, NULL);
testing::InSequence s;
EXPECT_CALL(d1, Completed_CreateTab(true, (HWND)1, (HWND)2, kTabHandle,
kSessionId));
// Execute replies in a worker thread.
ipc.message_loop()->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&SyncMsgSender::OnReplyReceived),
base::Unretained(&queue), r.get()));
ipc.Stop();
// Expect that tab 6 has been associated with the delegate.
EXPECT_EQ(&d1, tab2delegate[6]);
}
TEST(SyncMsgSender, OnChannelClosed) {
// TODO(stoyan): implement.
}
<|endoftext|>
|
<commit_before>#pragma once
#include "boost_defs.hpp"
#include "event_queue.hpp"
#include "modifier_flag_manager.hpp"
#include "stream_utility.hpp"
#include <boost/optional.hpp>
#include <json/json.hpp>
#include <unordered_set>
namespace krbn {
namespace manipulator {
namespace details {
class event_definition {
public:
enum class type {
none,
key_code,
pointing_button,
};
enum class modifier {
any,
caps_lock,
command,
control,
fn,
left_command,
left_control,
left_option,
left_shift,
option,
right_command,
right_control,
right_option,
right_shift,
shift,
end_,
};
virtual ~event_definition(void) {
}
type get_type(void) const {
return type_;
}
boost::optional<key_code> get_key_code(void) const {
if (type_ == type::key_code) {
return key_code_;
}
return boost::none;
}
boost::optional<pointing_button> get_pointing_button(void) const {
if (type_ == type::pointing_button) {
return pointing_button_;
}
return boost::none;
}
boost::optional<event_queue::queued_event::event> to_event(void) const {
switch (type_) {
case type::none:
return boost::none;
case type::key_code:
return event_queue::queued_event::event(key_code_);
case type::pointing_button:
return event_queue::queued_event::event(pointing_button_);
}
}
static std::unordered_set<modifier> make_modifiers(const nlohmann::json& json) {
std::unordered_set<modifier> modifiers;
for (const auto& j : json) {
if (j.is_string()) {
const std::string& name = j;
if (name == "any") {
modifiers.insert(modifier::any);
} else if (name == "caps_lock") {
modifiers.insert(modifier::caps_lock);
} else if (name == "command") {
modifiers.insert(modifier::command);
} else if (name == "control") {
modifiers.insert(modifier::control);
} else if (name == "fn") {
modifiers.insert(modifier::fn);
} else if (name == "left_command") {
modifiers.insert(modifier::left_command);
} else if (name == "left_control") {
modifiers.insert(modifier::left_control);
} else if (name == "left_option") {
modifiers.insert(modifier::left_option);
} else if (name == "left_shift") {
modifiers.insert(modifier::left_shift);
} else if (name == "option") {
modifiers.insert(modifier::option);
} else if (name == "right_command") {
modifiers.insert(modifier::right_command);
} else if (name == "right_control") {
modifiers.insert(modifier::right_control);
} else if (name == "right_option") {
modifiers.insert(modifier::right_option);
} else if (name == "right_shift") {
modifiers.insert(modifier::right_shift);
} else if (name == "shift") {
modifiers.insert(modifier::shift);
} else {
logger::get_logger().error("unknown modifier: {0}", name);
}
}
}
return modifiers;
}
static std::vector<modifier_flag> get_modifier_flags(modifier modifier) {
switch (modifier) {
case modifier::any:
return {};
case modifier::caps_lock:
return {modifier_flag::caps_lock};
case modifier::command:
return {modifier_flag::left_command, modifier_flag::right_command};
case modifier::control:
return {modifier_flag::left_control, modifier_flag::right_control};
case modifier::fn:
return {modifier_flag::fn};
case modifier::left_command:
return {modifier_flag::left_command};
case modifier::left_control:
return {modifier_flag::left_control};
case modifier::left_option:
return {modifier_flag::left_option};
case modifier::left_shift:
return {modifier_flag::left_shift};
case modifier::option:
return {modifier_flag::left_option, modifier_flag::right_option};
case modifier::right_command:
return {modifier_flag::right_command};
case modifier::right_control:
return {modifier_flag::right_control};
case modifier::right_option:
return {modifier_flag::right_option};
case modifier::right_shift:
return {modifier_flag::right_shift};
case modifier::shift:
return {modifier_flag::left_shift, modifier_flag::right_shift};
case modifier::end_:
return {};
}
}
static modifier get_modifier(modifier_flag modifier_flag) {
switch (modifier_flag) {
case modifier_flag::caps_lock:
return modifier::caps_lock;
case modifier_flag::fn:
return modifier::fn;
case modifier_flag::left_command:
return modifier::left_command;
case modifier_flag::left_control:
return modifier::left_control;
case modifier_flag::left_option:
return modifier::left_option;
case modifier_flag::left_shift:
return modifier::left_shift;
case modifier_flag::right_command:
return modifier::right_command;
case modifier_flag::right_control:
return modifier::right_control;
case modifier_flag::right_option:
return modifier::right_option;
case modifier_flag::right_shift:
return modifier::right_shift;
case modifier_flag::zero:
case modifier_flag::end_:
return modifier::end_;
}
}
protected:
event_definition(const nlohmann::json& json) : type_(type::none) {
// Set type_ and values.
{
const std::string key = "key_code";
if (json.find(key) != std::end(json) && json[key].is_string()) {
const std::string& name = json[key];
if (auto key_code = types::get_key_code(name)) {
type_ = type::key_code;
key_code_ = *key_code;
return;
}
}
}
{
const std::string key = "pointing_button";
if (json.find(key) != std::end(json) && json[key].is_string()) {
if (auto pointing_button = types::get_pointing_button(json[key])) {
type_ = type::pointing_button;
pointing_button_ = *pointing_button;
return;
}
}
}
}
event_definition(key_code key_code) : type_(type::key_code),
key_code_(key_code) {
}
event_definition(pointing_button pointing_button) : type_(type::pointing_button),
pointing_button_(pointing_button) {
}
type type_;
union {
key_code key_code_;
pointing_button pointing_button_;
};
};
class from_event_definition final : public event_definition {
public:
from_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end() && json[key].is_object()) {
auto& modifiers = json[key];
{
const std::string k = "mandatory";
if (modifiers.find(k) != modifiers.end()) {
mandatory_modifiers_ = make_modifiers(modifiers[k]);
}
}
{
const std::string k = "optional";
if (modifiers.find(k) != modifiers.end()) {
optional_modifiers_ = make_modifiers(modifiers[k]);
}
}
}
}
}
from_event_definition(key_code key_code,
std::unordered_set<modifier> mandatory_modifiers,
std::unordered_set<modifier> optional_modifiers) : event_definition(key_code),
mandatory_modifiers_(mandatory_modifiers),
optional_modifiers_(optional_modifiers) {
}
virtual ~from_event_definition(void) {
}
const std::unordered_set<modifier>& get_mandatory_modifiers(void) const {
return mandatory_modifiers_;
}
const std::unordered_set<modifier>& get_optional_modifiers(void) const {
return optional_modifiers_;
}
boost::optional<std::unordered_set<modifier_flag>> test_modifiers(const modifier_flag_manager& modifier_flag_manager) const {
std::unordered_set<modifier_flag> modifier_flags;
// If mandatory_modifiers_ contains modifier::any, return all active modifier_flags.
if (mandatory_modifiers_.find(modifier::any) != std::end(mandatory_modifiers_)) {
for (auto i = static_cast<uint32_t>(modifier_flag::zero) + 1; i != static_cast<uint32_t>(modifier_flag::end_); ++i) {
auto flag = modifier_flag(i);
if (modifier_flag_manager.is_pressed(flag)) {
modifier_flags.insert(flag);
}
}
return modifier_flags;
}
// Check modifier_flag state.
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_)) {
auto pair = test_modifier(modifier_flag_manager, m);
if (!pair.first) {
return boost::none;
}
if (pair.second != modifier_flag::zero) {
modifier_flags.insert(pair.second);
}
}
}
// If optional_modifiers_ does not contain modifier::any, we have to check modifier flags strictly.
if (optional_modifiers_.find(modifier::any) == std::end(optional_modifiers_)) {
std::unordered_set<modifier_flag> extra_modifier_flags;
for (auto m = static_cast<uint32_t>(modifier_flag::zero) + 1; m != static_cast<uint32_t>(modifier_flag::end_); ++m) {
extra_modifier_flags.insert(modifier_flag(m));
}
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_) ||
optional_modifiers_.find(m) != std::end(optional_modifiers_)) {
for (const auto& flag : get_modifier_flags(m)) {
extra_modifier_flags.erase(flag);
}
}
}
for (const auto& flag : extra_modifier_flags) {
if (modifier_flag_manager.is_pressed(flag)) {
return boost::none;
}
}
}
return modifier_flags;
}
static std::pair<bool, modifier_flag> test_modifier(const modifier_flag_manager& modifier_flag_manager,
modifier modifier) {
if (modifier == modifier::any) {
return std::make_pair(true, modifier_flag::zero);
}
auto modifier_flags = get_modifier_flags(modifier);
if (!modifier_flags.empty()) {
for (const auto& m : modifier_flags) {
if (modifier_flag_manager.is_pressed(m)) {
return std::make_pair(true, m);
}
}
}
return std::make_pair(false, modifier_flag::zero);
}
private:
std::unordered_set<modifier> mandatory_modifiers_;
std::unordered_set<modifier> optional_modifiers_;
};
class to_event_definition final : public event_definition {
public:
to_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end()) {
modifiers_ = make_modifiers(json[key]);
}
}
}
to_event_definition(key_code key_code,
std::unordered_set<modifier> modifiers) : event_definition(key_code),
modifiers_(modifiers) {
}
virtual ~to_event_definition(void) {
}
const std::unordered_set<modifier>& get_modifiers(void) const {
return modifiers_;
}
private:
std::unordered_set<modifier> modifiers_;
};
inline std::ostream& operator<<(std::ostream& stream, const event_definition::modifier& value) {
#define KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(MODIFIER) \
case event_definition::modifier::MODIFIER: \
stream << #MODIFIER; \
break;
switch (value) {
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(any);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(caps_lock);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(fn);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(end_);
}
#undef KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT
return stream;
}
template <template <class T, class A> class container>
inline std::ostream& operator<<(std::ostream& stream, const container<event_definition::modifier, std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
template <template <class T, class H, class K, class A> class container>
inline std::ostream& operator<<(std::ostream& stream,
const container<event_definition::modifier,
std::hash<event_definition::modifier>,
std::equal_to<event_definition::modifier>,
std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
} // namespace details
} // namespace manipulator
} // namespace krbn
<commit_msg>use boost/variant<commit_after>#pragma once
#include "boost_defs.hpp"
#include "event_queue.hpp"
#include "modifier_flag_manager.hpp"
#include "stream_utility.hpp"
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <json/json.hpp>
#include <unordered_set>
namespace krbn {
namespace manipulator {
namespace details {
class event_definition {
public:
enum class type {
none,
key_code,
pointing_button,
};
enum class modifier {
any,
caps_lock,
command,
control,
fn,
left_command,
left_control,
left_option,
left_shift,
option,
right_command,
right_control,
right_option,
right_shift,
shift,
end_,
};
virtual ~event_definition(void) {
}
type get_type(void) const {
return type_;
}
boost::optional<key_code> get_key_code(void) const {
if (type_ == type::key_code) {
return boost::get<key_code>(value_);
}
return boost::none;
}
boost::optional<pointing_button> get_pointing_button(void) const {
if (type_ == type::pointing_button) {
return boost::get<pointing_button>(value_);
}
return boost::none;
}
boost::optional<event_queue::queued_event::event> to_event(void) const {
switch (type_) {
case type::none:
return boost::none;
case type::key_code:
return event_queue::queued_event::event(boost::get<key_code>(value_));
case type::pointing_button:
return event_queue::queued_event::event(boost::get<pointing_button>(value_));
}
}
static std::unordered_set<modifier> make_modifiers(const nlohmann::json& json) {
std::unordered_set<modifier> modifiers;
for (const auto& j : json) {
if (j.is_string()) {
const std::string& name = j;
if (name == "any") {
modifiers.insert(modifier::any);
} else if (name == "caps_lock") {
modifiers.insert(modifier::caps_lock);
} else if (name == "command") {
modifiers.insert(modifier::command);
} else if (name == "control") {
modifiers.insert(modifier::control);
} else if (name == "fn") {
modifiers.insert(modifier::fn);
} else if (name == "left_command") {
modifiers.insert(modifier::left_command);
} else if (name == "left_control") {
modifiers.insert(modifier::left_control);
} else if (name == "left_option") {
modifiers.insert(modifier::left_option);
} else if (name == "left_shift") {
modifiers.insert(modifier::left_shift);
} else if (name == "option") {
modifiers.insert(modifier::option);
} else if (name == "right_command") {
modifiers.insert(modifier::right_command);
} else if (name == "right_control") {
modifiers.insert(modifier::right_control);
} else if (name == "right_option") {
modifiers.insert(modifier::right_option);
} else if (name == "right_shift") {
modifiers.insert(modifier::right_shift);
} else if (name == "shift") {
modifiers.insert(modifier::shift);
} else {
logger::get_logger().error("unknown modifier: {0}", name);
}
}
}
return modifiers;
}
static std::vector<modifier_flag> get_modifier_flags(modifier modifier) {
switch (modifier) {
case modifier::any:
return {};
case modifier::caps_lock:
return {modifier_flag::caps_lock};
case modifier::command:
return {modifier_flag::left_command, modifier_flag::right_command};
case modifier::control:
return {modifier_flag::left_control, modifier_flag::right_control};
case modifier::fn:
return {modifier_flag::fn};
case modifier::left_command:
return {modifier_flag::left_command};
case modifier::left_control:
return {modifier_flag::left_control};
case modifier::left_option:
return {modifier_flag::left_option};
case modifier::left_shift:
return {modifier_flag::left_shift};
case modifier::option:
return {modifier_flag::left_option, modifier_flag::right_option};
case modifier::right_command:
return {modifier_flag::right_command};
case modifier::right_control:
return {modifier_flag::right_control};
case modifier::right_option:
return {modifier_flag::right_option};
case modifier::right_shift:
return {modifier_flag::right_shift};
case modifier::shift:
return {modifier_flag::left_shift, modifier_flag::right_shift};
case modifier::end_:
return {};
}
}
static modifier get_modifier(modifier_flag modifier_flag) {
switch (modifier_flag) {
case modifier_flag::caps_lock:
return modifier::caps_lock;
case modifier_flag::fn:
return modifier::fn;
case modifier_flag::left_command:
return modifier::left_command;
case modifier_flag::left_control:
return modifier::left_control;
case modifier_flag::left_option:
return modifier::left_option;
case modifier_flag::left_shift:
return modifier::left_shift;
case modifier_flag::right_command:
return modifier::right_command;
case modifier_flag::right_control:
return modifier::right_control;
case modifier_flag::right_option:
return modifier::right_option;
case modifier_flag::right_shift:
return modifier::right_shift;
case modifier_flag::zero:
case modifier_flag::end_:
return modifier::end_;
}
}
protected:
event_definition(const nlohmann::json& json) : type_(type::none) {
// Set type_ and values.
{
const std::string key = "key_code";
if (json.find(key) != std::end(json) && json[key].is_string()) {
const std::string& name = json[key];
if (auto key_code = types::get_key_code(name)) {
type_ = type::key_code;
value_ = *key_code;
return;
}
}
}
{
const std::string key = "pointing_button";
if (json.find(key) != std::end(json) && json[key].is_string()) {
if (auto pointing_button = types::get_pointing_button(json[key])) {
type_ = type::pointing_button;
value_ = *pointing_button;
return;
}
}
}
}
event_definition(key_code key_code) : type_(type::key_code),
value_(key_code) {
}
event_definition(pointing_button pointing_button) : type_(type::pointing_button),
value_(pointing_button) {
}
type type_;
boost::variant<key_code,
pointing_button>
value_;
};
class from_event_definition final : public event_definition {
public:
from_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end() && json[key].is_object()) {
auto& modifiers = json[key];
{
const std::string k = "mandatory";
if (modifiers.find(k) != modifiers.end()) {
mandatory_modifiers_ = make_modifiers(modifiers[k]);
}
}
{
const std::string k = "optional";
if (modifiers.find(k) != modifiers.end()) {
optional_modifiers_ = make_modifiers(modifiers[k]);
}
}
}
}
}
from_event_definition(key_code key_code,
std::unordered_set<modifier> mandatory_modifiers,
std::unordered_set<modifier> optional_modifiers) : event_definition(key_code),
mandatory_modifiers_(mandatory_modifiers),
optional_modifiers_(optional_modifiers) {
}
virtual ~from_event_definition(void) {
}
const std::unordered_set<modifier>& get_mandatory_modifiers(void) const {
return mandatory_modifiers_;
}
const std::unordered_set<modifier>& get_optional_modifiers(void) const {
return optional_modifiers_;
}
boost::optional<std::unordered_set<modifier_flag>> test_modifiers(const modifier_flag_manager& modifier_flag_manager) const {
std::unordered_set<modifier_flag> modifier_flags;
// If mandatory_modifiers_ contains modifier::any, return all active modifier_flags.
if (mandatory_modifiers_.find(modifier::any) != std::end(mandatory_modifiers_)) {
for (auto i = static_cast<uint32_t>(modifier_flag::zero) + 1; i != static_cast<uint32_t>(modifier_flag::end_); ++i) {
auto flag = modifier_flag(i);
if (modifier_flag_manager.is_pressed(flag)) {
modifier_flags.insert(flag);
}
}
return modifier_flags;
}
// Check modifier_flag state.
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_)) {
auto pair = test_modifier(modifier_flag_manager, m);
if (!pair.first) {
return boost::none;
}
if (pair.second != modifier_flag::zero) {
modifier_flags.insert(pair.second);
}
}
}
// If optional_modifiers_ does not contain modifier::any, we have to check modifier flags strictly.
if (optional_modifiers_.find(modifier::any) == std::end(optional_modifiers_)) {
std::unordered_set<modifier_flag> extra_modifier_flags;
for (auto m = static_cast<uint32_t>(modifier_flag::zero) + 1; m != static_cast<uint32_t>(modifier_flag::end_); ++m) {
extra_modifier_flags.insert(modifier_flag(m));
}
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_) ||
optional_modifiers_.find(m) != std::end(optional_modifiers_)) {
for (const auto& flag : get_modifier_flags(m)) {
extra_modifier_flags.erase(flag);
}
}
}
for (const auto& flag : extra_modifier_flags) {
if (modifier_flag_manager.is_pressed(flag)) {
return boost::none;
}
}
}
return modifier_flags;
}
static std::pair<bool, modifier_flag> test_modifier(const modifier_flag_manager& modifier_flag_manager,
modifier modifier) {
if (modifier == modifier::any) {
return std::make_pair(true, modifier_flag::zero);
}
auto modifier_flags = get_modifier_flags(modifier);
if (!modifier_flags.empty()) {
for (const auto& m : modifier_flags) {
if (modifier_flag_manager.is_pressed(m)) {
return std::make_pair(true, m);
}
}
}
return std::make_pair(false, modifier_flag::zero);
}
private:
std::unordered_set<modifier> mandatory_modifiers_;
std::unordered_set<modifier> optional_modifiers_;
};
class to_event_definition final : public event_definition {
public:
to_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end()) {
modifiers_ = make_modifiers(json[key]);
}
}
}
to_event_definition(key_code key_code,
std::unordered_set<modifier> modifiers) : event_definition(key_code),
modifiers_(modifiers) {
}
virtual ~to_event_definition(void) {
}
const std::unordered_set<modifier>& get_modifiers(void) const {
return modifiers_;
}
private:
std::unordered_set<modifier> modifiers_;
};
inline std::ostream& operator<<(std::ostream& stream, const event_definition::modifier& value) {
#define KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(MODIFIER) \
case event_definition::modifier::MODIFIER: \
stream << #MODIFIER; \
break;
switch (value) {
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(any);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(caps_lock);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(fn);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(end_);
}
#undef KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT
return stream;
}
template <template <class T, class A> class container>
inline std::ostream& operator<<(std::ostream& stream, const container<event_definition::modifier, std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
template <template <class T, class H, class K, class A> class container>
inline std::ostream& operator<<(std::ostream& stream,
const container<event_definition::modifier,
std::hash<event_definition::modifier>,
std::equal_to<event_definition::modifier>,
std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
} // namespace details
} // namespace manipulator
} // namespace krbn
<|endoftext|>
|
<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "pci.hh"
#include "pcireg.hh"
#include "traps.h"
#include "kstream.hh"
static console_stream verbose(true);
extern int e1000attach(struct pci_func *pcif);
extern int e1000eattach(struct pci_func *pcif);
// Flag to do "lspci" at bootup
static int pci_show_devs = 0;
static int pci_show_addrs = 0;
// PCI "configuration mechanism one"
static u32 pci_conf1_addr_ioport = 0x0cf8;
static u32 pci_conf1_data_ioport = 0x0cfc;
// PCI driver table
struct pci_driver {
u32 key1, key2;
int (*attachfn) (struct pci_func *pcif);
};
// Forward declarations
static int pci_bridge_attach(struct pci_func *pcif);
// pci_attach_class matches the class and subclass of a PCI device
struct pci_driver pci_attach_class[] = {
{ PCI_CLASS_BRIDGE, PCI_SUBCLASS_BRIDGE_PCI, &pci_bridge_attach },
{ 0, 0, 0 },
};
// pci_attach_vendor matches the vendor ID and device ID of a PCI device
struct pci_driver pci_attach_vendor[] = {
// [E1000 5.2]
// QEMU emulates an e1000 82540EM
{ 0x8086, 0x100e, &e1000attach },
// josmp's dual ported e1000 82546GB copper
{ 0x8086, 0x1079, &e1000attach },
// tom's e1000 82541GI copper
{ 0x8086, 0x1076, &e1000attach },
// Both of ud0's e1000e (82573E, 82573L)
{ 0x8086, 0x108c, &e1000eattach },
{ 0x8086, 0x109A, &e1000eattach },
{ 0, 0, 0 },
};
static const char *pci_class[] =
{
"Unknown",
"Storage controller",
"Network controller",
"Display controller",
"Multimedia device",
"Memory controller",
"Bridge device",
};
static void
pci_print_func(struct pci_func *f)
{
const char *classname = pci_class[0];
if (PCI_CLASS(f->dev_class) < sizeof(pci_class) / sizeof(pci_class[0]))
classname = pci_class[PCI_CLASS(f->dev_class)];
cprintf("PCI: %x:%x.%d: %x:%x: class: %x.%x (%s) irq: %d int: %c\n",
f->bus->busno, f->dev, f->func,
PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),
PCI_CLASS(f->dev_class), PCI_SUBCLASS(f->dev_class), classname,
f->irq_line, "-ABCD"[f->int_pin]);
}
void
to_stream(print_stream *s, const struct pci_func &f)
{
s->print(sfmt(f.bus->busno).base(16).width(2).pad(), ':',
sfmt(f.dev).base(16).width(2).pad(), '.',
sfmt(f.func).base(16).width(2).pad());
}
static void
pci_conf1_set_addr(u32 seg,
u32 bus,
u32 dev,
u32 func,
u32 offset)
{
if (!(seg == 0 &&
bus < 256 &&
dev < 32 &&
func < 8 &&
offset < 256))
panic("pci_conf1_set_addr");
u32 v = (1 << 31) | // config-space
(bus << 16) | (dev << 11) | (func << 8) | (offset);
outl(pci_conf1_addr_ioport, v);
}
u32
pci_conf_read(u32 seg, u32 bus, u32 dev, u32 func, u32 offset, int width)
{
pci_conf1_set_addr(seg, bus, dev, func, offset);
switch (width) {
case 8:
return inb(pci_conf1_data_ioport + (offset & 3));
case 16:
return inw(pci_conf1_data_ioport + (offset & 2));
case 32:
return inl(pci_conf1_data_ioport);
}
panic("pci_conf_read: bad width %d", width);
}
static u32
pci_conf_read(struct pci_func *f, u32 off)
{
return pci_conf_read(0, f->bus->busno, f->dev, f->func, off, 32);
}
void
pci_conf_write(u32 seg, u32 bus, u32 dev, u32 func, u32 offset,
u32 val, int width)
{
pci_conf1_set_addr(seg, bus, dev, func, offset);
switch (width) {
case 8:
outb(pci_conf1_data_ioport, val + (offset & 3));
return;
case 16:
outl(pci_conf1_data_ioport, val + (offset & 2));
return;
case 32:
outw(pci_conf1_data_ioport, val);
return;
}
panic("pci_conf_write: bad width %d", width);
}
static void
pci_conf_write(struct pci_func *f, u32 off, u32 v)
{
pci_conf_write(0, f->bus->busno, f->dev, f->func, off, v, 32);
}
static int __attribute__((warn_unused_result))
pci_attach_match(u32 key1, u32 key2,
struct pci_driver *list, struct pci_func *pcif)
{
u32 i;
for (i = 0; list[i].attachfn; i++) {
if (list[i].key1 == key1 && list[i].key2 == key2) {
int r = list[i].attachfn(pcif);
if (r > 0)
return r;
if (r < 0)
cprintf("pci_attach_match: attaching "
"%x.%x (%p): %d\n",
key1, key2, list[i].attachfn, r);
}
}
return 0;
}
static int
pci_attach(struct pci_func *f)
{
return
pci_attach_match(PCI_CLASS(f->dev_class),
PCI_SUBCLASS(f->dev_class),
&pci_attach_class[0], f) ||
pci_attach_match(PCI_VENDOR(f->dev_id),
PCI_PRODUCT(f->dev_id),
&pci_attach_vendor[0], f);
}
static void
pci_scan_caplist(struct pci_func* f)
{
u32 cap_ptr = PCI_CAPLIST_PTR(pci_conf_read(f, PCI_CAPLISTPTR_REG));
for (int i = 0; i < 10 && cap_ptr != 0; i++) {
u32 cap_entry = pci_conf_read(f, cap_ptr);
switch (PCI_CAPLIST_CAP(cap_entry)) {
case PCI_CAP_MSI:
f->msi_capreg = cap_ptr;
break;
default:
break;
}
cap_ptr = PCI_CAPLIST_NEXT(cap_entry);
}
}
void
pci_msi_enable(struct pci_func *f, u8 irqnum)
{
// PCI System Architecture, Fourth Edition
assert(f->msi_capreg != 0);
u32 cap_entry = pci_conf_read(f, f->msi_capreg);
if (!(cap_entry & PCI_MSI_MCR_64BIT))
panic("pci_msi_enable only handles 64-bit address capable devices");
if (PCI_MSI_MCR_MMC(cap_entry) != 0)
panic("pci_msi_enable only handles 1 requested message");
// [PCI SA pg 253]
// Step 4. Assign a dword-aligned memory address to the device's
// Message Address Register.
// (The Message Address Register format is mandated by the x86
// architecture. See 9.11.1 in the Vol. 3 of the Intel architecture
// manual.)
pci_conf_write(f, f->msi_capreg + 4*1,
(0x0fee << 20) | // magic constant for northbridge
(0 << 12) | // destination ID
(1 << 3) | // redirection hint
(0 << 2)); // destination mode
pci_conf_write(f, f->msi_capreg + 4*2, 0);
// Step 5 and 6. Allocate messages for the device. Since we
// support only one message and that is the default value in
// the message control register, we do nothing.
// Step 7. Write base message data pattern into the device's
// Message Data Register.
// (The Message Data Register format is mandated by the x86
// architecture. See 9.11.2 in the Vol. 3 of the Intel architecture
// manual.
pci_conf_write(f, f->msi_capreg + 4*3,
(0 << 15) | // trigger mode (edge)
//(0 << 14) | // level for trigger mode (don't care)
(0 << 8) | // delivery mode (fixed)
(irqnum+T_IRQ0)); // vector
// Step 8. Set the MSI enable bit in the device's Message
// control register.
pci_conf_write(f, f->msi_capreg, cap_entry | (1 << 16));
}
static int
pci_scan_bus(struct pci_bus *bus)
{
verbose.println("pci: Scanning bus ", shex(bus->busno));
int totaldev = 0;
struct pci_func df;
memset(&df, 0, sizeof(df));
df.bus = bus;
for (df.dev = 0; df.dev < 32; df.dev++) {
u32 bhlc = pci_conf_read(&df, PCI_BHLC_REG);
if (PCI_HDRTYPE_TYPE(bhlc) > 1) // Unsupported or no device
continue;
totaldev++;
struct pci_func f = df;
for (f.func = 0; f.func < (PCI_HDRTYPE_MULTIFN(bhlc) ? 8 : 1);
f.func++) {
struct pci_func af = f;
af.dev_id = pci_conf_read(&f, PCI_ID_REG);
if (PCI_VENDOR(af.dev_id) == 0xffff)
continue;
u32 intr = pci_conf_read(&af, PCI_INTERRUPT_REG);
af.irq_line = PCI_INTERRUPT_LINE(intr);
af.int_pin = PCI_INTERRUPT_PIN(intr);
u32 cmd_status = pci_conf_read(&af, PCI_COMMAND_STATUS_REG);
if (cmd_status & PCI_STATUS_CAPLIST_SUPPORT)
pci_scan_caplist(&af);
af.dev_class = pci_conf_read(&af, PCI_CLASS_REG);
if (pci_show_devs)
pci_print_func(&af);
pci_attach(&af);
}
}
return totaldev;
}
static int
pci_bridge_attach(struct pci_func *pcif)
{
u32 busreg = pci_conf_read(pcif, PCI_BRIDGE_BUS_REG);
struct pci_bus nbus;
memset(&nbus, 0, sizeof(nbus));
nbus.parent_bridge = pcif;
nbus.busno = (busreg >> PCI_BRIDGE_BUS_SECONDARY_SHIFT) & 0xff;
if (pci_show_devs)
cprintf("PCI: %x:%x.%d: bridge to PCI bus %d--%d\n",
pcif->bus->busno, pcif->dev, pcif->func,
nbus.busno,
(busreg >> PCI_BRIDGE_BUS_SUBORDINATE_SHIFT) & 0xff);
pci_scan_bus(&nbus);
return 1;
}
void
pci_func_enable(struct pci_func *f)
{
pci_conf_write(f, PCI_COMMAND_STATUS_REG,
PCI_COMMAND_IO_ENABLE |
PCI_COMMAND_MEM_ENABLE |
PCI_COMMAND_MASTER_ENABLE);
u32 bar_width;
u32 bar;
for (bar = PCI_MAPREG_START; bar < PCI_MAPREG_END;
bar += bar_width)
{
u32 oldv = pci_conf_read(f, bar);
bar_width = 4;
pci_conf_write(f, bar, 0xffffffff);
u32 rv = pci_conf_read(f, bar);
if (rv == 0)
continue;
int regnum = PCI_MAPREG_NUM(bar);
u32 base, size;
if (PCI_MAPREG_TYPE(rv) == PCI_MAPREG_TYPE_MEM) {
if (PCI_MAPREG_MEM_TYPE(rv) == PCI_MAPREG_MEM_TYPE_64BIT)
bar_width = 8;
size = PCI_MAPREG_MEM_SIZE(rv);
base = PCI_MAPREG_MEM_ADDR(oldv);
if (pci_show_addrs)
cprintf(" mem region %d: %d bytes at 0x%x\n",
regnum, size, base);
} else {
size = PCI_MAPREG_IO_SIZE(rv);
base = PCI_MAPREG_IO_ADDR(oldv);
if (pci_show_addrs)
cprintf(" io region %d: %d bytes at 0x%x\n",
regnum, size, base);
}
pci_conf_write(f, bar, oldv);
f->reg_base[regnum] = base;
f->reg_size[regnum] = size;
if (size && !base)
cprintf("PCI device %02x:%02x.%d (%04x:%04x) "
"may be misconfigured: "
"region %d: base 0x%x, size %d\n",
f->bus->busno, f->dev, f->func,
PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),
regnum, base, size);
}
if (VERBOSE)
cprintf("PCI function %x:%x.%d (%x:%x) enabled\n",
f->bus->busno, f->dev, f->func,
PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id));
}
void
initpci(void)
{
if (!acpi_pci_scan_roots(pci_scan_bus)) {
// Assume a single root bus
static struct pci_bus root_bus;
memset(&root_bus, 0, sizeof(root_bus));
pci_scan_bus(&root_bus);
}
}
<commit_msg>pci: Don't assume MSI destination is APICID 0<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "pci.hh"
#include "pcireg.hh"
#include "traps.h"
#include "kstream.hh"
#include "cpu.hh"
static console_stream verbose(true);
extern int e1000attach(struct pci_func *pcif);
extern int e1000eattach(struct pci_func *pcif);
// Flag to do "lspci" at bootup
static int pci_show_devs = 0;
static int pci_show_addrs = 0;
// PCI "configuration mechanism one"
static u32 pci_conf1_addr_ioport = 0x0cf8;
static u32 pci_conf1_data_ioport = 0x0cfc;
// PCI driver table
struct pci_driver {
u32 key1, key2;
int (*attachfn) (struct pci_func *pcif);
};
// Forward declarations
static int pci_bridge_attach(struct pci_func *pcif);
// pci_attach_class matches the class and subclass of a PCI device
struct pci_driver pci_attach_class[] = {
{ PCI_CLASS_BRIDGE, PCI_SUBCLASS_BRIDGE_PCI, &pci_bridge_attach },
{ 0, 0, 0 },
};
// pci_attach_vendor matches the vendor ID and device ID of a PCI device
struct pci_driver pci_attach_vendor[] = {
// [E1000 5.2]
// QEMU emulates an e1000 82540EM
{ 0x8086, 0x100e, &e1000attach },
// josmp's dual ported e1000 82546GB copper
{ 0x8086, 0x1079, &e1000attach },
// tom's e1000 82541GI copper
{ 0x8086, 0x1076, &e1000attach },
// Both of ud0's e1000e (82573E, 82573L)
{ 0x8086, 0x108c, &e1000eattach },
{ 0x8086, 0x109A, &e1000eattach },
{ 0, 0, 0 },
};
static const char *pci_class[] =
{
"Unknown",
"Storage controller",
"Network controller",
"Display controller",
"Multimedia device",
"Memory controller",
"Bridge device",
};
static void
pci_print_func(struct pci_func *f)
{
const char *classname = pci_class[0];
if (PCI_CLASS(f->dev_class) < sizeof(pci_class) / sizeof(pci_class[0]))
classname = pci_class[PCI_CLASS(f->dev_class)];
cprintf("PCI: %x:%x.%d: %x:%x: class: %x.%x (%s) irq: %d int: %c\n",
f->bus->busno, f->dev, f->func,
PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),
PCI_CLASS(f->dev_class), PCI_SUBCLASS(f->dev_class), classname,
f->irq_line, "-ABCD"[f->int_pin]);
}
void
to_stream(print_stream *s, const struct pci_func &f)
{
s->print(sfmt(f.bus->busno).base(16).width(2).pad(), ':',
sfmt(f.dev).base(16).width(2).pad(), '.',
sfmt(f.func).base(16).width(2).pad());
}
static void
pci_conf1_set_addr(u32 seg,
u32 bus,
u32 dev,
u32 func,
u32 offset)
{
if (!(seg == 0 &&
bus < 256 &&
dev < 32 &&
func < 8 &&
offset < 256))
panic("pci_conf1_set_addr");
u32 v = (1 << 31) | // config-space
(bus << 16) | (dev << 11) | (func << 8) | (offset);
outl(pci_conf1_addr_ioport, v);
}
u32
pci_conf_read(u32 seg, u32 bus, u32 dev, u32 func, u32 offset, int width)
{
pci_conf1_set_addr(seg, bus, dev, func, offset);
switch (width) {
case 8:
return inb(pci_conf1_data_ioport + (offset & 3));
case 16:
return inw(pci_conf1_data_ioport + (offset & 2));
case 32:
return inl(pci_conf1_data_ioport);
}
panic("pci_conf_read: bad width %d", width);
}
static u32
pci_conf_read(struct pci_func *f, u32 off)
{
return pci_conf_read(0, f->bus->busno, f->dev, f->func, off, 32);
}
void
pci_conf_write(u32 seg, u32 bus, u32 dev, u32 func, u32 offset,
u32 val, int width)
{
pci_conf1_set_addr(seg, bus, dev, func, offset);
switch (width) {
case 8:
outb(pci_conf1_data_ioport, val + (offset & 3));
return;
case 16:
outl(pci_conf1_data_ioport, val + (offset & 2));
return;
case 32:
outw(pci_conf1_data_ioport, val);
return;
}
panic("pci_conf_write: bad width %d", width);
}
static void
pci_conf_write(struct pci_func *f, u32 off, u32 v)
{
pci_conf_write(0, f->bus->busno, f->dev, f->func, off, v, 32);
}
static int __attribute__((warn_unused_result))
pci_attach_match(u32 key1, u32 key2,
struct pci_driver *list, struct pci_func *pcif)
{
u32 i;
for (i = 0; list[i].attachfn; i++) {
if (list[i].key1 == key1 && list[i].key2 == key2) {
int r = list[i].attachfn(pcif);
if (r > 0)
return r;
if (r < 0)
cprintf("pci_attach_match: attaching "
"%x.%x (%p): %d\n",
key1, key2, list[i].attachfn, r);
}
}
return 0;
}
static int
pci_attach(struct pci_func *f)
{
return
pci_attach_match(PCI_CLASS(f->dev_class),
PCI_SUBCLASS(f->dev_class),
&pci_attach_class[0], f) ||
pci_attach_match(PCI_VENDOR(f->dev_id),
PCI_PRODUCT(f->dev_id),
&pci_attach_vendor[0], f);
}
static void
pci_scan_caplist(struct pci_func* f)
{
u32 cap_ptr = PCI_CAPLIST_PTR(pci_conf_read(f, PCI_CAPLISTPTR_REG));
for (int i = 0; i < 10 && cap_ptr != 0; i++) {
u32 cap_entry = pci_conf_read(f, cap_ptr);
switch (PCI_CAPLIST_CAP(cap_entry)) {
case PCI_CAP_MSI:
f->msi_capreg = cap_ptr;
break;
default:
break;
}
cap_ptr = PCI_CAPLIST_NEXT(cap_entry);
}
}
void
pci_msi_enable(struct pci_func *f, u8 irqnum)
{
// PCI System Architecture, Fourth Edition
assert(f->msi_capreg != 0);
u32 cap_entry = pci_conf_read(f, f->msi_capreg);
if (!(cap_entry & PCI_MSI_MCR_64BIT))
panic("pci_msi_enable only handles 64-bit address capable devices");
if (PCI_MSI_MCR_MMC(cap_entry) != 0)
panic("pci_msi_enable only handles 1 requested message");
// [PCI SA pg 253]
// Step 4. Assign a dword-aligned memory address to the device's
// Message Address Register.
// (The Message Address Register format is mandated by the x86
// architecture. See 9.11.1 in the Vol. 3 of the Intel architecture
// manual.)
uint64_t dest = cpus[0].hwid.num;
pci_conf_write(f, f->msi_capreg + 4*1,
(0x0fee << 20) | // magic constant for northbridge
(dest << 12) | // destination ID
(1 << 3) | // redirection hint
(0 << 2)); // destination mode
pci_conf_write(f, f->msi_capreg + 4*2, 0);
// Step 5 and 6. Allocate messages for the device. Since we
// support only one message and that is the default value in
// the message control register, we do nothing.
// Step 7. Write base message data pattern into the device's
// Message Data Register.
// (The Message Data Register format is mandated by the x86
// architecture. See 9.11.2 in the Vol. 3 of the Intel architecture
// manual.
pci_conf_write(f, f->msi_capreg + 4*3,
(0 << 15) | // trigger mode (edge)
//(0 << 14) | // level for trigger mode (don't care)
(0 << 8) | // delivery mode (fixed)
(irqnum+T_IRQ0)); // vector
// Step 8. Set the MSI enable bit in the device's Message
// control register.
pci_conf_write(f, f->msi_capreg, cap_entry | (1 << 16));
}
static int
pci_scan_bus(struct pci_bus *bus)
{
verbose.println("pci: Scanning bus ", shex(bus->busno));
int totaldev = 0;
struct pci_func df;
memset(&df, 0, sizeof(df));
df.bus = bus;
for (df.dev = 0; df.dev < 32; df.dev++) {
u32 bhlc = pci_conf_read(&df, PCI_BHLC_REG);
if (PCI_HDRTYPE_TYPE(bhlc) > 1) // Unsupported or no device
continue;
totaldev++;
struct pci_func f = df;
for (f.func = 0; f.func < (PCI_HDRTYPE_MULTIFN(bhlc) ? 8 : 1);
f.func++) {
struct pci_func af = f;
af.dev_id = pci_conf_read(&f, PCI_ID_REG);
if (PCI_VENDOR(af.dev_id) == 0xffff)
continue;
u32 intr = pci_conf_read(&af, PCI_INTERRUPT_REG);
af.irq_line = PCI_INTERRUPT_LINE(intr);
af.int_pin = PCI_INTERRUPT_PIN(intr);
u32 cmd_status = pci_conf_read(&af, PCI_COMMAND_STATUS_REG);
if (cmd_status & PCI_STATUS_CAPLIST_SUPPORT)
pci_scan_caplist(&af);
af.dev_class = pci_conf_read(&af, PCI_CLASS_REG);
if (pci_show_devs)
pci_print_func(&af);
pci_attach(&af);
}
}
return totaldev;
}
static int
pci_bridge_attach(struct pci_func *pcif)
{
u32 busreg = pci_conf_read(pcif, PCI_BRIDGE_BUS_REG);
struct pci_bus nbus;
memset(&nbus, 0, sizeof(nbus));
nbus.parent_bridge = pcif;
nbus.busno = (busreg >> PCI_BRIDGE_BUS_SECONDARY_SHIFT) & 0xff;
if (pci_show_devs)
cprintf("PCI: %x:%x.%d: bridge to PCI bus %d--%d\n",
pcif->bus->busno, pcif->dev, pcif->func,
nbus.busno,
(busreg >> PCI_BRIDGE_BUS_SUBORDINATE_SHIFT) & 0xff);
pci_scan_bus(&nbus);
return 1;
}
void
pci_func_enable(struct pci_func *f)
{
pci_conf_write(f, PCI_COMMAND_STATUS_REG,
PCI_COMMAND_IO_ENABLE |
PCI_COMMAND_MEM_ENABLE |
PCI_COMMAND_MASTER_ENABLE);
u32 bar_width;
u32 bar;
for (bar = PCI_MAPREG_START; bar < PCI_MAPREG_END;
bar += bar_width)
{
u32 oldv = pci_conf_read(f, bar);
bar_width = 4;
pci_conf_write(f, bar, 0xffffffff);
u32 rv = pci_conf_read(f, bar);
if (rv == 0)
continue;
int regnum = PCI_MAPREG_NUM(bar);
u32 base, size;
if (PCI_MAPREG_TYPE(rv) == PCI_MAPREG_TYPE_MEM) {
if (PCI_MAPREG_MEM_TYPE(rv) == PCI_MAPREG_MEM_TYPE_64BIT)
bar_width = 8;
size = PCI_MAPREG_MEM_SIZE(rv);
base = PCI_MAPREG_MEM_ADDR(oldv);
if (pci_show_addrs)
cprintf(" mem region %d: %d bytes at 0x%x\n",
regnum, size, base);
} else {
size = PCI_MAPREG_IO_SIZE(rv);
base = PCI_MAPREG_IO_ADDR(oldv);
if (pci_show_addrs)
cprintf(" io region %d: %d bytes at 0x%x\n",
regnum, size, base);
}
pci_conf_write(f, bar, oldv);
f->reg_base[regnum] = base;
f->reg_size[regnum] = size;
if (size && !base)
cprintf("PCI device %02x:%02x.%d (%04x:%04x) "
"may be misconfigured: "
"region %d: base 0x%x, size %d\n",
f->bus->busno, f->dev, f->func,
PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),
regnum, base, size);
}
if (VERBOSE)
cprintf("PCI function %x:%x.%d (%x:%x) enabled\n",
f->bus->busno, f->dev, f->func,
PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id));
}
void
initpci(void)
{
if (!acpi_pci_scan_roots(pci_scan_bus)) {
// Assume a single root bus
static struct pci_bus root_bus;
memset(&root_bus, 0, sizeof(root_bus));
pci_scan_bus(&root_bus);
}
}
<|endoftext|>
|
<commit_before>#include "GLTexture3D.h"
#include "GLTextureRectangle.h"
#include <iostream>
#include "GLUtility.h"
using namespace std;
// ----------------------------------------------------------------------------
GLTexture3D *GLTexture3D::New(int width, int height, int depth,
int internalformat, int format, int type,
void *data)
{
// Check if width and height are powers of two
unsigned int xs = static_cast<unsigned int>(width);
unsigned int ys = static_cast<unsigned int>(height);
unsigned int zs = static_cast<unsigned int>(depth);
if ((xs & (xs - 1)) || (ys & (ys - 1)) || (zs & (zs - 1)))
{
// Non-power-of-two sizes, check available extensions
if (GLEW_ARB_texture_non_power_of_two)
{
cout << "GLTexture: sizes are not powers of two, creating NPOTS texture" << endl;
GLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);
if (!tex->Allocate(format, type, data))
{
delete tex;
return 0;
}
return tex;
}
cerr << "GLTexture: non-power-of-two sized textures not supported" << endl;
return 0;
}
else
{
// Create a normal texture
GLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);
if (!tex->Allocate(format, type, data))
{
delete tex;
return 0;
}
return tex;
}
}
// ----------------------------------------------------------------------------
GLTexture3D::GLTexture3D(int width, int height, int depth, int internalformat)
: GLTexture(width, height, internalformat), depth(depth)
{
//cout << "GLTexture3D: Constructor" << endl;
}
// ----------------------------------------------------------------------------
GLTexture3D::~GLTexture3D()
{
//cout << "GLTexture3D: Destructor" << endl;
}
// ----------------------------------------------------------------------------
bool GLTexture3D::Allocate(int format, int type, void *data)
{
//cout << "GLTexture3D: Allocate" << endl;
// Store old binding to avoid messing up the state
glPushAttrib(GL_TEXTURE_BIT);
// Store new params
this->dataformat = format;
this->datatype = type;
BindToCurrent();
// Set texture object parameters
glTexParameterf(GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf(GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
// Try a proxy allocation to check available memory and parameters
glTexImage3D(GL_PROXY_TEXTURE_3D, 0, internalformat,
width, height, depth, 0, format, type, data);
GLint w;
glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0, GL_TEXTURE_WIDTH, &w);
GLUtility::CheckOpenGLError("GLTexture3D: Allocate() - proxy allocation");
bool eflag = GLUtility::GetErrorFlag();
if (w == 0 || eflag)
{
cerr << "GLTexture3D: Proxy allocation failed, may be out of video memory" << endl;
UnbindCurrent();
glPopAttrib();
return false;
}
// Allocate the texture
glTexImage3D(GetTextureTarget(), 0, internalformat,
width, height, depth, 0, format, type, data);
GLUtility::CheckOpenGLError("GLTexture3D: Allocate - glTexImage3D");
UnbindCurrent();
glPopAttrib();
if (GLUtility::GetErrorFlag())
{
cerr << "GLTexture3D: An OpenGL error occurred while allocating the texture" << endl;
GLUtility::ClearOpenGLError();
return false;
}
return true;
}
<commit_msg>Whitespace cleanup.<commit_after>#include "GLTexture3D.h"
#include "GLTextureRectangle.h"
#include <iostream>
#include "GLUtility.h"
using namespace std;
// ----------------------------------------------------------------------------
GLTexture3D *GLTexture3D::New(int width, int height, int depth,
int internalformat, int format, int type,
void *data)
{
// Check if width and height are powers of two
unsigned int xs = static_cast<unsigned int>(width);
unsigned int ys = static_cast<unsigned int>(height);
unsigned int zs = static_cast<unsigned int>(depth);
if ((xs & (xs - 1)) || (ys & (ys - 1)) || (zs & (zs - 1)))
{
// Non-power-of-two sizes, check available extensions
if (GLEW_ARB_texture_non_power_of_two)
{
cout << "GLTexture: sizes are not powers of two, creating NPOTS texture" << endl;
GLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);
if (!tex->Allocate(format, type, data))
{
delete tex;
return 0;
}
return tex;
}
cerr << "GLTexture: non-power-of-two sized textures not supported" << endl;
return 0;
}
else
{
// Create a normal texture
GLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);
if (!tex->Allocate(format, type, data))
{
delete tex;
return 0;
}
return tex;
}
}
// ----------------------------------------------------------------------------
GLTexture3D::GLTexture3D(int width, int height, int depth, int internalformat)
: GLTexture(width, height, internalformat), depth(depth)
{
//cout << "GLTexture3D: Constructor" << endl;
}
// ----------------------------------------------------------------------------
GLTexture3D::~GLTexture3D()
{
//cout << "GLTexture3D: Destructor" << endl;
}
// ----------------------------------------------------------------------------
bool GLTexture3D::Allocate(int format, int type, void *data)
{
//cout << "GLTexture3D: Allocate" << endl;
// Store old binding to avoid messing up the state
glPushAttrib(GL_TEXTURE_BIT);
// Store new params
this->dataformat = format;
this->datatype = type;
BindToCurrent();
// Set texture object parameters
glTexParameterf(GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
// Try a proxy allocation to check available memory and parameters
glTexImage3D(GL_PROXY_TEXTURE_3D, 0, internalformat,
width, height, depth, 0, format, type, data);
GLint w;
glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0, GL_TEXTURE_WIDTH, &w);
GLUtility::CheckOpenGLError("GLTexture3D: Allocate() - proxy allocation");
bool eflag = GLUtility::GetErrorFlag();
if (w == 0 || eflag)
{
cerr << "GLTexture3D: Proxy allocation failed, may be out of video memory" << endl;
UnbindCurrent();
glPopAttrib();
return false;
}
// Allocate the texture
glTexImage3D(GetTextureTarget(), 0, internalformat,
width, height, depth, 0, format, type, data);
GLUtility::CheckOpenGLError("GLTexture3D: Allocate - glTexImage3D");
UnbindCurrent();
glPopAttrib();
if (GLUtility::GetErrorFlag())
{
cerr << "GLTexture3D: An OpenGL error occurred while allocating the texture" << endl;
GLUtility::ClearOpenGLError();
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>#include "TimerWrapper.hpp"
namespace org_pqrs_KeyRemap4MacBook {
void
TimerWrapper::initialize(IOWorkLoop *_workLoop, OSObject *owner, IOTimerEventSource::Action func)
{
if (timer) terminate();
if (! _workLoop) return;
workLoop = _workLoop;
if (owner == NULL) {
owner = reinterpret_cast<OSObject *>(this);
}
timer = IOTimerEventSource::timerEventSource(owner, func);
if (workLoop->addEventSource(timer) != kIOReturnSuccess) {
timer->release();
timer = NULL;
}
}
void
TimerWrapper::terminate(void)
{
if (timer) {
timer->cancelTimeout();
if (workLoop) {
workLoop->removeEventSource(timer);
}
timer->release();
timer = NULL;
}
workLoop = NULL;
}
}
<commit_msg>update kext<commit_after>#include "TimerWrapper.hpp"
namespace org_pqrs_KeyRemap4MacBook {
void
TimerWrapper::initialize(IOWorkLoop *_workLoop, OSObject *owner, IOTimerEventSource::Action func)
{
if (timer) terminate();
if (! _workLoop) return;
workLoop = _workLoop;
if (owner == NULL) {
owner = reinterpret_cast<OSObject *>(this);
}
timer = IOTimerEventSource::timerEventSource(owner, func);
if (workLoop->addEventSource(timer) != kIOReturnSuccess) {
IOLog("[KeyRemap4MacBook ERROR] TimerWrapper addEventSource failed\n");
timer->release();
timer = NULL;
}
}
void
TimerWrapper::terminate(void)
{
if (timer) {
timer->cancelTimeout();
if (workLoop) {
workLoop->removeEventSource(timer);
}
timer->release();
timer = NULL;
}
workLoop = NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2016 ct_common authors. See LICENSE file for details.
#include "ct_common/common/constraint_a_binary_instances.h"
#include "ct_common/base/arithmetic_utils.h"
namespace ct_common {
#define CONSTRAINT_A_BINARY_SKELETON(CLASS_NAME, OP_TOKEN, EVAL_FUNC) \
REGISTER_CLASS_NAME(CLASS_NAME); \
\
CLASS_NAME::CLASS_NAME() = default; \
\
CLASS_NAME::~CLASS_NAME() = default; \
\
bool CLASS_NAME::EvaluateIntInternal( \
int loprd_val, int roprd_val) const { \
return EVAL_FUNC(loprd_val, roprd_val, precision_); \
} \
\
bool CLASS_NAME::EvaluateDoubleInternal( \
double loprd_val, double roprd_val) const { \
return EVAL_FUNC(loprd_val, roprd_val, precision_); \
} \
\
std::string CLASS_NAME::GetOpToken() const { \
return OP_TOKEN; \
}
#include "ct_common/common/constraint_a_binary_instances.inc"
#undef CONSTRAINT_A_BINARY_SKELETON
} // namespace ct_common
<commit_msg>fixed integer constraints<commit_after>// Copyright 2016 ct_common authors. See LICENSE file for details.
#include "ct_common/common/constraint_a_binary_instances.h"
#include "ct_common/base/arithmetic_utils.h"
namespace ct_common {
#define CONSTRAINT_A_BINARY_SKELETON(CLASS_NAME, OP_TOKEN, EVAL_FUNC) \
REGISTER_CLASS_NAME(CLASS_NAME); \
\
CLASS_NAME::CLASS_NAME() = default; \
\
CLASS_NAME::~CLASS_NAME() = default; \
\
bool CLASS_NAME::EvaluateIntInternal( \
int loprd_val, int roprd_val) const { \
return EVAL_FUNC(loprd_val, roprd_val); \
} \
\
bool CLASS_NAME::EvaluateDoubleInternal( \
double loprd_val, double roprd_val) const { \
return EVAL_FUNC(loprd_val, roprd_val, precision_); \
} \
\
std::string CLASS_NAME::GetOpToken() const { \
return OP_TOKEN; \
}
#include "ct_common/common/constraint_a_binary_instances.inc"
#undef CONSTRAINT_A_BINARY_SKELETON
} // namespace ct_common
<|endoftext|>
|
<commit_before>/*****************************************************************************
(c) 2013 Hobu, Inc. hobu.inc@gmail.com
Author: Andrew Bell andrew.bell.ia at gmail.com
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <hexer/Processor.hpp>
#include "las.hpp"
#include <fstream>
#include <sstream>
#include <boost/algorithm/string/compare.hpp>
using namespace std;
bool readHex(int& x, int& y, void* ctx)
{
static int pos = 0;
static int coords[] = {
0, 0,
1, 0,
2, 1,
3, 1,
4, 2,
4, 3,
4, 4,
3, 4,
2, 5,
1, 5,
0, 5,
-1, 4,
-2, 4,
-3, 3,
-3, 2,
-3, 1,
-2, 1,
-1, 0,
-1, 2,
0, 2,
1, 3,
2, 3
};
static int num_coords = sizeof(coords) / (sizeof(coords[0]));
if (pos + 1 < num_coords) {
x = coords[pos++];
y = coords[pos++];
return true;
}
return false;
}
std::string indent(int l)
{
std::string tabs;
tabs.append(l * 2, ' ');
return tabs;
}
void dumpPath(hexer::Path *p)
{
using namespace hexer;
static int level = 0;
Orientation o = p->orientation();
std::string ostring = ((o == CLOCKWISE) ? "CLOCKWISE" : "ANTICLOCKWISE");
indent(level);
cerr << indent(level) << "Path length = " << p->pathLength() << "!\n";
cerr << indent(level) << "Orientation = " << ostring << "!\n";
vector<Path *> paths = p->subPaths();
level++;
for (int pi = 0; pi != paths.size(); ++pi)
{
dumpPath(paths[pi]);
}
level--;
}
void hextest(std::string filename)
{
using namespace hexer;
vector<GridInfo *> infos;
GridInfo *gi = new GridInfo;
gi->m_hexsize = 10;
gi->m_density = 10;
infos.push_back(gi);
// LAS l(filename);
// l.open();
// process(infos, l.reader);
processHexes(infos, readHex);
// Dump hexes.
for (HexIter iter = gi->begin(); iter != gi->end(); ++iter)
{
HexInfo hi = *iter;
cerr << "Density/X/Y = " << hi.m_density << "/" <<
hi.m_center.m_x << "/" << hi.m_center.m_y << "!\n";
}
delete gi;
}
void pathtest(std::string filename)
{
using namespace hexer;
vector<GridInfo *> infos;
GridInfo *gi = new GridInfo;
infos.push_back(gi);
LAS l(filename);
l.open();
process(infos, l.reader);
for (std::vector<Path*>::size_type pi = 0; pi < gi->rootPaths().size(); ++pi)
{
Path *p = gi->rootPaths()[pi];
dumpPath(p);
}
delete gi;
}
void boundarytest(std::string filename)
{
using namespace hexer;
vector<GridInfo *> infos;
GridInfo *gi = new GridInfo;
infos.push_back(gi);
LAS l(filename);
l.open();
process(infos, l.reader);
std::ostringstream multi;
multi.setf(std::ios::fixed);
multi.precision(8);
gi->toWKT(multi);
std::cout << multi.str() << std::endl;
delete gi;
}
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "please specify a command and a filename. $ hextest PATH filename.las" << std::endl;
return 1;
}
std::string command(argv[1], strlen(argv[1]));
std::string filename(argv[2], strlen(argv[2]));
try
{
if (boost::iequals(command, "BOUNDARY"))
{
boundarytest(filename);
return 0;
}
if (boost::iequals(command, "PATH"))
{
pathtest(filename);
return 0;
}
if (boost::iequals(command, "HEX"))
{
hextest(filename);
return 0;
}
std::cout << "Command '" << command << "' not recognized" << std::endl;
return 1;
} catch (hexer::hexer_error const& e)
{
std::cout << "Hexer failed with error: '" << e.what() << "'" << std::endl;
return 1;
}
}
<commit_msg>use size_t for return<commit_after>/*****************************************************************************
(c) 2013 Hobu, Inc. hobu.inc@gmail.com
Author: Andrew Bell andrew.bell.ia at gmail.com
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include <hexer/Processor.hpp>
#include "las.hpp"
#include <fstream>
#include <sstream>
#include <boost/algorithm/string/compare.hpp>
using namespace std;
bool readHex(int& x, int& y, void* ctx)
{
static int pos = 0;
static int coords[] = {
0, 0,
1, 0,
2, 1,
3, 1,
4, 2,
4, 3,
4, 4,
3, 4,
2, 5,
1, 5,
0, 5,
-1, 4,
-2, 4,
-3, 3,
-3, 2,
-3, 1,
-2, 1,
-1, 0,
-1, 2,
0, 2,
1, 3,
2, 3
};
static int num_coords = sizeof(coords) / (sizeof(coords[0]));
if (pos + 1 < num_coords) {
x = coords[pos++];
y = coords[pos++];
return true;
}
return false;
}
std::string indent(int l)
{
std::string tabs;
tabs.append(l * 2, ' ');
return tabs;
}
void dumpPath(hexer::Path *p)
{
using namespace hexer;
static int level = 0;
Orientation o = p->orientation();
std::string ostring = ((o == CLOCKWISE) ? "CLOCKWISE" : "ANTICLOCKWISE");
indent(level);
cerr << indent(level) << "Path length = " << p->pathLength() << "!\n";
cerr << indent(level) << "Orientation = " << ostring << "!\n";
vector<Path *> paths = p->subPaths();
level++;
for (int pi = 0; pi != paths.size(); ++pi)
{
dumpPath(paths[pi]);
}
level--;
}
void hextest(std::string filename)
{
using namespace hexer;
vector<GridInfo *> infos;
GridInfo *gi = new GridInfo;
gi->m_hexsize = 10;
gi->m_density = 10;
infos.push_back(gi);
// LAS l(filename);
// l.open();
// process(infos, l.reader);
processHexes(infos, readHex);
// Dump hexes.
for (HexIter iter = gi->begin(); iter != gi->end(); ++iter)
{
HexInfo hi = *iter;
cerr << "Density/X/Y = " << hi.m_density << "/" <<
hi.m_center.m_x << "/" << hi.m_center.m_y << "!\n";
}
delete gi;
}
void pathtest(std::string filename)
{
using namespace hexer;
vector<GridInfo *> infos;
GridInfo *gi = new GridInfo;
infos.push_back(gi);
LAS l(filename);
l.open();
process(infos, l.reader);
for (std::vector<Path*>::size_type pi = 0; pi < gi->rootPaths().size(); ++pi)
{
Path *p = gi->rootPaths()[pi];
dumpPath(p);
}
delete gi;
}
void boundarytest(std::string filename)
{
using namespace hexer;
vector<GridInfo *> infos;
GridInfo *gi = new GridInfo;
infos.push_back(gi);
LAS l(filename);
l.open();
process(infos, l.reader);
std::ostringstream multi;
multi.setf(std::ios::fixed);
multi.precision(8);
gi->toWKT(multi);
std::cout << multi.str() << std::endl;
delete gi;
}
std::size_t main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "please specify a command and a filename. $ hextest PATH filename.las" << std::endl;
return 1;
}
std::string command(argv[1], strlen(argv[1]));
std::string filename(argv[2], strlen(argv[2]));
try
{
if (boost::iequals(command, "BOUNDARY"))
{
boundarytest(filename);
return 0;
}
if (boost::iequals(command, "PATH"))
{
pathtest(filename);
return 0;
}
if (boost::iequals(command, "HEX"))
{
hextest(filename);
return 0;
}
std::cout << "Command '" << command << "' not recognized" << std::endl;
return 1;
} catch (hexer::hexer_error const& e)
{
std::cout << "Hexer failed with error: '" << e.what() << "'" << std::endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mbubbleitem.h"
#include "mbubbleitem_p.h"
#include "mbubbleitemmodel.h"
#include "mimagewidget.h"
#include "mlabel.h"
#include "mwidgetcreator.h"
M_REGISTER_WIDGET(MBubbleItem)
MBubbleItemPrivate::MBubbleItemPrivate()
: MWidgetControllerPrivate(),
commentsLabel(NULL),
thumbsUpLabel(NULL),
commentsIcon(NULL),
thumbsUpIcon(NULL)
{
}
MBubbleItemPrivate::~MBubbleItemPrivate()
{
}
void MBubbleItemPrivate::init()
{
}
void MBubbleItemPrivate::createCommentsInfo()
{
Q_Q(MBubbleItem);
commentsLabel = new MLabel;
commentsLabel->setParent(q);
commentsIcon = new MImageWidget;
commentsIcon->setParent(q);
commentsIcon->setObjectName("InformationalIcon");
commentsIcon->setImage("icon-s-common-comments", commentsIcon->minimumSize().toSize());
q->addInformationWidget(commentsIcon);
q->addInformationWidget(commentsLabel);
refreshStyles();
}
void MBubbleItemPrivate::destroyCommentsInfo()
{
Q_Q(MBubbleItem);
q->removeInformationWidget(commentsLabel);
q->removeInformationWidget(commentsIcon);
if(commentsLabel->parent() == q)
delete commentsLabel;
if(commentsIcon->parent() == q)
delete commentsIcon;
commentsLabel = NULL;
commentsIcon = NULL;
}
void MBubbleItemPrivate::createThumbsUpInfo()
{
Q_Q(MBubbleItem);
thumbsUpLabel = new MLabel;
thumbsUpLabel->setParent(q);
thumbsUpIcon = new MImageWidget;
thumbsUpIcon->setParent(q);
thumbsUpIcon->setObjectName("InformationalIcon");
thumbsUpIcon->setImage("icon-s-common-like", thumbsUpIcon->minimumSize().toSize());
q->addInformationWidget(thumbsUpIcon);
q->addInformationWidget(thumbsUpLabel);
refreshStyles();
}
void MBubbleItemPrivate::destroyThumbsUpInfo()
{
Q_Q(MBubbleItem);
q->removeInformationWidget(thumbsUpLabel);
q->removeInformationWidget(thumbsUpIcon);
if(thumbsUpLabel->parent() == q)
delete thumbsUpLabel;
if(thumbsUpIcon->parent() == q)
delete thumbsUpIcon;
thumbsUpLabel = NULL;
thumbsUpIcon = NULL;
}
void MBubbleItemPrivate::refreshStyles()
{
Q_Q(MBubbleItem);
if (q->messageType() == MBubbleItem::Incoming) {
if (thumbsUpLabel)
thumbsUpLabel->setObjectName("InformationalLabelIncoming");
if (commentsLabel)
commentsLabel->setObjectName("InformationalLabelIncoming");
} else {
if (thumbsUpLabel)
thumbsUpLabel->setObjectName("InformationalLabelOutgoing");
if (commentsLabel)
commentsLabel->setObjectName("InformationalLabelOutgoing");
}
}
MBubbleItem::MBubbleItem(QGraphicsItem *parent)
: MWidgetController(new MBubbleItemPrivate, new MBubbleItemModel, parent)
{
Q_D(MBubbleItem);
d->init();
}
MBubbleItem::MBubbleItem(MBubbleItemPrivate *dd, MBubbleItemModel *model, QGraphicsItem *parent)
: MWidgetController(dd, model, parent)
{
Q_D(MBubbleItem);
d->init();
}
MBubbleItem::~MBubbleItem()
{
}
MImageWidget* MBubbleItem::avatar() const
{
return model()->avatar();
}
void MBubbleItem::setAvatar(MImageWidget* avatar)
{
MImageWidget *oldAvatar = model()->avatar();
if(oldAvatar == avatar)
return;
model()->setAvatar(avatar);
if(oldAvatar && oldAvatar->parent() == this)
delete oldAvatar;
}
void MBubbleItem::setAvatar(const QPixmap &avatar)
{
model()->beginTransaction();
if (!model()->avatar()) {
model()->setAvatar(new MImageWidget);
model()->avatar()->setParent(this);
}
model()->avatar()->setPixmap(avatar);
model()->commitTransaction();
}
QString MBubbleItem::senderName()
{
return model()->senderName();
}
void MBubbleItem::setSenderName(const QString &senderName)
{
model()->setSenderName(senderName);
}
QString MBubbleItem::timeStamp()
{
return model()->timeStamp();
}
void MBubbleItem::setTimeStamp(const QString &timeStamp)
{
model()->setTimeStamp(timeStamp);
}
QString MBubbleItem::message()
{
return model()->message();
}
void MBubbleItem::setMessage(const QString &message)
{
model()->setMessage(message);
}
MBubbleItem::MessageType MBubbleItem::messageType() const
{
return static_cast<MBubbleItem::MessageType>(model()->messageType());
}
void MBubbleItem::setMessageType(MessageType messageType)
{
Q_D(MBubbleItem);
model()->beginTransaction();
model()->setMessageType(messageType);
d->refreshStyles();
model()->commitTransaction();
}
void MBubbleItem::setCentralWidget(QGraphicsWidget* centralWidget)
{
QGraphicsWidget *oldCentralWidget = model()->centralWidget();
if(oldCentralWidget == centralWidget)
return;
model()->setCentralWidget(centralWidget);
if(oldCentralWidget && oldCentralWidget->parent() == this)
delete oldCentralWidget;
}
QGraphicsWidget* MBubbleItem::centralWidget()
{
return model()->centralWidget();
}
QStack<QGraphicsWidget*> MBubbleItem::informationWidgets()
{
return model()->informationWidgets();
}
void MBubbleItem::addInformationWidget(QGraphicsWidget *widget)
{
QStack<QGraphicsWidget*> stack = model()->informationWidgets();
stack.push(widget);
model()->setInformationWidgets(stack);
}
void MBubbleItem::removeInformationWidget(QGraphicsWidget *widget)
{
QStack<QGraphicsWidget*> stack = model()->informationWidgets();
int index = stack.indexOf(widget);
if (index >= 0) {
stack.remove(index);
model()->setInformationWidgets(stack);
}
}
QString MBubbleItem::commentsString()
{
Q_D(MBubbleItem);
if (d->commentsLabel)
return model()->commentsString();
return QString();
}
void MBubbleItem::setCommentsString(const QString &comments)
{
Q_D(MBubbleItem);
if(!comments.isEmpty()) {
if (!d->commentsLabel || !d->commentsIcon)
d->createCommentsInfo();
d->commentsLabel->setText(comments);
} else if (d->commentsLabel != NULL || d->commentsIcon)
d->destroyCommentsInfo();
model()->setCommentsString(comments);
}
QString MBubbleItem::thumbsUpString()
{
Q_D(MBubbleItem);
if (d->thumbsUpLabel)
return model()->thumbsUpString();
return QString();
}
void MBubbleItem::setThumbsUpString(const QString &thumbsUp)
{
Q_D(MBubbleItem);
if(!thumbsUp.isEmpty()) {
if (!d->thumbsUpLabel) {
Q_ASSERT(!d->thumbsUpIcon);
d->createThumbsUpInfo();
Q_ASSERT(d->thumbsUpLabel);
Q_ASSERT(d->thumbsUpIcon);
}
d->thumbsUpLabel->setText(thumbsUp);
} else if (d->thumbsUpLabel != NULL) {
Q_ASSERT(d->thumbsUpIcon);
d->destroyThumbsUpInfo();
}
model()->setThumbsUpString(thumbsUp);
}
<commit_msg>Changes: MBubbleItem - make coverity even more happy<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mbubbleitem.h"
#include "mbubbleitem_p.h"
#include "mbubbleitemmodel.h"
#include "mimagewidget.h"
#include "mlabel.h"
#include "mwidgetcreator.h"
M_REGISTER_WIDGET(MBubbleItem)
MBubbleItemPrivate::MBubbleItemPrivate()
: MWidgetControllerPrivate(),
commentsLabel(NULL),
thumbsUpLabel(NULL),
commentsIcon(NULL),
thumbsUpIcon(NULL)
{
}
MBubbleItemPrivate::~MBubbleItemPrivate()
{
}
void MBubbleItemPrivate::init()
{
}
void MBubbleItemPrivate::createCommentsInfo()
{
Q_Q(MBubbleItem);
commentsLabel = new MLabel;
commentsLabel->setParent(q);
commentsIcon = new MImageWidget;
commentsIcon->setParent(q);
commentsIcon->setObjectName("InformationalIcon");
commentsIcon->setImage("icon-s-common-comments", commentsIcon->minimumSize().toSize());
q->addInformationWidget(commentsIcon);
q->addInformationWidget(commentsLabel);
refreshStyles();
}
void MBubbleItemPrivate::destroyCommentsInfo()
{
Q_Q(MBubbleItem);
q->removeInformationWidget(commentsLabel);
q->removeInformationWidget(commentsIcon);
if(commentsLabel->parent() == q)
delete commentsLabel;
if(commentsIcon->parent() == q)
delete commentsIcon;
commentsLabel = NULL;
commentsIcon = NULL;
}
void MBubbleItemPrivate::createThumbsUpInfo()
{
Q_Q(MBubbleItem);
thumbsUpLabel = new MLabel;
thumbsUpLabel->setParent(q);
thumbsUpIcon = new MImageWidget;
thumbsUpIcon->setParent(q);
thumbsUpIcon->setObjectName("InformationalIcon");
thumbsUpIcon->setImage("icon-s-common-like", thumbsUpIcon->minimumSize().toSize());
q->addInformationWidget(thumbsUpIcon);
q->addInformationWidget(thumbsUpLabel);
refreshStyles();
}
void MBubbleItemPrivate::destroyThumbsUpInfo()
{
Q_Q(MBubbleItem);
q->removeInformationWidget(thumbsUpLabel);
q->removeInformationWidget(thumbsUpIcon);
if(thumbsUpLabel->parent() == q)
delete thumbsUpLabel;
if(thumbsUpIcon->parent() == q)
delete thumbsUpIcon;
thumbsUpLabel = NULL;
thumbsUpIcon = NULL;
}
void MBubbleItemPrivate::refreshStyles()
{
Q_Q(MBubbleItem);
if (q->messageType() == MBubbleItem::Incoming) {
if (thumbsUpLabel)
thumbsUpLabel->setObjectName("InformationalLabelIncoming");
if (commentsLabel)
commentsLabel->setObjectName("InformationalLabelIncoming");
} else {
if (thumbsUpLabel)
thumbsUpLabel->setObjectName("InformationalLabelOutgoing");
if (commentsLabel)
commentsLabel->setObjectName("InformationalLabelOutgoing");
}
}
MBubbleItem::MBubbleItem(QGraphicsItem *parent)
: MWidgetController(new MBubbleItemPrivate, new MBubbleItemModel, parent)
{
Q_D(MBubbleItem);
d->init();
}
MBubbleItem::MBubbleItem(MBubbleItemPrivate *dd, MBubbleItemModel *model, QGraphicsItem *parent)
: MWidgetController(dd, model, parent)
{
Q_D(MBubbleItem);
d->init();
}
MBubbleItem::~MBubbleItem()
{
}
MImageWidget* MBubbleItem::avatar() const
{
return model()->avatar();
}
void MBubbleItem::setAvatar(MImageWidget* avatar)
{
MImageWidget *oldAvatar = model()->avatar();
if(oldAvatar == avatar)
return;
model()->setAvatar(avatar);
if(oldAvatar && oldAvatar->parent() == this)
delete oldAvatar;
}
void MBubbleItem::setAvatar(const QPixmap &avatar)
{
model()->beginTransaction();
if (!model()->avatar()) {
model()->setAvatar(new MImageWidget);
model()->avatar()->setParent(this);
}
model()->avatar()->setPixmap(avatar);
model()->commitTransaction();
}
QString MBubbleItem::senderName()
{
return model()->senderName();
}
void MBubbleItem::setSenderName(const QString &senderName)
{
model()->setSenderName(senderName);
}
QString MBubbleItem::timeStamp()
{
return model()->timeStamp();
}
void MBubbleItem::setTimeStamp(const QString &timeStamp)
{
model()->setTimeStamp(timeStamp);
}
QString MBubbleItem::message()
{
return model()->message();
}
void MBubbleItem::setMessage(const QString &message)
{
model()->setMessage(message);
}
MBubbleItem::MessageType MBubbleItem::messageType() const
{
return static_cast<MBubbleItem::MessageType>(model()->messageType());
}
void MBubbleItem::setMessageType(MessageType messageType)
{
Q_D(MBubbleItem);
model()->beginTransaction();
model()->setMessageType(messageType);
d->refreshStyles();
model()->commitTransaction();
}
void MBubbleItem::setCentralWidget(QGraphicsWidget* centralWidget)
{
QGraphicsWidget *oldCentralWidget = model()->centralWidget();
if(oldCentralWidget == centralWidget)
return;
model()->setCentralWidget(centralWidget);
if(oldCentralWidget && oldCentralWidget->parent() == this)
delete oldCentralWidget;
}
QGraphicsWidget* MBubbleItem::centralWidget()
{
return model()->centralWidget();
}
QStack<QGraphicsWidget*> MBubbleItem::informationWidgets()
{
return model()->informationWidgets();
}
void MBubbleItem::addInformationWidget(QGraphicsWidget *widget)
{
QStack<QGraphicsWidget*> stack = model()->informationWidgets();
stack.push(widget);
model()->setInformationWidgets(stack);
}
void MBubbleItem::removeInformationWidget(QGraphicsWidget *widget)
{
QStack<QGraphicsWidget*> stack = model()->informationWidgets();
int index = stack.indexOf(widget);
if (index >= 0) {
stack.remove(index);
model()->setInformationWidgets(stack);
}
}
QString MBubbleItem::commentsString()
{
Q_D(MBubbleItem);
if (d->commentsLabel)
return model()->commentsString();
return QString();
}
void MBubbleItem::setCommentsString(const QString &comments)
{
Q_D(MBubbleItem);
if(!comments.isEmpty()) {
if (!d->commentsLabel)
d->createCommentsInfo();
Q_ASSERT(d->commentsLabel);
Q_ASSERT(d->commentsIcon);
d->commentsLabel->setText(comments);
} else if (d->commentsLabel) {
Q_ASSERT(d->commentsIcon);
d->destroyCommentsInfo();
Q_ASSERT(!d->commentsLabel);
Q_ASSERT(!d->commentsIcon);
}
model()->setCommentsString(comments);
}
QString MBubbleItem::thumbsUpString()
{
Q_D(MBubbleItem);
if (d->thumbsUpLabel)
return model()->thumbsUpString();
return QString();
}
void MBubbleItem::setThumbsUpString(const QString &thumbsUp)
{
Q_D(MBubbleItem);
if(!thumbsUp.isEmpty()) {
if (!d->thumbsUpLabel) {
Q_ASSERT(!d->thumbsUpIcon);
d->createThumbsUpInfo();
Q_ASSERT(d->thumbsUpLabel);
Q_ASSERT(d->thumbsUpIcon);
}
d->thumbsUpLabel->setText(thumbsUp);
} else if (d->thumbsUpLabel != NULL) {
Q_ASSERT(d->thumbsUpIcon);
d->destroyThumbsUpInfo();
}
model()->setThumbsUpString(thumbsUp);
}
<|endoftext|>
|
<commit_before>/*
* User.cpp
*
* Copyright (C) 2019-20 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
* with RStudio, then this program is licensed to you under the following terms:
*
* 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 <shared_core/system/User.hpp>
#include <pwd.h>
#include <boost/algorithm/string.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>
#include <shared_core/SafeConvert.hpp>
namespace rstudio {
namespace core {
namespace system {
namespace {
inline std::string getEnvVariable(const std::string& in_name)
{
char* value = ::getenv(in_name.c_str());
if (value)
return std::string(value);
return std::string();
}
} // anonymous namespace
struct User::Impl
{
template<class T>
using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>;
Impl() : UserId(-1), GroupId(-1)
{ };
template<typename T>
Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value)
{
struct passwd pwd;
struct passwd* tempPtrPwd;
// Get the maximum size of a passwd for this system.
long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);
if (buffSize == 1)
buffSize = 4096; // some systems return -1, be conservative!
std::vector<char> buffer(buffSize);
int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd);
if (tempPtrPwd == nullptr)
{
if (result == 0) // will happen if user is simply not found. Return EACCES (not found error).
result = EACCES;
Error error = systemError(result, "Failed to get user details.", ERROR_LOCATION);
error.addProperty("user-value", safe_convert::numberToString(in_value));
return error;
}
else
{
UserId = pwd.pw_uid;
GroupId = pwd.pw_gid;
Name = pwd.pw_name;
HomeDirectory = FilePath(pwd.pw_dir);
Shell = pwd.pw_shell;
}
return Success();
}
UidType UserId;
GidType GroupId;
std::string Name;
FilePath HomeDirectory;
std::string Shell;
};
PRIVATE_IMPL_DELETER_IMPL(User)
User::User(bool in_isEmpty) :
m_impl(new Impl())
{
m_impl->Name = in_isEmpty ? "" : "*";
}
User::User(const User& in_other) :
m_impl(new Impl(*in_other.m_impl))
{
}
Error User::getCurrentUser(User& out_currentUser)
{
return getUserFromIdentifier(::geteuid(), out_currentUser);
}
Error User::getUserFromIdentifier(const std::string& in_username, User& out_user)
{
User user;
Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str());
if (!error)
out_user = user;
return error;
}
Error User::getUserFromIdentifier(UidType in_userId, User& out_user)
{
User user;
Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId);
if (!error)
out_user = user;
return error;
}
FilePath User::getUserHomePath(const std::string& in_envOverride)
{
// use environment override if specified
if (!in_envOverride.empty())
{
using namespace boost::algorithm;
for (split_iterator<std::string::const_iterator> it =
make_split_iterator(in_envOverride, first_finder("|", is_iequal()));
it != split_iterator<std::string::const_iterator>();
++it)
{
std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it));
if (!envHomePath.empty())
{
FilePath userHomePath(envHomePath);
if (userHomePath.exists())
return userHomePath;
}
}
}
// otherwise use standard unix HOME
return FilePath(getEnvVariable("HOME"));
}
User& User::operator=(const User& in_other)
{
if (this == &in_other)
return *this;
if ((m_impl == nullptr) && (in_other.m_impl == nullptr))
return *this;
if (in_other.m_impl == nullptr)
{
m_impl.reset();
return *this;
}
if (m_impl == nullptr)
m_impl.reset(new Impl());
*m_impl = *in_other.m_impl;
return *this;
}
bool User::operator==(const User& in_other) const
{
// If one or the other is empty but not both, these objects aren't equal.
if (isEmpty() != in_other.isEmpty())
return false;
// Otherwise they're both empty or they're both not, so just return true if this user is empty.
if (isEmpty())
return true;
// If one or the other is all users but not both, these aren't the same user.
if (isAllUsers() != in_other.isAllUsers())
return false;
// Otherwise they're both all users or they're both not, so just return true if this user is all users.
if (isAllUsers())
return true;
return getUserId() == in_other.getUserId();
}
bool User::operator!=(const User &in_other) const
{
return !(*this == in_other);
}
bool User::exists() const
{
return !isEmpty() && !isAllUsers();
}
bool User::isAllUsers() const
{
return m_impl->Name == "*";
}
bool User::isEmpty() const
{
return m_impl->Name.empty();
}
const FilePath& User::getHomePath() const
{
return m_impl->HomeDirectory;
}
GidType User::getGroupId() const
{
return m_impl->GroupId;
}
UidType User::getUserId() const
{
return m_impl->UserId;
}
const std::string& User::getUsername() const
{
return m_impl->Name;
}
const std::string& User::getShell() const
{
return m_impl->Shell;
}
} // namespace system
} // namespace core
} // namespace rstudio
<commit_msg>correct typo (and also just treat any negative value the same)<commit_after>/*
* User.cpp
*
* Copyright (C) 2019-20 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
* with RStudio, then this program is licensed to you under the following terms:
*
* 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 <shared_core/system/User.hpp>
#include <pwd.h>
#include <boost/algorithm/string.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>
#include <shared_core/SafeConvert.hpp>
namespace rstudio {
namespace core {
namespace system {
namespace {
inline std::string getEnvVariable(const std::string& in_name)
{
char* value = ::getenv(in_name.c_str());
if (value)
return std::string(value);
return std::string();
}
} // anonymous namespace
struct User::Impl
{
template<class T>
using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>;
Impl() : UserId(-1), GroupId(-1)
{ };
template<typename T>
Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value)
{
struct passwd pwd;
struct passwd* tempPtrPwd;
// Get the maximum size of a passwd for this system.
long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);
if (buffSize < 0)
buffSize = 4096; // some systems return -1, be conservative!
std::vector<char> buffer(buffSize);
int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd);
if (tempPtrPwd == nullptr)
{
if (result == 0) // will happen if user is simply not found. Return EACCES (not found error).
result = EACCES;
Error error = systemError(result, "Failed to get user details.", ERROR_LOCATION);
error.addProperty("user-value", safe_convert::numberToString(in_value));
return error;
}
else
{
UserId = pwd.pw_uid;
GroupId = pwd.pw_gid;
Name = pwd.pw_name;
HomeDirectory = FilePath(pwd.pw_dir);
Shell = pwd.pw_shell;
}
return Success();
}
UidType UserId;
GidType GroupId;
std::string Name;
FilePath HomeDirectory;
std::string Shell;
};
PRIVATE_IMPL_DELETER_IMPL(User)
User::User(bool in_isEmpty) :
m_impl(new Impl())
{
m_impl->Name = in_isEmpty ? "" : "*";
}
User::User(const User& in_other) :
m_impl(new Impl(*in_other.m_impl))
{
}
Error User::getCurrentUser(User& out_currentUser)
{
return getUserFromIdentifier(::geteuid(), out_currentUser);
}
Error User::getUserFromIdentifier(const std::string& in_username, User& out_user)
{
User user;
Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str());
if (!error)
out_user = user;
return error;
}
Error User::getUserFromIdentifier(UidType in_userId, User& out_user)
{
User user;
Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId);
if (!error)
out_user = user;
return error;
}
FilePath User::getUserHomePath(const std::string& in_envOverride)
{
// use environment override if specified
if (!in_envOverride.empty())
{
using namespace boost::algorithm;
for (split_iterator<std::string::const_iterator> it =
make_split_iterator(in_envOverride, first_finder("|", is_iequal()));
it != split_iterator<std::string::const_iterator>();
++it)
{
std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it));
if (!envHomePath.empty())
{
FilePath userHomePath(envHomePath);
if (userHomePath.exists())
return userHomePath;
}
}
}
// otherwise use standard unix HOME
return FilePath(getEnvVariable("HOME"));
}
User& User::operator=(const User& in_other)
{
if (this == &in_other)
return *this;
if ((m_impl == nullptr) && (in_other.m_impl == nullptr))
return *this;
if (in_other.m_impl == nullptr)
{
m_impl.reset();
return *this;
}
if (m_impl == nullptr)
m_impl.reset(new Impl());
*m_impl = *in_other.m_impl;
return *this;
}
bool User::operator==(const User& in_other) const
{
// If one or the other is empty but not both, these objects aren't equal.
if (isEmpty() != in_other.isEmpty())
return false;
// Otherwise they're both empty or they're both not, so just return true if this user is empty.
if (isEmpty())
return true;
// If one or the other is all users but not both, these aren't the same user.
if (isAllUsers() != in_other.isAllUsers())
return false;
// Otherwise they're both all users or they're both not, so just return true if this user is all users.
if (isAllUsers())
return true;
return getUserId() == in_other.getUserId();
}
bool User::operator!=(const User &in_other) const
{
return !(*this == in_other);
}
bool User::exists() const
{
return !isEmpty() && !isAllUsers();
}
bool User::isAllUsers() const
{
return m_impl->Name == "*";
}
bool User::isEmpty() const
{
return m_impl->Name.empty();
}
const FilePath& User::getHomePath() const
{
return m_impl->HomeDirectory;
}
GidType User::getGroupId() const
{
return m_impl->GroupId;
}
UidType User::getUserId() const
{
return m_impl->UserId;
}
const std::string& User::getUsername() const
{
return m_impl->Name;
}
const std::string& User::getShell() const
{
return m_impl->Shell;
}
} // namespace system
} // namespace core
} // namespace rstudio
<|endoftext|>
|
<commit_before>#include "cpp_interface.h"
namespace BEEV
{
// Does some simple caching of prior results.
void
Cpp_interface::checkSat(const ASTVec & assertionsSMT2)
{
bm.GetRunTimes()->stop(RunTimes::Parsing);
checkInvariant();
assert(assertionsSMT2.size() == cache.size());
Entry& last_run = cache.back();
if ((last_run.node_number != assertionsSMT2.back().GetNodeNum()) && (last_run.result == SOLVER_SATISFIABLE))
{
// extra asserts might have been added to it,
// flipping from sat to unsat. But never from unsat to sat.
last_run.result = SOLVER_UNDECIDED;
}
// We might have run this query before, or it might already be shown to be unsat. If it was sat,
// we've stored the result (but not the model), so we can shortcut and return what we know.
if (!((last_run.result == SOLVER_SATISFIABLE) || last_run.result == SOLVER_UNSATISFIABLE))
{
resetSolver();
ASTNode query;
if (assertionsSMT2.size() > 1)
query = parserInterface->CreateNode(AND, assertionsSMT2);
else if (assertionsSMT2.size() == 1)
query = assertionsSMT2[0];
else
query = bm.ASTTrue;
SOLVER_RETURN_TYPE last_result = GlobalSTP->TopLevelSTP(query, bm.ASTFalse);
// Store away the answer. Might be timeout, or error though..
last_run = Entry(last_result);
last_run.node_number = assertionsSMT2.back().GetNodeNum();
// It's satisfiable, so everything beneath it is satisfiable too.
if (last_result == SOLVER_SATISFIABLE)
{
for (int i = 0; i < cache.size(); i++)
{
assert(cache[i].result != SOLVER_UNSATISFIABLE);
cache[i].result = SOLVER_SATISFIABLE;
}
}
}
if (bm.UserFlags.quick_statistics_flag)
{
bm.GetRunTimes()->print();
}
(GlobalSTP->tosat)->PrintOutput(last_run.result);
bm.GetRunTimes()->start(RunTimes::Parsing);
}
}
;
<commit_msg>Fix. Don't use the global nodefactory when we have a local one.<commit_after>#include "cpp_interface.h"
namespace BEEV
{
// Does some simple caching of prior results.
void
Cpp_interface::checkSat(const ASTVec & assertionsSMT2)
{
bm.GetRunTimes()->stop(RunTimes::Parsing);
checkInvariant();
assert(assertionsSMT2.size() == cache.size());
Entry& last_run = cache.back();
if ((last_run.node_number != assertionsSMT2.back().GetNodeNum()) && (last_run.result == SOLVER_SATISFIABLE))
{
// extra asserts might have been added to it,
// flipping from sat to unsat. But never from unsat to sat.
last_run.result = SOLVER_UNDECIDED;
}
// We might have run this query before, or it might already be shown to be unsat. If it was sat,
// we've stored the result (but not the model), so we can shortcut and return what we know.
if (!((last_run.result == SOLVER_SATISFIABLE) || last_run.result == SOLVER_UNSATISFIABLE))
{
resetSolver();
ASTNode query;
if (assertionsSMT2.size() > 1)
query = nf->CreateNode(AND, assertionsSMT2);
else if (assertionsSMT2.size() == 1)
query = assertionsSMT2[0];
else
query = bm.ASTTrue;
SOLVER_RETURN_TYPE last_result = GlobalSTP->TopLevelSTP(query, bm.ASTFalse);
// Store away the answer. Might be timeout, or error though..
last_run = Entry(last_result);
last_run.node_number = assertionsSMT2.back().GetNodeNum();
// It's satisfiable, so everything beneath it is satisfiable too.
if (last_result == SOLVER_SATISFIABLE)
{
for (int i = 0; i < cache.size(); i++)
{
assert(cache[i].result != SOLVER_UNSATISFIABLE);
cache[i].result = SOLVER_SATISFIABLE;
}
}
}
if (bm.UserFlags.quick_statistics_flag)
{
bm.GetRunTimes()->print();
}
(GlobalSTP->tosat)->PrintOutput(last_run.result);
bm.GetRunTimes()->start(RunTimes::Parsing);
}
}
;
<|endoftext|>
|
<commit_before>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER 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.
#if defined(_WINDOWS_) || defined(_MSC_VER)
# ifndef _WINDOWS_
# include <winsock2.h>
# endif
# define EWOULDBLOCK WSAEWOULDBLOCK
# define NErrno() WSAGetLastError()
#endif
#include "net.h"
#include "socket.h"
#include "select_poll.h"
SelectPoll::SelectPoll(void)
: rbytes_(kDefaultBufferLen)
, wbytes_(kDefaultBufferLen)
, handler_(NULL)
, spinlock_()
{
connectors_.clear();
FD_ZERO(&rset_);
FD_ZERO(&wset_);
}
SelectPoll::~SelectPoll(void)
{
CloseAll();
}
void
SelectPoll::CloseAll(void)
{
if (NULL == handler_)
return;
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
for (it = connectors_.begin(); it != connectors_.end(); ++it) {
if (NULL != it->second.second) {
handler_->CloseEvent(it->second.second);
it->second.second->Close();
delete it->second.second;
}
}
connectors_.clear();
}
bool
SelectPoll::Insert(int fd, int ev)
{
if (NULL == handler_)
return false;
LockerGuard<SpinLock> guard(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it == connectors_.end()) {
Socket* s = new Socket();
if (NULL == s)
return false;
s->Attach(fd);
s->SetNonBlock();
s->SetKeepAlive();
s->SetSelfReadBuffer(rbytes_);
s->SetSelfWriteBuffer(wbytes_);
connectors_[fd] = std::make_pair<int, Socket*>(ev, s);
}
return true;
}
void
SelectPoll::Remove(int fd)
{
if (NULL == handler_)
return;
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end()) {
if (NULL != it->second.second) {
handler_->CloseEvent(it->second.second);
it->second.second->Close();
delete it->second.second;
}
connectors_.erase(it);
}
}
bool
SelectPoll::AddEvent(int fd, int ev)
{
if (NULL == handler_)
return false;
LockerGuard<SpinLock> guard(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end())
it->second.first |= ev;
return true;
}
bool
SelectPoll::DelEvent(int fd, int ev)
{
if (NULL == handler_)
return false;
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end())
it->second.first &= ~ev;
return true;
}
Socket*
SelectPoll::GetConnector(int fd)
{
Socket* s = NULL;
{
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end())
s = it->second.second;
}
return s;
}
bool
SelectPoll::Polling(int ev, int millitm)
{
if (NULL == handler_)
return false;
struct timeval timeout;
if (-1 == millitm) {
timeout.tv_sec = 0;
timeout.tv_usec = 500;
}
else {
timeout.tv_sec = millitm / 1000;
timeout.tv_usec = (millitm % 1000 * 1000);
}
int max_fd = 0;
int ret = 0;
if (kEventTypeRead == ev) {
InitSet(ev, &rset_, &max_fd);
ret = select(max_fd + 1, &rset_, NULL, NULL, &timeout);
}
else if (kEventTypeWrite == ev) {
InitSet(ev, &wset_, &max_fd);
ret = select(max_fd + 1, NULL, &wset_, NULL, &timeout);
}
else {
return false;
}
if (kNetTypeError == ret || 0 == ret)
return false;
if (!DispatchEvent(ev))
return false;
return true;
}
bool
SelectPoll::InitSet(int ev, fd_set* set, int* max_fd)
{
if (NULL == set || NULL == max_fd)
return false;
FD_ZERO(set);
*max_fd = 0;
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
for (it = connectors_.begin(); it != connectors_.end();) {
if (NULL == it->second.second) {
connectors_.erase(it++);
}
else if (kNetTypeInval == it->second.second->fd()) {
delete it->second.second;
connectors_.erase(it++);
}
else {
if (it->second.first & ev)
FD_SET(it->first, set);
if (it->first > *max_fd)
*max_fd = it->first;
++it;
}
}
return true;
}
bool
SelectPoll::DispatchEvent(int ev)
{
if (NULL == handler_)
return false;
int fd;
Socket* s;
LockerGuard<SpinLock> guard(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
for (it = connectors_.begin(); it != connectors_.end(); ++it) {
fd = it->first;
s = it->second.second;
if (NULL == s)
continue;
if (kEventTypeRead == ev) {
if (FD_ISSET(fd, &rset_)) {
int read_bytes = s->DealWithAsyncRead();
if (read_bytes > 0) {
if (s->CheckValidMessageInReadBuffer())
handler_->ReadEvent(s);
}
else if (0 == read_bytes) {
handler_->CloseEvent(s);
s->Close();
}
else {
if (EWOULDBLOCK != NErrno()) {
handler_->CloseEvent(s);
s->Close();
}
}
}
}
else if (kEventTypeWrite == ev) {
if (FD_ISSET(fd, &wset_)) {
int write_bytes = s->DealWithAsyncWrite();
if (write_bytes > 0)
handler_->WriteEvent(s);
}
}
}
return true;
}
<commit_msg>improved select poll module<commit_after>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER 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.
#if defined(_WINDOWS_) || defined(_MSC_VER)
# ifndef _WINDOWS_
# include <winsock2.h>
# endif
# define EWOULDBLOCK WSAEWOULDBLOCK
# define NErrno() WSAGetLastError()
#endif
#include "net.h"
#include "socket.h"
#include "select_poll.h"
SelectPoll::SelectPoll(void)
: rbytes_(kDefaultBufferLen)
, wbytes_(kDefaultBufferLen)
, handler_(NULL)
, spinlock_()
{
connectors_.clear();
FD_ZERO(&rset_);
FD_ZERO(&wset_);
}
SelectPoll::~SelectPoll(void)
{
CloseAll();
}
void
SelectPoll::CloseAll(void)
{
if (NULL == handler_)
return;
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
for (it = connectors_.begin(); it != connectors_.end(); ++it) {
if (NULL != it->second.second) {
handler_->CloseEvent(it->second.second);
it->second.second->Close();
delete it->second.second;
}
}
connectors_.clear();
}
bool
SelectPoll::Insert(int fd, int ev)
{
if (NULL == handler_)
return false;
LockerGuard<SpinLock> guard(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it == connectors_.end()) {
Socket* s = new Socket();
if (NULL == s)
return false;
s->Attach(fd);
s->SetNonBlock();
s->SetKeepAlive();
s->SetSelfReadBuffer(rbytes_);
s->SetSelfWriteBuffer(wbytes_);
connectors_[fd] = std::make_pair<int, Socket*>(ev, s);
}
return true;
}
void
SelectPoll::Remove(int fd)
{
if (NULL == handler_)
return;
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end()) {
if (NULL != it->second.second) {
handler_->CloseEvent(it->second.second);
it->second.second->Close();
delete it->second.second;
}
connectors_.erase(it);
}
}
bool
SelectPoll::AddEvent(int fd, int ev)
{
if (NULL == handler_)
return false;
LockerGuard<SpinLock> guard(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end())
it->second.first |= ev;
return true;
}
bool
SelectPoll::DelEvent(int fd, int ev)
{
if (NULL == handler_)
return false;
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end())
it->second.first &= ~ev;
return true;
}
Socket*
SelectPoll::GetConnector(int fd)
{
Socket* s = NULL;
{
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
it = connectors_.find(fd);
if (it != connectors_.end())
s = it->second.second;
}
return s;
}
bool
SelectPoll::Polling(int ev, int millitm)
{
if (NULL == handler_)
return false;
struct timeval timeout;
if (-1 == millitm) {
timeout.tv_sec = 0;
timeout.tv_usec = 500;
}
else {
timeout.tv_sec = millitm / 1000;
timeout.tv_usec = (millitm % 1000 * 1000);
}
int max_fd = 0;
int ret = 0;
if (kEventTypeRead == ev) {
InitSet(ev, &rset_, &max_fd);
ret = select(max_fd + 1, &rset_, NULL, NULL, &timeout);
}
else if (kEventTypeWrite == ev) {
InitSet(ev, &wset_, &max_fd);
ret = select(max_fd + 1, NULL, &wset_, NULL, &timeout);
}
else {
return false;
}
if (kNetTypeError == ret || 0 == ret)
return false;
if (!DispatchEvent(ev))
return false;
return true;
}
bool
SelectPoll::InitSet(int ev, fd_set* set, int* max_fd)
{
if (NULL == set || NULL == max_fd)
return false;
FD_ZERO(set);
*max_fd = 0;
LockerGuard<SpinLock> gaurd(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
for (it = connectors_.begin(); it != connectors_.end();) {
if (NULL == it->second.second) {
connectors_.erase(it++);
}
else if (kNetTypeInval == it->second.second->fd()) {
delete it->second.second;
connectors_.erase(it++);
}
else {
if (it->second.first & ev)
FD_SET(it->first, set);
if (it->first > *max_fd)
*max_fd = it->first;
++it;
}
}
return true;
}
bool
SelectPoll::DispatchEvent(int ev)
{
if (NULL == handler_)
return false;
int fd;
Socket* s;
LockerGuard<SpinLock> guard(spinlock_);
std::map<int, std::pair<int, Socket*> >::iterator it;
for (it = connectors_.begin(); it != connectors_.end(); ++it) {
fd = it->first;
s = it->second.second;
if (NULL == s)
continue;
if (kEventTypeRead == ev) {
if (FD_ISSET(fd, &rset_)) {
int read_bytes = s->DealWithAsyncRead();
if (read_bytes > 0) {
if (s->CheckValidMessageInReadBuffer())
handler_->ReadEvent(s);
}
else if (0 == read_bytes) {
handler_->CloseEvent(s);
s->Close();
}
else {
if (EWOULDBLOCK != NErrno()) {
handler_->CloseEvent(s);
s->Close();
}
}
}
}
else if (kEventTypeWrite == ev) {
if (FD_ISSET(fd, &wset_)) {
int write_bytes = s->DealWithAsyncWrite();
if (write_bytes > 0) {
handler_->WriteEvent(s);
}
else if (write_bytes < 0) {
if (EWOULDBLOCK != NErrno()) {
handler_->CloseEvent(s);
s->Close();
}
}
}
}
}
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlTable.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-11-20 19:04: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
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#ifndef RPT_XMLTABLE_HXX
#include "xmlTable.hxx"
#endif
#ifndef RPT_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _REPORT_RPTUIDEF_HXX
#include "RptDef.hxx"
#endif
#ifndef RPT_XMLHELPER_HXX
#include "xmlHelper.hxx"
#endif
#ifndef RPT_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef RPT_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_REPORT_FORCENEWPAGE_HPP_
#include <com/sun/star/report/ForceNewPage.hpp>
#endif
#ifndef RPT_XMLCONDPRTEXPR_HXX
#include "xmlCondPrtExpr.hxx"
#endif
#ifndef RPT_XMLSTYLEIMPORT_HXX
#include "xmlStyleImport.hxx"
#endif
#include "xmlstrings.hrc"
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include <com/sun/star/report/XShape.hpp>
#include <com/sun/star/report/XFixedLine.hpp>
#define MIN_WIDTH 80
#define MIN_HEIGHT 20
namespace rptxml
{
using namespace ::xmloff;
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using namespace ::com::sun::star::xml::sax;
using ::com::sun::star::xml::sax::XAttributeList;
sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue)
{
sal_uInt16 nRet = report::ForceNewPage::NONE;
const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions();
SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap );
return nRet;
}
DBG_NAME( rpt_OXMLTable )
OXMLTable::OXMLTable( ORptFilter& rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,const uno::Reference< report::XSection >& _xSection
)
:SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_xSection(_xSection)
,m_nColSpan(1)
,m_nRowSpan(0)
,m_nRowIndex(0)
,m_nColumnIndex(0)
{
DBG_CTOR( rpt_OXMLTable,NULL);
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap();
const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;
static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
try
{
for(sal_Int16 i = 0; i < nLength; ++i)
{
rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_VISIBLE:
m_xSection->setVisible(sValue == s_sTRUE);
break;
case XML_TOK_FORCE_NEW_PAGE:
m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue));
break;
case XML_TOK_FORCE_NEW_COLUMN:
m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue));
break;
case XML_TOK_KEEP_TOGETHER:
m_xSection->setKeepTogether(sValue == s_sTRUE);
break;
case XML_TOK_SECTION_NAME:
m_xSection->setName(sValue);
break;
case XML_TOK_SECT_STYLE_NAME:
m_sStyleName = sValue;
break;
default:
break;
}
}
}
catch(Exception&)
{
OSL_ENSURE(0,"Exception catched while filling the section props");
}
}
// -----------------------------------------------------------------------------
OXMLTable::~OXMLTable()
{
DBG_DTOR( rpt_OXMLTable,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLTable::CreateChildContext(
sal_uInt16 _nPrefix,
const ::rtl::OUString& _rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
ORptFilter& rImport = GetOwnImport();
const SvXMLTokenMap& rTokenMap = rImport.GetColumnTokenMap();
Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory();
switch( rTokenMap.Get( _nPrefix, _rLocalName ) )
{
case XML_TOK_TABLE_COLUMNS:
case XML_TOK_TABLE_ROWS:
pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this);
break;
case XML_TOK_ROW:
incrementRowIndex();
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
break;
case XML_TOK_COLUMN:
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
break;
case XML_TOK_CONDITIONAL_PRINT_EXPRESSION:
pContext = new OXMLCondPrtExpr( rImport, _nPrefix, _rLocalName,xAttrList,m_xSection.get());
break;
default:
break;
}
if( !pContext )
pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLTable::GetOwnImport()
{
return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
void OXMLTable::EndElement()
{
try
{
if ( m_xSection.is() )
{
if ( m_sStyleName.getLength() )
{
const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles();
if ( pAutoStyles )
{
XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName));
if ( pAutoStyle )
{
pAutoStyle->FillPropertySet(m_xSection.get());
}
}
} // if ( m_sStyleName.getLength() )
// set height
::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin();
::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end();
sal_Int32 nHeight = 0;
for (; aIter != aEnd; ++aIter)
nHeight += *aIter;
m_xSection->setHeight( nHeight );
// set positions, widths, and heights
sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN);
sal_Int32 nPosY = 0;
::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin();
::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end();
for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i)
{
sal_Int32 nPosX = nLeftMargin;
::std::vector<TCell>::iterator aColIter = (*aRowIter).begin();
::std::vector<TCell>::iterator aColEnd = (*aRowIter).end();
for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j)
{
TCell& rCell = *aColIter;
if ( !rCell.xElements.empty())
{
::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin();
const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end();
for (;aCellIter != aCellEnd ; ++aCellIter)
{
uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY);
if ( xShape.is() )
{
xShape->setPositionX(xShape->getPositionX() + nLeftMargin);
}
else
{
sal_Int32 nWidth = rCell.nWidth;
sal_Int32 nColSpan = rCell.nColSpan;
if ( nColSpan > 1 )
{
::std::vector<TCell>::iterator aWidthIter = aColIter + 1;
while ( nColSpan > 1 )
{
nWidth += (aWidthIter++)->nWidth;
--nColSpan;
}
}
nHeight = rCell.nHeight;
sal_Int32 nRowSpan = rCell.nRowSpan;
if ( nRowSpan > 1 )
{
::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1;
while( nRowSpan > 1)
{
nHeight += (*aHeightIter)[j].nHeight;
++aHeightIter;
--nRowSpan;
}
}
Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY);
if ( xFixedLine.is() )
{
if ( xFixedLine->getOrientation() == 1 ) // vertical
{
OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),"Illegal pos of col iter. There should be an empty cell for the next line part.");
nWidth += m_aWidth[j+1];
if ( nWidth < MIN_WIDTH )
nWidth = MIN_WIDTH;
}
else if ( nHeight < MIN_HEIGHT )
nHeight = MIN_HEIGHT;
}
try
{
(*aCellIter)->setSize(awt::Size(nWidth,nHeight));
(*aCellIter)->setPosition(awt::Point(nPosX,nPosY));
}
catch(beans::PropertyVetoException)
{
OSL_ENSURE(0,"Could not set the correct position or size!");
}
}
}
}
nPosX += m_aWidth[j];
}
nPosY += m_aHeight[i];
}
} // if ( m_xComponent.is() )
}
catch(Exception&)
{
OSL_ENSURE(0,"OXMLTable::EndElement -> exception catched");
}
}
// -----------------------------------------------------------------------------
void OXMLTable::addCell(const Reference<XReportComponent>& _xElement)
{
uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY);
OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(),
"OXMLTable::addCell: Invalid column and row index");
if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() )
{
TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1];
if ( _xElement.is() )
rCell.xElements.push_back( _xElement );
if ( !xShape.is() )
{
rCell.nWidth = m_aWidth[m_nColumnIndex-1];
rCell.nHeight = m_aHeight[m_nRowIndex-1];
rCell.nColSpan = m_nColSpan;
rCell.nRowSpan = m_nRowSpan;
}
}
if ( !xShape.is() )
m_nColSpan = m_nRowSpan = 1;
}
// -----------------------------------------------------------------------------
void OXMLTable::incrementRowIndex()
{
++m_nRowIndex;
m_nColumnIndex = 0;
m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size()));
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.5.56); FILE MERGED 2008/04/01 15:23:39 thb 1.5.56.3: #i85898# Stripping all external header guards 2008/04/01 12:33:11 thb 1.5.56.2: #i85898# Stripping all external header guards 2008/03/31 13:32:12 rt 1.5.56.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: xmlTable.cxx,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.
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "xmlTable.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include "RptDef.hxx"
#include "xmlHelper.hxx"
#include "xmlEnums.hxx"
#ifndef RPT_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#include <com/sun/star/report/ForceNewPage.hpp>
#include "xmlCondPrtExpr.hxx"
#include "xmlStyleImport.hxx"
#include "xmlstrings.hrc"
#include <connectivity/dbtools.hxx>
#include <tools/debug.hxx>
#ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include <com/sun/star/report/XShape.hpp>
#include <com/sun/star/report/XFixedLine.hpp>
#define MIN_WIDTH 80
#define MIN_HEIGHT 20
namespace rptxml
{
using namespace ::xmloff;
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using namespace ::com::sun::star::xml::sax;
using ::com::sun::star::xml::sax::XAttributeList;
sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue)
{
sal_uInt16 nRet = report::ForceNewPage::NONE;
const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions();
SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap );
return nRet;
}
DBG_NAME( rpt_OXMLTable )
OXMLTable::OXMLTable( ORptFilter& rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,const uno::Reference< report::XSection >& _xSection
)
:SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_xSection(_xSection)
,m_nColSpan(1)
,m_nRowSpan(0)
,m_nRowIndex(0)
,m_nColumnIndex(0)
{
DBG_CTOR( rpt_OXMLTable,NULL);
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap();
const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;
static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
try
{
for(sal_Int16 i = 0; i < nLength; ++i)
{
rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_VISIBLE:
m_xSection->setVisible(sValue == s_sTRUE);
break;
case XML_TOK_FORCE_NEW_PAGE:
m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue));
break;
case XML_TOK_FORCE_NEW_COLUMN:
m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue));
break;
case XML_TOK_KEEP_TOGETHER:
m_xSection->setKeepTogether(sValue == s_sTRUE);
break;
case XML_TOK_SECTION_NAME:
m_xSection->setName(sValue);
break;
case XML_TOK_SECT_STYLE_NAME:
m_sStyleName = sValue;
break;
default:
break;
}
}
}
catch(Exception&)
{
OSL_ENSURE(0,"Exception catched while filling the section props");
}
}
// -----------------------------------------------------------------------------
OXMLTable::~OXMLTable()
{
DBG_DTOR( rpt_OXMLTable,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLTable::CreateChildContext(
sal_uInt16 _nPrefix,
const ::rtl::OUString& _rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
ORptFilter& rImport = GetOwnImport();
const SvXMLTokenMap& rTokenMap = rImport.GetColumnTokenMap();
Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory();
switch( rTokenMap.Get( _nPrefix, _rLocalName ) )
{
case XML_TOK_TABLE_COLUMNS:
case XML_TOK_TABLE_ROWS:
pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this);
break;
case XML_TOK_ROW:
incrementRowIndex();
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
break;
case XML_TOK_COLUMN:
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
break;
case XML_TOK_CONDITIONAL_PRINT_EXPRESSION:
pContext = new OXMLCondPrtExpr( rImport, _nPrefix, _rLocalName,xAttrList,m_xSection.get());
break;
default:
break;
}
if( !pContext )
pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLTable::GetOwnImport()
{
return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
void OXMLTable::EndElement()
{
try
{
if ( m_xSection.is() )
{
if ( m_sStyleName.getLength() )
{
const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles();
if ( pAutoStyles )
{
XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName));
if ( pAutoStyle )
{
pAutoStyle->FillPropertySet(m_xSection.get());
}
}
} // if ( m_sStyleName.getLength() )
// set height
::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin();
::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end();
sal_Int32 nHeight = 0;
for (; aIter != aEnd; ++aIter)
nHeight += *aIter;
m_xSection->setHeight( nHeight );
// set positions, widths, and heights
sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN);
sal_Int32 nPosY = 0;
::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin();
::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end();
for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i)
{
sal_Int32 nPosX = nLeftMargin;
::std::vector<TCell>::iterator aColIter = (*aRowIter).begin();
::std::vector<TCell>::iterator aColEnd = (*aRowIter).end();
for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j)
{
TCell& rCell = *aColIter;
if ( !rCell.xElements.empty())
{
::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin();
const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end();
for (;aCellIter != aCellEnd ; ++aCellIter)
{
uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY);
if ( xShape.is() )
{
xShape->setPositionX(xShape->getPositionX() + nLeftMargin);
}
else
{
sal_Int32 nWidth = rCell.nWidth;
sal_Int32 nColSpan = rCell.nColSpan;
if ( nColSpan > 1 )
{
::std::vector<TCell>::iterator aWidthIter = aColIter + 1;
while ( nColSpan > 1 )
{
nWidth += (aWidthIter++)->nWidth;
--nColSpan;
}
}
nHeight = rCell.nHeight;
sal_Int32 nRowSpan = rCell.nRowSpan;
if ( nRowSpan > 1 )
{
::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1;
while( nRowSpan > 1)
{
nHeight += (*aHeightIter)[j].nHeight;
++aHeightIter;
--nRowSpan;
}
}
Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY);
if ( xFixedLine.is() )
{
if ( xFixedLine->getOrientation() == 1 ) // vertical
{
OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),"Illegal pos of col iter. There should be an empty cell for the next line part.");
nWidth += m_aWidth[j+1];
if ( nWidth < MIN_WIDTH )
nWidth = MIN_WIDTH;
}
else if ( nHeight < MIN_HEIGHT )
nHeight = MIN_HEIGHT;
}
try
{
(*aCellIter)->setSize(awt::Size(nWidth,nHeight));
(*aCellIter)->setPosition(awt::Point(nPosX,nPosY));
}
catch(beans::PropertyVetoException)
{
OSL_ENSURE(0,"Could not set the correct position or size!");
}
}
}
}
nPosX += m_aWidth[j];
}
nPosY += m_aHeight[i];
}
} // if ( m_xComponent.is() )
}
catch(Exception&)
{
OSL_ENSURE(0,"OXMLTable::EndElement -> exception catched");
}
}
// -----------------------------------------------------------------------------
void OXMLTable::addCell(const Reference<XReportComponent>& _xElement)
{
uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY);
OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(),
"OXMLTable::addCell: Invalid column and row index");
if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() )
{
TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1];
if ( _xElement.is() )
rCell.xElements.push_back( _xElement );
if ( !xShape.is() )
{
rCell.nWidth = m_aWidth[m_nColumnIndex-1];
rCell.nHeight = m_aHeight[m_nRowIndex-1];
rCell.nColSpan = m_nColSpan;
rCell.nRowSpan = m_nRowSpan;
}
}
if ( !xShape.is() )
m_nColSpan = m_nRowSpan = 1;
}
// -----------------------------------------------------------------------------
void OXMLTable::incrementRowIndex()
{
++m_nRowIndex;
m_nColumnIndex = 0;
m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size()));
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// KMail Account Manager
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmacctmgr.h"
#include "kmacctmaildir.h"
#include "kmacctlocal.h"
#include "kmacctexppop.h"
#include "kmacctimap.h"
#include "networkaccount.h"
using KMail::NetworkAccount;
#include "kmacctcachedimap.h"
#include "broadcaststatus.h"
#include "kmfiltermgr.h"
#include "globalsettings.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kconfig.h>
#include <kapplication.h>
#include <qregexp.h>
#include <qvaluelist.h>
using KPIM::BroadcastStatus;
//-----------------------------------------------------------------------------
KMAcctMgr::KMAcctMgr(): QObject()
{
mAcctList.setAutoDelete(TRUE);
mAcctChecking.clear();
mAcctTodo.clear();
mTotalNewMailsArrived=0;
mDisplaySummary = false;
}
//-----------------------------------------------------------------------------
KMAcctMgr::~KMAcctMgr()
{
writeConfig(FALSE);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::writeConfig(bool withSync)
{
KConfig* config = KMKernel::config();
QString groupName;
KConfigGroupSaver saver(config, "General");
config->writeEntry("accounts", mAcctList.count());
// first delete all account groups in the config file:
QStringList accountGroups =
config->groupList().grep( QRegExp( "Account \\d+" ) );
for ( QStringList::Iterator it = accountGroups.begin() ;
it != accountGroups.end() ; ++it )
config->deleteGroup( *it );
// now write new account groups:
int i = 1;
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it, ++i ) {
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
(*it)->writeConfig(*config);
}
if (withSync) config->sync();
}
//-----------------------------------------------------------------------------
void KMAcctMgr::readConfig(void)
{
KConfig* config = KMKernel::config();
KMAccount* acct;
QString acctType, acctName;
QCString groupName;
int i, num;
uint id;
mAcctList.clear();
KConfigGroup general(config, "General");
num = general.readNumEntry("accounts", 0);
for (i=1; i<=num; i++)
{
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
acctType = config->readEntry("Type");
// Provide backwards compatibility
if (acctType == "advanced pop" || acctType == "experimental pop")
acctType = "pop";
acctName = config->readEntry("Name");
id = config->readUnsignedNumEntry("Id", 0);
if (acctName.isEmpty()) acctName = i18n("Account %1").arg(i);
acct = create(acctType, acctName, id);
if (!acct) continue;
add(acct);
acct->readConfig(*config);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleCheckMail(KMAccount *account, bool _interactive)
{
newMailArrived = false;
interactive = _interactive;
// queue the account
mAcctTodo.append(account);
if (account->checkingMail())
{
kdDebug(5006) << "account " << account->name() << " busy, queuing" << endl;
return;
}
processNextCheck(false);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::processNextCheck(bool _newMail)
{
kdDebug(5006) << "processNextCheck, remaining " << mAcctTodo.count() << endl;
KMAccount *curAccount = 0;
newMailArrived |= _newMail;
KMAccount* acct;
for ( acct = mAcctChecking.first(); acct; acct = mAcctChecking.next() )
{
if ( !acct->checkingMail() )
{
// check done
kdDebug(5006) << "account " << acct->name() << " finished check" << endl;
mAcctChecking.removeRef( acct );
kmkernel->filterMgr()->deref();
disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),
this, SLOT( processNextCheck( bool ) ) );
QString hostname = hostForAccount( acct );
if ( !hostname.isEmpty() ) {
if ( mServerConnections.find( hostname ) != mServerConnections.end() ) {
mServerConnections[hostname] -= 1;
kdDebug(5006) << "connections to server " << hostname
<< " now " << mServerConnections[hostname] << endl;
}
}
}
}
if (mAcctChecking.isEmpty())
{
// all checks finished, display summary
if ( mDisplaySummary )
BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(
mTotalNewMailsArrived );
emit checkedMail( newMailArrived, interactive, mTotalNewInFolder );
mTotalNewMailsArrived = 0;
mTotalNewInFolder.clear();
mDisplaySummary = false;
}
if (mAcctTodo.isEmpty()) return;
QString accountHostName;
curAccount = 0;
KMAcctList::Iterator it ( mAcctTodo.begin() );
KMAcctList::Iterator last ( mAcctTodo.end() );
for ( ; it != last; it++ )
{
accountHostName = hostForAccount(*it);
kdDebug(5006) << "for host " << accountHostName
<< " current connections="
<< (mServerConnections.find(accountHostName)==mServerConnections.end() ? 0 : mServerConnections[accountHostName])
<< " and limit is " << GlobalSettings::maxConnectionsPerHost()
<< endl;
bool connectionLimitForHostReached =
!accountHostName.isNull() &&
GlobalSettings::maxConnectionsPerHost() > 0 &&
mServerConnections.find( accountHostName ) != mServerConnections.end() &&
mServerConnections[accountHostName] >= GlobalSettings::maxConnectionsPerHost();
kdDebug(5006) << "connection limit reached: "
<< connectionLimitForHostReached << endl;
if ( !(*it)->checkingMail() && !connectionLimitForHostReached ) {
curAccount = (*it);
mAcctTodo.remove( curAccount );
break;
}
}
if ( !curAccount ) return; // no account or all of them are already checking
if (curAccount->type() != "imap" && curAccount->type() != "cachedimap" &&
curAccount->folder() == 0)
{
QString tmp = i18n("Account %1 has no mailbox defined:\n"
"mail checking aborted;\n"
"check your account settings.")
.arg(curAccount->name());
KMessageBox::information(0,tmp);
emit checkedMail( false, interactive, mTotalNewInFolder );
mTotalNewMailsArrived = 0;
mTotalNewInFolder.clear();
return;
}
connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),
this, SLOT( processNextCheck( bool ) ) );
BroadcastStatus::instance()->setStatusMsg(
i18n("Checking account %1 for new mail").arg(curAccount->name()));
kdDebug(5006) << "processing next mail check for " << curAccount->name() << endl;
curAccount->setCheckingMail(true);
mAcctChecking.append(curAccount);
kmkernel->filterMgr()->ref();
curAccount->processNewMail(interactive);
if ( !accountHostName.isEmpty() ) {
if ( mServerConnections.find( accountHostName ) != mServerConnections.end() )
mServerConnections[accountHostName] += 1;
else
mServerConnections[accountHostName] = 1;
kdDebug(5006) << "check mail started - connections for host "
<< accountHostName << " now is "
<< mServerConnections[accountHostName] << endl;
}
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::create(const QString &aType, const QString &aName, uint id)
{
KMAccount* act = 0;
if (id == 0)
id = createId();
if (aType == "local")
act = new KMAcctLocal(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
if (aType == "maildir")
act = new KMAcctMaildir(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
else if (aType == "pop")
act = new KMAcctExpPop(this, aName.isEmpty() ? i18n("POP Account") : aName, id);
else if (aType == "imap")
act = new KMAcctImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
else if (aType == "cachedimap")
act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n("Disconnected IMAP") : aName, id);
if (act)
{
if (aType != "imap" && aType != "cachedimap")
act->setFolder(kmkernel->inboxFolder());
connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),
this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );
}
return act;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::add(KMAccount *account)
{
if (account) {
mAcctList.append( account );
emit accountAdded( account );
}
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::findByName(const QString &aName)
{
if (aName.isEmpty()) return 0;
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
{
if ((*it)->name() == aName) return (*it);
}
return 0;
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::find(const uint id)
{
if (id == 0) return 0;
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
{
if ((*it)->id() == id) return (*it);
}
return 0;
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::first(void)
{
return mAcctList.first();
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::next(void)
{
return mAcctList.next();
}
//-----------------------------------------------------------------------------
bool KMAcctMgr::remove( KMAccount* acct )
{
if( !acct )
return false;
mAcctList.removeRef( acct );
emit accountRemoved( acct );
return true;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::checkMail(bool _interactive)
{
newMailArrived = false;
if (mAcctList.isEmpty())
{
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
mDisplaySummary = true;
mTotalNewMailsArrived=0;
mTotalNewInFolder.clear();
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it )
{
if (!it.current()->checkExclude())
singleCheckMail(it.current(), _interactive);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleInvalidateIMAPFolders(KMAccount *account) {
account->invalidateIMAPFolders();
}
void KMAcctMgr::invalidateIMAPFolders()
{
if (mAcctList.isEmpty()) {
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
singleInvalidateIMAPFolders(it.current());
}
//-----------------------------------------------------------------------------
QStringList KMAcctMgr::getAccounts(bool noImap) {
KMAccount *cur;
QStringList strList;
for (cur=mAcctList.first(); cur; cur=mAcctList.next()) {
if (!noImap || cur->type() != "imap") strList.append(cur->name());
}
return strList;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::intCheckMail(int item, bool _interactive)
{
KMAccount* cur;
newMailArrived = false;
mTotalNewMailsArrived = 0;
mTotalNewInFolder.clear();
int x = 0;
cur = mAcctList.first();
while (cur)
{
x++;
if (x > item) break;
cur=mAcctList.next();
}
mDisplaySummary = false;
singleCheckMail(cur, _interactive);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )
{
for ( QMap<QString, int>::const_iterator it = newInFolder.begin();
it != newInFolder.end();
++it )
{
mTotalNewMailsArrived += it.data();
if ( mTotalNewInFolder.find( it.key() ) == mTotalNewInFolder.end() )
mTotalNewInFolder[it.key()] = it.data();
else
mTotalNewInFolder[it.key()] += it.data();
}
}
//-----------------------------------------------------------------------------
uint KMAcctMgr::createId()
{
QValueList<uint> usedIds;
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
usedIds << it.current()->id();
usedIds << 0; // 0 is default for unknown
int newId;
do
{
newId = kapp->random();
} while ( usedIds.find(newId) != usedIds.end() );
return newId;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::cancelMailCheck()
{
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it ) {
it.current()->cancelMailCheck();
}
}
//-----------------------------------------------------------------------------
QString KMAcctMgr::hostForAccount( const KMAccount *acct ) const
{
const NetworkAccount *net_acct = dynamic_cast<const NetworkAccount*>( acct );
return net_acct ? net_acct->host() : QString::null;
}
#include "kmacctmgr.moc"
<commit_msg>Also use 'IMAP Account' as default name for disc. IMAP.<commit_after>// KMail Account Manager
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmacctmgr.h"
#include "kmacctmaildir.h"
#include "kmacctlocal.h"
#include "kmacctexppop.h"
#include "kmacctimap.h"
#include "networkaccount.h"
using KMail::NetworkAccount;
#include "kmacctcachedimap.h"
#include "broadcaststatus.h"
#include "kmfiltermgr.h"
#include "globalsettings.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kconfig.h>
#include <kapplication.h>
#include <qregexp.h>
#include <qvaluelist.h>
using KPIM::BroadcastStatus;
//-----------------------------------------------------------------------------
KMAcctMgr::KMAcctMgr(): QObject()
{
mAcctList.setAutoDelete(TRUE);
mAcctChecking.clear();
mAcctTodo.clear();
mTotalNewMailsArrived=0;
mDisplaySummary = false;
}
//-----------------------------------------------------------------------------
KMAcctMgr::~KMAcctMgr()
{
writeConfig(FALSE);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::writeConfig(bool withSync)
{
KConfig* config = KMKernel::config();
QString groupName;
KConfigGroupSaver saver(config, "General");
config->writeEntry("accounts", mAcctList.count());
// first delete all account groups in the config file:
QStringList accountGroups =
config->groupList().grep( QRegExp( "Account \\d+" ) );
for ( QStringList::Iterator it = accountGroups.begin() ;
it != accountGroups.end() ; ++it )
config->deleteGroup( *it );
// now write new account groups:
int i = 1;
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it, ++i ) {
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
(*it)->writeConfig(*config);
}
if (withSync) config->sync();
}
//-----------------------------------------------------------------------------
void KMAcctMgr::readConfig(void)
{
KConfig* config = KMKernel::config();
KMAccount* acct;
QString acctType, acctName;
QCString groupName;
int i, num;
uint id;
mAcctList.clear();
KConfigGroup general(config, "General");
num = general.readNumEntry("accounts", 0);
for (i=1; i<=num; i++)
{
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
acctType = config->readEntry("Type");
// Provide backwards compatibility
if (acctType == "advanced pop" || acctType == "experimental pop")
acctType = "pop";
acctName = config->readEntry("Name");
id = config->readUnsignedNumEntry("Id", 0);
if (acctName.isEmpty()) acctName = i18n("Account %1").arg(i);
acct = create(acctType, acctName, id);
if (!acct) continue;
add(acct);
acct->readConfig(*config);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleCheckMail(KMAccount *account, bool _interactive)
{
newMailArrived = false;
interactive = _interactive;
// queue the account
mAcctTodo.append(account);
if (account->checkingMail())
{
kdDebug(5006) << "account " << account->name() << " busy, queuing" << endl;
return;
}
processNextCheck(false);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::processNextCheck(bool _newMail)
{
kdDebug(5006) << "processNextCheck, remaining " << mAcctTodo.count() << endl;
KMAccount *curAccount = 0;
newMailArrived |= _newMail;
KMAccount* acct;
for ( acct = mAcctChecking.first(); acct; acct = mAcctChecking.next() )
{
if ( !acct->checkingMail() )
{
// check done
kdDebug(5006) << "account " << acct->name() << " finished check" << endl;
mAcctChecking.removeRef( acct );
kmkernel->filterMgr()->deref();
disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),
this, SLOT( processNextCheck( bool ) ) );
QString hostname = hostForAccount( acct );
if ( !hostname.isEmpty() ) {
if ( mServerConnections.find( hostname ) != mServerConnections.end() ) {
mServerConnections[hostname] -= 1;
kdDebug(5006) << "connections to server " << hostname
<< " now " << mServerConnections[hostname] << endl;
}
}
}
}
if (mAcctChecking.isEmpty())
{
// all checks finished, display summary
if ( mDisplaySummary )
BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(
mTotalNewMailsArrived );
emit checkedMail( newMailArrived, interactive, mTotalNewInFolder );
mTotalNewMailsArrived = 0;
mTotalNewInFolder.clear();
mDisplaySummary = false;
}
if (mAcctTodo.isEmpty()) return;
QString accountHostName;
curAccount = 0;
KMAcctList::Iterator it ( mAcctTodo.begin() );
KMAcctList::Iterator last ( mAcctTodo.end() );
for ( ; it != last; it++ )
{
accountHostName = hostForAccount(*it);
kdDebug(5006) << "for host " << accountHostName
<< " current connections="
<< (mServerConnections.find(accountHostName)==mServerConnections.end() ? 0 : mServerConnections[accountHostName])
<< " and limit is " << GlobalSettings::maxConnectionsPerHost()
<< endl;
bool connectionLimitForHostReached =
!accountHostName.isNull() &&
GlobalSettings::maxConnectionsPerHost() > 0 &&
mServerConnections.find( accountHostName ) != mServerConnections.end() &&
mServerConnections[accountHostName] >= GlobalSettings::maxConnectionsPerHost();
kdDebug(5006) << "connection limit reached: "
<< connectionLimitForHostReached << endl;
if ( !(*it)->checkingMail() && !connectionLimitForHostReached ) {
curAccount = (*it);
mAcctTodo.remove( curAccount );
break;
}
}
if ( !curAccount ) return; // no account or all of them are already checking
if (curAccount->type() != "imap" && curAccount->type() != "cachedimap" &&
curAccount->folder() == 0)
{
QString tmp = i18n("Account %1 has no mailbox defined:\n"
"mail checking aborted;\n"
"check your account settings.")
.arg(curAccount->name());
KMessageBox::information(0,tmp);
emit checkedMail( false, interactive, mTotalNewInFolder );
mTotalNewMailsArrived = 0;
mTotalNewInFolder.clear();
return;
}
connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),
this, SLOT( processNextCheck( bool ) ) );
BroadcastStatus::instance()->setStatusMsg(
i18n("Checking account %1 for new mail").arg(curAccount->name()));
kdDebug(5006) << "processing next mail check for " << curAccount->name() << endl;
curAccount->setCheckingMail(true);
mAcctChecking.append(curAccount);
kmkernel->filterMgr()->ref();
curAccount->processNewMail(interactive);
if ( !accountHostName.isEmpty() ) {
if ( mServerConnections.find( accountHostName ) != mServerConnections.end() )
mServerConnections[accountHostName] += 1;
else
mServerConnections[accountHostName] = 1;
kdDebug(5006) << "check mail started - connections for host "
<< accountHostName << " now is "
<< mServerConnections[accountHostName] << endl;
}
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::create(const QString &aType, const QString &aName, uint id)
{
KMAccount* act = 0;
if (id == 0)
id = createId();
if (aType == "local")
act = new KMAcctLocal(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
if (aType == "maildir")
act = new KMAcctMaildir(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
else if (aType == "pop")
act = new KMAcctExpPop(this, aName.isEmpty() ? i18n("POP Account") : aName, id);
else if (aType == "imap")
act = new KMAcctImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
else if (aType == "cachedimap")
act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
if (act)
{
if (aType != "imap" && aType != "cachedimap")
act->setFolder(kmkernel->inboxFolder());
connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),
this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );
}
return act;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::add(KMAccount *account)
{
if (account) {
mAcctList.append( account );
emit accountAdded( account );
}
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::findByName(const QString &aName)
{
if (aName.isEmpty()) return 0;
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
{
if ((*it)->name() == aName) return (*it);
}
return 0;
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::find(const uint id)
{
if (id == 0) return 0;
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
{
if ((*it)->id() == id) return (*it);
}
return 0;
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::first(void)
{
return mAcctList.first();
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::next(void)
{
return mAcctList.next();
}
//-----------------------------------------------------------------------------
bool KMAcctMgr::remove( KMAccount* acct )
{
if( !acct )
return false;
mAcctList.removeRef( acct );
emit accountRemoved( acct );
return true;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::checkMail(bool _interactive)
{
newMailArrived = false;
if (mAcctList.isEmpty())
{
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
mDisplaySummary = true;
mTotalNewMailsArrived=0;
mTotalNewInFolder.clear();
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it )
{
if (!it.current()->checkExclude())
singleCheckMail(it.current(), _interactive);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleInvalidateIMAPFolders(KMAccount *account) {
account->invalidateIMAPFolders();
}
void KMAcctMgr::invalidateIMAPFolders()
{
if (mAcctList.isEmpty()) {
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
singleInvalidateIMAPFolders(it.current());
}
//-----------------------------------------------------------------------------
QStringList KMAcctMgr::getAccounts(bool noImap) {
KMAccount *cur;
QStringList strList;
for (cur=mAcctList.first(); cur; cur=mAcctList.next()) {
if (!noImap || cur->type() != "imap") strList.append(cur->name());
}
return strList;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::intCheckMail(int item, bool _interactive)
{
KMAccount* cur;
newMailArrived = false;
mTotalNewMailsArrived = 0;
mTotalNewInFolder.clear();
int x = 0;
cur = mAcctList.first();
while (cur)
{
x++;
if (x > item) break;
cur=mAcctList.next();
}
mDisplaySummary = false;
singleCheckMail(cur, _interactive);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )
{
for ( QMap<QString, int>::const_iterator it = newInFolder.begin();
it != newInFolder.end();
++it )
{
mTotalNewMailsArrived += it.data();
if ( mTotalNewInFolder.find( it.key() ) == mTotalNewInFolder.end() )
mTotalNewInFolder[it.key()] = it.data();
else
mTotalNewInFolder[it.key()] += it.data();
}
}
//-----------------------------------------------------------------------------
uint KMAcctMgr::createId()
{
QValueList<uint> usedIds;
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
usedIds << it.current()->id();
usedIds << 0; // 0 is default for unknown
int newId;
do
{
newId = kapp->random();
} while ( usedIds.find(newId) != usedIds.end() );
return newId;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::cancelMailCheck()
{
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it ) {
it.current()->cancelMailCheck();
}
}
//-----------------------------------------------------------------------------
QString KMAcctMgr::hostForAccount( const KMAccount *acct ) const
{
const NetworkAccount *net_acct = dynamic_cast<const NetworkAccount*>( acct );
return net_acct ? net_acct->host() : QString::null;
}
#include "kmacctmgr.moc"
<|endoftext|>
|
<commit_before>#include <libmemcached/memcached.h>
#include <string>
#include <vector>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
bool fetch(std::string &key,
std::string &ret_val,
size_t *key_length,
size_t *value_length,
uint32_t *flags,
memcached_return *rc)
{
char ret_key[MEMCACHED_MAX_KEY];
char *value= memcached_fetch(&memc, ret_key, key_length,
value_length, flags, rc);
if (value)
{
ret_val.assign(value);
key.assign(ret_key);
return true;
}
return false;
}
std::string get(const std::string &key, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get(&memc, key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string get_by_key(const std::string &master_key,
const std::string &key,
size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get_by_key(&memc, master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
bool mget(std::vector<std::string> &keys)
{
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
/*
* Construct an array which will contain the length
* of each of the strings in the input vector. Also, to
* interface with the memcached C API, we need to convert
* the vector of std::string's to a vector of char *.
*/
real_keys.reserve(keys.size());
key_len.reserve(keys.size());
std::vector<std::string>::iterator it= keys.begin();
while (it != keys.end())
{
real_keys.push_back(const_cast<char *>((*it).c_str()));
key_len.push_back((*it).length());
++it;
}
/*
* If the std::vector of keys is empty then we cannot
* call memcached_mget as we will get undefined behavior.
*/
if (!real_keys.empty())
{
memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0],
real_keys.size());
return (rc == MEMCACHED_SUCCESS);
}
return false;
}
bool set(const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration, flags);
return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);
}
bool set_all(std::vector<std::string> &keys,
std::vector<std::string> &values,
time_t expiration,
uint32_t flags)
{
if (keys.size() != values.size())
{
return false;
}
bool retval= true;
std::vector<std::string>::iterator key_it= keys.begin();
std::vector<std::string>::iterator val_it= values.begin();
while (key_it != keys.end())
{
retval= set((*key_it), (*val_it), expiration, flags);
if (retval == false)
{
return retval;
}
++key_it;
++val_it;
}
return retval;
}
bool set_by_key(const std::string &master_key,
const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration,
flags);
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool add_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool append_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool cas_by_key(const std::string &master_key,
const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
// using 'remove' vs. 'delete' since 'delete' is a keyword
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool delete_by_key(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
bool flush(time_t expiration)
{
memcached_return rc= memcached_flush(&memc, expiration);
return (rc == MEMCACHED_SUCCESS);
}
bool fetch_execute(memcached_execute_function *callback,
void *context,
unsigned int num_of_callbacks)
{
memcached_return rc= memcached_fetch_execute(&memc,
callback,
context,
num_of_callbacks);
return (rc == MEMCACHED_SUCCESS);
}
const std::string lib_version() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
<commit_msg>Updated C++ interface to have include guards. Also modified the naming convention for the functions in the C++ interface. We should use camel case for the C++ interface.<commit_after>/*
* Summary: C++ interface for memcached server
*
* Copy: See Copyright for the status of this software.
*
* Authors: Padraig O'Sullivan, Patrick Galbraith
*/
#ifndef LIBMEMCACHEDPP_H
#define LIBMEMCACHEDPP_H
#include <libmemcached/memcached.h>
#include <string>
#include <vector>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
bool fetch(std::string &key,
std::string &ret_val,
size_t *key_length,
size_t *value_length,
uint32_t *flags,
memcached_return *rc)
{
char ret_key[MEMCACHED_MAX_KEY];
char *value= memcached_fetch(&memc, ret_key, key_length,
value_length, flags, rc);
if (value)
{
ret_val.assign(value);
key.assign(ret_key);
return true;
}
return false;
}
std::string get(const std::string &key, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get(&memc, key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string getByKey(const std::string &master_key,
const std::string &key,
size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get_by_key(&memc,
master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
bool mget(std::vector<std::string> &keys)
{
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
/*
* Construct an array which will contain the length
* of each of the strings in the input vector. Also, to
* interface with the memcached C API, we need to convert
* the vector of std::string's to a vector of char *.
*/
real_keys.reserve(keys.size());
key_len.reserve(keys.size());
std::vector<std::string>::iterator it= keys.begin();
while (it != keys.end())
{
real_keys.push_back(const_cast<char *>((*it).c_str()));
key_len.push_back((*it).length());
++it;
}
/*
* If the std::vector of keys is empty then we cannot
* call memcached_mget as we will get undefined behavior.
*/
if (!real_keys.empty())
{
memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0],
real_keys.size());
return (rc == MEMCACHED_SUCCESS);
}
return false;
}
bool set(const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration, flags);
return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);
}
bool setAll(std::vector<std::string> &keys,
std::vector<std::string> &values,
time_t expiration,
uint32_t flags)
{
if (keys.size() != values.size())
{
return false;
}
bool retval= true;
std::vector<std::string>::iterator key_it= keys.begin();
std::vector<std::string>::iterator val_it= values.begin();
while (key_it != keys.end())
{
retval= set((*key_it), (*val_it), expiration, flags);
if (retval == false)
{
return retval;
}
++key_it;
++val_it;
}
return retval;
}
bool setByKey(const std::string &master_key,
const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration,
flags);
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool addByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replaceByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prependByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool appendByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool casByKey(const std::string &master_key,
const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
// using 'remove' vs. 'delete' since 'delete' is a keyword
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool removeByKey(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
bool flush(time_t expiration)
{
memcached_return rc= memcached_flush(&memc, expiration);
return (rc == MEMCACHED_SUCCESS);
}
bool fetchExecute(memcached_execute_function *callback,
void *context,
unsigned int num_of_callbacks)
{
memcached_return rc= memcached_fetch_execute(&memc,
callback,
context,
num_of_callbacks);
return (rc == MEMCACHED_SUCCESS);
}
const std::string libVersion() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
#endif /* LIBMEMCACHEDPP_H */
<|endoftext|>
|
<commit_before>#include "ExecutionEngine.h"
#include <chrono>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>
#pragma GCC diagnostic pop
#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"
namespace dev
{
namespace eth
{
namespace jit
{
ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
/*if (auto cachedExec = Cache::findExec(key))
{
return run(*cachedExec, _data, _env);
}*/
auto module = Compiler({}).compile(_code);
//module->dump();
return run(std::move(module), _data, _env, _code);
}
namespace
{
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
ReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime)
{
// That function uses long jumps to handle "execeptions".
// Do not create any non-POD objects here
ReturnCode returnCode{};
auto sj = setjmp(_runtime->getJmpBuf());
if (sj == 0)
returnCode = _mainFunc(_runtime);
else
returnCode = static_cast<ReturnCode>(sj);
return returnCode;
}
}
ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
// TODO: Use it in evmcc
//llvm::sys::PrintStackTraceOnErrorSignal();
//static const auto program = "EVM JIT";
//llvm::PrettyStackTraceProgram X(1, &program);
static std::unique_ptr<llvm::ExecutionEngine> ee; // TODO: Use Managed Objects from LLVM?
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
EntryFuncPtr entryFuncPtr{};
auto&& mainFuncName = _module->getModuleIdentifier();
if (!ee)
{
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::EngineBuilder builder(_module.get());
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setUseMCJIT(true);
std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);
builder.setMCJITMemoryManager(memoryManager.get());
builder.setOptLevel(llvm::CodeGenOpt::None);
auto triple = llvm::Triple(llvm::sys::getProcessTriple());
if (triple.getOS() == llvm::Triple::OSType::Win32)
triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format
_module->setTargetTriple(triple.str());
ee.reset(builder.create());
if (!ee)
return ReturnCode::LLVMConfigError;
_module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module
memoryManager.release(); // and memory manager
//ee->setObjectCache(Cache::getObjectCache());
}
else
{
if (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(_module->getModuleIdentifier()))
{
entryFuncPtr = nullptr;
}
else
{
ee->addModule(_module.get());
//std::cerr << _module->getModuleIdentifier() << "\n";
_module.release();
}
}
assert(ee);
//ExecBundle exec;
//exec.engine.reset(builder.create());
//if (!exec.engine)
// return ReturnCode::LLVMConfigError;
// TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used
//auto finalizationStartTime = std::chrono::high_resolution_clock::now();
//exec.engine->finalizeObject();
//auto finalizationEndTime = std::chrono::high_resolution_clock::now();
//clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();
auto executionStartTime = std::chrono::high_resolution_clock::now();
std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
//auto& cachedExec = Cache::registerExec(key, std::move(exec));
Runtime runtime(_data, _env);
auto mainFunc = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);
auto returnCode = runEntryFunc(mainFunc, &runtime);
if (returnCode == ReturnCode::Return)
this->returnData = runtime.getReturnData();
auto executionEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
//clog(JIT) << "Max stack size: " << Stack::maxStackSize;
clog(JIT) << "\n";
return returnCode;
}
}
}
}
<commit_msg>Clean up ExecutionEngine<commit_after>#include "ExecutionEngine.h"
#include <chrono>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>
#pragma GCC diagnostic pop
#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"
namespace dev
{
namespace eth
{
namespace jit
{
ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
auto module = Compiler({}).compile(_code);
//module->dump();
return run(std::move(module), _data, _env, _code);
}
namespace
{
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
ReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime)
{
// That function uses long jumps to handle "execeptions".
// Do not create any non-POD objects here
ReturnCode returnCode{};
auto sj = setjmp(_runtime->getJmpBuf());
if (sj == 0)
returnCode = _mainFunc(_runtime);
else
returnCode = static_cast<ReturnCode>(sj);
return returnCode;
}
}
ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
// TODO: Use it in evmcc
//llvm::sys::PrintStackTraceOnErrorSignal();
//static const auto program = "EVM JIT";
//llvm::PrettyStackTraceProgram X(1, &program);
static std::unique_ptr<llvm::ExecutionEngine> ee; // TODO: Use Managed Objects from LLVM?
EntryFuncPtr entryFuncPtr{};
Runtime runtime(_data, _env);
auto&& mainFuncName = _module->getModuleIdentifier();
if (!ee)
{
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::EngineBuilder builder(_module.get());
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setUseMCJIT(true);
std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);
builder.setMCJITMemoryManager(memoryManager.get());
builder.setOptLevel(llvm::CodeGenOpt::None);
auto triple = llvm::Triple(llvm::sys::getProcessTriple());
if (triple.getOS() == llvm::Triple::OSType::Win32)
triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format
_module->setTargetTriple(triple.str());
ee.reset(builder.create());
if (!ee)
return ReturnCode::LLVMConfigError;
_module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module
memoryManager.release(); // and memory manager
//ee->setObjectCache(Cache::getObjectCache());
entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);
}
else
{
entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);
if (!entryFuncPtr)
{
ee->addModule(_module.get());
_module.release();
entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);
}
}
assert(entryFuncPtr);
auto executionStartTime = std::chrono::high_resolution_clock::now();
//auto mainFunc = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);
auto returnCode = runEntryFunc(entryFuncPtr, &runtime);
if (returnCode == ReturnCode::Return)
this->returnData = runtime.getReturnData();
auto executionEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
clog(JIT) << "\n";
return returnCode;
}
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <functional>
#include <unordered_map>
// Compare two lists to see if they're the same group; in most
// circumstances we should check for the equality of their sizes
// and early out with a false return if they weren't equal;
// however, this function is only called if the lists
// to be compared are equal to the prerequisite size anyway.
// It's provided for completeness and flexibility for other use-cases
/*
* as it turns out, this function isn't necessary because the nature of the combinations algorithm
prevents this via sequentially chopping off every member
from the given numbers list
* it's here for documentation purposes.
*
static bool isSameUnordered(const std::vector<int>& a, const std::vector<int>& b) {
std::unordered_map<int, int> m;
if (a.size() != b.size())
return false;
// if m[x] does not exist yet,
// the increment will first initialize it to 0
// and then add 1 accordingly;
// i.e., if m[x] does not exist,
// even simply reading its value
// will cause it to be zero-initialized
// (on GCC)
for (int x: a)
m[x]++;
for (int x: b) {
if (m[x] == 0)
return false;
m[x]++;
}
return true;
}
*/
// This is a recursive function designed to find
// all possible sum combinations for a given list of numbers.
// For a particular size of numbers of k, and a tuple of
// distinct integers t (which is always required and given size k),
// if the sum of t is equivalent to the target sum s,
// we have a winning value. Correspondingly, we print this winning value
// ( in addition to its sequence ) into an output file corresponding
// to the input file the sum value stems from.
// The running time of this function n and k is the following combination formula (where order doesn't matter):
// O(n! / k!(n - k)!) or O(nCk)
// The implementation of this function was originally in Python,
// and can be found here: http://stackoverflow.com/a/4633515
static void sum(std::ofstream& stream,
const int targetSum,
const int targetAmount,
const std::vector<int>& numbers,
const std::vector<int>& partial = std::vector<int>()) {
// Potentially skip iteration over winningTuples
if (partial.size() == (uint32_t) targetAmount)
{
// Compute the sum for this current group
int s = 0;
std::for_each(partial.begin(), partial.cend(), [&s](const int& x) -> void {
s += x;
});
// If we're valid, provide an output which shows the expression
if (s == targetSum) {
std::stringstream ss;
size_t c = 0;
for (int i: partial) {
ss << i;
if (++c != partial.size())
ss << " + ";
}
ss << " = " << targetSum << "\n";
stream << ss.str();
winningTuples.push_back(partial);
}
// There is no point in continuing if either of these are true,
// since we'll only be increasing the value/partial size if
// recurse down the tree further.
if (s >= targetSum)
return;
}
// Same principle with the sum check in the above block^^^
if (partial.size() >= (size_t)targetAmount)
return;
// For us to evaluate all possible combinations (up to the desired target amount)
// we develop a chain of values for every single value
// which individually inspects it self with every other possible
// sum in every list
// Each iteration successively creates a new variant of the given partial list,
// by taking the value in numbers corresponding to the current iteration,
// chopping off every value up to (inclusive) that iteration from the numbers list
// and creating a copy of that list with which we can use to evaluate within the next depth.
// So, if I have abcdefg numbers, all of the partial combinations for first level will be:
// ab, ac, ad, ae, af, ag
// And in the next level:
// abc, abd, abe, abf, abg;
// acd, ace, acf, acg;
// ade, adf, adg;
// aef, aeg;
// afg
// (and so on and so forth)
for (auto i = numbers.begin(); i != numbers.end(); ++i) {
int x = *i;
std::vector<int> remaining;
int index = std::distance(numbers.begin(), i);
remaining.reserve(numbers.size() - index);
for (auto j = i + 1; j != numbers.end(); ++j)
remaining.push_back(*j);
std::vector<int> newPartial(partial.begin(), partial.end());
newPartial.push_back(x);
sum(stream, targetSum, targetAmount, remaining, newPartial);
}
}
static bool parseInput(const std::string& inputPath, const std::string& outputPath) {
std::ifstream f;
f.open(inputPath);
std::ofstream output;
output.open(outputPath);
int targetSum = 0;
int targetAmount = 0;
std::vector<int> numbers;
if (f.is_open()) {
// Get the current line,
// evaluate its function accordingly,
// depending on the current line number
std::string line;
int lineNum = 0;
while (std::getline(f, line)) {
std::istringstream toInteger(line);
switch (lineNum) {
case 1: toInteger >> targetSum; break;
case 0: toInteger >> targetAmount; break;
default: {
int value;
toInteger >> value;
numbers.push_back(value);
} break;
}
lineNum++;
}
// Compute the sum.
output << "BEGIN " << inputPath << "\n\n";
output << "number count: " << numbers.size() << "\n";
output << "target amount: " << targetAmount << "\n";
output << "target sum: " << targetSum << "\n";
sum(output, targetSum, targetAmount, numbers);
output << "END input\n\n";
output.close();
winningTuples.clear();
} else {
std::cout << "Failure" << std::endl;
return false;
}
return true;
}
int main()
{
// Must <= the amount of test files generated via input_gen.py
int numTests = 3;
for (int i = 0; i < numTests; ++i) {
std::string inpath("input" + std::to_string(i) + ".txt");
if (!parseInput(inpath, "result_input" + std::to_string(i) + ".txt")) {
std::cout << "Could not read file \"" << inpath << '\"' << std::endl;
}
}
return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <functional>
#include <unordered_map>
// Compare two lists to see if they're the same group; in most
// circumstances we should check for the equality of their sizes
// and early out with a false return if they weren't equal;
// however, this function is only called if the lists
// to be compared are equal to the prerequisite size anyway.
// It's provided for completeness and flexibility for other use-cases
/*
* as it turns out, this function isn't necessary because the nature of the combinations algorithm
prevents this via sequentially chopping off every member
from the given numbers list
* it's here for documentation purposes.
*
static bool isSameUnordered(const std::vector<int>& a, const std::vector<int>& b) {
std::unordered_map<int, int> m;
if (a.size() != b.size())
return false;
// if m[x] does not exist yet,
// the increment will first initialize it to 0
// and then add 1 accordingly;
// i.e., if m[x] does not exist,
// even simply reading its value
// will cause it to be zero-initialized
// (on GCC)
for (int x: a)
m[x]++;
for (int x: b) {
if (m[x] == 0)
return false;
m[x]++;
}
return true;
}
*/
// This is a recursive function designed to find
// all possible sum combinations for a given list of numbers.
// For a particular size of numbers of k, and a tuple of
// distinct integers t (which is always required and given size k),
// if the sum of t is equivalent to the target sum s,
// we have a winning value. Correspondingly, we print this winning value
// ( in addition to its sequence ) into an output file corresponding
// to the input file the sum value stems from.
// The running time of this function n and k is the following combination formula (where order doesn't matter):
// O(n! / k!(n - k)!) or O(nCk)
// The implementation of this function was originally in Python,
// and can be found here: http://stackoverflow.com/a/4633515
static void sum(std::ofstream& stream,
const int targetSum,
const int targetAmount,
const std::vector<int>& numbers,
const std::vector<int>& partial = std::vector<int>()) {
if (partial.size() == (uint32_t) targetAmount)
{
// Compute the sum for this current group
int s = 0;
std::for_each(partial.begin(), partial.cend(), [&s](const int& x) -> void {
s += x;
});
// If we're valid, provide an output which shows the expression
if (s == targetSum) {
std::stringstream ss;
size_t c = 0;
for (int i: partial) {
ss << i;
if (++c != partial.size())
ss << " + ";
}
ss << " = " << targetSum << "\n";
stream << ss.str();
winningTuples.push_back(partial);
}
// There is no point in continuing if either of these are true,
// since we'll only be increasing the value/partial size if
// recurse down the tree further.
if (s >= targetSum)
return;
}
// Same principle with the sum check in the above block^^^
if (partial.size() >= (size_t)targetAmount)
return;
// For us to evaluate all possible combinations (up to the desired target amount)
// we develop a chain of values for every single value
// which individually inspects it self with every other possible
// sum in every list
// Each iteration successively creates a new variant of the given partial list,
// by taking the value in numbers corresponding to the current iteration,
// chopping off every value up to (inclusive) that iteration from the numbers list
// and creating a copy of that list with which we can use to evaluate within the next depth.
// So, if I have abcdefg numbers, all of the partial combinations for first level will be:
// ab, ac, ad, ae, af, ag
// And in the next level:
// abc, abd, abe, abf, abg;
// acd, ace, acf, acg;
// ade, adf, adg;
// aef, aeg;
// afg
// (and so on and so forth)
for (auto i = numbers.begin(); i != numbers.end(); ++i) {
int x = *i;
std::vector<int> remaining;
int index = std::distance(numbers.begin(), i);
remaining.reserve(numbers.size() - index);
for (auto j = i + 1; j != numbers.end(); ++j)
remaining.push_back(*j);
std::vector<int> newPartial(partial.begin(), partial.end());
newPartial.push_back(x);
sum(stream, targetSum, targetAmount, remaining, newPartial);
}
}
static bool parseInput(const std::string& inputPath, const std::string& outputPath) {
std::ifstream f;
f.open(inputPath);
std::ofstream output;
output.open(outputPath);
int targetSum = 0;
int targetAmount = 0;
std::vector<int> numbers;
if (f.is_open()) {
// Get the current line,
// evaluate its function accordingly,
// depending on the current line number
std::string line;
int lineNum = 0;
while (std::getline(f, line)) {
std::istringstream toInteger(line);
switch (lineNum) {
case 1: toInteger >> targetSum; break;
case 0: toInteger >> targetAmount; break;
default: {
int value;
toInteger >> value;
numbers.push_back(value);
} break;
}
lineNum++;
}
// Compute the sum.
output << "BEGIN " << inputPath << "\n\n";
output << "number count: " << numbers.size() << "\n";
output << "target amount: " << targetAmount << "\n";
output << "target sum: " << targetSum << "\n";
sum(output, targetSum, targetAmount, numbers);
output << "END input\n\n";
output.close();
winningTuples.clear();
} else {
return false;
}
return true;
}
int main()
{
// Must be <= the amount of test files generated via input_gen.py
int numTests = 3;
for (int i = 0; i < numTests; ++i) {
std::string inpath("input" + std::to_string(i) + ".txt");
if (!parseInput(inpath, "result_input" + std::to_string(i) + ".txt")) {
std::cout << "Could not read file \"" << inpath << '\"' << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>//===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "JSONRPCDispatcher.h"
#include "ProtocolHandlers.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/YAMLParser.h"
#include <istream>
using namespace clang;
using namespace clangd;
void JSONOutput::writeMessage(const Twine &Message) {
llvm::SmallString<128> Storage;
StringRef M = Message.toStringRef(Storage);
std::lock_guard<std::mutex> Guard(StreamMutex);
// Log without headers.
Logs << "--> " << M << '\n';
Logs.flush();
// Emit message with header.
Outs << "Content-Length: " << M.size() << "\r\n\r\n" << M;
Outs.flush();
}
void JSONOutput::log(const Twine &Message) {
std::lock_guard<std::mutex> Guard(StreamMutex);
Logs << Message;
Logs.flush();
}
void JSONOutput::mirrorInput(const Twine &Message) {
if (!InputMirror)
return;
*InputMirror << Message;
InputMirror->flush();
}
void RequestContext::reply(const llvm::Twine &Result) {
if (ID.empty()) {
Out.log("Attempted to reply to a notification!\n");
return;
}
Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
R"(,"result":)" + Result + "}");
}
void RequestContext::replyError(int code, const llvm::StringRef &Message) {
Out.log("Error " + llvm::Twine(code) + ": " + Message + "\n");
if (!ID.empty()) {
Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
R"(,"error":{"code":)" + llvm::Twine(code) +
R"(,"message":")" + llvm::yaml::escape(Message) +
R"("}})");
}
}
void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
assert(!Handlers.count(Method) && "Handler already registered!");
Handlers[Method] = std::move(H);
}
static void
callHandler(const llvm::StringMap<JSONRPCDispatcher::Handler> &Handlers,
llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,
llvm::yaml::MappingNode *Params,
const JSONRPCDispatcher::Handler &UnknownHandler, JSONOutput &Out) {
llvm::SmallString<64> MethodStorage;
auto I = Handlers.find(Method->getValue(MethodStorage));
auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Handler(RequestContext(Out, Id ? Id->getRawValue() : ""), Params);
}
bool JSONRPCDispatcher::call(StringRef Content, JSONOutput &Out) const {
llvm::SourceMgr SM;
llvm::yaml::Stream YAMLStream(Content, SM);
auto Doc = YAMLStream.begin();
if (Doc == YAMLStream.end())
return false;
auto *Root = Doc->getRoot();
if (!Root)
return false;
auto *Object = dyn_cast<llvm::yaml::MappingNode>(Root);
if (!Object)
return false;
llvm::yaml::ScalarNode *Version = nullptr;
llvm::yaml::ScalarNode *Method = nullptr;
llvm::yaml::MappingNode *Params = nullptr;
llvm::yaml::ScalarNode *Id = nullptr;
for (auto &NextKeyValue : *Object) {
auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
if (!KeyString)
return false;
llvm::SmallString<10> KeyStorage;
StringRef KeyValue = KeyString->getValue(KeyStorage);
llvm::yaml::Node *Value = NextKeyValue.getValue();
if (!Value)
return false;
if (KeyValue == "jsonrpc") {
// This should be "2.0". Always.
Version = dyn_cast<llvm::yaml::ScalarNode>(Value);
if (!Version || Version->getRawValue() != "\"2.0\"")
return false;
} else if (KeyValue == "method") {
Method = dyn_cast<llvm::yaml::ScalarNode>(Value);
} else if (KeyValue == "id") {
Id = dyn_cast<llvm::yaml::ScalarNode>(Value);
} else if (KeyValue == "params") {
if (!Method)
return false;
// We have to interleave the call of the function here, otherwise the
// YAMLParser will die because it can't go backwards. This is unfortunate
// because it will break clients that put the id after params. A possible
// fix would be to split the parsing and execution phases.
Params = dyn_cast<llvm::yaml::MappingNode>(Value);
callHandler(Handlers, Method, Id, Params, UnknownHandler, Out);
return true;
} else {
return false;
}
}
// In case there was a request with no params, call the handler on the
// leftovers.
if (!Method)
return false;
callHandler(Handlers, Method, Id, nullptr, UnknownHandler, Out);
return true;
}
void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
JSONRPCDispatcher &Dispatcher,
bool &IsDone) {
while (In.good()) {
// A Language Server Protocol message starts with a set of HTTP headers,
// delimited by \r\n, and terminated by an empty line (\r\n).
unsigned long long ContentLength = 0;
while (In.good()) {
std::string Line;
std::getline(In, Line);
if (!In.good() && errno == EINTR) {
In.clear();
continue;
}
Out.mirrorInput(Line);
// Mirror '\n' that gets consumed by std::getline, but is not included in
// the resulting Line.
// Note that '\r' is part of Line, so we don't need to mirror it
// separately.
if (!In.eof())
Out.mirrorInput("\n");
llvm::StringRef LineRef(Line);
// We allow YAML-style comments in headers. Technically this isn't part
// of the LSP specification, but makes writing tests easier.
if (LineRef.startswith("#"))
continue;
// Content-Type is a specified header, but does nothing.
// Content-Length is a mandatory header. It specifies the length of the
// following JSON.
// It is unspecified what sequence headers must be supplied in, so we
// allow any sequence.
// The end of headers is signified by an empty line.
if (LineRef.consume_front("Content-Length: ")) {
if (ContentLength != 0) {
Out.log("Warning: Duplicate Content-Length header received. "
"The previous value for this message (" +
std::to_string(ContentLength) + ") was ignored.\n");
}
llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
continue;
} else if (!LineRef.trim().empty()) {
// It's another header, ignore it.
continue;
} else {
// An empty line indicates the end of headers.
// Go ahead and read the JSON.
break;
}
}
if (ContentLength > 0) {
// Now read the JSON. Insert a trailing null byte as required by the YAML
// parser.
std::vector<char> JSON(ContentLength + 1, '\0');
In.read(JSON.data(), ContentLength);
Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
// If the stream is aborted before we read ContentLength bytes, In
// will have eofbit and failbit set.
if (!In) {
Out.log("Input was aborted. Read only " + std::to_string(In.gcount()) +
" bytes of expected " + std::to_string(ContentLength) + ".\n");
break;
}
llvm::StringRef JSONRef(JSON.data(), ContentLength);
// Log the message.
Out.log("<-- " + JSONRef + "\n");
// Finally, execute the action for this JSON message.
if (!Dispatcher.call(JSONRef, Out))
Out.log("JSON dispatch failed!\n");
// If we're done, exit the loop.
if (IsDone)
break;
} else {
Out.log("Warning: Missing Content-Length header, or message has zero "
"length.\n");
}
}
}
<commit_msg>[clangd] Harden clangd a bit against garbage input.<commit_after>//===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "JSONRPCDispatcher.h"
#include "ProtocolHandlers.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/YAMLParser.h"
#include <istream>
using namespace clang;
using namespace clangd;
void JSONOutput::writeMessage(const Twine &Message) {
llvm::SmallString<128> Storage;
StringRef M = Message.toStringRef(Storage);
std::lock_guard<std::mutex> Guard(StreamMutex);
// Log without headers.
Logs << "--> " << M << '\n';
Logs.flush();
// Emit message with header.
Outs << "Content-Length: " << M.size() << "\r\n\r\n" << M;
Outs.flush();
}
void JSONOutput::log(const Twine &Message) {
std::lock_guard<std::mutex> Guard(StreamMutex);
Logs << Message;
Logs.flush();
}
void JSONOutput::mirrorInput(const Twine &Message) {
if (!InputMirror)
return;
*InputMirror << Message;
InputMirror->flush();
}
void RequestContext::reply(const llvm::Twine &Result) {
if (ID.empty()) {
Out.log("Attempted to reply to a notification!\n");
return;
}
Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
R"(,"result":)" + Result + "}");
}
void RequestContext::replyError(int code, const llvm::StringRef &Message) {
Out.log("Error " + llvm::Twine(code) + ": " + Message + "\n");
if (!ID.empty()) {
Out.writeMessage(llvm::Twine(R"({"jsonrpc":"2.0","id":)") + ID +
R"(,"error":{"code":)" + llvm::Twine(code) +
R"(,"message":")" + llvm::yaml::escape(Message) +
R"("}})");
}
}
void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
assert(!Handlers.count(Method) && "Handler already registered!");
Handlers[Method] = std::move(H);
}
static void
callHandler(const llvm::StringMap<JSONRPCDispatcher::Handler> &Handlers,
llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,
llvm::yaml::MappingNode *Params,
const JSONRPCDispatcher::Handler &UnknownHandler, JSONOutput &Out) {
llvm::SmallString<64> MethodStorage;
auto I = Handlers.find(Method->getValue(MethodStorage));
auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Handler(RequestContext(Out, Id ? Id->getRawValue() : ""), Params);
}
bool JSONRPCDispatcher::call(StringRef Content, JSONOutput &Out) const {
llvm::SourceMgr SM;
llvm::yaml::Stream YAMLStream(Content, SM);
auto Doc = YAMLStream.begin();
if (Doc == YAMLStream.end())
return false;
auto *Object = dyn_cast_or_null<llvm::yaml::MappingNode>(Doc->getRoot());
if (!Object)
return false;
llvm::yaml::ScalarNode *Version = nullptr;
llvm::yaml::ScalarNode *Method = nullptr;
llvm::yaml::MappingNode *Params = nullptr;
llvm::yaml::ScalarNode *Id = nullptr;
for (auto &NextKeyValue : *Object) {
auto *KeyString =
dyn_cast_or_null<llvm::yaml::ScalarNode>(NextKeyValue.getKey());
if (!KeyString)
return false;
llvm::SmallString<10> KeyStorage;
StringRef KeyValue = KeyString->getValue(KeyStorage);
llvm::yaml::Node *Value = NextKeyValue.getValue();
if (!Value)
return false;
if (KeyValue == "jsonrpc") {
// This should be "2.0". Always.
Version = dyn_cast<llvm::yaml::ScalarNode>(Value);
if (!Version || Version->getRawValue() != "\"2.0\"")
return false;
} else if (KeyValue == "method") {
Method = dyn_cast<llvm::yaml::ScalarNode>(Value);
} else if (KeyValue == "id") {
Id = dyn_cast<llvm::yaml::ScalarNode>(Value);
} else if (KeyValue == "params") {
if (!Method)
return false;
// We have to interleave the call of the function here, otherwise the
// YAMLParser will die because it can't go backwards. This is unfortunate
// because it will break clients that put the id after params. A possible
// fix would be to split the parsing and execution phases.
Params = dyn_cast<llvm::yaml::MappingNode>(Value);
callHandler(Handlers, Method, Id, Params, UnknownHandler, Out);
return true;
} else {
return false;
}
}
// In case there was a request with no params, call the handler on the
// leftovers.
if (!Method)
return false;
callHandler(Handlers, Method, Id, nullptr, UnknownHandler, Out);
return true;
}
void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,
JSONRPCDispatcher &Dispatcher,
bool &IsDone) {
while (In.good()) {
// A Language Server Protocol message starts with a set of HTTP headers,
// delimited by \r\n, and terminated by an empty line (\r\n).
unsigned long long ContentLength = 0;
while (In.good()) {
std::string Line;
std::getline(In, Line);
if (!In.good() && errno == EINTR) {
In.clear();
continue;
}
Out.mirrorInput(Line);
// Mirror '\n' that gets consumed by std::getline, but is not included in
// the resulting Line.
// Note that '\r' is part of Line, so we don't need to mirror it
// separately.
if (!In.eof())
Out.mirrorInput("\n");
llvm::StringRef LineRef(Line);
// We allow YAML-style comments in headers. Technically this isn't part
// of the LSP specification, but makes writing tests easier.
if (LineRef.startswith("#"))
continue;
// Content-Type is a specified header, but does nothing.
// Content-Length is a mandatory header. It specifies the length of the
// following JSON.
// It is unspecified what sequence headers must be supplied in, so we
// allow any sequence.
// The end of headers is signified by an empty line.
if (LineRef.consume_front("Content-Length: ")) {
if (ContentLength != 0) {
Out.log("Warning: Duplicate Content-Length header received. "
"The previous value for this message (" +
std::to_string(ContentLength) + ") was ignored.\n");
}
llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
continue;
} else if (!LineRef.trim().empty()) {
// It's another header, ignore it.
continue;
} else {
// An empty line indicates the end of headers.
// Go ahead and read the JSON.
break;
}
}
if (ContentLength > 0) {
// Now read the JSON. Insert a trailing null byte as required by the YAML
// parser.
std::vector<char> JSON(ContentLength + 1, '\0');
In.read(JSON.data(), ContentLength);
Out.mirrorInput(StringRef(JSON.data(), In.gcount()));
// If the stream is aborted before we read ContentLength bytes, In
// will have eofbit and failbit set.
if (!In) {
Out.log("Input was aborted. Read only " + std::to_string(In.gcount()) +
" bytes of expected " + std::to_string(ContentLength) + ".\n");
break;
}
llvm::StringRef JSONRef(JSON.data(), ContentLength);
// Log the message.
Out.log("<-- " + JSONRef + "\n");
// Finally, execute the action for this JSON message.
if (!Dispatcher.call(JSONRef, Out))
Out.log("JSON dispatch failed!\n");
// If we're done, exit the loop.
if (IsDone)
break;
} else {
Out.log("Warning: Missing Content-Length header, or message has zero "
"length.\n");
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright 2013-present Barefoot Networks, 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 "bitvec.h"
#include "hex.h"
std::ostream &operator<<(std::ostream &os, const bitvec &bv) {
if (bv.size == 1) {
os << hex(bv.data);
} else {
bool first = true;
for (int i = bv.size-1; i >= 0; i--) {
if (first) {
if (!bv.ptr[i]) continue;
os << hex(bv.ptr[i]);
first = false;
} else {
os << hex(bv.ptr[i], sizeof(bv.data)*2, '0'); } }
if (first)
os << '0';
}
return os;
}
bitvec &bitvec::operator>>=(size_t count) {
if (size == 1) {
if (count >= bits_per_unit)
data = 0;
else
data >>= count;
return *this; }
int off = count / bits_per_unit;
count %= bits_per_unit;
for (size_t i = 0; i < size; i++)
if (i + off < size) {
ptr[i] = ptr[i+off] >> count;
if (count && i + off + 1 < size)
ptr[i] |= ptr[i+off+1] << (bits_per_unit - count);
} else {
ptr[i] = 0; }
while (size > 1 && !ptr[size-1]) size--;
if (size == 1) {
auto tmp = ptr[0];
delete [] ptr;
data = tmp; }
return *this;
}
bitvec &bitvec::operator<<=(size_t count) {
size_t needsize = (max().index() + count + bits_per_unit - 1)/bits_per_unit;
if (needsize > size) expand(needsize);
if (size == 1) {
data <<= count;
return *this; }
int off = count / bits_per_unit;
count %= bits_per_unit;
for (int i = size-1; i >= 0; i--)
if (i >= off) {
ptr[i] = ptr[i-off] << count;
if (count && i > off)
ptr[i] |= ptr[i-off-1] >> (bits_per_unit - count);
} else {
ptr[i] = 0; }
return *this;
}
bitvec bitvec::getslice(size_t idx, size_t sz) const {
if (idx >= size * bits_per_unit) return bitvec();
if (idx + sz > size * bits_per_unit)
sz = size * bits_per_unit - idx;
if (size > 1) {
bitvec rv;
unsigned shift = idx % bits_per_unit;
idx /= bits_per_unit;
if (sz > bits_per_unit) {
rv.expand((sz-1)/bits_per_unit + 1);
for (size_t i = 0; i < rv.size; i++) {
if (shift != 0 && i != 0)
rv.ptr[i-1] |= ptr[idx + 1] << (bits_per_unit - shift);
rv.ptr[i] = ptr[idx] >> shift; }
if ((sz %= bits_per_unit))
rv.ptr[rv.size-1] &= ~(~(uintptr_t)1 << (sz-1));
} else {
rv.data = ptr[idx] >> shift;
if (shift != 0 && idx + 1 < size)
rv.data |= ptr[idx + 1] << (bits_per_unit - shift);
rv.data &= ~(~(uintptr_t)1 << (sz-1)); }
return rv;
} else {
return bitvec((data >> idx) & ~(~(uintptr_t)1 << (sz-1))); }
}
int bitvec::ffs(unsigned start) const {
uintptr_t val = ~0ULL;
unsigned idx = start / bits_per_unit;
val <<= (start % bits_per_unit);
while (idx < size && !(val &= word(idx))) {
++idx;
val = ~0ULL; }
if (idx >= size) return -1;
unsigned rv = idx * bits_per_unit;
#if defined(__GNUC__) || defined(__clang__)
rv += builtin_ctz(val);
#else
while ((val & 0xff) == 0) { rv += 8; val >>= 8; }
while ((val & 1) == 0) { rv++; val >>= 1; }
#endif
return rv;
}
unsigned bitvec::ffz(unsigned start) const {
uintptr_t val = 0;
unsigned idx = start / bits_per_unit;
val = ~(~val << (start % bits_per_unit));
while (!~(val |= word(idx))) {
++idx;
val = 0; }
unsigned rv = idx * bits_per_unit;
#if defined(__GNUC__) || defined(__clang__)
rv += builtin_ctz(~val);
#else
while ((val & 0xff) == 0xff) { rv += 8; val >>= 8; }
while (val & 1) { rv++; val >>= 1; }
#endif
return rv;
}
bool bitvec::is_contiguous() const {
// Empty bitvec is not contiguous
if (empty())
return false;
return max().index() - min().index() + 1 == popcount();
}
<commit_msg>Adjusted getslice function of bitvec to return empty bitvec when the size requested is 0. (#744)<commit_after>/*
Copyright 2013-present Barefoot Networks, 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 "bitvec.h"
#include "hex.h"
std::ostream &operator<<(std::ostream &os, const bitvec &bv) {
if (bv.size == 1) {
os << hex(bv.data);
} else {
bool first = true;
for (int i = bv.size-1; i >= 0; i--) {
if (first) {
if (!bv.ptr[i]) continue;
os << hex(bv.ptr[i]);
first = false;
} else {
os << hex(bv.ptr[i], sizeof(bv.data)*2, '0'); } }
if (first)
os << '0';
}
return os;
}
bitvec &bitvec::operator>>=(size_t count) {
if (size == 1) {
if (count >= bits_per_unit)
data = 0;
else
data >>= count;
return *this; }
int off = count / bits_per_unit;
count %= bits_per_unit;
for (size_t i = 0; i < size; i++)
if (i + off < size) {
ptr[i] = ptr[i+off] >> count;
if (count && i + off + 1 < size)
ptr[i] |= ptr[i+off+1] << (bits_per_unit - count);
} else {
ptr[i] = 0; }
while (size > 1 && !ptr[size-1]) size--;
if (size == 1) {
auto tmp = ptr[0];
delete [] ptr;
data = tmp; }
return *this;
}
bitvec &bitvec::operator<<=(size_t count) {
size_t needsize = (max().index() + count + bits_per_unit - 1)/bits_per_unit;
if (needsize > size) expand(needsize);
if (size == 1) {
data <<= count;
return *this; }
int off = count / bits_per_unit;
count %= bits_per_unit;
for (int i = size-1; i >= 0; i--)
if (i >= off) {
ptr[i] = ptr[i-off] << count;
if (count && i > off)
ptr[i] |= ptr[i-off-1] >> (bits_per_unit - count);
} else {
ptr[i] = 0; }
return *this;
}
bitvec bitvec::getslice(size_t idx, size_t sz) const {
if (sz == 0) return bitvec();
if (idx >= size * bits_per_unit) return bitvec();
if (idx + sz > size * bits_per_unit)
sz = size * bits_per_unit - idx;
if (size > 1) {
bitvec rv;
unsigned shift = idx % bits_per_unit;
idx /= bits_per_unit;
if (sz > bits_per_unit) {
rv.expand((sz-1)/bits_per_unit + 1);
for (size_t i = 0; i < rv.size; i++) {
if (shift != 0 && i != 0)
rv.ptr[i-1] |= ptr[idx + 1] << (bits_per_unit - shift);
rv.ptr[i] = ptr[idx] >> shift; }
if ((sz %= bits_per_unit))
rv.ptr[rv.size-1] &= ~(~(uintptr_t)1 << (sz-1));
} else {
rv.data = ptr[idx] >> shift;
if (shift != 0 && idx + 1 < size)
rv.data |= ptr[idx + 1] << (bits_per_unit - shift);
rv.data &= ~(~(uintptr_t)1 << (sz-1)); }
return rv;
} else {
return bitvec((data >> idx) & ~(~(uintptr_t)1 << (sz-1))); }
}
int bitvec::ffs(unsigned start) const {
uintptr_t val = ~0ULL;
unsigned idx = start / bits_per_unit;
val <<= (start % bits_per_unit);
while (idx < size && !(val &= word(idx))) {
++idx;
val = ~0ULL; }
if (idx >= size) return -1;
unsigned rv = idx * bits_per_unit;
#if defined(__GNUC__) || defined(__clang__)
rv += builtin_ctz(val);
#else
while ((val & 0xff) == 0) { rv += 8; val >>= 8; }
while ((val & 1) == 0) { rv++; val >>= 1; }
#endif
return rv;
}
unsigned bitvec::ffz(unsigned start) const {
uintptr_t val = 0;
unsigned idx = start / bits_per_unit;
val = ~(~val << (start % bits_per_unit));
while (!~(val |= word(idx))) {
++idx;
val = 0; }
unsigned rv = idx * bits_per_unit;
#if defined(__GNUC__) || defined(__clang__)
rv += builtin_ctz(~val);
#else
while ((val & 0xff) == 0xff) { rv += 8; val >>= 8; }
while (val & 1) { rv++; val >>= 1; }
#endif
return rv;
}
bool bitvec::is_contiguous() const {
// Empty bitvec is not contiguous
if (empty())
return false;
return max().index() - min().index() + 1 == popcount();
}
<|endoftext|>
|
<commit_before>/*
utilities.cpp
KNode, the KDE newsreader
Copyright (c) 1999-2001 the KNode authors.
See file AUTHORS for details
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
*/
#include <qframe.h>
#include <qlayout.h>
#include <kconfig.h>
#include <klocale.h>
#include <kglobal.h>
#include <kmessagebox.h>
#include <kdialogbase.h>
#include <kdebug.h>
#include <kio/netaccess.h>
#include <ktempfile.h>
#include <kfiledialog.h>
#include "knlistbox.h"
#include "knglobals.h"
#include "utilities.h"
//================================================================================
KNFile::KNFile(const QString& fname)
: QFile(fname), filePos(0), readBytes(0)
{
buffer.resize(512);
dataPtr=buffer.data();
dataPtr[0]='\0';
}
KNFile::~KNFile()
{
}
const QCString& KNFile::readLine()
{
filePos=at();
readBytes=QFile::readLine(dataPtr, buffer.size()-1);
if(readBytes!=-1) {
while ((dataPtr[readBytes-1]!='\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { // don't get tricked by files without newline
at(filePos);
if (!increaseBuffer() ||
(readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {
readBytes=1;
break;
}
}
} else
readBytes=1;
dataPtr[readBytes-1] = '\0';
return buffer;
}
const QCString& KNFile::readLineWnewLine()
{
filePos=at();
readBytes=QFile::readLine(dataPtr, buffer.size()-1);
if(readBytes!=-1) {
while ((dataPtr[readBytes-1]!='\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { // don't get tricked by files without newline
at(filePos);
if (!increaseBuffer() ||
(readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {
dataPtr[0] = '\0';
break;
}
}
}
else dataPtr[0] = '\0';
return buffer;
}
int KNFile::findString(const char *s)
{
QCString searchBuffer;
searchBuffer.resize(2048);
char *buffPtr = searchBuffer.data(), *pos;
int readBytes, currentFilePos;
while (!atEnd()) {
currentFilePos = at();
readBytes = readBlock(buffPtr, 2047);
if (readBytes == -1)
return -1;
else
buffPtr[readBytes] = 0; // terminate string
pos = strstr(buffPtr,s);
if (pos == 0) {
if (!atEnd())
at(at()-strlen(s));
else
return -1;
} else {
return currentFilePos + (pos-buffPtr);
}
}
return -1;
}
bool KNFile::increaseBuffer()
{
if(buffer.resize(2*buffer.size())) {;
dataPtr=buffer.data();
dataPtr[0]='\0';
kdDebug(5003) << "KNFile::increaseBuffer() : buffer doubled" << endl;
return true;
}
else return false;
}
//===============================================================================
QString KNSaveHelper::lastPath;
KNSaveHelper::KNSaveHelper(QString saveName, QWidget *parent)
: p_arent(parent), s_aveName(saveName), file(0), tmpFile(0)
{
}
KNSaveHelper::~KNSaveHelper()
{
if (file) { // local filesystem, just close the file
delete file;
} else
if (tmpFile) { // network location, initiate transaction
tmpFile->close();
if (KIO::NetAccess::upload(tmpFile->name(),url) == false)
KNHelper::displayRemoteFileError();
tmpFile->unlink(); // delete temp file
delete tmpFile;
}
}
QFile* KNSaveHelper::getFile(QString dialogTitle)
{
if (lastPath.isEmpty())
lastPath = "file:/";
url = KFileDialog::getSaveURL(lastPath+s_aveName,QString::null,p_arent,dialogTitle);
if (url.isEmpty())
return 0;
lastPath = url.url(-1);
lastPath.truncate(lastPath.length()-url.fileName().length());
if (url.isLocalFile()) {
if (QFileInfo(url.path()).exists() &&
(KMessageBox::warningContinueCancel(knGlobals.topWidget,
i18n("A file named %1 already exists.\nDo you want to replace it?").arg(url.path()),
dialogTitle, i18n("&Replace")) != KMessageBox::Continue)) {
return 0;
}
file = new QFile(url.path());
if(!file->open(IO_WriteOnly)) {
KNHelper::displayExternalFileError();
delete file;
file = 0;
}
return file;
} else {
tmpFile = new KTempFile();
if (tmpFile->status()!=0) {
KNHelper::displayTempFileError();
delete tmpFile;
tmpFile = 0;
return 0;
}
return tmpFile->file();
}
}
//===============================================================================
QString KNLoadHelper::l_astPath;
KNLoadHelper::KNLoadHelper(QWidget *parent)
: p_arent(parent), f_ile(0)
{
}
KNLoadHelper::~KNLoadHelper()
{
delete f_ile;
if (!t_empName.isEmpty())
KIO::NetAccess::removeTempFile(t_empName);
}
KNFile* KNLoadHelper::getFile(QString dialogTitle)
{
if (f_ile)
return f_ile;
KURL url = KFileDialog::getOpenURL(l_astPath,QString::null,p_arent,dialogTitle);
if (url.isEmpty())
return 0;
l_astPath = url.url(-1);
l_astPath.truncate(l_astPath.length()-url.fileName().length());
return setURL(url);
}
KNFile* KNLoadHelper::setURL(KURL url)
{
if (f_ile)
return f_ile;
u_rl = url;
if (u_rl.isEmpty())
return 0;
QString fileName;
if (!u_rl.isLocalFile()) {
if (KIO::NetAccess::download(u_rl, t_empName))
fileName = t_empName;
} else
fileName = u_rl.path();
if (fileName.isEmpty())
return 0;
f_ile = new KNFile(fileName);
if(!f_ile->open(IO_ReadOnly)) {
KNHelper::displayExternalFileError();
delete f_ile;
f_ile = 0;
}
return f_ile;
}
//===============================================================================
// **** keyboard selection dialog *********************************************
int KNHelper::selectDialog(QWidget *parent, const QString &caption, const QStringList &options, int initialValue)
{
KDialogBase *dlg=new KDialogBase(KDialogBase::Plain, caption, KDialogBase::Ok|KDialogBase::Cancel,
KDialogBase::Ok, parent);
QFrame *page = dlg->plainPage();
QHBoxLayout *pageL = new QHBoxLayout(page,8,5);
KNDialogListBox *list = new KNDialogListBox(true, page);
pageL->addWidget(list);
QString s;
for ( QStringList::ConstIterator it = options.begin(); it != options.end(); ++it ) {
s = (*it);
s.replace(QRegExp("&"),""); // remove accelerators
list->insertItem(s);
}
list->setCurrentItem(initialValue);
list->setFocus();
restoreWindowSize("selectBox", dlg, QSize(247,174));
int ret;
if (dlg->exec())
ret = list->currentItem();
else
ret = -1;
saveWindowSize("selectBox", dlg->size());
delete dlg;
return ret;
}
// **** window geometry managing *********************************************
void KNHelper::saveWindowSize(const QString &name, const QSize &s)
{
KConfig *c=KGlobal::config();
c->setGroup("WINDOW_SIZES");
c->writeEntry(name, s);
}
void KNHelper::restoreWindowSize(const QString &name, QWidget *d, const QSize &defaultSize)
{
KConfig *c=KGlobal::config();
c->setGroup("WINDOW_SIZES");
QSize s=c->readSizeEntry(name,&defaultSize);
if(s.isValid()) d->resize(s);
}
// **** scramble password strings **********************************************
const QString KNHelper::encryptStr(const QString& aStr)
{
uint i,val,len = aStr.length();
QCString result;
for (i=0; i<len; i++)
{
val = aStr[i] - ' ';
val = (255-' ') - val;
result += (char)(val + ' ');
}
return result;
}
const QString KNHelper::decryptStr(const QString& aStr)
{
return encryptStr(aStr);
}
// **** rot13 *******************************************************************
QString KNHelper::rot13(const QString &s)
{
QString r(s);
for (int i=0; (uint)i<r.length(); i++) {
if ( r[i] >= QChar('A') && r[i] <= QChar('M') ||
r[i] >= QChar('a') && r[i] <= QChar('m') )
r[i] = (char)((int)QChar(r[i]) + 13);
else
if ( r[i] >= QChar('N') && r[i] <= QChar('Z') ||
r[i] >= QChar('n') && r[i] <= QChar('z') )
r[i] = (char)((int)QChar(r[i]) - 13);
}
return r;
}
// **** us-ascii check **********************************************************
bool KNHelper::isUsAscii(const QString &s)
{
for (uint i=0; i<s.length(); i++)
if (s.at(i).latin1()<=0) // c==0: non-latin1, c<0: non-us-ascii
return false;
return true;
}
// **** text rewraping *********************************************************
int findBreakPos(const QString &text, int start)
{
int i;
for(i=start;i>=0;i--)
if(text[i].isSpace())
break;
if(i>0)
return i;
for(i=start;i<(int)text.length();i++) // ok, the line is to long
if(text[i].isSpace())
break;
return i;
}
void appendTextWPrefix(QString &result, const QString &text, int wrapAt, const QString &prefix)
{
QString txt=text;
int breakPos;
while(!txt.isEmpty()) {
if((int)(prefix.length()+txt.length()) > wrapAt) {
breakPos=findBreakPos(txt,wrapAt-prefix.length());
result+=(prefix+txt.left(breakPos)+"\n");
txt.remove(0,breakPos+1);
} else {
result+=(prefix+txt+"\n");
txt=QString::null;
}
}
}
QString KNHelper::rewrapStringList(QStringList text, int wrapAt, QChar quoteChar, bool stopAtSig, bool alwaysSpace)
{
QString quoted, lastPrefix, thisPrefix, leftover, thisLine;
int breakPos;
for(QStringList::Iterator line=text.begin(); line!=text.end(); ++line) {
if(stopAtSig && (*line)=="-- ")
break;
thisLine=(*line);
if (!alwaysSpace && (thisLine[0]==quoteChar))
thisLine.prepend(quoteChar); // second quote level without space
else
thisLine.prepend(quoteChar+' ');
thisPrefix=QString::null;
QChar c;
for(int idx=0; idx<(int)(thisLine.length()); idx++) {
c=thisLine.at(idx);
if( (c==' ') ||
(c==quoteChar) || (c=='>') ||(c=='|') || (c==':') || (c=='#') || (c=='[') || (c=='{'))
thisPrefix.append(c);
else
break;
}
thisLine.remove(0,thisPrefix.length());
thisLine = thisLine.stripWhiteSpace();
if(!leftover.isEmpty()) { // don't break paragraphs, tables and quote levels
if(thisLine.isEmpty() || (thisPrefix!=lastPrefix) || thisLine.contains(" ") || thisLine.contains('\t'))
appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);
else
thisLine.prepend(leftover+" ");
leftover=QString::null;
}
if((int)(thisPrefix.length()+thisLine.length()) > wrapAt) {
breakPos=findBreakPos(thisLine,wrapAt-thisPrefix.length());
if(breakPos < (int)(thisLine.length())) {
leftover=thisLine.right(thisLine.length()-breakPos-1);
thisLine.truncate(breakPos);
}
}
quoted+=thisPrefix+thisLine+"\n";
lastPrefix=thisPrefix;
}
if (!leftover.isEmpty())
appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);
return quoted;
}
// **** misc. message-boxes **********************************************************
void KNHelper::displayInternalFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to load/save configuration!\nWrong permissions on home directory?\nYou should close KNode now to avoid data loss!"));
}
void KNHelper::displayExternalFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to load/save file!"));
}
void KNHelper::displayRemoteFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to save remote file!"));
}
void KNHelper::displayTempFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to create temporary file!"));
}
<commit_msg>fixed a broken hack in KNSaveHelper<commit_after>/*
utilities.cpp
KNode, the KDE newsreader
Copyright (c) 1999-2001 the KNode authors.
See file AUTHORS for details
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
*/
#include <qframe.h>
#include <qlayout.h>
#include <kconfig.h>
#include <klocale.h>
#include <kglobal.h>
#include <kmessagebox.h>
#include <kdialogbase.h>
#include <kdebug.h>
#include <kio/netaccess.h>
#include <ktempfile.h>
#include <kfiledialog.h>
#include "knlistbox.h"
#include "knglobals.h"
#include "utilities.h"
//================================================================================
KNFile::KNFile(const QString& fname)
: QFile(fname), filePos(0), readBytes(0)
{
buffer.resize(512);
dataPtr=buffer.data();
dataPtr[0]='\0';
}
KNFile::~KNFile()
{
}
const QCString& KNFile::readLine()
{
filePos=at();
readBytes=QFile::readLine(dataPtr, buffer.size()-1);
if(readBytes!=-1) {
while ((dataPtr[readBytes-1]!='\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { // don't get tricked by files without newline
at(filePos);
if (!increaseBuffer() ||
(readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {
readBytes=1;
break;
}
}
} else
readBytes=1;
dataPtr[readBytes-1] = '\0';
return buffer;
}
const QCString& KNFile::readLineWnewLine()
{
filePos=at();
readBytes=QFile::readLine(dataPtr, buffer.size()-1);
if(readBytes!=-1) {
while ((dataPtr[readBytes-1]!='\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { // don't get tricked by files without newline
at(filePos);
if (!increaseBuffer() ||
(readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {
dataPtr[0] = '\0';
break;
}
}
}
else dataPtr[0] = '\0';
return buffer;
}
int KNFile::findString(const char *s)
{
QCString searchBuffer;
searchBuffer.resize(2048);
char *buffPtr = searchBuffer.data(), *pos;
int readBytes, currentFilePos;
while (!atEnd()) {
currentFilePos = at();
readBytes = readBlock(buffPtr, 2047);
if (readBytes == -1)
return -1;
else
buffPtr[readBytes] = 0; // terminate string
pos = strstr(buffPtr,s);
if (pos == 0) {
if (!atEnd())
at(at()-strlen(s));
else
return -1;
} else {
return currentFilePos + (pos-buffPtr);
}
}
return -1;
}
bool KNFile::increaseBuffer()
{
if(buffer.resize(2*buffer.size())) {;
dataPtr=buffer.data();
dataPtr[0]='\0';
kdDebug(5003) << "KNFile::increaseBuffer() : buffer doubled" << endl;
return true;
}
else return false;
}
//===============================================================================
QString KNSaveHelper::lastPath;
KNSaveHelper::KNSaveHelper(QString saveName, QWidget *parent)
: p_arent(parent), s_aveName(saveName), file(0), tmpFile(0)
{
}
KNSaveHelper::~KNSaveHelper()
{
if (file) { // local filesystem, just close the file
delete file;
} else
if (tmpFile) { // network location, initiate transaction
tmpFile->close();
if (KIO::NetAccess::upload(tmpFile->name(),url) == false)
KNHelper::displayRemoteFileError();
tmpFile->unlink(); // delete temp file
delete tmpFile;
}
}
QFile* KNSaveHelper::getFile(QString dialogTitle)
{
if (lastPath.isEmpty())
lastPath = "file:/";
url = KFileDialog::getSaveURL(lastPath+s_aveName,QString::null,p_arent,dialogTitle);
if (url.isEmpty())
return 0;
lastPath = url.upURL().url();
if (url.isLocalFile()) {
if (QFileInfo(url.path()).exists() &&
(KMessageBox::warningContinueCancel(knGlobals.topWidget,
i18n("A file named %1 already exists.\nDo you want to replace it?").arg(url.path()),
dialogTitle, i18n("&Replace")) != KMessageBox::Continue)) {
return 0;
}
file = new QFile(url.path());
if(!file->open(IO_WriteOnly)) {
KNHelper::displayExternalFileError();
delete file;
file = 0;
}
return file;
} else {
tmpFile = new KTempFile();
if (tmpFile->status()!=0) {
KNHelper::displayTempFileError();
delete tmpFile;
tmpFile = 0;
return 0;
}
return tmpFile->file();
}
}
//===============================================================================
QString KNLoadHelper::l_astPath;
KNLoadHelper::KNLoadHelper(QWidget *parent)
: p_arent(parent), f_ile(0)
{
}
KNLoadHelper::~KNLoadHelper()
{
delete f_ile;
if (!t_empName.isEmpty())
KIO::NetAccess::removeTempFile(t_empName);
}
KNFile* KNLoadHelper::getFile(QString dialogTitle)
{
if (f_ile)
return f_ile;
KURL url = KFileDialog::getOpenURL(l_astPath,QString::null,p_arent,dialogTitle);
if (url.isEmpty())
return 0;
l_astPath = url.url(-1);
l_astPath.truncate(l_astPath.length()-url.fileName().length());
return setURL(url);
}
KNFile* KNLoadHelper::setURL(KURL url)
{
if (f_ile)
return f_ile;
u_rl = url;
if (u_rl.isEmpty())
return 0;
QString fileName;
if (!u_rl.isLocalFile()) {
if (KIO::NetAccess::download(u_rl, t_empName))
fileName = t_empName;
} else
fileName = u_rl.path();
if (fileName.isEmpty())
return 0;
f_ile = new KNFile(fileName);
if(!f_ile->open(IO_ReadOnly)) {
KNHelper::displayExternalFileError();
delete f_ile;
f_ile = 0;
}
return f_ile;
}
//===============================================================================
// **** keyboard selection dialog *********************************************
int KNHelper::selectDialog(QWidget *parent, const QString &caption, const QStringList &options, int initialValue)
{
KDialogBase *dlg=new KDialogBase(KDialogBase::Plain, caption, KDialogBase::Ok|KDialogBase::Cancel,
KDialogBase::Ok, parent);
QFrame *page = dlg->plainPage();
QHBoxLayout *pageL = new QHBoxLayout(page,8,5);
KNDialogListBox *list = new KNDialogListBox(true, page);
pageL->addWidget(list);
QString s;
for ( QStringList::ConstIterator it = options.begin(); it != options.end(); ++it ) {
s = (*it);
s.replace(QRegExp("&"),""); // remove accelerators
list->insertItem(s);
}
list->setCurrentItem(initialValue);
list->setFocus();
restoreWindowSize("selectBox", dlg, QSize(247,174));
int ret;
if (dlg->exec())
ret = list->currentItem();
else
ret = -1;
saveWindowSize("selectBox", dlg->size());
delete dlg;
return ret;
}
// **** window geometry managing *********************************************
void KNHelper::saveWindowSize(const QString &name, const QSize &s)
{
KConfig *c=KGlobal::config();
c->setGroup("WINDOW_SIZES");
c->writeEntry(name, s);
}
void KNHelper::restoreWindowSize(const QString &name, QWidget *d, const QSize &defaultSize)
{
KConfig *c=KGlobal::config();
c->setGroup("WINDOW_SIZES");
QSize s=c->readSizeEntry(name,&defaultSize);
if(s.isValid()) d->resize(s);
}
// **** scramble password strings **********************************************
const QString KNHelper::encryptStr(const QString& aStr)
{
uint i,val,len = aStr.length();
QCString result;
for (i=0; i<len; i++)
{
val = aStr[i] - ' ';
val = (255-' ') - val;
result += (char)(val + ' ');
}
return result;
}
const QString KNHelper::decryptStr(const QString& aStr)
{
return encryptStr(aStr);
}
// **** rot13 *******************************************************************
QString KNHelper::rot13(const QString &s)
{
QString r(s);
for (int i=0; (uint)i<r.length(); i++) {
if ( r[i] >= QChar('A') && r[i] <= QChar('M') ||
r[i] >= QChar('a') && r[i] <= QChar('m') )
r[i] = (char)((int)QChar(r[i]) + 13);
else
if ( r[i] >= QChar('N') && r[i] <= QChar('Z') ||
r[i] >= QChar('n') && r[i] <= QChar('z') )
r[i] = (char)((int)QChar(r[i]) - 13);
}
return r;
}
// **** us-ascii check **********************************************************
bool KNHelper::isUsAscii(const QString &s)
{
for (uint i=0; i<s.length(); i++)
if (s.at(i).latin1()<=0) // c==0: non-latin1, c<0: non-us-ascii
return false;
return true;
}
// **** text rewraping *********************************************************
int findBreakPos(const QString &text, int start)
{
int i;
for(i=start;i>=0;i--)
if(text[i].isSpace())
break;
if(i>0)
return i;
for(i=start;i<(int)text.length();i++) // ok, the line is to long
if(text[i].isSpace())
break;
return i;
}
void appendTextWPrefix(QString &result, const QString &text, int wrapAt, const QString &prefix)
{
QString txt=text;
int breakPos;
while(!txt.isEmpty()) {
if((int)(prefix.length()+txt.length()) > wrapAt) {
breakPos=findBreakPos(txt,wrapAt-prefix.length());
result+=(prefix+txt.left(breakPos)+"\n");
txt.remove(0,breakPos+1);
} else {
result+=(prefix+txt+"\n");
txt=QString::null;
}
}
}
QString KNHelper::rewrapStringList(QStringList text, int wrapAt, QChar quoteChar, bool stopAtSig, bool alwaysSpace)
{
QString quoted, lastPrefix, thisPrefix, leftover, thisLine;
int breakPos;
for(QStringList::Iterator line=text.begin(); line!=text.end(); ++line) {
if(stopAtSig && (*line)=="-- ")
break;
thisLine=(*line);
if (!alwaysSpace && (thisLine[0]==quoteChar))
thisLine.prepend(quoteChar); // second quote level without space
else
thisLine.prepend(quoteChar+' ');
thisPrefix=QString::null;
QChar c;
for(int idx=0; idx<(int)(thisLine.length()); idx++) {
c=thisLine.at(idx);
if( (c==' ') ||
(c==quoteChar) || (c=='>') ||(c=='|') || (c==':') || (c=='#') || (c=='[') || (c=='{'))
thisPrefix.append(c);
else
break;
}
thisLine.remove(0,thisPrefix.length());
thisLine = thisLine.stripWhiteSpace();
if(!leftover.isEmpty()) { // don't break paragraphs, tables and quote levels
if(thisLine.isEmpty() || (thisPrefix!=lastPrefix) || thisLine.contains(" ") || thisLine.contains('\t'))
appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);
else
thisLine.prepend(leftover+" ");
leftover=QString::null;
}
if((int)(thisPrefix.length()+thisLine.length()) > wrapAt) {
breakPos=findBreakPos(thisLine,wrapAt-thisPrefix.length());
if(breakPos < (int)(thisLine.length())) {
leftover=thisLine.right(thisLine.length()-breakPos-1);
thisLine.truncate(breakPos);
}
}
quoted+=thisPrefix+thisLine+"\n";
lastPrefix=thisPrefix;
}
if (!leftover.isEmpty())
appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);
return quoted;
}
// **** misc. message-boxes **********************************************************
void KNHelper::displayInternalFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to load/save configuration!\nWrong permissions on home directory?\nYou should close KNode now to avoid data loss!"));
}
void KNHelper::displayExternalFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to load/save file!"));
}
void KNHelper::displayRemoteFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to save remote file!"));
}
void KNHelper::displayTempFileError(QWidget *w)
{
KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n("Unable to create temporary file!"));
}
<|endoftext|>
|
<commit_before>#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define SZ(x) ((int)((x).size()))
#define PB(x) push_back(x);
#define INF (0x3f3f3f3f)
#define MEMSET(x,v) memset(x,v,sizeof(x));
typedef long long LL;
typedef pair<int, int> PII; typedef pair<PII, int> PII2;
typedef vector<int> VI; typedef vector<VI> VVI;
int main() {
return 0;
}
<commit_msg>Fixed DefaultCode.cpp<commit_after>#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define SZ(x) ((int)((x).size()))
#define PB(x) push_back(x)
#define INF (0x3f3f3f3f)
#define MEMSET(x,v) memset(x,v,sizeof(x))
typedef long long LL;
typedef pair<int, int> PII; typedef pair<PII, int> PII2;
int main() {
return 0;
}
<|endoftext|>
|
<commit_before>#include "tileManager.h"
#include "scene/scene.h"
#include "tile/mapTile.h"
#include "view/view.h"
#include <chrono>
#include <algorithm>
TileManager::TileManager() {
// Instantiate workers
for (size_t i = 0; i < MAX_WORKERS; i++) {
m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker()));
}
}
TileManager::TileManager(TileManager&& _other) :
m_view(std::move(_other.m_view)),
m_tileSet(std::move(_other.m_tileSet)),
m_dataSources(std::move(_other.m_dataSources)),
m_workers(std::move(_other.m_workers)),
m_queuedTiles(std::move(_other.m_queuedTiles)) {
}
TileManager::~TileManager() {
for (auto& worker : m_workers) {
if (!worker->isFree()) {
worker->abort();
worker->getTileResult();
}
// We stop all workers before we destroy the resources they use.
// TODO: This will wait for any pending network requests to finish,
// which could delay closing of the application.
}
m_dataSources.clear();
m_tileSet.clear();
}
void TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, DataSource* _source) {
std::lock_guard<std::mutex> lock(m_queueTileMutex);
m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(std::move(_rawData), _tileId, _source)));
}
void TileManager::addToWorkerQueue(std::shared_ptr<TileData>& _parsedData, const TileID& _tileID, DataSource* _source) {
std::lock_guard<std::mutex> lock(m_queueTileMutex);
m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(_parsedData, _tileID, _source)));
}
void TileManager::updateTileSet() {
m_tileSetChanged = false;
// Check if any native worker needs to be dispatched i.e. queuedTiles is not empty
{
auto workersIter = m_workers.begin();
auto queuedTilesIter = m_queuedTiles.begin();
while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) {
auto& worker = *workersIter;
if (worker->isFree()) {
worker->processTileData(std::move(*queuedTilesIter), m_scene->getStyles(), *m_view);
queuedTilesIter = m_queuedTiles.erase(queuedTilesIter);
}
++workersIter;
}
}
// Check if any incoming tiles are finished
for (auto& worker : m_workers) {
if (!worker->isFree() && worker->isFinished()) {
// Get result from worker and move it into tile set
auto tile = worker->getTileResult();
const TileID& id = tile->getID();
logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y);
std::swap(m_tileSet[id], tile);
cleanProxyTiles(id);
m_tileSetChanged = true;
}
}
if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) {
// No new tiles have come into view and no tiles have finished loading,
// so the tileset is unchanged
return;
}
const std::set<TileID>& visibleTiles = m_view->getVisibleTiles();
// Loop over visibleTiles and add any needed tiles to tileSet
{
auto setTilesIter = m_tileSet.begin();
auto visTilesIter = visibleTiles.begin();
while (visTilesIter != visibleTiles.end()) {
if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) {
// tileSet is missing an element present in visibleTiles
addTile(*visTilesIter);
m_tileSetChanged = true;
++visTilesIter;
} else if (setTilesIter->first < *visTilesIter) {
// visibleTiles is missing an element present in tileSet (handled below)
++setTilesIter;
} else {
// tiles in both sets match, move on
++setTilesIter;
++visTilesIter;
}
}
}
// Loop over tileSet and remove any tiles that are neither visible nor proxies
{
auto setTilesIter = m_tileSet.begin();
auto visTilesIter = visibleTiles.begin();
while (setTilesIter != m_tileSet.end()) {
if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) {
// visibleTiles is missing an element present in tileSet
if (setTilesIter->second->getProxyCounter() <= 0) {
removeTile(setTilesIter);
m_tileSetChanged = true;
} else {
++setTilesIter;
}
} else if (*visTilesIter < setTilesIter->first) {
// tileSet is missing an element present in visibleTiles (shouldn't occur)
++visTilesIter;
} else {
// tiles in both sets match, move on
++setTilesIter;
++visTilesIter;
}
}
}
}
void TileManager::addTile(const TileID& _tileID) {
std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection()));
m_tileSet[_tileID] = std::move(tile);
for (auto& source : m_dataSources) {
if (!source->loadTileData(_tileID, *this)) {
logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _tileID.z, _tileID.x, _tileID.y);
}
}
//Add Proxy if corresponding proxy MapTile ready
updateProxyTiles(_tileID, m_view->isZoomIn());
}
void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) {
const TileID& id = _tileIter->first;
// Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable
for(auto& dataSource : m_dataSources) {
dataSource->cancelLoadingTile(id);
cleanProxyTiles(id);
}
// Remove tile from queue, if present
const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(),
[&](std::unique_ptr<TileTask>& p) {
return (p->tileID == id);
});
if (found != m_queuedTiles.end()) {
logMsg("Erasing tile: [%d,%d,%d]\n", id.x, id.y, id.z);
m_queuedTiles.erase(found);
cleanProxyTiles(id);
}
// If a worker is processing this tile, abort it
for (const auto& worker : m_workers) {
if (!worker->isFree() && worker->getTileID() == id) {
worker->abort();
// Proxy tiles will be cleaned in update loop
}
}
// Remove tile from set
_tileIter = m_tileSet.erase(_tileIter);
}
void TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) {
if (_zoomingIn) {
// zoom in - add parent
const auto& parentID = _tileID.getParent();
const auto& parentTileIter = m_tileSet.find(parentID);
if (parentID.isValid() && parentTileIter != m_tileSet.end()) {
parentTileIter->second->incProxyCounter();
}
} else {
for(int i = 0; i < 4; i++) {
const auto& childID = _tileID.getChild(i);
const auto& childTileIter = m_tileSet.find(childID);
if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {
childTileIter->second->incProxyCounter();
}
}
}
}
void TileManager::cleanProxyTiles(const TileID& _tileID) {
// check if parent proxy is present
const auto& parentID = _tileID.getParent();
const auto& parentTileIter = m_tileSet.find(parentID);
if (parentID.isValid() && parentTileIter != m_tileSet.end()) {
parentTileIter->second->decProxyCounter();
}
// check if child proxies are present
for(int i = 0; i < 4; i++) {
const auto& childID = _tileID.getChild(i);
const auto& childTileIter = m_tileSet.find(childID);
if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {
childTileIter->second->decProxyCounter();
}
}
}
<commit_msg>one less log message.. HURRAY!!<commit_after>#include "tileManager.h"
#include "scene/scene.h"
#include "tile/mapTile.h"
#include "view/view.h"
#include <chrono>
#include <algorithm>
TileManager::TileManager() {
// Instantiate workers
for (size_t i = 0; i < MAX_WORKERS; i++) {
m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker()));
}
}
TileManager::TileManager(TileManager&& _other) :
m_view(std::move(_other.m_view)),
m_tileSet(std::move(_other.m_tileSet)),
m_dataSources(std::move(_other.m_dataSources)),
m_workers(std::move(_other.m_workers)),
m_queuedTiles(std::move(_other.m_queuedTiles)) {
}
TileManager::~TileManager() {
for (auto& worker : m_workers) {
if (!worker->isFree()) {
worker->abort();
worker->getTileResult();
}
// We stop all workers before we destroy the resources they use.
// TODO: This will wait for any pending network requests to finish,
// which could delay closing of the application.
}
m_dataSources.clear();
m_tileSet.clear();
}
void TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, DataSource* _source) {
std::lock_guard<std::mutex> lock(m_queueTileMutex);
m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(std::move(_rawData), _tileId, _source)));
}
void TileManager::addToWorkerQueue(std::shared_ptr<TileData>& _parsedData, const TileID& _tileID, DataSource* _source) {
std::lock_guard<std::mutex> lock(m_queueTileMutex);
m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(_parsedData, _tileID, _source)));
}
void TileManager::updateTileSet() {
m_tileSetChanged = false;
// Check if any native worker needs to be dispatched i.e. queuedTiles is not empty
{
auto workersIter = m_workers.begin();
auto queuedTilesIter = m_queuedTiles.begin();
while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) {
auto& worker = *workersIter;
if (worker->isFree()) {
worker->processTileData(std::move(*queuedTilesIter), m_scene->getStyles(), *m_view);
queuedTilesIter = m_queuedTiles.erase(queuedTilesIter);
}
++workersIter;
}
}
// Check if any incoming tiles are finished
for (auto& worker : m_workers) {
if (!worker->isFree() && worker->isFinished()) {
// Get result from worker and move it into tile set
auto tile = worker->getTileResult();
const TileID& id = tile->getID();
logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y);
std::swap(m_tileSet[id], tile);
cleanProxyTiles(id);
m_tileSetChanged = true;
}
}
if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) {
// No new tiles have come into view and no tiles have finished loading,
// so the tileset is unchanged
return;
}
const std::set<TileID>& visibleTiles = m_view->getVisibleTiles();
// Loop over visibleTiles and add any needed tiles to tileSet
{
auto setTilesIter = m_tileSet.begin();
auto visTilesIter = visibleTiles.begin();
while (visTilesIter != visibleTiles.end()) {
if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) {
// tileSet is missing an element present in visibleTiles
addTile(*visTilesIter);
m_tileSetChanged = true;
++visTilesIter;
} else if (setTilesIter->first < *visTilesIter) {
// visibleTiles is missing an element present in tileSet (handled below)
++setTilesIter;
} else {
// tiles in both sets match, move on
++setTilesIter;
++visTilesIter;
}
}
}
// Loop over tileSet and remove any tiles that are neither visible nor proxies
{
auto setTilesIter = m_tileSet.begin();
auto visTilesIter = visibleTiles.begin();
while (setTilesIter != m_tileSet.end()) {
if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) {
// visibleTiles is missing an element present in tileSet
if (setTilesIter->second->getProxyCounter() <= 0) {
removeTile(setTilesIter);
m_tileSetChanged = true;
} else {
++setTilesIter;
}
} else if (*visTilesIter < setTilesIter->first) {
// tileSet is missing an element present in visibleTiles (shouldn't occur)
++visTilesIter;
} else {
// tiles in both sets match, move on
++setTilesIter;
++visTilesIter;
}
}
}
}
void TileManager::addTile(const TileID& _tileID) {
std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection()));
m_tileSet[_tileID] = std::move(tile);
for (auto& source : m_dataSources) {
if (!source->loadTileData(_tileID, *this)) {
logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _tileID.z, _tileID.x, _tileID.y);
}
}
//Add Proxy if corresponding proxy MapTile ready
updateProxyTiles(_tileID, m_view->isZoomIn());
}
void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) {
const TileID& id = _tileIter->first;
// Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable
for(auto& dataSource : m_dataSources) {
dataSource->cancelLoadingTile(id);
cleanProxyTiles(id);
}
// Remove tile from queue, if present
const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(),
[&](std::unique_ptr<TileTask>& p) {
return (p->tileID == id);
});
if (found != m_queuedTiles.end()) {
m_queuedTiles.erase(found);
cleanProxyTiles(id);
}
// If a worker is processing this tile, abort it
for (const auto& worker : m_workers) {
if (!worker->isFree() && worker->getTileID() == id) {
worker->abort();
// Proxy tiles will be cleaned in update loop
}
}
// Remove tile from set
_tileIter = m_tileSet.erase(_tileIter);
}
void TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) {
if (_zoomingIn) {
// zoom in - add parent
const auto& parentID = _tileID.getParent();
const auto& parentTileIter = m_tileSet.find(parentID);
if (parentID.isValid() && parentTileIter != m_tileSet.end()) {
parentTileIter->second->incProxyCounter();
}
} else {
for(int i = 0; i < 4; i++) {
const auto& childID = _tileID.getChild(i);
const auto& childTileIter = m_tileSet.find(childID);
if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {
childTileIter->second->incProxyCounter();
}
}
}
}
void TileManager::cleanProxyTiles(const TileID& _tileID) {
// check if parent proxy is present
const auto& parentID = _tileID.getParent();
const auto& parentTileIter = m_tileSet.find(parentID);
if (parentID.isValid() && parentTileIter != m_tileSet.end()) {
parentTileIter->second->decProxyCounter();
}
// check if child proxies are present
for(int i = 0; i < 4; i++) {
const auto& childID = _tileID.getChild(i);
const auto& childTileIter = m_tileSet.find(childID);
if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {
childTileIter->second->decProxyCounter();
}
}
}
<|endoftext|>
|
<commit_before>/*
* ContextToGL.cpp
*
* Copyright (C) 2021 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "mmcore/view/ContextToGL.h"
#include "mmcore/utility/log/Log.h"
namespace megamol::core::view {
using utility::log::Log;
ContextToGL::ContextToGL(void)
: Renderer3DModuleGL()
, _getContextSlot("getContext", "Slot for non-GL context")
{
this->_getContextSlot.SetCompatibleCall<core::view::CallRender3DDescription>();
this->MakeSlotAvailable(&this->_getContextSlot);
}
ContextToGL::~ContextToGL(void) {
this->Release();
}
bool ContextToGL::create(void) {
if (!_utils.isInitialized()) {
if (!_utils.InitPrimitiveRendering(this->GetCoreInstance()->ShaderSourceFactory())) {
Log::DefaultLog.WriteError("[ContextToGL] Unable to initialize RenderUtility.");
}
}
return true;
}
void ContextToGL::release(void) {
}
bool ContextToGL::GetExtents(CallRender3DGL& call) {
auto cr = _getContextSlot.CallAs<CallRender3D>();
if (cr == nullptr) return false;
// no copy constructor available
auto cast_in = dynamic_cast<AbstractCallRender*>(&call);
auto cast_out = dynamic_cast<AbstractCallRender*>(cr);
*cast_out = *cast_in;
if (!_framebuffer) {
_framebuffer = std::make_shared<CPUFramebuffer>();
}
cr->SetFramebuffer(_framebuffer);
(*cr)(view::CallRender3D::FnGetExtents);
call.AccessBoundingBoxes() = cr->AccessBoundingBoxes();
call.SetTimeFramesCount(cr->TimeFramesCount());
return true;
}
bool ContextToGL::Render(CallRender3DGL& call) {
auto cr = _getContextSlot.CallAs<CallRender3D>();
if (cr == nullptr) return false;
// no copy constructor available
auto cast_in = dynamic_cast<AbstractCallRender*>(&call);
auto cast_out = dynamic_cast<AbstractCallRender*>(cr);
*cast_out = *cast_in;
if (!_framebuffer) {
_framebuffer = std::make_shared<CPUFramebuffer>();
}
cr->SetFramebuffer(_framebuffer);
(*cr)(view::CallRender3D::FnRender);
Camera_2 cam;
call.GetCamera(cam);
cam_type::snapshot_type snapshot;
cam_type::matrix_type viewTemp, projTemp;
// Generate complete snapshot and calculate matrices
cam.calc_matrices(snapshot, viewTemp, projTemp, core::thecam::snapshot_content::all);
auto width = cam.resolution_gate().width();
auto height = cam.resolution_gate().height();
auto lhs_fbo = call.GetFramebufferObject();
if (lhs_fbo != NULL) {
// module own fbo
auto new_fbo = vislib::graphics::gl::FramebufferObject();
new_fbo.Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,
vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);
new_fbo.Enable();
new_fbo.BindColourTexture();
glClear(GL_COLOR_BUFFER_BIT);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _framebuffer->colorBuffer.data());
glBindTexture(GL_TEXTURE_2D, 0);
if (_framebuffer->depthBufferActive) {
new_fbo.BindDepthTexture();
glClear(GL_DEPTH_BUFFER_BIT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
_framebuffer->depthBuffer.data());
glBindTexture(GL_TEXTURE_2D, 0);
}
float right = (width + static_cast<float>(width)) / 2.0f;
float left = (width - static_cast<float>(width)) / 2.0f;
float bottom = (height + static_cast<float>(height)) / 2.0f;
float up = (height - static_cast<float>(height)) / 2.0f;
glm::vec3 pos_bottom_left = {left, bottom, 0.0f};
glm::vec3 pos_upper_left = {left, up, 0.0f};
glm::vec3 pos_upper_right = {right, up, 0.0f};
glm::vec3 pos_bottom_right = {right, bottom, 0.0f};
_utils.Push2DColorTexture(
new_fbo.GetColourTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right,true);
if (_framebuffer->depthBufferActive) {
_utils.Push2DDepthTexture(
new_fbo.GetDepthTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right, true);
}
new_fbo.Disable();
// draw into lhs fbo
if ((lhs_fbo->GetWidth() != width) || (lhs_fbo->GetHeight() != height)) {
lhs_fbo->Release();
lhs_fbo->Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,
vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);
}
if (lhs_fbo->IsValid() && !lhs_fbo->IsEnabled()) {
lhs_fbo->Enable();
}
glm::mat4 ortho = glm::ortho(0.0f, static_cast<float>(width), 0.0f, static_cast<float>(height), -1.0f, 1.0f);
_utils.DrawTextures(ortho, glm::vec2(width, height));
if (lhs_fbo->IsValid()) {
lhs_fbo->Disable();
}
} else {
return false;
}
return true;
}
} // namespace megamol::core::view
<commit_msg>forward input events<commit_after>/*
* ContextToGL.cpp
*
* Copyright (C) 2021 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "mmcore/view/ContextToGL.h"
#include "mmcore/utility/log/Log.h"
namespace megamol::core::view {
using utility::log::Log;
ContextToGL::ContextToGL(void)
: Renderer3DModuleGL()
, _getContextSlot("getContext", "Slot for non-GL context")
{
this->_getContextSlot.SetCompatibleCall<core::view::CallRender3DDescription>();
this->MakeSlotAvailable(&this->_getContextSlot);
}
ContextToGL::~ContextToGL(void) {
this->Release();
}
bool ContextToGL::create(void) {
if (!_utils.isInitialized()) {
if (!_utils.InitPrimitiveRendering(this->GetCoreInstance()->ShaderSourceFactory())) {
Log::DefaultLog.WriteError("[ContextToGL] Unable to initialize RenderUtility.");
}
}
return true;
}
void ContextToGL::release(void) {
}
bool ContextToGL::GetExtents(CallRender3DGL& call) {
auto cr = _getContextSlot.CallAs<CallRender3D>();
if (cr == nullptr) return false;
// no copy constructor available
auto cast_in = dynamic_cast<AbstractCallRender*>(&call);
auto cast_out = dynamic_cast<AbstractCallRender*>(cr);
*cast_out = *cast_in;
if (!_framebuffer) {
_framebuffer = std::make_shared<CPUFramebuffer>();
}
cr->SetFramebuffer(_framebuffer);
(*cr)(view::CallRender3D::FnGetExtents);
call.AccessBoundingBoxes() = cr->AccessBoundingBoxes();
call.SetTimeFramesCount(cr->TimeFramesCount());
return true;
}
bool ContextToGL::Render(CallRender3DGL& call) {
auto cr = _getContextSlot.CallAs<CallRender3D>();
if (cr == nullptr) return false;
// no copy constructor available
auto cast_in = dynamic_cast<AbstractCallRender*>(&call);
auto cast_out = dynamic_cast<AbstractCallRender*>(cr);
*cast_out = *cast_in;
if (!_framebuffer) {
_framebuffer = std::make_shared<CPUFramebuffer>();
}
cr->SetFramebuffer(_framebuffer);
cr->SetInputEvent(call.GetInputEvent());
auto const& ie = cr->GetInputEvent();
switch (ie.tag) {
case InputEvent::Tag::Char: {
(*cr)(view::CallRender3D::FnOnChar);
} break;
case InputEvent::Tag::Key: {
(*cr)(view::CallRender3D::FnOnKey);
} break;
case InputEvent::Tag::MouseButton: {
(*cr)(view::CallRender3D::FnOnMouseButton);
} break;
case InputEvent::Tag::MouseMove: {
(*cr)(view::CallRender3D::FnOnMouseMove);
} break;
case InputEvent::Tag::MouseScroll: {
(*cr)(view::CallRender3D::FnOnMouseScroll);
} break;
}
(*cr)(view::CallRender3D::FnRender);
Camera_2 cam;
call.GetCamera(cam);
cam_type::snapshot_type snapshot;
cam_type::matrix_type viewTemp, projTemp;
// Generate complete snapshot and calculate matrices
cam.calc_matrices(snapshot, viewTemp, projTemp, core::thecam::snapshot_content::all);
auto width = cam.resolution_gate().width();
auto height = cam.resolution_gate().height();
auto lhs_fbo = call.GetFramebufferObject();
if (lhs_fbo != NULL) {
// module own fbo
auto new_fbo = vislib::graphics::gl::FramebufferObject();
new_fbo.Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,
vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);
new_fbo.Enable();
new_fbo.BindColourTexture();
glClear(GL_COLOR_BUFFER_BIT);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _framebuffer->colorBuffer.data());
glBindTexture(GL_TEXTURE_2D, 0);
if (_framebuffer->depthBufferActive) {
new_fbo.BindDepthTexture();
glClear(GL_DEPTH_BUFFER_BIT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
_framebuffer->depthBuffer.data());
glBindTexture(GL_TEXTURE_2D, 0);
}
float right = (width + static_cast<float>(width)) / 2.0f;
float left = (width - static_cast<float>(width)) / 2.0f;
float bottom = (height + static_cast<float>(height)) / 2.0f;
float up = (height - static_cast<float>(height)) / 2.0f;
glm::vec3 pos_bottom_left = {left, bottom, 0.0f};
glm::vec3 pos_upper_left = {left, up, 0.0f};
glm::vec3 pos_upper_right = {right, up, 0.0f};
glm::vec3 pos_bottom_right = {right, bottom, 0.0f};
_utils.Push2DColorTexture(
new_fbo.GetColourTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right,true);
if (_framebuffer->depthBufferActive) {
_utils.Push2DDepthTexture(
new_fbo.GetDepthTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right, true);
}
new_fbo.Disable();
// draw into lhs fbo
if ((lhs_fbo->GetWidth() != width) || (lhs_fbo->GetHeight() != height)) {
lhs_fbo->Release();
lhs_fbo->Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,
vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);
}
if (lhs_fbo->IsValid() && !lhs_fbo->IsEnabled()) {
lhs_fbo->Enable();
}
glm::mat4 ortho = glm::ortho(0.0f, static_cast<float>(width), 0.0f, static_cast<float>(height), -1.0f, 1.0f);
_utils.DrawTextures(ortho, glm::vec2(width, height));
if (lhs_fbo->IsValid()) {
lhs_fbo->Disable();
}
} else {
return false;
}
return true;
}
} // namespace megamol::core::view
<|endoftext|>
|
<commit_before>//
// C++ Interface: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef _BUILTIN_FUNCS_HPP
#define _BUILTIN_FUNCS_HPP
#include "Common.hpp"
#include "Func.hpp"
#include <cmath>
#include <cstdlib>
#include <cassert>
#include "RandomNumberGenerators.hpp"
/* Wrappers for all the builtin functions
The arg_list pointer is a list of floats. Its
size is equal to the number of arguments the parameter
takes */
class FuncWrappers {
/* Values to optimize the sigmoid function */
static const int R = 32767;
static const int RR = 65534;
public:
static inline float int_wrapper(float * arg_list) {
return floor(arg_list[0]);
}
static inline float sqr_wrapper(float * arg_list) {
return pow(arg_list[0], 2);
}
static inline float sigmoid_wrapper(float * arg_list)
{
const double t = (1+exp(-arg_list[0]*arg_list[1]));
return (fabs(t) > 0.00001) ? 1.0/t : 0;
}
static inline float sign_wrapper(float * arg_list) {
return -arg_list[0];
}
static inline float min_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[1];
return arg_list[0];
}
static inline float max_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[0];
return arg_list[1];
}
static inline float bor_wrapper(float * arg_list) {
return (float)((int)arg_list[0] || (int)arg_list[1]);
}
static inline float band_wrapper(float * arg_list) {
return (float)((int)arg_list[0] && (int)arg_list[1]);
}
static inline float bnot_wrapper(float * arg_list) {
return (float)(!(int)arg_list[0]);
}
static inline float if_wrapper(float * arg_list) {
if ((int)arg_list[0] == 0)
return arg_list[2];
//std::cout <<"NOT ZERO: " << arg_list[0] << std::endl;
return arg_list[1];
}
static inline float rand_wrapper(float * arg_list) {
float l=1;
// printf("RAND ARG:(%d)\n", (int)arg_list[0]);
if ((int)arg_list[0] > 0)
l = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);
return l;
}
static inline float equal_wrapper(float * arg_list) {
return (arg_list[0] == arg_list[1]);
}
static inline float above_wrapper(float * arg_list) {
return (arg_list[0] > arg_list[1]);
}
static inline float below_wrapper(float * arg_list) {
return (arg_list[0] < arg_list[1]);
}
static float sin_wrapper(float * arg_list) {
const float d = sinf(*arg_list);
return d;
}
static inline float cos_wrapper(float * arg_list) {
return (cos (arg_list[0]));
}
static inline float tan_wrapper(float * arg_list) {
return (tan(arg_list[0]));
}
static inline float asin_wrapper(float * arg_list) {
return (asin (arg_list[0]));
}
static inline float acos_wrapper(float * arg_list) {
return (acos (arg_list[0]));
}
static inline float atan_wrapper(float * arg_list) {
return (atan (arg_list[0]));
}
static inline float atan2_wrapper(float * arg_list) {
return (atan2 (arg_list[0], arg_list[1]));
}
static inline float pow_wrapper(float * arg_list) {
return (pow (arg_list[0], arg_list[1]));
}
static inline float exp_wrapper(float * arg_list) {
return (exp(arg_list[0]));
}
static inline float abs_wrapper(float * arg_list) {
return (fabs(arg_list[0]));
}
static inline float log_wrapper(float* arg_list) {
return (log (arg_list[0]));
}
static inline float log10_wrapper(float * arg_list) {
return (log10 (arg_list[0]));
}
static inline float sqrt_wrapper(float * arg_list) {
return (sqrt (arg_list[0]));
}
static inline float print_wrapper(float * arg_list) {
int len = sizeof(arg_list)/sizeof(float);
for (int i = 0; i < len; i++)
{
std::cout << arg_list[0];
if (i != (len-1))
std::cout << " ";
}
if (len > 0)
std::cout << std::endl;
if (len > 0)
return arg_list[0];
else
return 0;
}
static inline float nchoosek_wrapper(float * arg_list) {
unsigned long cnm = 1UL;
int i, f;
int n, m;
n = (int)arg_list[0];
m = (int)arg_list[1];
if (m*2 >n) m = n-m;
for (i=1 ; i <= m; n--, i++)
{
if ((f=n) % i == 0)
f /= i;
else cnm /= i;
cnm *= f;
}
return (float)cnm;
}
static inline float fact_wrapper(float * arg_list) {
int result = 1;
int n = (int)arg_list[0];
while (n > 1) {
result = result * n;
n--;
}
return (float)result;
}
};
#include <map>
class BuiltinFuncs {
public:
static int init_builtin_func_db();
static int destroy_builtin_func_db();
static int load_all_builtin_func();
static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );
static int insert_func( Func *func );
static int remove_func( Func *func );
static Func *find_func( const std::string & name );
private:
static std::map<std::string, Func*> builtin_func_tree;
static volatile bool initialized;
};
#endif
<commit_msg>typo<commit_after>//
// C++ Interface: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef _BUILTIN_FUNCS_HPP
#define _BUILTIN_FUNCS_HPP
#include "Common.hpp"
#include "Func.hpp"
#include <cmath>
#include <cstdlib>
#include <cassert>
#include "RandomNumberGenerators.hpp"
/* Wrappers for all the builtin functions
The arg_list pointer is a list of floats. Its
size is equal to the number of arguments the parameter
takes */
class FuncWrappers {
/* Values to optimize the sigmoid function */
static const int R = 32767;
static const int RR = 65534;
public:
static inline float int_wrapper(float * arg_list) {
return floor(arg_list[0]);
}
static inline float sqr_wrapper(float * arg_list) {
return pow(arg_list[0], 2);
}
static inline float sigmoid_wrapper(float * arg_list)
{
const double t = (1+exp(-arg_list[0]*arg_list[1]));
return (fabs(t) > 0.00001) ? 1.0/t : 0;
}
static inline float sign_wrapper(float * arg_list) {
return -arg_list[0];
}
static inline float min_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[1];
return arg_list[0];
}
static inline float max_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[0];
return arg_list[1];
}
static inline float bor_wrapper(float * arg_list) {
return (float)((int)arg_list[0] || (int)arg_list[1]);
}
static inline float band_wrapper(float * arg_list) {
return (float)((int)arg_list[0] && (int)arg_list[1]);
}
static inline float bnot_wrapper(float * arg_list) {
return (float)(!(int)arg_list[0]);
}
static inline float if_wrapper(float * arg_list) {
if ((int)arg_list[0] == 0)
return arg_list[2];
//std::cout <<"NOT ZERO: " << arg_list[0] << std::endl;
return arg_list[1];
}
static inline float rand_wrapper(float * arg_list) {
float l=1;
// printf("RAND ARG:(%d)\n", (int)arg_list[0]);
if ((int)arg_list[0] > 0)
l = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);
return l;
}
static inline float equal_wrapper(float * arg_list) {
return (arg_list[0] == arg_list[1]);
}
static inline float above_wrapper(float * arg_list) {
return (arg_list[0] > arg_list[1]);
}
static inline float below_wrapper(float * arg_list) {
return (arg_list[0] < arg_list[1]);
}
static float sin_wrapper(float * arg_list) {
const float d = sinf(*arg_list);
return d;
}
static inline float cos_wrapper(float * arg_list) {
return (cos (arg_list[0]));
}
static inline float tan_wrapper(float * arg_list) {
return (tan(arg_list[0]));
}
static inline float asin_wrapper(float * arg_list) {
return (asin (arg_list[0]));
}
static inline float acos_wrapper(float * arg_list) {
return (acos (arg_list[0]));
}
static inline float atan_wrapper(float * arg_list) {
return (atan (arg_list[0]));
}
static inline float atan2_wrapper(float * arg_list) {
return (atan2 (arg_list[0], arg_list[1]));
}
static inline float pow_wrapper(float * arg_list) {
return (pow (arg_list[0], arg_list[1]));
}
static inline float exp_wrapper(float * arg_list) {
return (exp(arg_list[0]));
}
static inline float abs_wrapper(float * arg_list) {
return (fabs(arg_list[0]));
}
static inline float log_wrapper(float* arg_list) {
return (log (arg_list[0]));
}
static inline float log10_wrapper(float * arg_list) {
return (log10 (arg_list[0]));
}
static inline float sqrt_wrapper(float * arg_list) {
return (sqrt (arg_list[0]));
}
static inline float print_wrapper(float * arg_list) {
int len = sizeof(arg_list)/sizeof(float);
for (int i = 0; i < len; i++)
{
std::cout << arg_list[i];
if (i != (len-1))
std::cout << " ";
}
if (len > 0)
std::cout << std::endl;
if (len > 0)
return arg_list[0];
else
return 0;
}
static inline float nchoosek_wrapper(float * arg_list) {
unsigned long cnm = 1UL;
int i, f;
int n, m;
n = (int)arg_list[0];
m = (int)arg_list[1];
if (m*2 >n) m = n-m;
for (i=1 ; i <= m; n--, i++)
{
if ((f=n) % i == 0)
f /= i;
else cnm /= i;
cnm *= f;
}
return (float)cnm;
}
static inline float fact_wrapper(float * arg_list) {
int result = 1;
int n = (int)arg_list[0];
while (n > 1) {
result = result * n;
n--;
}
return (float)result;
}
};
#include <map>
class BuiltinFuncs {
public:
static int init_builtin_func_db();
static int destroy_builtin_func_db();
static int load_all_builtin_func();
static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );
static int insert_func( Func *func );
static int remove_func( Func *func );
static Func *find_func( const std::string & name );
private:
static std::map<std::string, Func*> builtin_func_tree;
static volatile bool initialized;
};
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
*
* 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 "spriterenderercomponent.h"
#include <texture.h>
#include <game.h>
#include "graphics/item.h"
#include "graphics/engine.h"
#include "graphics/material.h"
#include "graphics/mesh.h"
#include "graphics/materialinstance.h"
#include "engine/gameobject.h"
#include "engine/asset.h"
#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>
#include <QtCore/QMimeData>
#include <QtCore/QVariant>
REGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent )
using namespace GluonEngine;
class SpriteRendererComponent::SpriteRendererComponentPrivate
{
public:
SpriteRendererComponentPrivate()
{
item = 0;
texture = 0;
material = 0;
size = QSizeF( 1.0f, 1.0f );
color.setRgb( 255, 255, 255 );
}
GluonGraphics::Item* item;
GluonEngine::Asset* texture;
GluonGraphics::MaterialInstance* material;
QColor color;
QSizeF size;
};
SpriteRendererComponent::SpriteRendererComponent( QObject* parent )
: Component( parent )
, d( new SpriteRendererComponentPrivate )
{
}
SpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other )
: Component( other )
, d( other.d )
{
}
SpriteRendererComponent::~SpriteRendererComponent()
{
delete d;
}
QString SpriteRendererComponent::category() const
{
return QString( "Graphics Rendering" );
}
void SpriteRendererComponent::initialize()
{
if( !d->item )
{
d->item = GluonGraphics::Engine::instance()->createItem( "default" );
}
if( d->material )
{
Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() );
if( materialAsset )
materialAsset->load();
Asset* texture = 0;
if( d->material->property( "texture0" ).type() == QVariant::String )
texture = gameProject()->findChild<Asset*>( d->material->property( "texture0" ).toString() );
else
texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( "texture0" ) ) );
if( texture )
texture->load();
d->item->setMaterialInstance( d->material );
}
}
void SpriteRendererComponent::start()
{
}
void SpriteRendererComponent::draw( int timeLapse )
{
Q_UNUSED( timeLapse )
if( d->item )
{
QMatrix4x4 transform = gameObject()->transform();
transform.scale( d->size.width() / 2, d->size.height() / 2 );
d->item->setTransform( transform );
}
}
void SpriteRendererComponent::cleanup()
{
if( d->item )
{
GluonGraphics::Engine::instance()->destroyItem( d->item );
d->item = 0;
}
}
void SpriteRendererComponent::setSize( const QSizeF& size )
{
d->size = size;
}
QSizeF SpriteRendererComponent::size()
{
return d->size;
}
GluonGraphics::MaterialInstance*
SpriteRendererComponent::material()
{
return d->material;
}
void SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material )
{
d->material = material;
if( d->item )
{
if(material)
{
d->item->setMaterialInstance( material );
}
else
{
d->item->setMaterialInstance(GluonGraphics::Engine::instance()->material("default")->instance("default"));
}
}
}
void SpriteRendererComponent::setMaterial( const QString& path )
{
setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) );
}
Q_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent );
#include "spriterenderercomponent.moc"
<commit_msg>Add name sanitizing to the string based texture asset locator<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
*
* 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 "spriterenderercomponent.h"
#include <texture.h>
#include <game.h>
#include "graphics/item.h"
#include "graphics/engine.h"
#include "graphics/material.h"
#include "graphics/mesh.h"
#include "graphics/materialinstance.h"
#include "engine/gameobject.h"
#include "engine/asset.h"
#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>
#include <QtCore/QMimeData>
#include <QtCore/QVariant>
REGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent )
using namespace GluonEngine;
class SpriteRendererComponent::SpriteRendererComponentPrivate
{
public:
SpriteRendererComponentPrivate()
{
item = 0;
texture = 0;
material = 0;
size = QSizeF( 1.0f, 1.0f );
color.setRgb( 255, 255, 255 );
}
GluonGraphics::Item* item;
GluonEngine::Asset* texture;
GluonGraphics::MaterialInstance* material;
QColor color;
QSizeF size;
};
SpriteRendererComponent::SpriteRendererComponent( QObject* parent )
: Component( parent )
, d( new SpriteRendererComponentPrivate )
{
}
SpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other )
: Component( other )
, d( other.d )
{
}
SpriteRendererComponent::~SpriteRendererComponent()
{
delete d;
}
QString SpriteRendererComponent::category() const
{
return QString( "Graphics Rendering" );
}
void SpriteRendererComponent::initialize()
{
if( !d->item )
{
d->item = GluonGraphics::Engine::instance()->createItem( "default" );
}
if( d->material )
{
Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() );
if( materialAsset )
materialAsset->load();
Asset* texture = 0;
if( d->material->property( "texture0" ).type() == QVariant::String )
{
QString theName( d->material->property( "texture0" ).toString() );
QString theObjectName = GluonObject::nameToObjectName( theName );
texture = gameProject()->findChild<Asset*>( theObjectName );
if(!texture)
debug( QString( "Texture failed to load - attempted to load texture named %1" ).arg( theName ) );
}
else
texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( "texture0" ) ) );
if( texture )
texture->load();
d->item->setMaterialInstance( d->material );
}
}
void SpriteRendererComponent::start()
{
}
void SpriteRendererComponent::draw( int timeLapse )
{
Q_UNUSED( timeLapse )
if( d->item )
{
QMatrix4x4 transform = gameObject()->transform();
transform.scale( d->size.width() / 2, d->size.height() / 2 );
d->item->setTransform( transform );
}
}
void SpriteRendererComponent::cleanup()
{
if( d->item )
{
GluonGraphics::Engine::instance()->destroyItem( d->item );
d->item = 0;
}
}
void SpriteRendererComponent::setSize( const QSizeF& size )
{
d->size = size;
}
QSizeF SpriteRendererComponent::size()
{
return d->size;
}
GluonGraphics::MaterialInstance*
SpriteRendererComponent::material()
{
return d->material;
}
void SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material )
{
d->material = material;
if( d->item )
{
if(material)
{
d->item->setMaterialInstance( material );
}
else
{
d->item->setMaterialInstance(GluonGraphics::Engine::instance()->material("default")->instance("default"));
}
}
}
void SpriteRendererComponent::setMaterial( const QString& path )
{
setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) );
}
Q_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent );
#include "spriterenderercomponent.moc"
<|endoftext|>
|
<commit_before>/*
broadcaststatus.cpp
This file is part of KDEPIM.
Author: Don Sanders <sanders@kde.org>
Copyright (C) 2000 Don Sanders <sanders@kde.org>
License GPL
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qdatetime.h>
#include <klocale.h>
#include <kglobal.h>
#include "broadcaststatus.h"
#include "progressmanager.h"
KPIM::BroadcastStatus* KPIM::BroadcastStatus::instance_ = 0;
namespace KPIM {
BroadcastStatus* BroadcastStatus::instance()
{
if (!instance_)
instance_ = new BroadcastStatus();
return instance_;
}
BroadcastStatus::BroadcastStatus()
{
}
void BroadcastStatus::setStatusMsg( const QString& message )
{
mStatusMsg = message;
if( !mTransientActive )
emit statusMsg( message );
}
void BroadcastStatus::setStatusMsgWithTimestamp( const QString& message )
{
KLocale* locale = KGlobal::locale();
setStatusMsg( i18n( "%1 is a time, %2 is a status message", "[%1] %2" )
.arg( locale->formatTime( QTime::currentTime(),
true /* with seconds */ ) )
.arg( message ) );
}
void BroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer,
KPIM::ProgressItem* item )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission complete. %n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission complete. %n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 );
else
statusMsg = i18n( "Transmission complete. %n message in %1 KB.",
"Transmission complete. %n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 );
}
else
statusMsg = i18n( "Transmission complete. %n new message.",
"Transmission complete. %n new messages.",
numMessages );
}
else
statusMsg = i18n( "Transmission complete. No new messages." );
setStatusMsgWithTimestamp( statusMsg );
if ( item )
item->setStatus( statusMsg );
}
void BroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,
int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer,
KPIM::ProgressItem* item )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission for account %3 complete. "
"%n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission for account %3 complete. "
"%n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 )
.arg( account );
else
statusMsg = i18n( "Transmission for account %2 complete. "
"%n message in %1 KB.",
"Transmission for account %2 complete. "
"%n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. "
"%n new message.",
"Transmission for account %1 complete. "
"%n new messages.",
numMessages )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. No new messages.")
.arg( account );
setStatusMsgWithTimestamp( statusMsg );
if ( item )
item->setStatus( statusMsg );
}
void BroadcastStatus::setTransientStatusMsg( const QString& msg )
{
mTransientActive = true;
emit statusMsg( msg );
}
void BroadcastStatus::reset()
{
mTransientActive = false;
// restore
emit statusMsg( mStatusMsg );
}
}
#include "broadcaststatus.moc"
<commit_msg>Introduced a new bool member and didn't initialize it. Bad Till. No cookie for me tonight.<commit_after>/*
broadcaststatus.cpp
This file is part of KDEPIM.
Author: Don Sanders <sanders@kde.org>
Copyright (C) 2000 Don Sanders <sanders@kde.org>
License GPL
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qdatetime.h>
#include <klocale.h>
#include <kglobal.h>
#include "broadcaststatus.h"
#include "progressmanager.h"
KPIM::BroadcastStatus* KPIM::BroadcastStatus::instance_ = 0;
namespace KPIM {
BroadcastStatus* BroadcastStatus::instance()
{
if (!instance_)
instance_ = new BroadcastStatus();
return instance_;
}
BroadcastStatus::BroadcastStatus()
:mTransientActive( false )
{
}
void BroadcastStatus::setStatusMsg( const QString& message )
{
mStatusMsg = message;
if( !mTransientActive )
emit statusMsg( message );
}
void BroadcastStatus::setStatusMsgWithTimestamp( const QString& message )
{
KLocale* locale = KGlobal::locale();
setStatusMsg( i18n( "%1 is a time, %2 is a status message", "[%1] %2" )
.arg( locale->formatTime( QTime::currentTime(),
true /* with seconds */ ) )
.arg( message ) );
}
void BroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer,
KPIM::ProgressItem* item )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission complete. %n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission complete. %n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 );
else
statusMsg = i18n( "Transmission complete. %n message in %1 KB.",
"Transmission complete. %n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 );
}
else
statusMsg = i18n( "Transmission complete. %n new message.",
"Transmission complete. %n new messages.",
numMessages );
}
else
statusMsg = i18n( "Transmission complete. No new messages." );
setStatusMsgWithTimestamp( statusMsg );
if ( item )
item->setStatus( statusMsg );
}
void BroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,
int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer,
KPIM::ProgressItem* item )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission for account %3 complete. "
"%n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission for account %3 complete. "
"%n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 )
.arg( account );
else
statusMsg = i18n( "Transmission for account %2 complete. "
"%n message in %1 KB.",
"Transmission for account %2 complete. "
"%n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. "
"%n new message.",
"Transmission for account %1 complete. "
"%n new messages.",
numMessages )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. No new messages.")
.arg( account );
setStatusMsgWithTimestamp( statusMsg );
if ( item )
item->setStatus( statusMsg );
}
void BroadcastStatus::setTransientStatusMsg( const QString& msg )
{
mTransientActive = true;
emit statusMsg( msg );
}
void BroadcastStatus::reset()
{
mTransientActive = false;
// restore
emit statusMsg( mStatusMsg );
}
}
#include "broadcaststatus.moc"
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit 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 "DataManager.h"
#include "OrbitBase/Logging.h"
#include "OrbitClientData/ModuleData.h"
#include "OrbitClientData/ProcessData.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
using orbit_client_protos::FunctionInfo;
using orbit_grpc_protos::ModuleInfo;
using orbit_grpc_protos::ProcessInfo;
using orbit_grpc_protos::TracepointInfo;
void DataManager::UpdateProcessInfos(const std::vector<ProcessInfo>& process_infos) {
CHECK(std::this_thread::get_id() == main_thread_id_);
// Note that at this point the data manager does not remove old processes.
// To do it correctly we may need to implement some callback logic here
// since the ProcessData can be in use by some views.
for (const ProcessInfo& info : process_infos) {
int32_t process_id = info.pid();
auto it = process_map_.find(process_id);
if (it != process_map_.end()) {
it->second.SetProcessInfo(info);
} else {
auto [inserted_it, success] = process_map_.try_emplace(process_id, info);
CHECK(success);
}
}
}
void DataManager::UpdateModuleInfos(int32_t process_id,
const std::vector<ModuleInfo>& module_infos) {
CHECK(std::this_thread::get_id() == main_thread_id_);
auto process_it = process_map_.find(process_id);
CHECK(process_it != process_map_.end());
ProcessData& process = process_it->second;
for (const auto& module_info : module_infos) {
auto module_it = module_map_.find(module_info.file_path());
if (module_it == module_map_.end()) {
const auto [inserted_it, success] = module_map_.try_emplace(
module_info.file_path(), std::make_unique<ModuleData>(module_info));
CHECK(success);
} else {
ModuleData* module = (*module_it).second.get();
if (!module->is_loaded()) continue;
// When a module is already loaded (has loaded symbols), it could be the case that the
// modules base address changed. Since the module base address is *currently* saved in
// FunctionInfo, these need to be updated.
// TODO(169309553): As soon as module base address is not part of FunctionInfo anymore, remove
// the following.
if (module_info.address_start() != process.GetModuleBaseAddress(module->file_path())) {
module->UpdateFunctionsModuleBaseAddress(module_info.address_start());
}
}
}
process.UpdateModuleInfos(module_infos);
}
void DataManager::SelectFunction(const FunctionInfo& function) {
CHECK(std::this_thread::get_id() == main_thread_id_);
if (!selected_functions_.contains(function)) {
selected_functions_.insert(function);
}
}
void DataManager::DeselectFunction(const FunctionInfo& function) {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_functions_.erase(function);
}
void DataManager::set_visible_functions(absl::flat_hash_set<uint64_t> visible_functions) {
CHECK(std::this_thread::get_id() == main_thread_id_);
visible_functions_ = std::move(visible_functions);
}
void DataManager::set_selected_thread_id(int32_t thread_id) {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_thread_id_ = thread_id;
}
bool DataManager::IsFunctionVisible(uint64_t function_address) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return visible_functions_.contains(function_address);
}
int32_t DataManager::selected_thread_id() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_thread_id_;
}
const TextBox* DataManager::selected_text_box() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_text_box_;
}
void DataManager::set_selected_text_box(const TextBox* text_box) {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_text_box_ = text_box;
}
void DataManager::ClearSelectedFunctions() {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_functions_.clear();
}
const ProcessData* DataManager::GetProcessByPid(int32_t process_id) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
auto it = process_map_.find(process_id);
if (it == process_map_.end()) {
return nullptr;
}
return &it->second;
}
const ModuleData* DataManager::GetModuleByPath(const std::string& path) const {
return GetMutableModuleByPath(path);
}
ModuleData* DataManager::GetMutableModuleByPath(const std::string& path) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
auto it = module_map_.find(path);
if (it == module_map_.end()) {
return nullptr;
}
return it->second.get();
}
bool DataManager::IsFunctionSelected(const FunctionInfo& function) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_functions_.contains(function);
}
std::vector<FunctionInfo> DataManager::GetSelectedFunctions() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return std::vector<FunctionInfo>(selected_functions_.begin(), selected_functions_.end());
}
std::vector<FunctionInfo> DataManager::GetSelectedAndOrbitFunctions() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
CHECK(selected_process_ != nullptr);
std::vector<FunctionInfo> result = GetSelectedFunctions();
// Collect OrbitFunctions
for (const auto& [module_path, _] : selected_process_->GetMemoryMap()) {
const ModuleData* module = module_map_.at(module_path).get();
if (!module->is_loaded()) continue;
const std::vector<FunctionInfo>& orbit_functions = module->GetOrbitFunctions();
result.insert(result.end(), orbit_functions.begin(), orbit_functions.end());
}
return result;
}
void DataManager::set_selected_process(int32_t pid) {
CHECK(std::this_thread::get_id() == main_thread_id_);
const ProcessData* process = GetProcessByPid(pid);
CHECK(process != nullptr);
selected_process_ = process;
}
const ProcessData* DataManager::selected_process() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_process_;
}
void DataManager::SelectTracepoint(const TracepointInfo& info) {
if (!IsTracepointSelected(info)) selected_tracepoints_.emplace(info);
}
void DataManager::DeselectTracepoint(const TracepointInfo& info) {
CHECK(IsTracepointSelected(info));
selected_tracepoints_.erase(info);
}
bool DataManager::IsTracepointSelected(const TracepointInfo& info) const {
return selected_tracepoints_.contains(info);
}
const TracepointInfoSet& DataManager::selected_tracepoints() const { return selected_tracepoints_; }
const ModuleData* DataManager::FindModuleByAddress(int32_t process_id, uint64_t absolute_address) {
CHECK(std::this_thread::get_id() == main_thread_id_);
const ProcessData* process = GetProcessByPid(process_id);
if (process == nullptr) return nullptr;
const auto& result = process->FindModuleByAddress(absolute_address);
if (!result) return nullptr;
const std::string& module_path = result.value().first;
return module_map_.at(module_path).get();
}
const FunctionInfo* DataManager::FindFunctionByAddress(int32_t process_id,
uint64_t absolute_address,
bool is_exact) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
const ProcessData* process = GetProcessByPid(process_id);
if (process == nullptr) return nullptr;
const auto& result = process->FindModuleByAddress(absolute_address);
if (!result) return nullptr;
const std::string& module_path = result.value().first;
const uint64_t module_base_address = result.value().second;
const ModuleData* module = module_map_.at(module_path).get();
const uint64_t relative_address = absolute_address - module_base_address;
return module->FindFunctionByRelativeAddress(relative_address, is_exact);
}
[[nodiscard]] absl::flat_hash_map<std::string, ModuleData*> DataManager::GetModulesLoadedByProcess(
const ProcessData* process) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
absl::flat_hash_map<std::string, ModuleData*> result;
for (const auto& [module_path, _] : process->GetMemoryMap()) {
result[module_path] = module_map_.at(module_path).get();
}
return result;
}<commit_msg>Fix crash because of wrong order in DataManager<commit_after>// Copyright (c) 2020 The Orbit 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 "DataManager.h"
#include "OrbitBase/Logging.h"
#include "OrbitClientData/ModuleData.h"
#include "OrbitClientData/ProcessData.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
using orbit_client_protos::FunctionInfo;
using orbit_grpc_protos::ModuleInfo;
using orbit_grpc_protos::ProcessInfo;
using orbit_grpc_protos::TracepointInfo;
void DataManager::UpdateProcessInfos(const std::vector<ProcessInfo>& process_infos) {
CHECK(std::this_thread::get_id() == main_thread_id_);
// Note that at this point the data manager does not remove old processes.
// To do it correctly we may need to implement some callback logic here
// since the ProcessData can be in use by some views.
for (const ProcessInfo& info : process_infos) {
int32_t process_id = info.pid();
auto it = process_map_.find(process_id);
if (it != process_map_.end()) {
it->second.SetProcessInfo(info);
} else {
auto [inserted_it, success] = process_map_.try_emplace(process_id, info);
CHECK(success);
}
}
}
void DataManager::UpdateModuleInfos(int32_t process_id,
const std::vector<ModuleInfo>& module_infos) {
CHECK(std::this_thread::get_id() == main_thread_id_);
auto process_it = process_map_.find(process_id);
CHECK(process_it != process_map_.end());
ProcessData& process = process_it->second;
process.UpdateModuleInfos(module_infos);
for (const auto& module_info : module_infos) {
auto module_it = module_map_.find(module_info.file_path());
if (module_it == module_map_.end()) {
const auto [inserted_it, success] = module_map_.try_emplace(
module_info.file_path(), std::make_unique<ModuleData>(module_info));
CHECK(success);
} else {
ModuleData* module = (*module_it).second.get();
if (!module->is_loaded()) continue;
// When a module is already loaded (has loaded symbols), it could be the case that the
// modules base address changed. Since the module base address is *currently* saved in
// FunctionInfo, these need to be updated.
// TODO(169309553): As soon as module base address is not part of FunctionInfo anymore, remove
// the following.
if (module_info.address_start() != process.GetModuleBaseAddress(module->file_path())) {
module->UpdateFunctionsModuleBaseAddress(module_info.address_start());
}
}
}
}
void DataManager::SelectFunction(const FunctionInfo& function) {
CHECK(std::this_thread::get_id() == main_thread_id_);
if (!selected_functions_.contains(function)) {
selected_functions_.insert(function);
}
}
void DataManager::DeselectFunction(const FunctionInfo& function) {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_functions_.erase(function);
}
void DataManager::set_visible_functions(absl::flat_hash_set<uint64_t> visible_functions) {
CHECK(std::this_thread::get_id() == main_thread_id_);
visible_functions_ = std::move(visible_functions);
}
void DataManager::set_selected_thread_id(int32_t thread_id) {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_thread_id_ = thread_id;
}
bool DataManager::IsFunctionVisible(uint64_t function_address) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return visible_functions_.contains(function_address);
}
int32_t DataManager::selected_thread_id() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_thread_id_;
}
const TextBox* DataManager::selected_text_box() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_text_box_;
}
void DataManager::set_selected_text_box(const TextBox* text_box) {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_text_box_ = text_box;
}
void DataManager::ClearSelectedFunctions() {
CHECK(std::this_thread::get_id() == main_thread_id_);
selected_functions_.clear();
}
const ProcessData* DataManager::GetProcessByPid(int32_t process_id) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
auto it = process_map_.find(process_id);
if (it == process_map_.end()) {
return nullptr;
}
return &it->second;
}
const ModuleData* DataManager::GetModuleByPath(const std::string& path) const {
return GetMutableModuleByPath(path);
}
ModuleData* DataManager::GetMutableModuleByPath(const std::string& path) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
auto it = module_map_.find(path);
if (it == module_map_.end()) {
return nullptr;
}
return it->second.get();
}
bool DataManager::IsFunctionSelected(const FunctionInfo& function) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_functions_.contains(function);
}
std::vector<FunctionInfo> DataManager::GetSelectedFunctions() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return std::vector<FunctionInfo>(selected_functions_.begin(), selected_functions_.end());
}
std::vector<FunctionInfo> DataManager::GetSelectedAndOrbitFunctions() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
CHECK(selected_process_ != nullptr);
std::vector<FunctionInfo> result = GetSelectedFunctions();
// Collect OrbitFunctions
for (const auto& [module_path, _] : selected_process_->GetMemoryMap()) {
const ModuleData* module = module_map_.at(module_path).get();
if (!module->is_loaded()) continue;
const std::vector<FunctionInfo>& orbit_functions = module->GetOrbitFunctions();
result.insert(result.end(), orbit_functions.begin(), orbit_functions.end());
}
return result;
}
void DataManager::set_selected_process(int32_t pid) {
CHECK(std::this_thread::get_id() == main_thread_id_);
const ProcessData* process = GetProcessByPid(pid);
CHECK(process != nullptr);
selected_process_ = process;
}
const ProcessData* DataManager::selected_process() const {
CHECK(std::this_thread::get_id() == main_thread_id_);
return selected_process_;
}
void DataManager::SelectTracepoint(const TracepointInfo& info) {
if (!IsTracepointSelected(info)) selected_tracepoints_.emplace(info);
}
void DataManager::DeselectTracepoint(const TracepointInfo& info) {
CHECK(IsTracepointSelected(info));
selected_tracepoints_.erase(info);
}
bool DataManager::IsTracepointSelected(const TracepointInfo& info) const {
return selected_tracepoints_.contains(info);
}
const TracepointInfoSet& DataManager::selected_tracepoints() const { return selected_tracepoints_; }
const ModuleData* DataManager::FindModuleByAddress(int32_t process_id, uint64_t absolute_address) {
CHECK(std::this_thread::get_id() == main_thread_id_);
const ProcessData* process = GetProcessByPid(process_id);
if (process == nullptr) return nullptr;
const auto& result = process->FindModuleByAddress(absolute_address);
if (!result) return nullptr;
const std::string& module_path = result.value().first;
return module_map_.at(module_path).get();
}
const FunctionInfo* DataManager::FindFunctionByAddress(int32_t process_id,
uint64_t absolute_address,
bool is_exact) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
const ProcessData* process = GetProcessByPid(process_id);
if (process == nullptr) return nullptr;
const auto& result = process->FindModuleByAddress(absolute_address);
if (!result) return nullptr;
const std::string& module_path = result.value().first;
const uint64_t module_base_address = result.value().second;
const ModuleData* module = module_map_.at(module_path).get();
const uint64_t relative_address = absolute_address - module_base_address;
return module->FindFunctionByRelativeAddress(relative_address, is_exact);
}
[[nodiscard]] absl::flat_hash_map<std::string, ModuleData*> DataManager::GetModulesLoadedByProcess(
const ProcessData* process) const {
CHECK(std::this_thread::get_id() == main_thread_id_);
absl::flat_hash_map<std::string, ModuleData*> result;
for (const auto& [module_path, _] : process->GetMemoryMap()) {
result[module_path] = module_map_.at(module_path).get();
}
return result;
}<|endoftext|>
|
<commit_before>
#pragma once
#include "ksp_plugin/part.hpp"
#include <list>
#include <string>
#include "base/array.hpp"
#include "base/hexadecimal.hpp"
#include "base/not_null.hpp"
namespace principia {
namespace ksp_plugin {
namespace internal_part {
using base::Array;
using base::HexadecimalEncode;
using base::make_not_null_unique;
using base::UniqueBytes;
Part::Part(
PartId const part_id,
std::string const& name,
Mass const& mass,
DegreesOfFreedom<Barycentric> const& degrees_of_freedom,
std::function<void()> deletion_callback)
: part_id_(part_id),
name_(name),
mass_(mass),
degrees_of_freedom_(degrees_of_freedom),
tail_(make_not_null_unique<DiscreteTrajectory<Barycentric>>()),
subset_node_(make_not_null_unique<Subset<Part>::Node>()),
deletion_callback_(std::move(deletion_callback)) {}
Part::~Part() {
LOG(INFO) << "Destroying part " << ShortDebugString();
CHECK(!is_piled_up());
if (deletion_callback_ != nullptr) {
deletion_callback_();
}
}
PartId Part::part_id() const {
return part_id_;
}
void Part::set_mass(Mass const& mass) {
mass_ = mass;
}
Mass const& Part::mass() const {
return mass_;
}
void Part::clear_intrinsic_force() {
intrinsic_force_ = Vector<Force, Barycentric>{};
}
void Part::increment_intrinsic_force(
Vector<Force, Barycentric> const& intrinsic_force) {
intrinsic_force_ += intrinsic_force;
}
Vector<Force, Barycentric> const& Part::intrinsic_force() const {
return intrinsic_force_;
}
void Part::set_degrees_of_freedom(
DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {
degrees_of_freedom_ = degrees_of_freedom;
}
DegreesOfFreedom<Barycentric> const&
Part::degrees_of_freedom() const {
return degrees_of_freedom_;
}
DiscreteTrajectory<Barycentric>& Part::tail() {
return *tail_;
}
DiscreteTrajectory<Barycentric> const& Part::tail() const {
return *tail_;
}
bool Part::tail_is_authoritative() const {
return tail_is_authoritative_;
}
void Part::set_tail_is_authoritative(bool const tail_is_authoritative) {
tail_is_authoritative_ = tail_is_authoritative;
}
void Part::set_containing_pile_up(IteratorOn<std::list<PileUp>> const pile_up) {
CHECK(!is_piled_up());
LOG(INFO) << "Adding part " << ShortDebugString() << " to the pile up at "
<< &*pile_up.iterator();
containing_pile_up_ = pile_up;
}
std::experimental::optional<IteratorOn<std::list<PileUp>>>
Part::containing_pile_up() const {
return containing_pile_up_;
}
bool Part::is_piled_up() const {
// TODO(egg): |has_value()| once we have a standard |optional|.
return static_cast<bool>(containing_pile_up_);
}
void Part::clear_pile_up() {
if (is_piled_up()) {
IteratorOn<std::list<PileUp>> pile_up = *containing_pile_up_;
for (not_null<Part*> const part : pile_up.iterator()->parts()) {
LOG(INFO) << "Removing part " << part->ShortDebugString()
<< " from its pile up at " << &*pile_up.iterator();
part->containing_pile_up_ = std::experimental::nullopt;
}
CHECK(!is_piled_up());
pile_up.Erase();
}
}
void Part::WriteToMessage(not_null<serialization::Part*> const message) const {
message->set_part_id(part_id_);
message->set_name(name_);
mass_.WriteToMessage(message->mutable_mass());
intrinsic_force_.WriteToMessage(message->mutable_intrinsic_force());
if (containing_pile_up_) {
message->set_containing_pile_up(containing_pile_up_->distance_from_begin());
}
degrees_of_freedom_.WriteToMessage(message->mutable_degrees_of_freedom());
tail_->WriteToMessage(message->mutable_tail(), /*forks=*/{});
message->set_tail_is_authoritative(tail_is_authoritative_);
}
not_null<std::unique_ptr<Part>> Part::ReadFromMessage(
serialization::Part const& message,
std::function<void()> deletion_callback) {
not_null<std::unique_ptr<Part>> part =
make_not_null_unique<Part>(message.part_id(),
message.name(),
Mass::ReadFromMessage(message.mass()),
DegreesOfFreedom<Barycentric>::ReadFromMessage(
message.degrees_of_freedom()),
std::move(deletion_callback));
part->increment_intrinsic_force(
Vector<Force, Barycentric>::ReadFromMessage(message.intrinsic_force()));
part->tail_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(message.tail(),
/*forks=*/{});
part->set_tail_is_authoritative(message.tail_is_authoritative());
return part;
}
void Part::FillContainingPileUpFromMessage(
serialization::Part const& message,
not_null<std::list<PileUp>*> const pile_ups) {
if (message.has_containing_pile_up()) {
auto it = pile_ups->begin();
std::advance(it, message.containing_pile_up());
containing_pile_up_ = IteratorOn<std::list<PileUp>>(pile_ups, it);
}
}
std::string Part::ShortDebugString() const {
UniqueBytes hex_id(sizeof(part_id_) * 2 + 1);
Array<std::uint8_t const> id_bytes(
reinterpret_cast<std::uint8_t const*>(&part_id_), sizeof(part_id_));
HexadecimalEncode(id_bytes, hex_id.get());
hex_id.data[sizeof(part_id_) * 2] = '\0';
return name_ + " (" + reinterpret_cast<char const*>(hex_id.data.get()) + ")";
}
std::ostream& operator<<(std::ostream& out, Part const& part) {
return out << "{"
<< part.part_id() << ", "
<< part.mass() << "}";
}
} // namespace internal_part
} // namespace ksp_plugin
} // namespace principia
<commit_msg>to the nearest tonne, how much does this Kerbal weigh?<commit_after>
#pragma once
#include "ksp_plugin/part.hpp"
#include <list>
#include <string>
#include "base/array.hpp"
#include "base/hexadecimal.hpp"
#include "base/not_null.hpp"
namespace principia {
namespace ksp_plugin {
namespace internal_part {
using base::Array;
using base::HexadecimalEncode;
using base::make_not_null_unique;
using base::UniqueBytes;
Part::Part(
PartId const part_id,
std::string const& name,
Mass const& mass,
DegreesOfFreedom<Barycentric> const& degrees_of_freedom,
std::function<void()> deletion_callback)
: part_id_(part_id),
name_(name),
mass_(mass),
degrees_of_freedom_(degrees_of_freedom),
tail_(make_not_null_unique<DiscreteTrajectory<Barycentric>>()),
subset_node_(make_not_null_unique<Subset<Part>::Node>()),
deletion_callback_(std::move(deletion_callback)) {
CHECK_GT(mass_, Mass{}) << ShortDebugString();
}
Part::~Part() {
LOG(INFO) << "Destroying part " << ShortDebugString();
CHECK(!is_piled_up());
if (deletion_callback_ != nullptr) {
deletion_callback_();
}
}
PartId Part::part_id() const {
return part_id_;
}
void Part::set_mass(Mass const& mass) {
CHECK_GT(mass, Mass{}) << ShortDebugString();
mass_ = mass;
}
Mass const& Part::mass() const {
return mass_;
}
void Part::clear_intrinsic_force() {
intrinsic_force_ = Vector<Force, Barycentric>{};
}
void Part::increment_intrinsic_force(
Vector<Force, Barycentric> const& intrinsic_force) {
intrinsic_force_ += intrinsic_force;
}
Vector<Force, Barycentric> const& Part::intrinsic_force() const {
return intrinsic_force_;
}
void Part::set_degrees_of_freedom(
DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {
degrees_of_freedom_ = degrees_of_freedom;
}
DegreesOfFreedom<Barycentric> const&
Part::degrees_of_freedom() const {
return degrees_of_freedom_;
}
DiscreteTrajectory<Barycentric>& Part::tail() {
return *tail_;
}
DiscreteTrajectory<Barycentric> const& Part::tail() const {
return *tail_;
}
bool Part::tail_is_authoritative() const {
return tail_is_authoritative_;
}
void Part::set_tail_is_authoritative(bool const tail_is_authoritative) {
tail_is_authoritative_ = tail_is_authoritative;
}
void Part::set_containing_pile_up(IteratorOn<std::list<PileUp>> const pile_up) {
CHECK(!is_piled_up());
LOG(INFO) << "Adding part " << ShortDebugString() << " to the pile up at "
<< &*pile_up.iterator();
containing_pile_up_ = pile_up;
}
std::experimental::optional<IteratorOn<std::list<PileUp>>>
Part::containing_pile_up() const {
return containing_pile_up_;
}
bool Part::is_piled_up() const {
// TODO(egg): |has_value()| once we have a standard |optional|.
return static_cast<bool>(containing_pile_up_);
}
void Part::clear_pile_up() {
if (is_piled_up()) {
IteratorOn<std::list<PileUp>> pile_up = *containing_pile_up_;
for (not_null<Part*> const part : pile_up.iterator()->parts()) {
LOG(INFO) << "Removing part " << part->ShortDebugString()
<< " from its pile up at " << &*pile_up.iterator();
part->containing_pile_up_ = std::experimental::nullopt;
}
CHECK(!is_piled_up());
pile_up.Erase();
}
}
void Part::WriteToMessage(not_null<serialization::Part*> const message) const {
message->set_part_id(part_id_);
message->set_name(name_);
mass_.WriteToMessage(message->mutable_mass());
intrinsic_force_.WriteToMessage(message->mutable_intrinsic_force());
if (containing_pile_up_) {
message->set_containing_pile_up(containing_pile_up_->distance_from_begin());
}
degrees_of_freedom_.WriteToMessage(message->mutable_degrees_of_freedom());
tail_->WriteToMessage(message->mutable_tail(), /*forks=*/{});
message->set_tail_is_authoritative(tail_is_authoritative_);
}
not_null<std::unique_ptr<Part>> Part::ReadFromMessage(
serialization::Part const& message,
std::function<void()> deletion_callback) {
not_null<std::unique_ptr<Part>> part =
make_not_null_unique<Part>(message.part_id(),
message.name(),
Mass::ReadFromMessage(message.mass()),
DegreesOfFreedom<Barycentric>::ReadFromMessage(
message.degrees_of_freedom()),
std::move(deletion_callback));
part->increment_intrinsic_force(
Vector<Force, Barycentric>::ReadFromMessage(message.intrinsic_force()));
part->tail_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(message.tail(),
/*forks=*/{});
part->set_tail_is_authoritative(message.tail_is_authoritative());
return part;
}
void Part::FillContainingPileUpFromMessage(
serialization::Part const& message,
not_null<std::list<PileUp>*> const pile_ups) {
if (message.has_containing_pile_up()) {
auto it = pile_ups->begin();
std::advance(it, message.containing_pile_up());
containing_pile_up_ = IteratorOn<std::list<PileUp>>(pile_ups, it);
}
}
std::string Part::ShortDebugString() const {
UniqueBytes hex_id(sizeof(part_id_) * 2 + 1);
Array<std::uint8_t const> id_bytes(
reinterpret_cast<std::uint8_t const*>(&part_id_), sizeof(part_id_));
HexadecimalEncode(id_bytes, hex_id.get());
hex_id.data[sizeof(part_id_) * 2] = '\0';
return name_ + " (" + reinterpret_cast<char const*>(hex_id.data.get()) + ")";
}
std::ostream& operator<<(std::ostream& out, Part const& part) {
return out << "{"
<< part.part_id() << ", "
<< part.mass() << "}";
}
} // namespace internal_part
} // namespace ksp_plugin
} // namespace principia
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
#include "common/platform.hpp" // NORETURN, FASTCALL, etc
#include "stm/lib_globals.hpp" // AbortHandler
#include "stm/macros.hpp" // barrier signatures
#include "stm/txthread.hpp" // TxThread stuff
#include "policies/policies.hpp" // curr_policy
#include "algs/algs.hpp" // stms
#include "algs/tml_inline.hpp"
using stm::UNRECOVERABLE;
using stm::TxThread;
using stm::AbortHandler;
using stm::stms;
using stm::curr_policy;
using stm::CGL;
namespace {
/**
* The abort handler is set during sys_init. We overwrite it with
* abort_irrevocable when a transaction becomes irrevocable, and we save the
* old one here so we can restore it during commit.
*/
AbortHandler old_abort_handler = NULL;
/**
* Handler for abort attempts while irrevocable. Useful for trapping problems
* early.
*/
NORETURN void abort_irrevocable(TxThread* tx)
{
UNRECOVERABLE("Irrevocable thread attempted to abort.");
}
/**
* Handler for rollback attempts while irrevocable. Useful for trapping
* problems early.
*
* NB: For whatever reason a 'using stm::scope_t' triggers an ICE in Mac OS
* X's default gcc-4.2.1. It's fine if we use the fully qualified
* namespace here.
*/
stm::scope_t* rollback_irrevocable(STM_ROLLBACK_SIG(,,))
{
UNRECOVERABLE("Irrevocable thread attempted to rollback.");
return NULL;
}
/**
* Resets all of the barriers to be the curr_policy bariers, except for
* tmabort which reverts to the one we saved, and tmbegin which should be
* done manually in the caller.
*/
inline void unset_irrevocable_barriers(TxThread& tx)
{
tx.tmread = stms[curr_policy.ALG_ID].read;
tx.tmwrite = stms[curr_policy.ALG_ID].write;
tx.tmcommit = stms[curr_policy.ALG_ID].commit;
tx.tmrollback = stms[curr_policy.ALG_ID].rollback;
TxThread::tmirrevoc = stms[curr_policy.ALG_ID].irrevoc;
tx.tmabort = old_abort_handler;
}
/**
* custom commit for irrevocable transactions
*/
TM_FASTCALL void commit_irrevocable(TxThread* tx)
{
// make self non-irrevocable, and unset local r/w/c barriers
tx->irrevocable = false;
unset_irrevocable_barriers(*tx);
// now allow other transactions to run
CFENCE;
TxThread::tmbegin = stms[curr_policy.ALG_ID].begin;
// finally, call the standard commit cleanup routine
OnReadOnlyCommit(tx);
}
/**
* Sets all of the barriers to be irrevocable, except tmbegin.
*/
inline void set_irrevocable_barriers(TxThread& tx)
{
tx.tmread = stms[CGL].read;
tx.tmwrite = stms[CGL].write;
tx.tmcommit = commit_irrevocable;
tx.tmrollback = rollback_irrevocable;
TxThread::tmirrevoc = stms[CGL].irrevoc;
old_abort_handler = tx.tmabort;
tx.tmabort = abort_irrevocable;
}
}
namespace stm
{
/**
* The 'Serial' algorithm requires a custom override for irrevocability,
* which we implement here.
*/
void serial_irrevoc_override(TxThread* tx);
/**
* Try to become irrevocable, inflight. This happens via mode
* switching. If the inflight irrevocability fails, we fall-back to an
* abort-and-restart-as-irrevocable scheme, based on the understanding
* that the begin_blocker tmbegin barrier will configure us as irrevocable
* and let us through if we have our irrevocable flag set. In addition to
* letting us through, it will set our barrier pointers to be the
* irrevocable barriers---it has to be done here because the rollback that
* the abort triggers will reset anything we try and set here.
*/
void become_irrevoc()
{
TxThread* tx = Self;
// special code for degenerate STM implementations
//
// NB: stm::is_irrevoc relies on how this works, so if it changes then
// please update that code as well.
if (TxThread::tmirrevoc == stms[CGL].irrevoc)
return;
if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))
return;
if (curr_policy.ALG_ID == Serial) {
serial_irrevoc_override(tx);
return;
}
if (curr_policy.ALG_ID == TML) {
if (!tx->tmlHasLock)
beforewrite_TML(tx);
return;
}
// prevent new txns from starting. If this fails, it means one of
// three things:
//
// - Someone else became irrevoc
// - Thread creation is in progress
// - Adaptivity is in progress
//
// The first of these cases requires us to abort, because the irrevoc
// thread is running the 'wait for everyone' code that immediately
// follows this CAS. Since we can't distinguish the three cases,
// we'll just abort all the time. The impact should be minimal.
if (!bcasptr(&TxThread::tmbegin, stms[curr_policy.ALG_ID].begin,
&begin_blocker))
tx->tmabort(tx);
// wait for everyone to be out of a transaction (scope == NULL)
for (unsigned i = 0; i < threadcount.val; ++i)
while ((i != (tx->id-1)) && (threads[i]->scope))
spin64();
// try to become irrevocable inflight
tx->irrevocable = TxThread::tmirrevoc(tx);
// If inflight succeeded, switch our barriers and return true.
if (tx->irrevocable) {
set_irrevocable_barriers(*tx);
return;
}
// Otherwise we tmabort (but mark ourselves as irrevocable so that we get
// through the begin_blocker after the abort). We don't switch the barriers
// here because a) one of the barriers that we'd like to switch is
// rollback, which is used by tmabort and b) rollback is designed to reset
// our barriers to the default read-only barriers for the algorithm which
// will just overwrite what we do here
//
// begin_blocker sets our barriers to be irrevocable if we have our
// irrevocable flag set.
tx->irrevocable = true;
tx->tmabort(tx);
}
/**
* True if the current algorithm is irrevocable.
*/
bool is_irrevoc(const TxThread& tx)
{
if (tx.irrevocable || TxThread::tmirrevoc == stms[CGL].irrevoc)
return true;
if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))
return true;
if ((curr_policy.ALG_ID == TML) && (tx.tmlHasLock))
return true;
if (curr_policy.ALG_ID == Serial)
return true;
return false;
}
/**
* Custom begin method that blocks the starting thread, in order to get
* rendezvous correct during mode switching and GRL irrevocability. It
* doubles as an irrevocability mechanism for implementations where we don't
* have (or can't write) an in-flight irrevocability mechanism.
*/
bool begin_blocker(TxThread* tx)
{
// if the caller is trying to restart as irrevocable, let them
if (tx->irrevocable) {
set_irrevocable_barriers(*tx);
return true;
}
// adapt without longjmp
while (true) {
// first, clear the outer scope, because it's our 'tx/nontx' flag
scope_t* b = tx->scope;
tx->scope = 0;
// next, wait for the begin_blocker to be uninstalled
while (TxThread::tmbegin == begin_blocker)
spin64();
CFENCE;
// now re-install the scope
#ifdef STM_CPU_SPARC
tx->scope = b; WBR;
#else
casptr((volatile uintptr_t*)&tx->scope, (uintptr_t)0, (uintptr_t)b);
#endif
// read the begin function pointer AFTER setting the scope
bool TM_FASTCALL (*beginner)(TxThread*) = TxThread::tmbegin;
// if begin_blocker is no longer installed, we can call the pointer
// to start a transaction, and then return. Otherwise, we missed our
// window, so we need to go back to the top of the loop.
if (beginner != begin_blocker)
return beginner(tx);
}
}
}
<commit_msg>Fixed the allocation logic for irrevocable transactions. Becoming irrevocable used to mess up the allocator's counter logic, which meant that we'd hit malloc and free from transactional contexts. Not sure how anything irrevocable ever worked... always concerning. :-|<commit_after>/**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
#include "profiling.hpp" // Trigger
#include "common/platform.hpp" // NORETURN, FASTCALL, etc
#include "stm/lib_globals.hpp" // AbortHandler
#include "stm/macros.hpp" // barrier signatures
#include "stm/txthread.hpp" // TxThread stuff
#include "policies/policies.hpp" // curr_policy
#include "algs/algs.hpp" // stms
#include "algs/tml_inline.hpp"
using stm::UNRECOVERABLE;
using stm::TxThread;
using stm::AbortHandler;
using stm::stms;
using stm::curr_policy;
using stm::CGL;
using stm::Trigger;
namespace {
/**
* The abort handler is set during sys_init. We overwrite it with
* abort_irrevocable when a transaction becomes irrevocable, and we save the
* old one here so we can restore it during commit.
*/
AbortHandler old_abort_handler = NULL;
/**
* Handler for abort attempts while irrevocable. Useful for trapping problems
* early.
*/
NORETURN void abort_irrevocable(TxThread* tx)
{
UNRECOVERABLE("Irrevocable thread attempted to abort.");
}
/**
* Handler for rollback attempts while irrevocable. Useful for trapping
* problems early.
*
* NB: For whatever reason a 'using stm::scope_t' triggers an ICE in Mac OS
* X's default gcc-4.2.1. It's fine if we use the fully qualified
* namespace here.
*/
stm::scope_t* rollback_irrevocable(STM_ROLLBACK_SIG(,,))
{
UNRECOVERABLE("Irrevocable thread attempted to rollback.");
return NULL;
}
/**
* Resets all of the barriers to be the curr_policy bariers, except for
* tmabort which reverts to the one we saved, and tmbegin which should be
* done manually in the caller.
*/
inline void unset_irrevocable_barriers(TxThread& tx)
{
tx.tmread = stms[curr_policy.ALG_ID].read;
tx.tmwrite = stms[curr_policy.ALG_ID].write;
tx.tmcommit = stms[curr_policy.ALG_ID].commit;
tx.tmrollback = stms[curr_policy.ALG_ID].rollback;
TxThread::tmirrevoc = stms[curr_policy.ALG_ID].irrevoc;
tx.tmabort = old_abort_handler;
}
/**
* custom commit for irrevocable transactions
*/
TM_FASTCALL void commit_irrevocable(TxThread* tx)
{
// make self non-irrevocable, and unset local r/w/c barriers
tx->irrevocable = false;
unset_irrevocable_barriers(*tx);
// now allow other transactions to run
CFENCE;
TxThread::tmbegin = stms[curr_policy.ALG_ID].begin;
// finally, call the standard commit cleanup routine
// OnReadOnlyCommit(tx);
// NB: We need custom commit logic here, in particular, we don't want to
// notify the allocator of anything because irrevocable transactions
// don't buffer allocations.
tx->abort_hist.onCommit(tx->consec_aborts);
tx->consec_aborts = 0;
++tx->num_commits;
Trigger::onCommitSTM(tx);
}
/**
* Sets all of the barriers to be irrevocable, except tmbegin.
*/
inline void set_irrevocable_barriers(TxThread& tx)
{
tx.tmread = stms[CGL].read;
tx.tmwrite = stms[CGL].write;
tx.tmcommit = commit_irrevocable;
tx.tmrollback = rollback_irrevocable;
TxThread::tmirrevoc = stms[CGL].irrevoc;
old_abort_handler = tx.tmabort;
tx.tmabort = abort_irrevocable;
}
}
namespace stm
{
/**
* The 'Serial' algorithm requires a custom override for irrevocability,
* which we implement here.
*/
void serial_irrevoc_override(TxThread* tx);
/**
* Try to become irrevocable, inflight. This happens via mode
* switching. If the inflight irrevocability fails, we fall-back to an
* abort-and-restart-as-irrevocable scheme, based on the understanding
* that the begin_blocker tmbegin barrier will configure us as irrevocable
* and let us through if we have our irrevocable flag set. In addition to
* letting us through, it will set our barrier pointers to be the
* irrevocable barriers---it has to be done here because the rollback that
* the abort triggers will reset anything we try and set here.
*/
void become_irrevoc()
{
TxThread* tx = Self;
// special code for degenerate STM implementations
//
// NB: stm::is_irrevoc relies on how this works, so if it changes then
// please update that code as well.
if (TxThread::tmirrevoc == stms[CGL].irrevoc)
return;
if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))
return;
if (curr_policy.ALG_ID == Serial) {
serial_irrevoc_override(tx);
return;
}
if (curr_policy.ALG_ID == TML) {
if (!tx->tmlHasLock)
beforewrite_TML(tx);
return;
}
// prevent new txns from starting. If this fails, it means one of
// three things:
//
// - Someone else became irrevoc
// - Thread creation is in progress
// - Adaptivity is in progress
//
// The first of these cases requires us to abort, because the irrevoc
// thread is running the 'wait for everyone' code that immediately
// follows this CAS. Since we can't distinguish the three cases,
// we'll just abort all the time. The impact should be minimal.
if (!bcasptr(&TxThread::tmbegin, stms[curr_policy.ALG_ID].begin,
&begin_blocker))
tx->tmabort(tx);
// wait for everyone to be out of a transaction (scope == NULL)
for (unsigned i = 0; i < threadcount.val; ++i)
while ((i != (tx->id-1)) && (threads[i]->scope))
spin64();
// try to become irrevocable inflight
tx->irrevocable = TxThread::tmirrevoc(tx);
// If inflight succeeded, switch our barriers and return true.
if (tx->irrevocable) {
tx->allocator.onTxCommit(); // tell the allocator do cleanup
set_irrevocable_barriers(*tx);
return;
}
// Otherwise we tmabort (but mark ourselves as irrevocable so that we get
// through the begin_blocker after the abort). We don't switch the barriers
// here because a) one of the barriers that we'd like to switch is
// rollback, which is used by tmabort and b) rollback is designed to reset
// our barriers to the default read-only barriers for the algorithm which
// will just overwrite what we do here
//
// begin_blocker sets our barriers to be irrevocable if we have our
// irrevocable flag set.
tx->irrevocable = true;
tx->tmabort(tx);
}
/**
* True if the current algorithm is irrevocable.
*/
bool is_irrevoc(const TxThread& tx)
{
if (tx.irrevocable || TxThread::tmirrevoc == stms[CGL].irrevoc)
return true;
if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))
return true;
if ((curr_policy.ALG_ID == TML) && (tx.tmlHasLock))
return true;
if (curr_policy.ALG_ID == Serial)
return true;
return false;
}
/**
* Custom begin method that blocks the starting thread, in order to get
* rendezvous correct during mode switching and GRL irrevocability. It
* doubles as an irrevocability mechanism for implementations where we don't
* have (or can't write) an in-flight irrevocability mechanism.
*/
bool begin_blocker(TxThread* tx)
{
// if the caller is trying to restart as irrevocable, let them
// NB: do not notify allocator of anything because irrevocable
// transactions don't buffer allocation.
if (tx->irrevocable) {
set_irrevocable_barriers(*tx);
return true;
}
// adapt without longjmp
while (true) {
// first, clear the outer scope, because it's our 'tx/nontx' flag
scope_t* b = tx->scope;
tx->scope = 0;
// next, wait for the begin_blocker to be uninstalled
while (TxThread::tmbegin == begin_blocker)
spin64();
CFENCE;
// now re-install the scope
#ifdef STM_CPU_SPARC
tx->scope = b; WBR;
#else
casptr((volatile uintptr_t*)&tx->scope, (uintptr_t)0, (uintptr_t)b);
#endif
// read the begin function pointer AFTER setting the scope
bool TM_FASTCALL (*beginner)(TxThread*) = TxThread::tmbegin;
// if begin_blocker is no longer installed, we can call the pointer
// to start a transaction, and then return. Otherwise, we missed our
// window, so we need to go back to the top of the loop.
if (beginner != begin_blocker)
return beginner(tx);
}
}
}
<|endoftext|>
|
<commit_before>#include "Arduino.h"
#include "DFR_Key.h"
static int DEFAULT_KEY_PIN = 0;
static int DEFAULT_THRESHOLD = 5;
/*
To use any alternate set of values you will need to enable it by a define.
The define should NOT be done in code or it will impact all users. Visual
Studio users can set 'DF_ROBOT_V1' in the Preprocessor definitions of the
project, or add '-DDF_ROBOT_V1' under advanced options.
Users of the standard Arduino IDE should create the file 'platform.local.txt'
under <arduino_install>/hardware.arduino/avr and add the following line but
be aware that when you upgrade your IDE this file may need to be re-created:
compiler.cpp.extra_flags=-DDF_ROBOT_V1
If further values are added in the future then of course adjust the name
of the define that you specify accordingly.
*/
#ifdef DF_ROBOT_V1
static int RIGHTKEY_ARV = 0;
static int DOWNKEY_ARV = 98; //that's read "analogue read value"
static int UPKEY_ARV = 254;
static int LEFTKEY_ARV = 407;
static int SELKEY_ARV = 638;
static int NOKEY_ARV = 1023;
#else
static int UPKEY_ARV = 144; //that's read "analogue read value"
static int DOWNKEY_ARV = 329;
static int LEFTKEY_ARV = 505;
static int RIGHTKEY_ARV = 0;
static int SELKEY_ARV = 742;
static int NOKEY_ARV = 1023;
#endif // ALT_VALUES
DFR_Key::DFR_Key()
{
_refreshRate = 10;
_keyPin = DEFAULT_KEY_PIN;
_threshold = DEFAULT_THRESHOLD;
_keyIn = NO_KEY;
_curInput = NO_KEY;
_curKey = NO_KEY;
_prevInput = NO_KEY;
_prevKey = NO_KEY;
_oldTime = 0;
}
int DFR_Key::getKey()
{
if (millis() > _oldTime + _refreshRate)
{
_prevInput = _curInput;
_curInput = analogRead(_keyPin);
if (_curInput == _prevInput)
{
_change = false;
_curKey = _prevKey;
}
else
{
_change = true;
_prevKey = _curKey;
if (_curInput > UPKEY_ARV - _threshold && _curInput < UPKEY_ARV + _threshold ) _curKey = UP_KEY;
else if (_curInput > DOWNKEY_ARV - _threshold && _curInput < DOWNKEY_ARV + _threshold ) _curKey = DOWN_KEY;
else if (_curInput > RIGHTKEY_ARV - _threshold && _curInput < RIGHTKEY_ARV + _threshold ) _curKey = RIGHT_KEY;
else if (_curInput > LEFTKEY_ARV - _threshold && _curInput < LEFTKEY_ARV + _threshold ) _curKey = LEFT_KEY;
else if (_curInput > SELKEY_ARV - _threshold && _curInput < SELKEY_ARV + _threshold ) _curKey = SELECT_KEY;
else _curKey = NO_KEY;
}
if (_change) return _curKey; else return SAMPLE_WAIT;
_oldTime = millis();
}
}
void DFR_Key::setRate(int rate)
{
_refreshRate = rate;
}<commit_msg>Modified order of keypad defines for SwainSmart v1.1<commit_after>#include "Arduino.h"
#include "DFR_Key.h"
static int DEFAULT_KEY_PIN = 0;
static int DEFAULT_THRESHOLD = 5;
/*
To use any alternate set of values you will need to enable it by a define.
The define should NOT be done in code or it will impact all users. Visual
Studio users can set 'DF_ROBOT_V1' in the Preprocessor definitions of the
project, or add '-DDF_ROBOT_V1' under advanced options.
Users of the standard Arduino IDE should create the file 'platform.local.txt'
under <arduino_install>/hardware.arduino/avr and add the following line but
be aware that when you upgrade your IDE this file may need to be re-created:
compiler.cpp.extra_flags=-DDF_ROBOT_V1
If further values are added in the future then of course adjust the name
of the define that you specify accordingly.
*/
#ifdef DF_ROBOT_V1
static int RIGHTKEY_ARV = 0; //that's read "analogue read value"
static int DOWNKEY_ARV = 98;
static int UPKEY_ARV = 254;
static int LEFTKEY_ARV = 407;
static int SELKEY_ARV = 638;
static int NOKEY_ARV = 1023;
#else
static int RIGHTKEY_ARV = 0;
static int UPKEY_ARV = 144;
static int DOWNKEY_ARV = 329;
static int LEFTKEY_ARV = 505;
static int SELKEY_ARV = 742;
static int NOKEY_ARV = 1023;
#endif
DFR_Key::DFR_Key()
{
_refreshRate = 10;
_keyPin = DEFAULT_KEY_PIN;
_threshold = DEFAULT_THRESHOLD;
_keyIn = NO_KEY;
_curInput = NO_KEY;
_curKey = NO_KEY;
_prevInput = NO_KEY;
_prevKey = NO_KEY;
_oldTime = 0;
}
int DFR_Key::getKey()
{
if (millis() > _oldTime + _refreshRate)
{
_prevInput = _curInput;
_curInput = analogRead(_keyPin);
if (_curInput == _prevInput)
{
_change = false;
_curKey = _prevKey;
}
else
{
_change = true;
_prevKey = _curKey;
if (_curInput > UPKEY_ARV - _threshold && _curInput < UPKEY_ARV + _threshold ) _curKey = UP_KEY;
else if (_curInput > DOWNKEY_ARV - _threshold && _curInput < DOWNKEY_ARV + _threshold ) _curKey = DOWN_KEY;
else if (_curInput > RIGHTKEY_ARV - _threshold && _curInput < RIGHTKEY_ARV + _threshold ) _curKey = RIGHT_KEY;
else if (_curInput > LEFTKEY_ARV - _threshold && _curInput < LEFTKEY_ARV + _threshold ) _curKey = LEFT_KEY;
else if (_curInput > SELKEY_ARV - _threshold && _curInput < SELKEY_ARV + _threshold ) _curKey = SELECT_KEY;
else _curKey = NO_KEY;
}
if (_change) return _curKey; else return SAMPLE_WAIT;
_oldTime = millis();
}
}
void DFR_Key::setRate(int rate)
{
_refreshRate = rate;
}<|endoftext|>
|
<commit_before>#include <maya/MFnMesh.h>
#include <maya/MFnMeshData.h>
#include <maya/MEulerRotation.h>
#include <maya/MQuaternion.h>
#include <maya/MFnArrayAttrsData.h>
#include "Asset.h"
#include "AssetNode.h"
#include "AssetNodeOptions.h"
#include "OutputInstancerObject.h"
#include "hapiutil.h"
#include "util.h"
OutputInstancerObject::OutputInstancerObject(
HAPI_NodeId nodeId
) :
OutputObject(
nodeId
),
myGeoInfo(HAPI_GeoInfo_Create()),
myLastSopCookCount(0)
{
}
OutputInstancerObject::~OutputInstancerObject() {}
OutputObject::ObjectType
OutputInstancerObject::type()
{
return OutputObject::OBJECT_TYPE_INSTANCER;
}
void
OutputInstancerObject::update()
{
HAPI_Result hapiResult;
hapiResult = HAPI_GetNodeInfo(
Util::theHAPISession.get(),
myNodeId, &myNodeInfo
);
CHECK_HAPI(hapiResult);
hapiResult = HAPI_GetObjectInfo(
Util::theHAPISession.get(),
myNodeId, &myObjectInfo
);
CHECK_HAPI(hapiResult);
// Get the SOP nodes
int geoCount;
hapiResult = HAPI_ComposeChildNodeList(
Util::theHAPISession.get(),
myNodeId,
HAPI_NODETYPE_SOP,
HAPI_NODEFLAGS_DISPLAY,
false,
&geoCount
);
CHECK_HAPI(hapiResult);
std::vector<HAPI_NodeId> geoNodeIds(geoCount);
if(geoCount > 0)
{
hapiResult = HAPI_GetComposedChildNodeList(
Util::theHAPISession.get(),
myNodeId,
&geoNodeIds.front(),
geoCount
);
CHECK_HAPI(hapiResult);
hapiResult = HAPI_GetNodeInfo(
Util::theHAPISession.get(),
geoNodeIds[0],
&mySopNodeInfo
);
CHECK_HAPI(hapiResult);
hapiResult = HAPI_GetGeoInfo(
Util::theHAPISession.get(),
geoNodeIds[0],
&myGeoInfo
);
CHECK_HAPI(hapiResult);
}
if(mySopNodeInfo.totalCookCount > myLastSopCookCount)
{
// clear the arrays
myInstancedObjectNames.clear();
myInstancedObjectIndices.clear();
myUniqueInstObjNames.clear();
myHoudiniInstanceAttribute.clear();
myHoudiniNameAttribute.clear();
hapiResult = HAPI_GetPartInfo(
Util::theHAPISession.get(),
mySopNodeInfo.id, 0,
&myPartInfo
);
CHECK_HAPI(hapiResult);
if(myObjectInfo.objectToInstanceId >= 0)
{
myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, 0);
return;
}
// fill array of size pointCount of instanced names
HAPI_AttributeInfo attrInfo;
MStringArray instanceAttrs;
hapiGetPointAttribute(mySopNodeInfo.id, 0, "instance", attrInfo, instanceAttrs);
for(unsigned int i=0; i<instanceAttrs.length(); i++)
{
MStringArray splitObjName;
instanceAttrs[i].split('/', splitObjName);
myInstancedObjectNames.append(splitObjName[splitObjName.length()-1]);
myHoudiniInstanceAttribute.append(instanceAttrs[i]);
}
MStringArray nameAttrs;
hapiGetPointAttribute(mySopNodeInfo.id, 0, "name", attrInfo, nameAttrs);
for(unsigned int ii = 0; ii < nameAttrs.length(); ii++)
{
myHoudiniNameAttribute.append(nameAttrs[ii]);
}
// get a list of unique instanced names, and compute the object indices that would
// be passed to Maya instancer
for(unsigned int i = 0; i< myInstancedObjectNames.length(); ++i)
{
bool duplicate = false;
unsigned int j = 0;
for(; j< myUniqueInstObjNames.length(); ++j)
{
if(myUniqueInstObjNames[j] == myInstancedObjectNames[i])
{
duplicate = true;
break;
}
}
if(!duplicate)
myUniqueInstObjNames.append(myInstancedObjectNames[i]);
myInstancedObjectIndices.append((int) j);
}
// Workaround a crash where we can't determine the object to instance.
if(!myInstancedObjectNames.length())
{
myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, -1);
}
}
}
MIntArray
OutputInstancerObject::getInstancedObjIds()
{
MIntArray ret;
if(myObjectInfo.objectToInstanceId >= 0)
ret.append(myObjectInfo.objectToInstanceId);
return ret;
}
MStringArray
OutputInstancerObject::getUniqueInstObjNames()
{
return myUniqueInstObjNames;
}
MStatus
OutputInstancerObject::compute(
const MTime &time,
const MPlug &plug,
MDataBlock& data,
MDataHandle& handle,
AssetNodeOptions::AccessorDataBlock &options,
bool &needToSyncOutputs,
const bool needToRecomputeOutputData
)
{
update();
if(myGeoInfo.partCount <= 0)
return MS::kFailure;
if((mySopNodeInfo.totalCookCount > myLastSopCookCount) || needToRecomputeOutputData)
{
MDataHandle instancerDataHandle = handle.child(AssetNode::outputInstancerData);
MArrayDataHandle instancedObjectNamesHandle = handle.child(AssetNode::outputInstancedObjectNames);
MArrayDataHandle houdiniInstanceAttributeHandle = handle.child(AssetNode::outputHoudiniInstanceAttribute);
MArrayDataHandle houdiniNameAttributeHandle = handle.child(AssetNode::outputHoudiniNameAttribute);
MArrayDataHandle instanceTransformHandle = handle.child(AssetNode::outputInstanceTransform);
MObject arrayDataObj = instancerDataHandle.data();
MFnArrayAttrsData arrayDataFn(arrayDataObj);
if(arrayDataObj.isNull())
{
arrayDataObj = arrayDataFn.create();
instancerDataHandle.set(arrayDataObj);
arrayDataObj = instancerDataHandle.data();
arrayDataFn.setObject(arrayDataObj);
}
MVectorArray positions = arrayDataFn.vectorArray("position");
MVectorArray rotations = arrayDataFn.vectorArray("rotation");
MVectorArray scales = arrayDataFn.vectorArray("scale");
MIntArray objectIndices = arrayDataFn.intArray("objectIndex");
unsigned int size = myPartInfo.pointCount;
HAPI_Transform * instTransforms = new HAPI_Transform[size];
CHECK_HAPI(HAPI_GetInstanceTransformsOnPart(
Util::theHAPISession.get(),
0,
mySopNodeInfo.id,
HAPI_SRT,
instTransforms,
0, size
));
Util::resizeArrayDataHandle(houdiniInstanceAttributeHandle, size);
Util::resizeArrayDataHandle(houdiniNameAttributeHandle, size);
Util::resizeArrayDataHandle(instanceTransformHandle, size);
if(positions.length() != size && !options.useInstancerNode())
{
needToSyncOutputs = true;
}
positions.setLength(size);
rotations.setLength(size);
scales.setLength(size);
objectIndices.setLength(size);
for(unsigned int j=0; j<size; j++)
{
HAPI_Transform it = instTransforms[j];
MVector p(it.position[0], it.position[1], it.position[2]);
MVector r = MQuaternion(it.rotationQuaternion[0],
it.rotationQuaternion[1], it.rotationQuaternion[2],
it.rotationQuaternion[3]).asEulerRotation().asVector();
MVector s(it.scale[0], it.scale[1], it.scale[2]);
int objIndex = myInstancedObjectIndices[j];
if (options.preserveScale())
p *= 100.0;
positions[j] = p;
rotations[j] = r;
scales[j] = s;
objectIndices[j] = objIndex;
CHECK_MSTATUS(houdiniInstanceAttributeHandle.jumpToArrayElement(j));
MDataHandle intanceAttributeHandle = houdiniInstanceAttributeHandle.outputValue();
intanceAttributeHandle .set(myHoudiniInstanceAttribute[j]);
CHECK_MSTATUS(houdiniNameAttributeHandle.jumpToArrayElement(j));
MDataHandle nameAttributeHandle = houdiniNameAttributeHandle.outputValue();
nameAttributeHandle.set(myHoudiniNameAttribute[j]);
CHECK_MSTATUS(instanceTransformHandle.jumpToArrayElement(j));
MDataHandle transformHandle = instanceTransformHandle.outputValue();
MDataHandle translateHandle = transformHandle.child(AssetNode::outputInstanceTranslate);
MDataHandle rotateHandle = transformHandle.child(AssetNode::outputInstanceRotate);
MDataHandle scaleHandle = transformHandle.child(AssetNode::outputInstanceScale);
MDataHandle txHandle = translateHandle.child(AssetNode::outputInstanceTranslateX);
txHandle.set(p.x);
MDataHandle tyHandle = translateHandle.child(AssetNode::outputInstanceTranslateY);
tyHandle.set(p.y);
MDataHandle tzHandle = translateHandle.child(AssetNode::outputInstanceTranslateZ);
tzHandle.set(p.z);
MDataHandle rxHandle = rotateHandle.child(AssetNode::outputInstanceRotateX);
rxHandle.set(r.x);
MDataHandle ryHandle = rotateHandle.child(AssetNode::outputInstanceRotateY);
ryHandle.set(r.y);
MDataHandle rzHandle = rotateHandle.child(AssetNode::outputInstanceRotateZ);
rzHandle.set(r.z);
MDataHandle sxHandle = scaleHandle.child(AssetNode::outputInstanceScaleX);
sxHandle.set(s.x);
MDataHandle syHandle = scaleHandle.child(AssetNode::outputInstanceScaleY);
syHandle.set(s.y);
MDataHandle szHandle = scaleHandle.child(AssetNode::outputInstanceScaleZ);
szHandle.set(s.z);
}
houdiniInstanceAttributeHandle.setAllClean();
houdiniNameAttributeHandle.setAllClean();
instanceTransformHandle.setAllClean();
delete[] instTransforms;
if(myObjectInfo.objectToInstanceId >= 0)
{
// instancing a single object
Util::resizeArrayDataHandle(instancedObjectNamesHandle, 1);
HAPI_ObjectInfo instanceObjectInfo;
CHECK_HAPI(HAPI_GetObjectInfo(
Util::theHAPISession.get(),
myObjectInfo.objectToInstanceId,
&instanceObjectInfo
));
MString name = Util::HAPIString(instanceObjectInfo.nameSH);
CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(0));
MDataHandle h = instancedObjectNamesHandle.outputValue();
h.set(name);
} else
{
// instancing multiple objects
Util::resizeArrayDataHandle(instancedObjectNamesHandle,
myUniqueInstObjNames.length());
for(unsigned int i=0; i< myUniqueInstObjNames.length(); i++)
{
CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(i));
MDataHandle h = instancedObjectNamesHandle.outputValue();
h.set(myUniqueInstObjNames[i]);
}
}
instancedObjectNamesHandle.setAllClean();
myLastSopCookCount = mySopNodeInfo.totalCookCount;
}
return MS::kSuccess;
}
<commit_msg>fix typo that caused instance transforms to sometimes not be computed in the maya plugin.<commit_after>#include <maya/MFnMesh.h>
#include <maya/MFnMeshData.h>
#include <maya/MEulerRotation.h>
#include <maya/MQuaternion.h>
#include <maya/MFnArrayAttrsData.h>
#include "Asset.h"
#include "AssetNode.h"
#include "AssetNodeOptions.h"
#include "OutputInstancerObject.h"
#include "hapiutil.h"
#include "util.h"
OutputInstancerObject::OutputInstancerObject(
HAPI_NodeId nodeId
) :
OutputObject(
nodeId
),
myGeoInfo(HAPI_GeoInfo_Create()),
myLastSopCookCount(0)
{
}
OutputInstancerObject::~OutputInstancerObject() {}
OutputObject::ObjectType
OutputInstancerObject::type()
{
return OutputObject::OBJECT_TYPE_INSTANCER;
}
void
OutputInstancerObject::update()
{
HAPI_Result hapiResult;
hapiResult = HAPI_GetNodeInfo(
Util::theHAPISession.get(),
myNodeId, &myNodeInfo
);
CHECK_HAPI(hapiResult);
hapiResult = HAPI_GetObjectInfo(
Util::theHAPISession.get(),
myNodeId, &myObjectInfo
);
CHECK_HAPI(hapiResult);
// Get the SOP nodes
int geoCount;
hapiResult = HAPI_ComposeChildNodeList(
Util::theHAPISession.get(),
myNodeId,
HAPI_NODETYPE_SOP,
HAPI_NODEFLAGS_DISPLAY,
false,
&geoCount
);
CHECK_HAPI(hapiResult);
std::vector<HAPI_NodeId> geoNodeIds(geoCount);
if(geoCount > 0)
{
hapiResult = HAPI_GetComposedChildNodeList(
Util::theHAPISession.get(),
myNodeId,
&geoNodeIds.front(),
geoCount
);
CHECK_HAPI(hapiResult);
hapiResult = HAPI_GetNodeInfo(
Util::theHAPISession.get(),
geoNodeIds[0],
&mySopNodeInfo
);
CHECK_HAPI(hapiResult);
hapiResult = HAPI_GetGeoInfo(
Util::theHAPISession.get(),
geoNodeIds[0],
&myGeoInfo
);
CHECK_HAPI(hapiResult);
}
if(mySopNodeInfo.totalCookCount > myLastSopCookCount)
{
// clear the arrays
myInstancedObjectNames.clear();
myInstancedObjectIndices.clear();
myUniqueInstObjNames.clear();
myHoudiniInstanceAttribute.clear();
myHoudiniNameAttribute.clear();
hapiResult = HAPI_GetPartInfo(
Util::theHAPISession.get(),
mySopNodeInfo.id, 0,
&myPartInfo
);
CHECK_HAPI(hapiResult);
if(myObjectInfo.objectToInstanceId >= 0)
{
myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, 0);
return;
}
// fill array of size pointCount of instanced names
HAPI_AttributeInfo attrInfo;
MStringArray instanceAttrs;
hapiGetPointAttribute(mySopNodeInfo.id, 0, "instance", attrInfo, instanceAttrs);
for(unsigned int i=0; i<instanceAttrs.length(); i++)
{
MStringArray splitObjName;
instanceAttrs[i].split('/', splitObjName);
myInstancedObjectNames.append(splitObjName[splitObjName.length()-1]);
myHoudiniInstanceAttribute.append(instanceAttrs[i]);
}
MStringArray nameAttrs;
hapiGetPointAttribute(mySopNodeInfo.id, 0, "name", attrInfo, nameAttrs);
for(unsigned int ii = 0; ii < nameAttrs.length(); ii++)
{
myHoudiniNameAttribute.append(nameAttrs[ii]);
}
// get a list of unique instanced names, and compute the object indices that would
// be passed to Maya instancer
for(unsigned int i = 0; i< myInstancedObjectNames.length(); ++i)
{
bool duplicate = false;
unsigned int j = 0;
for(; j< myUniqueInstObjNames.length(); ++j)
{
if(myUniqueInstObjNames[j] == myInstancedObjectNames[i])
{
duplicate = true;
break;
}
}
if(!duplicate)
myUniqueInstObjNames.append(myInstancedObjectNames[i]);
myInstancedObjectIndices.append((int) j);
}
// Workaround a crash where we can't determine the object to instance.
if(!myInstancedObjectNames.length())
{
myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, -1);
}
}
}
MIntArray
OutputInstancerObject::getInstancedObjIds()
{
MIntArray ret;
if(myObjectInfo.objectToInstanceId >= 0)
ret.append(myObjectInfo.objectToInstanceId);
return ret;
}
MStringArray
OutputInstancerObject::getUniqueInstObjNames()
{
return myUniqueInstObjNames;
}
MStatus
OutputInstancerObject::compute(
const MTime &time,
const MPlug &plug,
MDataBlock& data,
MDataHandle& handle,
AssetNodeOptions::AccessorDataBlock &options,
bool &needToSyncOutputs,
const bool needToRecomputeOutputData
)
{
update();
if(myGeoInfo.partCount <= 0)
return MS::kFailure;
if((mySopNodeInfo.totalCookCount > myLastSopCookCount) || needToRecomputeOutputData)
{
MDataHandle instancerDataHandle = handle.child(AssetNode::outputInstancerData);
MArrayDataHandle instancedObjectNamesHandle = handle.child(AssetNode::outputInstancedObjectNames);
MArrayDataHandle houdiniInstanceAttributeHandle = handle.child(AssetNode::outputHoudiniInstanceAttribute);
MArrayDataHandle houdiniNameAttributeHandle = handle.child(AssetNode::outputHoudiniNameAttribute);
MArrayDataHandle instanceTransformHandle = handle.child(AssetNode::outputInstanceTransform);
MObject arrayDataObj = instancerDataHandle.data();
MFnArrayAttrsData arrayDataFn(arrayDataObj);
if(arrayDataObj.isNull())
{
arrayDataObj = arrayDataFn.create();
instancerDataHandle.set(arrayDataObj);
arrayDataObj = instancerDataHandle.data();
arrayDataFn.setObject(arrayDataObj);
}
MVectorArray positions = arrayDataFn.vectorArray("position");
MVectorArray rotations = arrayDataFn.vectorArray("rotation");
MVectorArray scales = arrayDataFn.vectorArray("scale");
MIntArray objectIndices = arrayDataFn.intArray("objectIndex");
unsigned int size = myPartInfo.pointCount;
HAPI_Transform * instTransforms = new HAPI_Transform[size];
CHECK_HAPI(HAPI_GetInstanceTransformsOnPart(
Util::theHAPISession.get(),
mySopNodeInfo.id,
0,
HAPI_SRT,
instTransforms,
0, size
));
Util::resizeArrayDataHandle(houdiniInstanceAttributeHandle, size);
Util::resizeArrayDataHandle(houdiniNameAttributeHandle, size);
Util::resizeArrayDataHandle(instanceTransformHandle, size);
if(positions.length() != size && !options.useInstancerNode())
{
needToSyncOutputs = true;
}
positions.setLength(size);
rotations.setLength(size);
scales.setLength(size);
objectIndices.setLength(size);
for(unsigned int j=0; j<size; j++)
{
HAPI_Transform it = instTransforms[j];
MVector p(it.position[0], it.position[1], it.position[2]);
MVector r = MQuaternion(it.rotationQuaternion[0],
it.rotationQuaternion[1], it.rotationQuaternion[2],
it.rotationQuaternion[3]).asEulerRotation().asVector();
MVector s(it.scale[0], it.scale[1], it.scale[2]);
int objIndex = myInstancedObjectIndices[j];
if (options.preserveScale())
p *= 100.0;
positions[j] = p;
rotations[j] = r;
scales[j] = s;
objectIndices[j] = objIndex;
CHECK_MSTATUS(houdiniInstanceAttributeHandle.jumpToArrayElement(j));
MDataHandle intanceAttributeHandle = houdiniInstanceAttributeHandle.outputValue();
intanceAttributeHandle .set(myHoudiniInstanceAttribute[j]);
CHECK_MSTATUS(houdiniNameAttributeHandle.jumpToArrayElement(j));
MDataHandle nameAttributeHandle = houdiniNameAttributeHandle.outputValue();
nameAttributeHandle.set(myHoudiniNameAttribute[j]);
CHECK_MSTATUS(instanceTransformHandle.jumpToArrayElement(j));
MDataHandle transformHandle = instanceTransformHandle.outputValue();
MDataHandle translateHandle = transformHandle.child(AssetNode::outputInstanceTranslate);
MDataHandle rotateHandle = transformHandle.child(AssetNode::outputInstanceRotate);
MDataHandle scaleHandle = transformHandle.child(AssetNode::outputInstanceScale);
MDataHandle txHandle = translateHandle.child(AssetNode::outputInstanceTranslateX);
txHandle.set(p.x);
MDataHandle tyHandle = translateHandle.child(AssetNode::outputInstanceTranslateY);
tyHandle.set(p.y);
MDataHandle tzHandle = translateHandle.child(AssetNode::outputInstanceTranslateZ);
tzHandle.set(p.z);
MDataHandle rxHandle = rotateHandle.child(AssetNode::outputInstanceRotateX);
rxHandle.set(r.x);
MDataHandle ryHandle = rotateHandle.child(AssetNode::outputInstanceRotateY);
ryHandle.set(r.y);
MDataHandle rzHandle = rotateHandle.child(AssetNode::outputInstanceRotateZ);
rzHandle.set(r.z);
MDataHandle sxHandle = scaleHandle.child(AssetNode::outputInstanceScaleX);
sxHandle.set(s.x);
MDataHandle syHandle = scaleHandle.child(AssetNode::outputInstanceScaleY);
syHandle.set(s.y);
MDataHandle szHandle = scaleHandle.child(AssetNode::outputInstanceScaleZ);
szHandle.set(s.z);
}
houdiniInstanceAttributeHandle.setAllClean();
houdiniNameAttributeHandle.setAllClean();
instanceTransformHandle.setAllClean();
delete[] instTransforms;
if(myObjectInfo.objectToInstanceId >= 0)
{
// instancing a single object
Util::resizeArrayDataHandle(instancedObjectNamesHandle, 1);
HAPI_ObjectInfo instanceObjectInfo;
CHECK_HAPI(HAPI_GetObjectInfo(
Util::theHAPISession.get(),
myObjectInfo.objectToInstanceId,
&instanceObjectInfo
));
MString name = Util::HAPIString(instanceObjectInfo.nameSH);
CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(0));
MDataHandle h = instancedObjectNamesHandle.outputValue();
h.set(name);
} else
{
// instancing multiple objects
Util::resizeArrayDataHandle(instancedObjectNamesHandle,
myUniqueInstObjNames.length());
for(unsigned int i=0; i< myUniqueInstObjNames.length(); i++)
{
CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(i));
MDataHandle h = instancedObjectNamesHandle.outputValue();
h.set(myUniqueInstObjNames[i]);
}
}
instancedObjectNamesHandle.setAllClean();
myLastSopCookCount = mySopNodeInfo.totalCookCount;
}
return MS::kSuccess;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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 HOLDER 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 <graphene/chain/database.hpp>
#include <graphene/chain/db_with.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/global_property_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <graphene/chain/transaction_object.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
#include <graphene/chain/witness_object.hpp>
#include <graphene/chain/protocol/fee_schedule.hpp>
#include <fc/uint128.hpp>
namespace graphene { namespace chain {
void database::update_global_dynamic_data( const signed_block& b )
{
const dynamic_global_property_object& _dgp =
dynamic_global_property_id_type(0)(*this);
uint32_t missed_blocks = get_slot_at_time( b.timestamp );
assert( missed_blocks != 0 );
missed_blocks--;
for( uint32_t i = 0; i < missed_blocks; ++i ) {
const auto& witness_missed = get_scheduled_witness( i+1 )(*this);
if( witness_missed.id != b.witness ) {
const auto& witness_account = witness_missed.witness_account(*this);
/*
if( (fc::time_point::now() - b.timestamp) < fc::seconds(30) )
wlog( "Witness ${name} missed block ${n} around ${t}", ("name",witness_account.name)("n",b.block_num())("t",b.timestamp) );
*/
modify( witness_missed, [&]( witness_object& w ) {
w.total_missed++;
});
}
}
// dynamic global properties updating
modify( _dgp, [&]( dynamic_global_property_object& dgp ){
if( BOOST_UNLIKELY( b.block_num() == 1 ) )
dgp.recently_missed_count = 0;
else if( _checkpoints.size() && _checkpoints.rbegin()->first >= b.block_num() )
dgp.recently_missed_count = 0;
else if( missed_blocks )
dgp.recently_missed_count += GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT*missed_blocks;
else if( dgp.recently_missed_count > GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT )
dgp.recently_missed_count -= GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT;
else if( dgp.recently_missed_count > 0 )
dgp.recently_missed_count--;
dgp.head_block_number = b.block_num();
dgp.head_block_id = b.id();
dgp.time = b.timestamp;
dgp.current_witness = b.witness;
dgp.recent_slots_filled = (
(dgp.recent_slots_filled << 1)
+ 1) << missed_blocks;
dgp.current_aslot += missed_blocks+1;
});
if( !(get_node_properties().skip_flags & skip_undo_history_check) )
{
GRAPHENE_ASSERT( _dgp.recently_missed_count < GRAPHENE_MAX_UNDO_HISTORY, undo_database_exception,
"The database does not have enough undo history to support a blockchain with so many missed blocks. "
"Please add a checkpoint if you would like to continue applying blocks beyond this point.",
("recently_missed",_dgp.recently_missed_count)("max_undo",GRAPHENE_MAX_UNDO_HISTORY) );
}
_undo_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );
_fork_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );
}
void database::update_signing_witness(const witness_object& signing_witness, const signed_block& new_block)
{
const global_property_object& gpo = get_global_properties();
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
uint64_t new_block_aslot = dpo.current_aslot + get_slot_at_time( new_block.timestamp );
share_type witness_pay = std::min( gpo.parameters.witness_pay_per_block, dpo.witness_budget );
modify( dpo, [&]( dynamic_global_property_object& _dpo )
{
_dpo.witness_budget -= witness_pay;
} );
deposit_witness_pay( signing_witness, witness_pay );
modify( signing_witness, [&]( witness_object& _wit )
{
_wit.last_aslot = new_block_aslot;
} );
}
void database::clear_expired_transactions()
{
//Look for expired transactions in the deduplication list, and remove them.
//Transactions must have expired by at least two forking windows in order to be removed.
auto& transaction_idx = static_cast<transaction_index&>(get_mutable_index(implementation_ids, impl_transaction_object_type));
const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
while( (!dedupe_index.empty()) && (head_block_time() > dedupe_index.rbegin()->trx.expiration) )
transaction_idx.remove(*dedupe_index.rbegin());
}
void database::clear_expired_proposals()
{
const auto& proposal_expiration_index = get_index_type<proposal_index>().indices().get<by_expiration>();
while( !proposal_expiration_index.empty() && proposal_expiration_index.begin()->expiration_time <= head_block_time() )
{
const proposal_object& proposal = *proposal_expiration_index.begin();
processed_transaction result;
try {
if( proposal.is_authorized_to_execute(*this) )
{
result = push_proposal(proposal);
//TODO: Do something with result so plugins can process it.
continue;
}
} catch( const fc::exception& e ) {
elog("Failed to apply proposed transaction on its expiration. Deleting it.\n${proposal}\n${error}",
("proposal", proposal)("error", e.to_detail_string()));
}
remove(proposal);
}
}
void database::clear_expired_orders()
{
detail::with_skip_flags( *this,
get_node_properties().skip_flags | skip_authority_check, [&](){
transaction_evaluation_state cancel_context(this);
//Cancel expired limit orders
auto& limit_index = get_index_type<limit_order_index>().indices().get<by_expiration>();
while( !limit_index.empty() && limit_index.begin()->expiration <= head_block_time() )
{
limit_order_cancel_operation canceler;
const limit_order_object& order = *limit_index.begin();
canceler.fee_paying_account = order.seller;
canceler.order = order.id;
apply_operation(cancel_context, canceler);
}
});
//Process expired force settlement orders
auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
if( !settlement_index.empty() )
{
asset_id_type current_asset = settlement_index.begin()->settlement_asset_id();
asset max_settlement_volume;
auto next_asset = [¤t_asset, &settlement_index] {
auto bound = settlement_index.upper_bound(current_asset);
if( bound == settlement_index.end() )
return false;
current_asset = bound->settlement_asset_id();
return true;
};
// At each iteration, we either consume the current order and remove it, or we move to the next asset
for( auto itr = settlement_index.lower_bound(current_asset);
itr != settlement_index.end();
itr = settlement_index.lower_bound(current_asset) )
{
const force_settlement_object& order = *itr;
auto order_id = order.id;
current_asset = order.settlement_asset_id();
const asset_object& mia_object = get(current_asset);
const asset_bitasset_data_object mia = mia_object.bitasset_data(*this);
// Has this order not reached its settlement date?
if( order.settlement_date > head_block_time() )
{
if( next_asset() )
continue;
break;
}
// Can we still settle in this asset?
if( mia.current_feed.settlement_price.is_null() )
{
ilog("Canceling a force settlement in ${asset} because settlement price is null",
("asset", mia_object.symbol));
cancel_order(order);
continue;
}
if( max_settlement_volume.asset_id != current_asset )
max_settlement_volume = mia_object.amount(mia.max_force_settlement_volume(mia_object.dynamic_data(*this).current_supply));
if( mia.force_settled_volume >= max_settlement_volume.amount )
{
/*
ilog("Skipping force settlement in ${asset}; settled ${settled_volume} / ${max_volume}",
("asset", mia_object.symbol)("settlement_price_null",mia.current_feed.settlement_price.is_null())
("settled_volume", mia.force_settled_volume)("max_volume", max_settlement_volume));
*/
if( next_asset() )
continue;
break;
}
auto& pays = order.balance;
auto receives = (order.balance * mia.current_feed.settlement_price);
receives.amount = (fc::uint128_t(receives.amount.value) *
(GRAPHENE_100_PERCENT - mia.options.force_settlement_offset_percent) / GRAPHENE_100_PERCENT).to_uint64();
assert(receives <= order.balance * mia.current_feed.settlement_price);
price settlement_price = pays / receives;
auto& call_index = get_index_type<call_order_index>().indices().get<by_collateral>();
asset settled = mia_object.amount(mia.force_settled_volume);
// Match against the least collateralized short until the settlement is finished or we reach max settlements
while( settled < max_settlement_volume && find_object(order_id) )
{
auto itr = call_index.lower_bound(boost::make_tuple(price::min(mia_object.bitasset_data(*this).options.short_backing_asset,
mia_object.get_id())));
// There should always be a call order, since asset exists!
assert(itr != call_index.end() && itr->debt_type() == mia_object.get_id());
asset max_settlement = max_settlement_volume - settled;
settled += match(*itr, order, settlement_price, max_settlement);
}
modify(mia, [settled](asset_bitasset_data_object& b) {
b.force_settled_volume = settled.amount;
});
}
}
}
void database::update_expired_feeds()
{
auto& asset_idx = get_index_type<asset_index>().indices();
for( const asset_object& a : asset_idx )
{
if( !a.is_market_issued() )
continue;
const asset_bitasset_data_object& b = a.bitasset_data(*this);
if( b.feed_is_expired(head_block_time()) )
{
modify(b, [this](asset_bitasset_data_object& a) {
a.update_median_feeds(head_block_time());
});
check_call_orders(b.current_feed.settlement_price.base.asset_id(*this));
}
if( !b.current_feed.core_exchange_rate.is_null() &&
a.options.core_exchange_rate != b.current_feed.core_exchange_rate )
modify(a, [&b](asset_object& a) {
a.options.core_exchange_rate = b.current_feed.core_exchange_rate;
});
}
}
void database::update_maintenance_flag( bool new_maintenance_flag )
{
modify( get_dynamic_global_properties(), [&]( dynamic_global_property_object& dpo )
{
auto maintenance_flag = dynamic_global_property_object::maintenance_flag;
dpo.dynamic_flags =
(dpo.dynamic_flags & ~maintenance_flag)
| (new_maintenance_flag ? maintenance_flag : 0);
} );
return;
}
void database::update_withdraw_permissions()
{
auto& permit_index = get_index_type<withdraw_permission_index>().indices().get<by_expiration>();
while( !permit_index.empty() && permit_index.begin()->expiration <= head_block_time() )
remove(*permit_index.begin());
}
} }
<commit_msg>db_update.cpp: Fix compiler warning<commit_after>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* 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 HOLDER 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 <graphene/chain/database.hpp>
#include <graphene/chain/db_with.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/global_property_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <graphene/chain/transaction_object.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
#include <graphene/chain/witness_object.hpp>
#include <graphene/chain/protocol/fee_schedule.hpp>
#include <fc/uint128.hpp>
namespace graphene { namespace chain {
void database::update_global_dynamic_data( const signed_block& b )
{
const dynamic_global_property_object& _dgp =
dynamic_global_property_id_type(0)(*this);
uint32_t missed_blocks = get_slot_at_time( b.timestamp );
assert( missed_blocks != 0 );
missed_blocks--;
for( uint32_t i = 0; i < missed_blocks; ++i ) {
const auto& witness_missed = get_scheduled_witness( i+1 )(*this);
if( witness_missed.id != b.witness ) {
/*
const auto& witness_account = witness_missed.witness_account(*this);
if( (fc::time_point::now() - b.timestamp) < fc::seconds(30) )
wlog( "Witness ${name} missed block ${n} around ${t}", ("name",witness_account.name)("n",b.block_num())("t",b.timestamp) );
*/
modify( witness_missed, [&]( witness_object& w ) {
w.total_missed++;
});
}
}
// dynamic global properties updating
modify( _dgp, [&]( dynamic_global_property_object& dgp ){
if( BOOST_UNLIKELY( b.block_num() == 1 ) )
dgp.recently_missed_count = 0;
else if( _checkpoints.size() && _checkpoints.rbegin()->first >= b.block_num() )
dgp.recently_missed_count = 0;
else if( missed_blocks )
dgp.recently_missed_count += GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT*missed_blocks;
else if( dgp.recently_missed_count > GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT )
dgp.recently_missed_count -= GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT;
else if( dgp.recently_missed_count > 0 )
dgp.recently_missed_count--;
dgp.head_block_number = b.block_num();
dgp.head_block_id = b.id();
dgp.time = b.timestamp;
dgp.current_witness = b.witness;
dgp.recent_slots_filled = (
(dgp.recent_slots_filled << 1)
+ 1) << missed_blocks;
dgp.current_aslot += missed_blocks+1;
});
if( !(get_node_properties().skip_flags & skip_undo_history_check) )
{
GRAPHENE_ASSERT( _dgp.recently_missed_count < GRAPHENE_MAX_UNDO_HISTORY, undo_database_exception,
"The database does not have enough undo history to support a blockchain with so many missed blocks. "
"Please add a checkpoint if you would like to continue applying blocks beyond this point.",
("recently_missed",_dgp.recently_missed_count)("max_undo",GRAPHENE_MAX_UNDO_HISTORY) );
}
_undo_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );
_fork_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );
}
void database::update_signing_witness(const witness_object& signing_witness, const signed_block& new_block)
{
const global_property_object& gpo = get_global_properties();
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
uint64_t new_block_aslot = dpo.current_aslot + get_slot_at_time( new_block.timestamp );
share_type witness_pay = std::min( gpo.parameters.witness_pay_per_block, dpo.witness_budget );
modify( dpo, [&]( dynamic_global_property_object& _dpo )
{
_dpo.witness_budget -= witness_pay;
} );
deposit_witness_pay( signing_witness, witness_pay );
modify( signing_witness, [&]( witness_object& _wit )
{
_wit.last_aslot = new_block_aslot;
} );
}
void database::clear_expired_transactions()
{
//Look for expired transactions in the deduplication list, and remove them.
//Transactions must have expired by at least two forking windows in order to be removed.
auto& transaction_idx = static_cast<transaction_index&>(get_mutable_index(implementation_ids, impl_transaction_object_type));
const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
while( (!dedupe_index.empty()) && (head_block_time() > dedupe_index.rbegin()->trx.expiration) )
transaction_idx.remove(*dedupe_index.rbegin());
}
void database::clear_expired_proposals()
{
const auto& proposal_expiration_index = get_index_type<proposal_index>().indices().get<by_expiration>();
while( !proposal_expiration_index.empty() && proposal_expiration_index.begin()->expiration_time <= head_block_time() )
{
const proposal_object& proposal = *proposal_expiration_index.begin();
processed_transaction result;
try {
if( proposal.is_authorized_to_execute(*this) )
{
result = push_proposal(proposal);
//TODO: Do something with result so plugins can process it.
continue;
}
} catch( const fc::exception& e ) {
elog("Failed to apply proposed transaction on its expiration. Deleting it.\n${proposal}\n${error}",
("proposal", proposal)("error", e.to_detail_string()));
}
remove(proposal);
}
}
void database::clear_expired_orders()
{
detail::with_skip_flags( *this,
get_node_properties().skip_flags | skip_authority_check, [&](){
transaction_evaluation_state cancel_context(this);
//Cancel expired limit orders
auto& limit_index = get_index_type<limit_order_index>().indices().get<by_expiration>();
while( !limit_index.empty() && limit_index.begin()->expiration <= head_block_time() )
{
limit_order_cancel_operation canceler;
const limit_order_object& order = *limit_index.begin();
canceler.fee_paying_account = order.seller;
canceler.order = order.id;
apply_operation(cancel_context, canceler);
}
});
//Process expired force settlement orders
auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
if( !settlement_index.empty() )
{
asset_id_type current_asset = settlement_index.begin()->settlement_asset_id();
asset max_settlement_volume;
auto next_asset = [¤t_asset, &settlement_index] {
auto bound = settlement_index.upper_bound(current_asset);
if( bound == settlement_index.end() )
return false;
current_asset = bound->settlement_asset_id();
return true;
};
// At each iteration, we either consume the current order and remove it, or we move to the next asset
for( auto itr = settlement_index.lower_bound(current_asset);
itr != settlement_index.end();
itr = settlement_index.lower_bound(current_asset) )
{
const force_settlement_object& order = *itr;
auto order_id = order.id;
current_asset = order.settlement_asset_id();
const asset_object& mia_object = get(current_asset);
const asset_bitasset_data_object mia = mia_object.bitasset_data(*this);
// Has this order not reached its settlement date?
if( order.settlement_date > head_block_time() )
{
if( next_asset() )
continue;
break;
}
// Can we still settle in this asset?
if( mia.current_feed.settlement_price.is_null() )
{
ilog("Canceling a force settlement in ${asset} because settlement price is null",
("asset", mia_object.symbol));
cancel_order(order);
continue;
}
if( max_settlement_volume.asset_id != current_asset )
max_settlement_volume = mia_object.amount(mia.max_force_settlement_volume(mia_object.dynamic_data(*this).current_supply));
if( mia.force_settled_volume >= max_settlement_volume.amount )
{
/*
ilog("Skipping force settlement in ${asset}; settled ${settled_volume} / ${max_volume}",
("asset", mia_object.symbol)("settlement_price_null",mia.current_feed.settlement_price.is_null())
("settled_volume", mia.force_settled_volume)("max_volume", max_settlement_volume));
*/
if( next_asset() )
continue;
break;
}
auto& pays = order.balance;
auto receives = (order.balance * mia.current_feed.settlement_price);
receives.amount = (fc::uint128_t(receives.amount.value) *
(GRAPHENE_100_PERCENT - mia.options.force_settlement_offset_percent) / GRAPHENE_100_PERCENT).to_uint64();
assert(receives <= order.balance * mia.current_feed.settlement_price);
price settlement_price = pays / receives;
auto& call_index = get_index_type<call_order_index>().indices().get<by_collateral>();
asset settled = mia_object.amount(mia.force_settled_volume);
// Match against the least collateralized short until the settlement is finished or we reach max settlements
while( settled < max_settlement_volume && find_object(order_id) )
{
auto itr = call_index.lower_bound(boost::make_tuple(price::min(mia_object.bitasset_data(*this).options.short_backing_asset,
mia_object.get_id())));
// There should always be a call order, since asset exists!
assert(itr != call_index.end() && itr->debt_type() == mia_object.get_id());
asset max_settlement = max_settlement_volume - settled;
settled += match(*itr, order, settlement_price, max_settlement);
}
modify(mia, [settled](asset_bitasset_data_object& b) {
b.force_settled_volume = settled.amount;
});
}
}
}
void database::update_expired_feeds()
{
auto& asset_idx = get_index_type<asset_index>().indices();
for( const asset_object& a : asset_idx )
{
if( !a.is_market_issued() )
continue;
const asset_bitasset_data_object& b = a.bitasset_data(*this);
if( b.feed_is_expired(head_block_time()) )
{
modify(b, [this](asset_bitasset_data_object& a) {
a.update_median_feeds(head_block_time());
});
check_call_orders(b.current_feed.settlement_price.base.asset_id(*this));
}
if( !b.current_feed.core_exchange_rate.is_null() &&
a.options.core_exchange_rate != b.current_feed.core_exchange_rate )
modify(a, [&b](asset_object& a) {
a.options.core_exchange_rate = b.current_feed.core_exchange_rate;
});
}
}
void database::update_maintenance_flag( bool new_maintenance_flag )
{
modify( get_dynamic_global_properties(), [&]( dynamic_global_property_object& dpo )
{
auto maintenance_flag = dynamic_global_property_object::maintenance_flag;
dpo.dynamic_flags =
(dpo.dynamic_flags & ~maintenance_flag)
| (new_maintenance_flag ? maintenance_flag : 0);
} );
return;
}
void database::update_withdraw_permissions()
{
auto& permit_index = get_index_type<withdraw_permission_index>().indices().get<by_expiration>();
while( !permit_index.empty() && permit_index.begin()->expiration <= head_block_time() )
remove(*permit_index.begin());
}
} }
<|endoftext|>
|
<commit_before>#include "AliPHOSTracker.h"
#include "AliPHOSClusterizerv1.h"
#include "AliPHOSTrackSegmentMakerv1.h"
#include "AliPHOSTrackSegmentMakerv2.h"
#include "AliPHOSPIDv1.h"
#include "AliRunLoader.h"
#include "AliESD.h"
//-------------------------------------------------------------------------
// PHOS tracker.
// Matches ESD tracks with the PHOS and makes the PID.
// Currently, has only one function implemented : PropagateBack(AliESD*)
//-------------------------------------------------------------------------
ClassImp(AliPHOSTracker)
Bool_t AliPHOSTracker::fgDebug = kFALSE ;
Int_t AliPHOSTracker::PropagateBack(AliESD *esd) {
// Called by AliReconstruction
// Creates the tracksegments and Recparticles
// Makes the PID
Int_t eventNumber = fRunLoader->GetEventNumber() ;
TString headerFile(fRunLoader->GetFileName()) ;
TString branchName(fRunLoader->GetEventFolder()->GetName()) ;
AliPHOSTrackSegmentMakerv1 tsm(headerFile, branchName);
// AliPHOSTrackSegmentMakerv2 tsm(headerFile, branchName);
tsm.SetESD(esd) ;
AliPHOSPIDv1 pid(headerFile, branchName);
pid.SetESD(esd) ;
SetDebug() ;
// do current event; the loop over events is done by AliReconstruction::Run()
tsm.SetEventRange(eventNumber, eventNumber) ;
pid.SetEventRange(eventNumber, eventNumber) ;
if ( Debug() ) {
tsm.ExecuteTask("deb all") ;
pid.ExecuteTask("deb all") ;
}
else {
tsm.ExecuteTask("") ;
pid.ExecuteTask("") ;
}
return 0;
}
<commit_msg>Verbose output commented out<commit_after>#include "AliPHOSTracker.h"
#include "AliPHOSClusterizerv1.h"
#include "AliPHOSTrackSegmentMakerv1.h"
#include "AliPHOSTrackSegmentMakerv2.h"
#include "AliPHOSPIDv1.h"
#include "AliRunLoader.h"
#include "AliESD.h"
//-------------------------------------------------------------------------
// PHOS tracker.
// Matches ESD tracks with the PHOS and makes the PID.
// Currently, has only one function implemented : PropagateBack(AliESD*)
//-------------------------------------------------------------------------
ClassImp(AliPHOSTracker)
Bool_t AliPHOSTracker::fgDebug = kFALSE ;
Int_t AliPHOSTracker::PropagateBack(AliESD *esd) {
// Called by AliReconstruction
// Creates the tracksegments and Recparticles
// Makes the PID
Int_t eventNumber = fRunLoader->GetEventNumber() ;
TString headerFile(fRunLoader->GetFileName()) ;
TString branchName(fRunLoader->GetEventFolder()->GetName()) ;
AliPHOSTrackSegmentMakerv1 tsm(headerFile, branchName);
// AliPHOSTrackSegmentMakerv2 tsm(headerFile, branchName);
tsm.SetESD(esd) ;
AliPHOSPIDv1 pid(headerFile, branchName);
pid.SetESD(esd) ;
//PH SetDebug() ;
// do current event; the loop over events is done by AliReconstruction::Run()
tsm.SetEventRange(eventNumber, eventNumber) ;
pid.SetEventRange(eventNumber, eventNumber) ;
if ( Debug() ) {
tsm.ExecuteTask("deb all") ;
pid.ExecuteTask("deb all") ;
}
else {
tsm.ExecuteTask("") ;
pid.ExecuteTask("") ;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "version.hpp"
#include <cutehmi/CuteHMI.hpp>
#include <cutehmi/ProjectModel.hpp>
#include <cutehmi/ErrorInfo.hpp>
#include <cutehmi/xml/ProjectBackend.hpp>
#include <cutehmi/app/CuteApp.hpp>
//<workaround id="cutehmi_view-4" target="Qt" cause="bug">
#include <QApplication>
// Instead of:
// #include <QGuiApplication>
//</workaround>
#include <QQmlApplicationEngine>
#include <QIcon>
#include <QDir>
#include <QtDebug>
#include <QCommandLineParser>
#include <QQmlContext>
#include <QUrl>
#include <QCursor>
#include <QTranslator>
#include <QLibraryInfo>
#include <QFile>
namespace cutehmi {
namespace view {
void loadXMLFile(const QString & filePath, Project & project, QQmlContext & qmlContext)
{
if (filePath.isEmpty()) {
Prompt::Warning(QObject::tr("Empty filename has been provided."));
return;
}
qDebug() << "Loading project file '" << filePath << "'...";
QFile file(filePath);
xml::ProjectBackend xmlBackend(& file, & qmlContext);
try {
project.load(xmlBackend);
Notification::Note(QObject::tr("Succesfuly loaded project file '%1'.").arg(filePath));
} catch (const xml::ProjectBackend::DeviceOpenReadException & ) {
if (!QFileInfo(filePath).exists())
Prompt::Warning(QObject::tr("Could not load project file. File '%1' does not exist.").arg(filePath));
else
Prompt::Warning(QObject::tr("Could not load project file. File '%1' could not be opened for reading.").arg(filePath));
} catch (const Exception & e) {
Prompt::Critical(QObject::tr("Error while parsing '%1' document.").arg(filePath) + "\n\n" + e.what());
}
}
}
}
int main(int argc, char * argv[])
{
QCoreApplication::setOrganizationDomain("cutehmi");
QCoreApplication::setApplicationName("CuteHMI");
QCoreApplication::setApplicationVersion(CUTEHMI_APP_VERSION);
if (qgetenv("QT_IM_MODULE").isEmpty())
qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
qDebug() << "Input method: " << qgetenv("QT_IM_MODULE");
if (qgetenv("QT_IM_MODULE") == "qtvirtualkeyboard") {
if (qgetenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH").isEmpty())
qputenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH", QByteArray(QDir("../layouts").absolutePath().toLocal8Bit()));
qDebug() << "Qt Virtual Keyboard layouts path: " << qgetenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH");
}
//<principle id="Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication">
// "In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the
// platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application
// should make the QApplication be the first created, and last destroyed QObject."
//<workaround id="cutehmi_view-4" target="Qt" cause="bug">
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
cutehmi::app::CuteApp app(argc, argv);
// Instead of:
// QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
// QGuiApplication app(argc, argv);
//<workaround>
app.setWindowIcon(QIcon(":/img/icon.png"));
QCommandLineParser cmd;
cmd.setApplicationDescription("CuteHMI");
cmd.addHelpOption();
cmd.addVersionOption();
QCommandLineOption fullScreenOption({"f", "fullscreen"}, QCoreApplication::translate("main", "Run application in full screen mode."));
cmd.addOption(fullScreenOption);
QCommandLineOption projectOption({"p", "project"}, QCoreApplication::translate("main", "Load CuteHMI project <file>."), QCoreApplication::translate("main", "file"));
cmd.addOption(projectOption);
QCommandLineOption hideCursorOption({"t", "touch"}, QCoreApplication::translate("main", "Touch screen (hides mouse cursor)."));
cmd.addOption(hideCursorOption);
QCommandLineOption styleOption("qstyle", QCoreApplication::translate("main", "Set Qt Quick <style>."), QCoreApplication::translate("main", "style"));
cmd.addOption(styleOption);
QCommandLineOption langOption("lang", QCoreApplication::translate("main", "Choose application <language>."), QCoreApplication::translate("main", "language"));
cmd.addOption(langOption);
QCommandLineOption basedirOption("basedir", QCoreApplication::translate("main", "Set base directory to <dir>."), QCoreApplication::translate("main", "dir"));
cmd.addOption(basedirOption);
cmd.process(app);
qDebug() << "Default locale: " << QLocale();
QTranslator qtTranslator;
if (cmd.isSet(langOption))
qtTranslator.load("qt_" + cmd.value(langOption), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
else
qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(& qtTranslator);
if (cmd.isSet(styleOption)) {
qputenv("QT_QUICK_CONTROLS_STYLE", cmd.value(styleOption).toLocal8Bit());
qDebug() << "Qt Quick style: " << cmd.value(styleOption);
}
if (cmd.isSet(hideCursorOption))
QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
//<workaround id="cutehmi_view-5" target="Qt" cause="bug">
// When run on raw Xorg server application does not show up cursor unless some controls are hovered.
else
QGuiApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
//</workaround>
QDir baseDir(QCoreApplication::applicationDirPath());
if (cmd.isSet(basedirOption))
baseDir = cmd.value(basedirOption);
QString baseDirPath = baseDir.absolutePath() + "/";
qDebug() << "Base directory: " << baseDirPath;
qDebug() << "Library paths: " << QCoreApplication::libraryPaths();
std::unique_ptr<QQmlApplicationEngine> engine(new QQmlApplicationEngine);
engine->addImportPath(baseDirPath + "../QML");
qDebug() << "QML import paths: " << engine->importPathList();
engine->rootContext()->setContextProperty("cutehmi_bin_mainScreenURL", "qrc:/qml/DefaultScreen.qml");
engine->load(QUrl(QStringLiteral("qrc:/qml/MainWindow.qml")));
if (!cmd.value(projectOption).isNull()) {
cutehmi::CuteHMI & cuteHMI = cutehmi::CuteHMI::Instance();
cutehmi::view::loadXMLFile(baseDirPath + cmd.value(projectOption), *cuteHMI.project(), *engine->rootContext());
cutehmi::ProjectNode * appNode = cuteHMI.project()->model()->root().child("cutehmi_app_1");
if (appNode) {
QString source;
appNode->invoke("cutehmi::app::MainScreen", "source", Q_RETURN_ARG(QString, source));
QUrl sourceUrl(source);
if (sourceUrl.isValid()) {
// Assure that URL is not mixing relative path with explicitly specified scheme, which is forbidden. QUrl::isValid() doesn't check this out.
if (!sourceUrl.scheme().isEmpty() && QDir::isRelativePath(sourceUrl.path()))
cutehmi::Prompt::Critical(QObject::tr("URL '%1' contains relative path along with URL scheme, which is forbidden.").arg(sourceUrl.url()));
else {
// If source URL is relative (does not contain scheme), then make absolute URL: file:///baseDirPath/sourceUrl.
if (sourceUrl.isRelative())
sourceUrl = QUrl::fromLocalFile(baseDirPath).resolved(sourceUrl);
// Check if file exists and eventually set context property.
if (sourceUrl.isLocalFile() && !QFile::exists(sourceUrl.toLocalFile()))
cutehmi::Prompt::Critical(QObject::tr("Main screen file '%1' does not exist.").arg(sourceUrl.url()));
else
engine->rootContext()->setContextProperty("cutehmi_bin_mainScreenURL", sourceUrl.url());
}
} else
cutehmi::Prompt::Critical(QObject::tr("Invalid format of main screen URL '%1'.").arg(source));
}
}
//<principle id="Qt-Qt_5_9_1_Reference_Documentation-Qt_Core-C++_Classes-QCoreApplication-exec">
// "We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function because on some
// platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level
// windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after
// the exec() call."
QObject::connect(& app, & cutehmi::app::CuteApp::aboutToQuit, [&]() {
// It's quite important to destroy "engine" before cutehmi::CuteHMI::Instance() members, because they
// may still be used by some QML components (for example in "Component.onDestroyed" handlers).
engine.reset();
cutehmi::CuteHMI::Destroy();
if (cmd.isSet(hideCursorOption))
QGuiApplication::restoreOverrideCursor();
//<workaround ref="cutehmi_view-5">
else
QGuiApplication::restoreOverrideCursor();
//</workaround>
});
//</principle>
return app.exec();
//</principle>
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<commit_msg>Change 'basedir' option semantics.<commit_after>#include "version.hpp"
#include <cutehmi/CuteHMI.hpp>
#include <cutehmi/ProjectModel.hpp>
#include <cutehmi/ErrorInfo.hpp>
#include <cutehmi/xml/ProjectBackend.hpp>
#include <cutehmi/app/CuteApp.hpp>
//<workaround id="cutehmi_view-4" target="Qt" cause="bug">
#include <QApplication>
// Instead of:
// #include <QGuiApplication>
//</workaround>
#include <QQmlApplicationEngine>
#include <QIcon>
#include <QDir>
#include <QtDebug>
#include <QCommandLineParser>
#include <QQmlContext>
#include <QUrl>
#include <QCursor>
#include <QTranslator>
#include <QLibraryInfo>
#include <QFile>
namespace cutehmi {
namespace view {
void loadXMLFile(const QString & filePath, Project & project, QQmlContext & qmlContext)
{
if (filePath.isEmpty()) {
Prompt::Warning(QObject::tr("Empty filename has been provided."));
return;
}
qDebug() << "Loading project file '" << filePath << "'...";
QFile file(filePath);
xml::ProjectBackend xmlBackend(& file, & qmlContext);
try {
project.load(xmlBackend);
Notification::Note(QObject::tr("Succesfuly loaded project file '%1'.").arg(filePath));
} catch (const xml::ProjectBackend::DeviceOpenReadException & ) {
if (!QFileInfo(filePath).exists())
Prompt::Warning(QObject::tr("Could not load project file. File '%1' does not exist.").arg(filePath));
else
Prompt::Warning(QObject::tr("Could not load project file. File '%1' could not be opened for reading.").arg(filePath));
} catch (const Exception & e) {
Prompt::Critical(QObject::tr("Error while parsing '%1' document.").arg(filePath) + "\n\n" + e.what());
}
}
}
}
int main(int argc, char * argv[])
{
QCoreApplication::setOrganizationDomain("cutehmi");
QCoreApplication::setApplicationName("CuteHMI");
QCoreApplication::setApplicationVersion(CUTEHMI_APP_VERSION);
if (qgetenv("QT_IM_MODULE").isEmpty())
qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
qDebug() << "Input method: " << qgetenv("QT_IM_MODULE");
if (qgetenv("QT_IM_MODULE") == "qtvirtualkeyboard") {
if (qgetenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH").isEmpty())
qputenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH", QByteArray(QDir("../layouts").absolutePath().toLocal8Bit()));
qDebug() << "Qt Virtual Keyboard layouts path: " << qgetenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH");
}
//<principle id="Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication">
// "In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the
// platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application
// should make the QApplication be the first created, and last destroyed QObject."
//<workaround id="cutehmi_view-4" target="Qt" cause="bug">
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
cutehmi::app::CuteApp app(argc, argv);
// Instead of:
// QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
// QGuiApplication app(argc, argv);
//<workaround>
app.setWindowIcon(QIcon(":/img/icon.png"));
QCommandLineParser cmd;
cmd.setApplicationDescription("CuteHMI");
cmd.addHelpOption();
cmd.addVersionOption();
QCommandLineOption fullScreenOption({"f", "fullscreen"}, QCoreApplication::translate("main", "Run application in full screen mode."));
cmd.addOption(fullScreenOption);
QCommandLineOption projectOption({"p", "project"}, QCoreApplication::translate("main", "Load CuteHMI project <file>."), QCoreApplication::translate("main", "file"));
cmd.addOption(projectOption);
QCommandLineOption hideCursorOption({"t", "touch"}, QCoreApplication::translate("main", "Touch screen (hides mouse cursor)."));
cmd.addOption(hideCursorOption);
QCommandLineOption styleOption("qstyle", QCoreApplication::translate("main", "Set Qt Quick <style>."), QCoreApplication::translate("main", "style"));
cmd.addOption(styleOption);
QCommandLineOption langOption("lang", QCoreApplication::translate("main", "Choose application <language>."), QCoreApplication::translate("main", "language"));
cmd.addOption(langOption);
QCommandLineOption basedirOption("basedir", QCoreApplication::translate("main", "Set base directory to <dir>."), QCoreApplication::translate("main", "dir"));
cmd.addOption(basedirOption);
cmd.process(app);
qDebug() << "Default locale: " << QLocale();
QTranslator qtTranslator;
if (cmd.isSet(langOption))
qtTranslator.load("qt_" + cmd.value(langOption), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
else
qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(& qtTranslator);
if (cmd.isSet(styleOption)) {
qputenv("QT_QUICK_CONTROLS_STYLE", cmd.value(styleOption).toLocal8Bit());
qDebug() << "Qt Quick style: " << cmd.value(styleOption);
}
if (cmd.isSet(hideCursorOption))
QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
//<workaround id="cutehmi_view-5" target="Qt" cause="bug">
// When run on raw Xorg server application does not show up cursor unless some controls are hovered.
else
QGuiApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
//</workaround>
QDir baseDir(QCoreApplication::applicationDirPath() + "/..");
if (cmd.isSet(basedirOption))
baseDir = cmd.value(basedirOption);
QString baseDirPath = baseDir.absolutePath() + "/";
qDebug() << "Base directory: " << baseDirPath;
qDebug() << "Library paths: " << QCoreApplication::libraryPaths();
std::unique_ptr<QQmlApplicationEngine> engine(new QQmlApplicationEngine);
engine->addImportPath(baseDirPath + "QML");
qDebug() << "QML import paths: " << engine->importPathList();
engine->rootContext()->setContextProperty("cutehmi_bin_mainScreenURL", "qrc:/qml/DefaultScreen.qml");
engine->load(QUrl(QStringLiteral("qrc:/qml/MainWindow.qml")));
if (!cmd.value(projectOption).isNull()) {
cutehmi::CuteHMI & cuteHMI = cutehmi::CuteHMI::Instance();
cutehmi::view::loadXMLFile(baseDirPath + cmd.value(projectOption), *cuteHMI.project(), *engine->rootContext());
cutehmi::ProjectNode * appNode = cuteHMI.project()->model()->root().child("cutehmi_app_1");
if (appNode) {
QString source;
appNode->invoke("cutehmi::app::MainScreen", "source", Q_RETURN_ARG(QString, source));
QUrl sourceUrl(source);
if (sourceUrl.isValid()) {
// Assure that URL is not mixing relative path with explicitly specified scheme, which is forbidden. QUrl::isValid() doesn't check this out.
if (!sourceUrl.scheme().isEmpty() && QDir::isRelativePath(sourceUrl.path()))
cutehmi::Prompt::Critical(QObject::tr("URL '%1' contains relative path along with URL scheme, which is forbidden.").arg(sourceUrl.url()));
else {
// If source URL is relative (does not contain scheme), then make absolute URL: file:///baseDirPath/sourceUrl.
if (sourceUrl.isRelative())
sourceUrl = QUrl::fromLocalFile(baseDirPath).resolved(sourceUrl);
// Check if file exists and eventually set context property.
if (sourceUrl.isLocalFile() && !QFile::exists(sourceUrl.toLocalFile()))
cutehmi::Prompt::Critical(QObject::tr("Main screen file '%1' does not exist.").arg(sourceUrl.url()));
else
engine->rootContext()->setContextProperty("cutehmi_bin_mainScreenURL", sourceUrl.url());
}
} else
cutehmi::Prompt::Critical(QObject::tr("Invalid format of main screen URL '%1'.").arg(source));
}
}
//<principle id="Qt-Qt_5_9_1_Reference_Documentation-Qt_Core-C++_Classes-QCoreApplication-exec">
// "We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function because on some
// platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level
// windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after
// the exec() call."
QObject::connect(& app, & cutehmi::app::CuteApp::aboutToQuit, [&]() {
// It's quite important to destroy "engine" before cutehmi::CuteHMI::Instance() members, because they
// may still be used by some QML components (for example in "Component.onDestroyed" handlers).
engine.reset();
cutehmi::CuteHMI::Destroy();
if (cmd.isSet(hideCursorOption))
QGuiApplication::restoreOverrideCursor();
//<workaround ref="cutehmi_view-5">
else
QGuiApplication::restoreOverrideCursor();
//</workaround>
});
//</principle>
return app.exec();
//</principle>
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<|endoftext|>
|
<commit_before>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
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/>.
*************************************************************************/
#ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#include <vector>
#include <limits>
#include <string>
#include <boost/shared_ptr.hpp>
#include <Eigen/Core>
#include <ff/utils/assertions.hpp>
#include <ff/utils/profiling.hpp>
#include <fl/util/traits.hpp>
#include <ff/utils/helper_functions.hpp>
#include <fl/distribution/gaussian.hpp>
#include <ff/distributions/sum_of_deltas.hpp>
#include <fl/distribution/interface/gaussian_map.hpp>
#include <ff/models/observation_models/interfaces/rao_blackwell_observation_model.hpp>
#include <ff/models/process_models/interfaces/stationary_process_model.hpp>
namespace fl
{
template<typename ProcessModel, typename ObservationModel>
class RaoBlackwellCoordinateParticleFilter
{
public:
typedef typename Traits<ProcessModel>::Scalar Scalar;
typedef typename Traits<ProcessModel>::State State;
typedef typename Traits<ProcessModel>::Input Input;
typedef typename Traits<ProcessModel>::Noise Noise;
typedef typename ObservationModel::Observation Observation;
// state distribution
typedef SumOfDeltas<State> StateDistributionType;
public:
RaoBlackwellCoordinateParticleFilter(
const boost::shared_ptr<ProcessModel> process_model,
const boost::shared_ptr<ObservationModel> observation_model,
const std::vector<std::vector<size_t>>& sampling_blocks,
const Scalar& max_kl_divergence = 0):
observation_model_(observation_model),
process_model_(process_model),
max_kl_divergence_(max_kl_divergence)
{
static_assert_base(
ProcessModel,
StationaryProcessModel<State, Input>);
static_assert_base(
ProcessModel,
GaussianMap<State, Noise>);
static_assert_base(
ObservationModel,
RaoBlackwellObservationModel<State, Observation>);
SamplingBlocks(sampling_blocks);
}
virtual ~RaoBlackwellCoordinateParticleFilter() {}
public:
void Filter(const Observation& observation,
const Scalar& delta_time,
const Input& input)
{
observation_model_->SetObservation(observation, delta_time);
loglikes_ = std::vector<Scalar>(samples_.size(), 0);
noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->NoiseDimension()));
next_samples_ = samples_;
for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++)
{
INIT_PROFILING;
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++)
noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.Sample()(0);
}
MEASURE("sampling");
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
process_model_->Condition(delta_time,
samples_[particle_index],
input);
}
MEASURE("conditioning");
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
next_samples_[particle_index] = process_model_->MapStandardGaussian(noises_[particle_index]);
}
MEASURE("propagation");
bool update_occlusions = (block_index == sampling_blocks_.size()-1);
std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_,
indices_,
update_occlusions);
MEASURE("evaluation");
std::vector<Scalar> delta_loglikes(new_loglikes.size());
for(size_t i = 0; i < delta_loglikes.size(); i++)
delta_loglikes[i] = new_loglikes[i] - loglikes_[i];
loglikes_ = new_loglikes;
UpdateWeights(delta_loglikes);
MEASURE("updating weights");
}
samples_ = next_samples_;
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
void Resample(const size_t& sample_count)
{
std::vector<State> samples(sample_count);
std::vector<size_t> indices(sample_count);
std::vector<Noise> noises(sample_count);
std::vector<State> next_samples(sample_count);
std::vector<Scalar> loglikes(sample_count);
fl::hf::DiscreteSampler sampler(log_weights_);
for(size_t i = 0; i < sample_count; i++)
{
size_t index = sampler.Sample();
samples[i] = samples_[index];
indices[i] = indices_[index];
noises[i] = noises_[index];
next_samples[i] = next_samples_[index];
loglikes[i] = loglikes_[index];
}
samples_ = samples;
indices_ = indices;
noises_ = noises;
next_samples_ = next_samples;
loglikes_ = loglikes;
log_weights_ = std::vector<Scalar>(samples_.size(), 0.);
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
private:
void UpdateWeights(std::vector<Scalar> log_weight_diffs)
{
for(size_t i = 0; i < log_weight_diffs.size(); i++)
log_weights_[i] += log_weight_diffs[i];
std::vector<Scalar> weights = log_weights_;
fl::hf::Sort(weights, 1);
for(int i = weights.size() - 1; i >= 0; i--)
weights[i] -= weights[0];
weights = fl::hf::Apply<Scalar, Scalar>(weights, std::exp);
weights = fl::hf::SetSum(weights, Scalar(1));
// compute KL divergence to uniform distribution KL(p|u)
Scalar kl_divergence = std::log(Scalar(weights.size()));
for(size_t i = 0; i < weights.size(); i++)
{
Scalar information = - std::log(weights[i]) * weights[i];
if(!std::isfinite(information))
information = 0; // the limit for weight -> 0 is equal to 0
kl_divergence -= information;
}
if(kl_divergence > max_kl_divergence_)
Resample(samples_.size());
}
public:
// set
void Samples(const std::vector<State >& samples)
{
samples_ = samples;
indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset();
log_weights_ = std::vector<Scalar>(samples_.size(), 0);
}
void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks)
{
sampling_blocks_ = sampling_blocks;
// make sure sizes are consistent
size_t dimension = 0;
for(size_t i = 0; i < sampling_blocks_.size(); i++)
for(size_t j = 0; j < sampling_blocks_[i].size(); j++)
dimension++;
if(dimension != process_model_->NoiseDimension())
{
std::cout << "the dimension of the sampling blocks is " << dimension
<< " while the dimension of the noise is "
<< process_model_->NoiseDimension() << std::endl;
exit(-1);
}
}
// get
const std::vector<State>& Samples() const
{
return samples_;
}
StateDistributionType& StateDistribution()
{
return state_distribution_;
}
private:
// internal state TODO: THIS COULD BE MADE MORE COMPACT!!
StateDistributionType state_distribution_;
std::vector<State > samples_;
std::vector<size_t> indices_;
std::vector<Scalar> log_weights_;
std::vector<Noise> noises_;
std::vector<State> next_samples_;
std::vector<Scalar> loglikes_;
// observation model
boost::shared_ptr<ObservationModel> observation_model_;
// process model
boost::shared_ptr<ProcessModel> process_model_;
// parameters
std::vector<std::vector<size_t>> sampling_blocks_;
Scalar max_kl_divergence_;
// distribution for sampling
Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_;
};
}
#endif
<commit_msg>Filter function fixed<commit_after>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
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/>.
*************************************************************************/
#ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#include <vector>
#include <limits>
#include <string>
#include <boost/shared_ptr.hpp>
#include <Eigen/Core>
#include <fl/util/assertions.hpp>
#include <fl/util/profiling.hpp>
#include <fl/util/traits.hpp>
#include <ff/utils/helper_functions.hpp>
#include <fl/distribution/gaussian.hpp>
#include <ff/distributions/sum_of_deltas.hpp>
#include <fl/distribution/interface/gaussian_map.hpp>
#include <ff/models/observation_models/interfaces/rao_blackwell_observation_model.hpp>
#include <ff/models/process_models/interfaces/stationary_process_model.hpp>
namespace fl
{
template<typename ProcessModel, typename ObservationModel>
class RaoBlackwellCoordinateParticleFilter
{
public:
typedef typename Traits<ProcessModel>::Scalar Scalar;
typedef typename Traits<ProcessModel>::State State;
typedef typename Traits<ProcessModel>::Input Input;
typedef typename Traits<ProcessModel>::Noise Noise;
typedef typename ObservationModel::Observation Observation;
// state distribution
typedef SumOfDeltas<State> StateDistributionType;
public:
RaoBlackwellCoordinateParticleFilter(
const boost::shared_ptr<ProcessModel> process_model,
const boost::shared_ptr<ObservationModel> observation_model,
const std::vector<std::vector<size_t>>& sampling_blocks,
const Scalar& max_kl_divergence = 0):
observation_model_(observation_model),
process_model_(process_model),
max_kl_divergence_(max_kl_divergence)
{
static_assert_base(
ProcessModel,
StationaryProcessModel<State, Input>);
static_assert_base(
ProcessModel,
GaussianMap<State, Noise>);
static_assert_base(
ObservationModel,
RaoBlackwellObservationModel<State, Observation>);
SamplingBlocks(sampling_blocks);
}
virtual ~RaoBlackwellCoordinateParticleFilter() { }
public:
void Filter(const Observation& observation,
const Scalar& delta_time,
const Input& input)
{
observation_model_->SetObservation(observation, delta_time);
loglikes_ = std::vector<Scalar>(samples_.size(), 0);
noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->NoiseDimension()));
next_samples_ = samples_;
for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++)
{
INIT_PROFILING;
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++)
noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.Sample()(0);
}
MEASURE("sampling");
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
process_model_->Condition(delta_time,
samples_[particle_index],
input);
next_samples_[particle_index] = process_model_->MapStandardGaussian(noises_[particle_index]);
}
MEASURE("propagation");
bool update_occlusions = (block_index == sampling_blocks_.size()-1);
std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_,
indices_,
update_occlusions);
MEASURE("evaluation");
std::vector<Scalar> delta_loglikes(new_loglikes.size());
for(size_t i = 0; i < delta_loglikes.size(); i++)
delta_loglikes[i] = new_loglikes[i] - loglikes_[i];
loglikes_ = new_loglikes;
UpdateWeights(delta_loglikes);
MEASURE("updating weights");
}
samples_ = next_samples_;
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
void Resample(const size_t& sample_count)
{
std::vector<State> samples(sample_count);
std::vector<size_t> indices(sample_count);
std::vector<Noise> noises(sample_count);
std::vector<State> next_samples(sample_count);
std::vector<Scalar> loglikes(sample_count);
fl::hf::DiscreteSampler sampler(log_weights_);
for(size_t i = 0; i < sample_count; i++)
{
size_t index = sampler.Sample();
samples[i] = samples_[index];
indices[i] = indices_[index];
noises[i] = noises_[index];
next_samples[i] = next_samples_[index];
loglikes[i] = loglikes_[index];
}
samples_ = samples;
indices_ = indices;
noises_ = noises;
next_samples_ = next_samples;
loglikes_ = loglikes;
log_weights_ = std::vector<Scalar>(samples_.size(), 0.);
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
private:
void UpdateWeights(std::vector<Scalar> log_weight_diffs)
{
for(size_t i = 0; i < log_weight_diffs.size(); i++)
log_weights_[i] += log_weight_diffs[i];
std::vector<Scalar> weights = log_weights_;
fl::hf::Sort(weights, 1);
for(int i = weights.size() - 1; i >= 0; i--)
weights[i] -= weights[0];
weights = fl::hf::Apply<Scalar, Scalar>(weights, std::exp);
weights = fl::hf::SetSum(weights, Scalar(1));
// compute KL divergence to uniform distribution KL(p|u)
Scalar kl_divergence = std::log(Scalar(weights.size()));
for(size_t i = 0; i < weights.size(); i++)
{
Scalar information = - std::log(weights[i]) * weights[i];
if(!std::isfinite(information))
information = 0; // the limit for weight -> 0 is equal to 0
kl_divergence -= information;
}
if(kl_divergence > max_kl_divergence_)
Resample(samples_.size());
}
public:
// set
void Samples(const std::vector<State >& samples)
{
samples_ = samples;
indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset();
log_weights_ = std::vector<Scalar>(samples_.size(), 0);
}
void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks)
{
sampling_blocks_ = sampling_blocks;
// make sure sizes are consistent
size_t dimension = 0;
for(size_t i = 0; i < sampling_blocks_.size(); i++)
for(size_t j = 0; j < sampling_blocks_[i].size(); j++)
dimension++;
if(dimension != process_model_->NoiseDimension())
{
std::cout << "the dimension of the sampling blocks is " << dimension
<< " while the dimension of the noise is "
<< process_model_->NoiseDimension() << std::endl;
exit(-1);
}
}
// get
const std::vector<State>& Samples() const
{
return samples_;
}
StateDistributionType& StateDistribution()
{
return state_distribution_;
}
private:
// internal state TODO: THIS COULD BE MADE MORE COMPACT!!
StateDistributionType state_distribution_;
std::vector<State > samples_;
std::vector<size_t> indices_;
std::vector<Scalar> log_weights_;
std::vector<Noise> noises_;
std::vector<State> next_samples_;
std::vector<Scalar> loglikes_;
// observation model
boost::shared_ptr<ObservationModel> observation_model_;
// process model
boost::shared_ptr<ProcessModel> process_model_;
// parameters
std::vector<std::vector<size_t>> sampling_blocks_;
Scalar max_kl_divergence_;
// distribution for sampling
Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Nicolas Pope
*/
#ifndef DHARC_NODE_HPP_
#define DHARC_NODE_HPP_
#include <ostream>
#include <istream>
#include <string>
#include <cstdint>
#include "dharc/rpc_packer.hpp"
namespace dharc {
static_assert(sizeof(double) <= 64, "Double is too big");
/* Constants for special node types */
enum {
kNullNode = 0,
kTrueNode = 1,
kFalseNode = 2
};
/**
* Node Identifier, Plain Old Data type.
* Represents a concept and point in the dharc hypergraph. Two Nodes
* together identify an arc in the hypergraph. Any raw data type can
* be represented by a corresponding Node and Nodes can be compared with
* each other.
*/
struct Node {
enum struct Type : uint8_t {
special,
integer,
real,
character,
constant,
allocated,
};
Type t;
union {
uint64_t ui;
int64_t i;
double d;
char c;
};
/* Type casting to a Node */
Node() = default;
constexpr Node(Type type, int64_t value) : t(type), i(value) {}
explicit constexpr Node(int value) : t(Type::integer), i(value) {}
explicit constexpr Node(float value) : t(Type::real), d(value) {}
explicit constexpr Node(double value) : t(Type::real), d(value) {}
explicit constexpr Node(char value) : t(Type::character), c(value) {}
explicit constexpr Node(bool value)
: t(Type::special), i((value) ? kTrueNode : kFalseNode) {}
/**
* Generate a Node from a string.
* The string must be a valid format or the null Node is returned.
* Integers (Base 10), floating point numbers, characters expressed as
* 'a', the keywords "true", "false and "null" are all valid. Raw Node
* strings of the form "[<type>:<number>]" are also accepted.
*
* @param str Valid node string.
* @return null Node or Node form the string.
*/
explicit Node(const std::string &str);
/** Same as for Node(const std::string &str); */
explicit Node(const char *str);
/* Type casting from a Node */
explicit operator int() const;
explicit operator float() const;
explicit operator double() const;
explicit operator char() const;
explicit operator bool() const;
/**
* Convert the Node to a string object.
* Special types are converted to corresponding words and numeric types
* are converted to standard base 10 string form. Other kinds of Node
* are shown as <type>:<number>. Calling fromString on the returned
* string is guaranteed to reproduce the same Node.
*
* @return String representation of the node.
*/
explicit operator std::string() const;
};
/**
* Integer NID literals.
* e.g. Nid x = 1234_n;
*/
constexpr Node operator"" _n(unsigned long long value) {
return Node(static_cast<int>(value));
}
/**
* Real NID literals.
* e.g. Nid x = 12.34_n;
*/
constexpr Node operator"" _n(long double value) {
return Node(static_cast<double>(value));
}
/**
* Character NID literals.
* e.g. Nid x = 'a'_n;
*/
constexpr Node operator"" _n(char value) {
return Node(Node::Type::character, value);
}
/* Special node constants */
constexpr Node null_n = Node(Node::Type::special, kNullNode);
constexpr Node true_n = Node(Node::Type::special, kTrueNode);
constexpr Node false_n = Node(Node::Type::special, kFalseNode);
/* Relational operators */
constexpr bool operator==(const Node &a, const Node &b) {
return a.t == b.t && a.i == b.i;
}
constexpr bool operator!=(const Node &a, const Node &b) {
return a.t != b.t || a.i != b.i;
}
constexpr bool operator<(const Node &a, const Node &b) {
return a.t < b.t || (a.t == b.t && a.i < b.i);
}
constexpr bool operator>(const Node &a, const Node &b) {
return a.t > b.t || (a.t == b.t && a.i > b.i);
}
constexpr bool operator<=(const Node &a, const Node &b) {
return a.t <= b.t || (a.t == b.t && a.i <= b.i);
}
constexpr bool operator>=(const Node &a, const Node &b) {
return a.t >= b.t || (a.t == b.t && a.i >= b.i);
}
/* Stream Operators */
std::ostream &operator<<(std::ostream &os, const Node &n);
std::istream &operator>>(std::istream &is, Node &n);
/* Pack and unpack for remote procedure call */
namespace rpc {
template <>
struct Packer<Node> {
static void pack(std::ostream &os, const Node &n);
static Node unpack(std::istream &is);
};
}; // namespace rpc
}; // namespace dharc
#endif // DHARC_NODE_HPP_
<commit_msg>Fixed uninitialized node components bug<commit_after>/*
* Copyright 2015 Nicolas Pope
*/
#ifndef DHARC_NODE_HPP_
#define DHARC_NODE_HPP_
#include <ostream>
#include <istream>
#include <string>
#include <cstdint>
#include "dharc/rpc_packer.hpp"
namespace dharc {
static_assert(sizeof(double) <= 64, "Double is too big");
/* Constants for special node types */
enum {
kNullNode = 0,
kTrueNode = 1,
kFalseNode = 2
};
/**
* Node Identifier, Plain Old Data type.
* Represents a concept and point in the dharc hypergraph. Two Nodes
* together identify an arc in the hypergraph. Any raw data type can
* be represented by a corresponding Node and Nodes can be compared with
* each other.
*/
struct Node {
enum struct Type : uint8_t {
special,
integer,
real,
character,
constant,
allocated,
};
Type t;
union {
uint64_t ui;
int64_t i;
double d;
char c;
};
/* Type casting to a Node */
Node() = default;
constexpr Node(Type type, int64_t value) : t(type), i(value) {}
explicit constexpr Node(int value) : t(Type::integer), i(value) {}
explicit constexpr Node(float value) : t(Type::real), d(value) {}
explicit constexpr Node(double value) : t(Type::real), d(value) {}
explicit constexpr Node(char value) : t(Type::character), i(value) {}
explicit constexpr Node(bool value)
: t(Type::special), i((value) ? kTrueNode : kFalseNode) {}
/**
* Generate a Node from a string.
* The string must be a valid format or the null Node is returned.
* Integers (Base 10), floating point numbers, characters expressed as
* 'a', the keywords "true", "false and "null" are all valid. Raw Node
* strings of the form "[<type>:<number>]" are also accepted.
*
* @param str Valid node string.
* @return null Node or Node form the string.
*/
explicit Node(const std::string &str);
/** Same as for Node(const std::string &str); */
explicit Node(const char *str);
/* Type casting from a Node */
explicit operator int() const;
explicit operator float() const;
explicit operator double() const;
explicit operator char() const;
explicit operator bool() const;
/**
* Convert the Node to a string object.
* Special types are converted to corresponding words and numeric types
* are converted to standard base 10 string form. Other kinds of Node
* are shown as <type>:<number>. Calling fromString on the returned
* string is guaranteed to reproduce the same Node.
*
* @return String representation of the node.
*/
explicit operator std::string() const;
};
/**
* Integer NID literals.
* e.g. Nid x = 1234_n;
*/
constexpr Node operator"" _n(unsigned long long value) {
return Node(static_cast<int>(value));
}
/**
* Real NID literals.
* e.g. Nid x = 12.34_n;
*/
constexpr Node operator"" _n(long double value) {
return Node(static_cast<double>(value));
}
/**
* Character NID literals.
* e.g. Nid x = 'a'_n;
*/
constexpr Node operator"" _n(char value) {
return Node(Node::Type::character, value);
}
/* Special node constants */
constexpr Node null_n = Node(Node::Type::special, kNullNode);
constexpr Node true_n = Node(Node::Type::special, kTrueNode);
constexpr Node false_n = Node(Node::Type::special, kFalseNode);
/* Relational operators */
constexpr bool operator==(const Node &a, const Node &b) {
return a.t == b.t && a.i == b.i;
}
constexpr bool operator!=(const Node &a, const Node &b) {
return a.t != b.t || a.i != b.i;
}
constexpr bool operator<(const Node &a, const Node &b) {
return a.t < b.t || (a.t == b.t && a.i < b.i);
}
constexpr bool operator>(const Node &a, const Node &b) {
return a.t > b.t || (a.t == b.t && a.i > b.i);
}
constexpr bool operator<=(const Node &a, const Node &b) {
return a.t <= b.t || (a.t == b.t && a.i <= b.i);
}
constexpr bool operator>=(const Node &a, const Node &b) {
return a.t >= b.t || (a.t == b.t && a.i >= b.i);
}
/* Stream Operators */
std::ostream &operator<<(std::ostream &os, const Node &n);
std::istream &operator>>(std::istream &is, Node &n);
/* Pack and unpack for remote procedure call */
namespace rpc {
template <>
struct Packer<Node> {
static void pack(std::ostream &os, const Node &n);
static Node unpack(std::istream &is);
};
}; // namespace rpc
}; // namespace dharc
#endif // DHARC_NODE_HPP_
<|endoftext|>
|
<commit_before>#include "..\I<%= $cur_module.name %>.h"
#include "logging/RhoLog.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "<%= $cur_module.name %>"
#include "ruby/ext/rho/rhoruby.h"
#include "common/StringConverter.h"
#include "common/AutoPointer.h"
using namespace rho;
using namespace rho::common;
extern "C"
{
void rho_wm_impl_performOnUiThread(rho::common::IRhoRunnable* pTask);
VALUE getRuby_<%= $cur_module.name %>_Module();
<% if $cur_module.is_template_default_instance %>
VALUE rb_<%= $cur_module.name %>_s_default(VALUE klass)
{
rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();
return rho_ruby_create_object_with_id( klass, convertToStringA(strDefaultID).c_str() );
}
VALUE rb_<%= $cur_module.name %>_s_set_default(VALUE klass, VALUE valObj)
{
const char* szID = rho_ruby_get_object_id( valObj );
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->setDefaultID(convertToStringW(szID));
return rho_ruby_get_NIL();
}
<% end %>
extern "C" static void
string_iter(const char* szVal, void* par)
{
rho::Vector<rho::StringW>& ar = *((rho::Vector<rho::StringW>*)(par));
ar.addElement( convertToStringW(szVal) );
}
static void getStringArrayFromValue(VALUE val, rho::Vector<rho::StringW>& res)
{
rho_ruby_enum_strary(val, string_iter, &res);
}
extern "C" static void hash_eachstr(const char* szName, const char* szVal, void* par)
{
rho::Hashtable<rho::StringW, rho::StringW>& hash = *((rho::Hashtable<rho::StringW, rho::StringW>*)(par));
hash.put( convertToStringW(szName), convertToStringW(szVal) );
}
static void getStringHashFromValue(VALUE val, rho::Hashtable<rho::StringW, rho::StringW>& res)
{
rho_ruby_enum_strhash(val, hash_eachstr, &res);
}
//Module instance methods
<% $cur_module.methods.each do |module_method| %>
<% if module_method.access == ModuleMethod::ACCESS_STATIC %>
<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, true)%>
<% else %>
static VALUE _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(int argc, VALUE *argv, I<%= $cur_module.name %>* pObj)
<% end %>
{
CMethodResult oRes;
<% if module_method.is_factory_method %>
oRes.setRubyObjectClass(getRuby_<%= $cur_module.name %>_Module());
<% end %>
rho::common::IRhoRunnable* pFunctor = 0;
bool bUseCallback = false;
int nCallbackArg = 0;
<% functor_params = ""; first_arg = 0; %>
<% module_method.params.each do |param| %>
nCallbackArg = <%= first_arg + 1 %>;
<% if !param.can_be_nil %>
if ( argc == <%= first_arg %> )
{
oRes.setArgError(L"Wrong number of arguments: " + convertToStringW(argc) + L" instead of " + convertToStringW(<%= module_method.params.size() %>) );
return oRes.toRuby();
}
<% end %>
<% if param.type == MethodParam::TYPE_STRING %>
<%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;
if ( argc > <%= first_arg %> )
{
if ( rho_ruby_is_string(argv[<%= first_arg %>]) )
{
arg<%= first_arg %> = convertToStringW(getStringFromValue(argv[<%= first_arg %>]));
<% if first_arg == 0 %>
oRes.setStringParam(getStringFromValue(argv[<%= first_arg %>]));
<% end %>
}
else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))
{
oRes.setArgError(L"Type error: argument " L<%= "\"#{first_arg}\"" %> L" should be " L<%= "\"#{param.type.downcase}\"" %> );
return oRes.toRuby();
}
}
<% end %>
<% if param.type == MethodParam::TYPE_ARRAY %>
<%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;
if ( argc > <%= first_arg %> )
{
if ( rho_ruby_is_array(argv[<%= first_arg %>]) )
getStringArrayFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);
else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))
{
oRes.setArgError(L"Type error: argument " L<%= "\"#{first_arg}\"" %> L" should be " L<%= "\"#{param.type.downcase}\"" %> );
return oRes.toRuby();
}
}
<% end %>
<% if param.type == MethodParam::TYPE_HASH %>
<%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;
if ( argc > <%= first_arg %> )
{
if ( rho_ruby_is_hash(argv[<%= first_arg %>]) )
getStringHashFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);
else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))
{
oRes.setArgError(L"Type error: argument " L<%= "\"#{first_arg}\"" %> L" should be " L<%= "\"#{param.type.downcase}\"" %> );
return oRes.toRuby();
}
}
<% end %>
<% functor_params += "arg#{first_arg}, " %>
<% first_arg = first_arg+1 %>
<% end %>
if ( argc > nCallbackArg )
{
<% if module_method.has_callback == ModuleMethod::CALLBACK_NONE %>
oRes.setArgError(L"Wrong number of arguments: " + convertToStringW(argc) + L" instead of " + convertToStringW(<%= module_method.params.size() %>) );
return oRes.toRuby();
<% end %>
if ( !rho_ruby_is_string(argv[nCallbackArg]) )
{
oRes.setArgError(L"Type error: callback should be String");
return oRes.toRuby();
}
oRes.setCallInUIThread(<%= module_method.is_run_in_ui_thread ? "true" : "false" %>);
oRes.setRubyCallback( getStringFromValue(argv[nCallbackArg]) );
if ( argc > nCallbackArg + 1 )
{
if ( !rho_ruby_is_string(argv[nCallbackArg + 1]) )
{
oRes.setArgError(L"Type error: callback parameter should be String");
return oRes.toRuby();
}
oRes.setCallbackParam( getStringFromValue(argv[nCallbackArg + 1]) );
}
}
<% if module_method.access != ModuleMethod::ACCESS_STATIC %>
pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( pObj, &I<%= $cur_module.name %>::<%= module_method.name %>, <%= functor_params %> oRes );
<% else %>
pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS(), &I<%= $cur_module.name %>Singleton::<%= module_method.name %>, <%= functor_params %> oRes );
<% end %>
<% if module_method.is_run_in_ui_thread %>
rho_wm_impl_performOnUiThread( pFunctor );
<% elsif module_method.is_run_in_thread %>
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );
<% else %>
if ( bUseCallback )
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );
else
{
delete pFunctor;
<% if module_method.access != ModuleMethod::ACCESS_STATIC %>
pObj-><%= module_method.name %>( <%= functor_params %> oRes );
<% else %>
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()-><%= module_method.name %>( <%= functor_params %> oRes );
<% end %>
}
<% end %>
return oRes.toRuby();
}
<% if module_method.access != ModuleMethod::ACCESS_STATIC %>
<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, module_method.access == ModuleMethod::ACCESS_STATIC)%>
{
const char* szID = rho_ruby_get_object_id( obj );
I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(convertToStringW(szID));
return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);
}
<% end %>
<% if $cur_module.is_template_default_instance && module_method.access == ModuleMethod::ACCESS_INSTANCE%>
<%= api_generator_MakeRubyMethodDecl($cur_module.name + "_def", module_method, true)%>
{
rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();
I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(strDefaultID);
return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);
}
<% end %>
<% end %>
}<commit_msg>api_generator:cpp: fix ruby wrap<commit_after>#include "..\I<%= $cur_module.name %>.h"
#include "logging/RhoLog.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "<%= $cur_module.name %>"
#include "ruby/ext/rho/rhoruby.h"
#include "common/StringConverter.h"
#include "common/AutoPointer.h"
using namespace rho;
using namespace rho::common;
extern "C"
{
void rho_wm_impl_performOnUiThread(rho::common::IRhoRunnable* pTask);
VALUE getRuby_<%= $cur_module.name %>_Module();
<% if $cur_module.is_template_default_instance %>
VALUE rb_<%= $cur_module.name %>_s_default(VALUE klass)
{
rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();
return rho_ruby_create_object_with_id( klass, convertToStringA(strDefaultID).c_str() );
}
VALUE rb_<%= $cur_module.name %>_s_setDefault(VALUE klass, VALUE valObj)
{
const char* szID = rho_ruby_get_object_id( valObj );
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->setDefaultID(convertToStringW(szID));
return rho_ruby_get_NIL();
}
<% end %>
extern "C" static void
string_iter(const char* szVal, void* par)
{
rho::Vector<rho::StringW>& ar = *((rho::Vector<rho::StringW>*)(par));
ar.addElement( convertToStringW(szVal) );
}
static void getStringArrayFromValue(VALUE val, rho::Vector<rho::StringW>& res)
{
rho_ruby_enum_strary(val, string_iter, &res);
}
extern "C" static void hash_eachstr(const char* szName, const char* szVal, void* par)
{
rho::Hashtable<rho::StringW, rho::StringW>& hash = *((rho::Hashtable<rho::StringW, rho::StringW>*)(par));
hash.put( convertToStringW(szName), convertToStringW(szVal) );
}
static void getStringHashFromValue(VALUE val, rho::Hashtable<rho::StringW, rho::StringW>& res)
{
rho_ruby_enum_strhash(val, hash_eachstr, &res);
}
//Module instance methods
<% $cur_module.methods.each do |module_method| %>
<% if module_method.access == ModuleMethod::ACCESS_STATIC %>
<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, true)%>
<% else %>
static VALUE _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(int argc, VALUE *argv, I<%= $cur_module.name %>* pObj)
<% end %>
{
CMethodResult oRes;
<% if module_method.is_factory_method %>
oRes.setRubyObjectClass(getRuby_<%= $cur_module.name %>_Module());
<% end %>
rho::common::IRhoRunnable* pFunctor = 0;
bool bUseCallback = false;
int nCallbackArg = 0;
<% functor_params = ""; first_arg = 0; %>
<% module_method.params.each do |param| %>
nCallbackArg = <%= first_arg + 1 %>;
<% if !param.can_be_nil %>
if ( argc == <%= first_arg %> )
{
oRes.setArgError(L"Wrong number of arguments: " + convertToStringW(argc) + L" instead of " + convertToStringW(<%= module_method.params.size() %>) );
return oRes.toRuby();
}
<% end %>
<% if param.type == MethodParam::TYPE_STRING %>
<%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;
if ( argc > <%= first_arg %> )
{
if ( rho_ruby_is_string(argv[<%= first_arg %>]) )
{
arg<%= first_arg %> = convertToStringW(getStringFromValue(argv[<%= first_arg %>]));
<% if first_arg == 0 %>
oRes.setStringParam(getStringFromValue(argv[<%= first_arg %>]));
<% end %>
}
else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))
{
oRes.setArgError(L"Type error: argument " L<%= "\"#{first_arg}\"" %> L" should be " L<%= "\"#{param.type.downcase}\"" %> );
return oRes.toRuby();
}
}
<% end %>
<% if param.type == MethodParam::TYPE_ARRAY %>
<%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;
if ( argc > <%= first_arg %> )
{
if ( rho_ruby_is_array(argv[<%= first_arg %>]) )
getStringArrayFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);
else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))
{
oRes.setArgError(L"Type error: argument " L<%= "\"#{first_arg}\"" %> L" should be " L<%= "\"#{param.type.downcase}\"" %> );
return oRes.toRuby();
}
}
<% end %>
<% if param.type == MethodParam::TYPE_HASH %>
<%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;
if ( argc > <%= first_arg %> )
{
if ( rho_ruby_is_hash(argv[<%= first_arg %>]) )
getStringHashFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);
else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))
{
oRes.setArgError(L"Type error: argument " L<%= "\"#{first_arg}\"" %> L" should be " L<%= "\"#{param.type.downcase}\"" %> );
return oRes.toRuby();
}
}
<% end %>
<% functor_params += "arg#{first_arg}, " %>
<% first_arg = first_arg+1 %>
<% end %>
if ( argc > nCallbackArg )
{
<% if module_method.has_callback == ModuleMethod::CALLBACK_NONE %>
oRes.setArgError(L"Wrong number of arguments: " + convertToStringW(argc) + L" instead of " + convertToStringW(<%= module_method.params.size() %>) );
return oRes.toRuby();
<% end %>
if ( !rho_ruby_is_string(argv[nCallbackArg]) )
{
oRes.setArgError(L"Type error: callback should be String");
return oRes.toRuby();
}
oRes.setCallInUIThread(<%= module_method.is_run_in_ui_thread ? "true" : "false" %>);
oRes.setRubyCallback( getStringFromValue(argv[nCallbackArg]) );
if ( argc > nCallbackArg + 1 )
{
if ( !rho_ruby_is_string(argv[nCallbackArg + 1]) )
{
oRes.setArgError(L"Type error: callback parameter should be String");
return oRes.toRuby();
}
oRes.setCallbackParam( getStringFromValue(argv[nCallbackArg + 1]) );
}
}
<% if module_method.access != ModuleMethod::ACCESS_STATIC %>
pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( pObj, &I<%= $cur_module.name %>::<%= module_method.name %>, <%= functor_params %> oRes );
<% else %>
pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS(), &I<%= $cur_module.name %>Singleton::<%= module_method.name %>, <%= functor_params %> oRes );
<% end %>
<% if module_method.is_run_in_ui_thread %>
rho_wm_impl_performOnUiThread( pFunctor );
<% elsif module_method.is_run_in_thread %>
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );
<% else %>
if ( bUseCallback )
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );
else
{
delete pFunctor;
<% if module_method.access != ModuleMethod::ACCESS_STATIC %>
pObj-><%= module_method.name %>( <%= functor_params %> oRes );
<% else %>
C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()-><%= module_method.name %>( <%= functor_params %> oRes );
<% end %>
}
<% end %>
return oRes.toRuby();
}
<% if module_method.access != ModuleMethod::ACCESS_STATIC %>
<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, module_method.access == ModuleMethod::ACCESS_STATIC)%>
{
const char* szID = rho_ruby_get_object_id( obj );
I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(convertToStringW(szID));
return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);
}
<% end %>
<% if $cur_module.is_template_default_instance && module_method.access == ModuleMethod::ACCESS_INSTANCE%>
<%= api_generator_MakeRubyMethodDecl($cur_module.name + "_def", module_method, true)%>
{
rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();
I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(strDefaultID);
return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);
}
<% end %>
<% end %>
}<|endoftext|>
|
<commit_before>#ifndef GENERIC_CIFY_HPP
# define GENERIC_CIFY_HPP
# pragma once
#include <utility>
namespace generic
{
namespace
{
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I, typename L, typename R, typename ...A>
inline F cify(L&& l, R (*)(A...) noexcept(noexcept(
::std::declval<F>()(::std::declval<A>()...))))
{
static L l_(::std::forward<L>(l));
static bool full;
if (full)
{
l_.~L();
new (static_cast<void*>(&l_)) L(::std::forward<L>(l));
}
else
{
full = true;
}
struct S
{
static R f(A... args) noexcept(noexcept(
::std::declval<F>()(::std::forward<A>(args)...)))
{
return l_(::std::forward<A>(args)...);
}
};
return &S::f;
}
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I, typename L, typename R, typename ...A>
inline F thread_local_cify(L&& l, R (*)(A...) noexcept(noexcept(
::std::declval<F>()(::std::declval<A>()...))))
{
static thread_local L l_(::std::forward<L>(l));
static thread_local bool full;
if (full)
{
l_.~L();
new (static_cast<void*>(&l_)) L(::std::forward<L>(l));
}
else
{
full = true;
}
struct S
{
static R f(A... args) noexcept(noexcept(
::std::declval<F>()(::std::forward<A>(args)...)))
{
return l_(::std::forward<A>(args)...);
}
};
return &S::f;
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I = 0, typename L>
inline F cify(L&& l)
{
return cify<F, I>(::std::forward<L>(l), F());
}
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I = 0, typename L>
inline F thread_local_cify(L&& l)
{
return thread_local_cify<F, I>(::std::forward<L>(l), F());
}
}
#endif // GENERIC_CIFY_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_CIFY_HPP
# define GENERIC_CIFY_HPP
# pragma once
#include <utility>
namespace generic
{
namespace
{
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I, typename L, typename R, typename ...A>
inline F cify(L&& l, R (*)(A...) noexcept(noexcept(
::std::declval<F>()(::std::declval<A>()...))))
{
static L l_(::std::forward<L>(l));
static bool full;
if (full)
{
l_.~L();
new (static_cast<void*>(&l_)) L(::std::forward<L>(l));
}
else
{
full = true;
}
return +[](A... args) noexcept(noexcept(
::std::declval<F>()(::std::forward<A>(args)...)))
{
return l_(::std::forward<A>(args)...);
};
}
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I, typename L, typename R, typename ...A>
inline F thread_local_cify(L&& l, R (*)(A...) noexcept(noexcept(
::std::declval<F>()(::std::declval<A>()...))))
{
static thread_local L l_(::std::forward<L>(l));
static thread_local bool full;
if (full)
{
l_.~L();
new (static_cast<void*>(&l_)) L(::std::forward<L>(l));
}
else
{
full = true;
}
return +[](A... args) noexcept(noexcept(
::std::declval<F>()(::std::forward<A>(args)...)))
{
return l_(::std::forward<A>(args)...);
};
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I = 0, typename L>
inline F cify(L&& l)
{
return cify<F, I>(::std::forward<L>(l), F());
}
//////////////////////////////////////////////////////////////////////////////
template <typename F, int I = 0, typename L>
inline F thread_local_cify(L&& l)
{
return thread_local_cify<F, I>(::std::forward<L>(l), F());
}
}
#endif // GENERIC_CIFY_HPP
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/make_counted.hpp>
#include "vast/bitmap_algorithms.hpp"
#include "vast/error.hpp"
#include "vast/event.hpp"
#include "vast/ids.hpp"
#include "vast/load.hpp"
#include "vast/logger.hpp"
#include "vast/save.hpp"
#include "vast/segment_store.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/filesystem.hpp"
#include "vast/concept/printable/vast/uuid.hpp"
#include "vast/const_table_slice_handle.hpp"
#include "vast/segment_store.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"
namespace vast {
segment_store_ptr segment_store::make(caf::actor_system& sys, path dir,
size_t max_segment_size,
size_t in_memory_segments) {
VAST_ASSERT(max_segment_size > 0);
auto x = caf::make_counted<segment_store>(
sys, std::move(dir), max_segment_size, in_memory_segments);
// Materialize meta data of existing segments.
if (exists(x->meta_path()))
if (auto result = load(x->meta_path(), x->segments_); !result) {
VAST_ERROR("failed to unarchive meta data:", to_string(result.error()));
return nullptr;
}
return x;
}
segment_store::~segment_store() {
// nop
}
caf::error segment_store::put(const_table_slice_handle xs) {
if (auto error = builder_.add(xs))
return error;
if (!segments_.inject(xs->offset(), xs->offset() + xs->rows(), builder_.id()))
return make_error(ec::unspecified, "failed to update range_map");
if (builder_.table_slice_bytes() < max_segment_size_)
return caf::none;
// We have exceeded our maximum segment size and now finish
auto x = builder_.finish();
if (!x)
return x.error();
auto seg_ptr = *x;
if (!exists(segment_path()))
if (auto result = mkdir(segment_path()); !result)
return result.error();
auto filename = segment_path() / to_string(seg_ptr->id());
if (auto result = save(filename, seg_ptr); !result)
return result.error();
VAST_DEBUG("wrote new segment to", filename.trim(-3));
// Keep new segment in the cache.
cache_.emplace(seg_ptr->id(), seg_ptr);
return flush();
}
caf::error segment_store::flush() {
auto result = save(meta_path(), segments_);
return result ? caf::none : result.error();
}
caf::expected<std::vector<const_table_slice_handle>>
segment_store::get(const ids& xs) {
// Collect candidate segments by seeking through the ID set and
// probing each ID interval.
std::vector<const uuid*> candidates;
auto f = [](auto x) { return std::pair{x.left, x.right}; };
auto g = [&](auto x) {
auto ptr = &x.value;
if (candidates.empty() || candidates.back() != ptr)
candidates.push_back(ptr);
return caf::none;
};
auto begin = segments_.begin();
auto end = segments_.end();
if (auto error = traverse(xs, begin, end, f, g))
return error;
// Process candidates in reverse order for maximum LRU cache hits.
std::vector<const_table_slice_handle> result;
VAST_DEBUG("processing", candidates.size(), "candidates");
for (auto cand = candidates.rbegin(); cand != candidates.rend(); ++cand) {
auto& id = **cand;
caf::expected<std::vector<const_table_slice_handle>> slices{caf::no_error};
if (id == builder_.id()) {
VAST_DEBUG("looking into builder");
slices = builder_.lookup(xs);
} else {
segment_ptr seg_ptr = nullptr;
auto i = cache_.find(id);
if (i != cache_.end()) {
VAST_DEBUG("got cache hit for segment", id);
seg_ptr = i->second;
} else {
VAST_DEBUG("got cache miss for segment", id);
if (auto res = load(segment_path() / to_string(id), seg_ptr); !res)
return res.error();
i = cache_.emplace(id, seg_ptr).first;
}
VAST_ASSERT(seg_ptr != nullptr);
slices = seg_ptr->lookup(xs);
}
if (!slices)
return slices.error();
result.reserve(result.size() + slices->size());
result.insert(result.end(), slices->begin(), slices->end());
}
return result;
}
segment_store::segment_store(caf::actor_system& sys, path dir,
uint64_t max_segment_size, size_t in_memory_segments)
: actor_system_{sys},
dir_{std::move(dir)},
max_segment_size_{max_segment_size},
cache_{in_memory_segments},
builder_{actor_system_} {
// nop
}
} // namespace vast
<commit_msg>Log serialization error<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <caf/make_counted.hpp>
#include "vast/bitmap_algorithms.hpp"
#include "vast/error.hpp"
#include "vast/event.hpp"
#include "vast/ids.hpp"
#include "vast/load.hpp"
#include "vast/logger.hpp"
#include "vast/save.hpp"
#include "vast/segment_store.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/filesystem.hpp"
#include "vast/concept/printable/vast/uuid.hpp"
#include "vast/const_table_slice_handle.hpp"
#include "vast/segment_store.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"
namespace vast {
segment_store_ptr segment_store::make(caf::actor_system& sys, path dir,
size_t max_segment_size,
size_t in_memory_segments) {
VAST_ASSERT(max_segment_size > 0);
auto x = caf::make_counted<segment_store>(
sys, std::move(dir), max_segment_size, in_memory_segments);
// Materialize meta data of existing segments.
if (exists(x->meta_path()))
if (auto result = load(x->meta_path(), x->segments_); !result) {
VAST_ERROR("failed to unarchive meta data:", to_string(result.error()));
return nullptr;
}
return x;
}
segment_store::~segment_store() {
// nop
}
caf::error segment_store::put(const_table_slice_handle xs) {
if (auto error = builder_.add(xs))
return error;
if (!segments_.inject(xs->offset(), xs->offset() + xs->rows(), builder_.id()))
return make_error(ec::unspecified, "failed to update range_map");
if (builder_.table_slice_bytes() < max_segment_size_)
return caf::none;
// We have exceeded our maximum segment size and now finish
auto x = builder_.finish();
if (!x)
return x.error();
auto seg_ptr = *x;
if (!exists(segment_path()))
if (auto result = mkdir(segment_path()); !result)
return result.error();
auto filename = segment_path() / to_string(seg_ptr->id());
if (auto result = save(filename, seg_ptr); !result)
return result.error();
VAST_DEBUG("wrote new segment to", filename.trim(-3));
// Keep new segment in the cache.
cache_.emplace(seg_ptr->id(), seg_ptr);
return flush();
}
caf::error segment_store::flush() {
auto result = save(meta_path(), segments_);
return result ? caf::none : result.error();
}
caf::expected<std::vector<const_table_slice_handle>>
segment_store::get(const ids& xs) {
// Collect candidate segments by seeking through the ID set and
// probing each ID interval.
std::vector<const uuid*> candidates;
auto f = [](auto x) { return std::pair{x.left, x.right}; };
auto g = [&](auto x) {
auto ptr = &x.value;
if (candidates.empty() || candidates.back() != ptr)
candidates.push_back(ptr);
return caf::none;
};
auto begin = segments_.begin();
auto end = segments_.end();
if (auto error = traverse(xs, begin, end, f, g))
return error;
// Process candidates in reverse order for maximum LRU cache hits.
std::vector<const_table_slice_handle> result;
VAST_DEBUG("processing", candidates.size(), "candidates");
for (auto cand = candidates.rbegin(); cand != candidates.rend(); ++cand) {
auto& id = **cand;
caf::expected<std::vector<const_table_slice_handle>> slices{caf::no_error};
if (id == builder_.id()) {
VAST_DEBUG("looking into builder");
slices = builder_.lookup(xs);
} else {
segment_ptr seg_ptr = nullptr;
auto i = cache_.find(id);
if (i != cache_.end()) {
VAST_DEBUG("got cache hit for segment", id);
seg_ptr = i->second;
} else {
VAST_DEBUG("got cache miss for segment", id);
if (auto res = load(segment_path() / to_string(id), seg_ptr); !res) {
VAST_ERROR("unable to load segment:", res.error());
return res.error();
}
i = cache_.emplace(id, seg_ptr).first;
}
VAST_ASSERT(seg_ptr != nullptr);
slices = seg_ptr->lookup(xs);
}
if (!slices)
return slices.error();
result.reserve(result.size() + slices->size());
result.insert(result.end(), slices->begin(), slices->end());
}
return result;
}
segment_store::segment_store(caf::actor_system& sys, path dir,
uint64_t max_segment_size, size_t in_memory_segments)
: actor_system_{sys},
dir_{std::move(dir)},
max_segment_size_{max_segment_size},
cache_{in_memory_segments},
builder_{actor_system_} {
// nop
}
} // namespace vast
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Z-functions
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// z-functions: return z, z[i] is the length of the longest substring
// starting from S[i] which is also a prefix of S
vector<int> get_ZFunction(string s){
int len = s.length();
vector<int> z(len);
int L = 0, R = 0;
for(int i = 1; i < len; i++ ){
if (i > R){
L = R = i;
while (R < len && s[R-L] == s[R]) R++;
z[i] = R - L; R--;
} else {
int k = i - L;
if(z[k] < R - i + 1) z[i] = z[k];
else {
L = i;
while (R < len && s[R - L] == s[R]) R++;
z[i] = R - L; R--;
}
}
}
z[0] = len;
return z;
}
///////////////////////////////////////////////////////////////////////////////
// Knuth-Morris-Pratt
///////////////////////////////////////////////////////////////////////////////
/*
Searches for the string w in the string s (of length k). Returns the
0-based index of the first match (k if no match is found). Algorithm
runs in O(k) time.
*/
#include <cassert>
using namespace std;
typedef vector<int> VI;
class KnuthMorrisPratt {
public:
void build_table(string& w, VI& t){
int sz = w.size();
t = VI(sz);
int i = 2, j = 0;
t[0] = -1; t[1] = 0;
while (i < sz) {
if (w[i - 1] == w[j]) { t[i] = j + 1; i++; j++; }
else if (j > 0) j = t[j];
else { t[i] = 0; i++; }
}
}
// returh the index of the first match, or the length of s if w is not found
int KMP(string s, string w){
int m = 0, i = 0;
VI t;
build_table(w, t);
int sz_s = s.size();
int sz_w = w.size();
while (m+i < sz_s) {
if (w[i] == s[m+i]) {
i++;
if (i == sz_w) return m;
} else {
m += i - t[i];
if (i > 0) i = t[i];
}
}
return s.length();
}
};
int main(){
KnuthMorrisPratt solve;
assert(solve.KMP("win", "I wanna win.") == 3);
assert(solve.KMP("I wanna win.", "win") == 8);
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Prefix Function
// Given a string. Return an array of numbers,
// where is defined as follows: it is a maximum length of the longest
// proper suffix substring that matches the prefix (suffix own - so not
// the entire line). In particular, the value is set equal to zero.
// For example, the string "abcabcd" prefix function is: [1, 0, 0, 1, 2, 3, 0]
///////////////////////////////////////////////////////////////////////////////
vector<int> prefix_function (string s){
int n = (int) s.length();
vector<int> pi (n);
for (int i=1; i<n; ++i){
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j]) ++j;
pi[i] = j;
}
return pi;
}
<commit_msg>Update StringMatching.cpp<commit_after>///////////////////////////////////////////////////////////////////////////////
// Z-functions
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// z-functions: return z, z[i] is the length of the longest substring
// starting from S[i] which is also a prefix of S
vector<int> get_ZFunction(string s){
int len = s.length();
vector<int> z(len);
int L = 0, R = 0;
for(int i = 1; i < len; i++ ){
if (i > R){
L = R = i;
while (R < len && s[R-L] == s[R]) R++;
z[i] = R - L; R--;
} else {
int k = i - L;
if(z[k] < R - i + 1) z[i] = z[k];
else {
L = i;
while (R < len && s[R - L] == s[R]) R++;
z[i] = R - L; R--;
}
}
}
z[0] = len;
return z;
}
///////////////////////////////////////////////////////////////////////////////
// Knuth-Morris-Pratt
///////////////////////////////////////////////////////////////////////////////
/*
Searches for the string key in the string s (of length k). Returns the
0-based index of the first match (k if no match is found). Algorithm
runs in O(k) time.
*/
#include <cassert>
using namespace std;
typedef vector<int> VI;
class KnuthMorrisPratt {
public:
void build_table(string& key, VI& t){
int sz = key.size();
t = VI(sz);
int i = 2, j = 0;
t[0] = -1; t[1] = 0;
while (i < sz) {
if (key[i - 1] == key[j]) { t[i] = j + 1; i++; j++; }
else if (j > 0) j = t[j];
else { t[i] = 0; i++; }
}
}
// return the index of the first match, or the length of s if key is not found
int KMP(string s, string key){
int m = 0, i = 0;
VI t;
build_table(key, t);
int sz_s = s.size();
int sz_w = key.size();
while (m+i < sz_s) {
if (key[i] == s[m+i]) {
i++;
if (i == sz_w) return m;
} else {
m += i - t[i];
if (i > 0) i = t[i];
}
}
return s.length();
}
};
int main(){
KnuthMorrisPratt solve;
assert(solve.KMP("win", "I wanna win.") == 3);
assert(solve.KMP("I wanna win.", "win") == 8);
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Prefix Function
// Given a string. Return an array of numbers,
// where is defined as follows: it is a maximum length of the longest
// proper suffix substring that matches the prefix (suffix own - so not
// the entire line). In particular, the value is set equal to zero.
// For example, the string "abcabcd" prefix function is: [1, 0, 0, 1, 2, 3, 0]
///////////////////////////////////////////////////////////////////////////////
vector<int> prefix_function (string s){
int n = (int) s.length();
vector<int> pi (n);
for (int i=1; i<n; ++i){
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j]) ++j;
pi[i] = j;
}
return pi;
}
<|endoftext|>
|
<commit_before>// C++ Actor Framework Exercices
// Christian Schirin, 2017-05-17
// Exercise 1: Polynomial Evaluator
#include <string>
#include <iostream>
#include "caf/all.hpp"
using std::endl;
using std::string;
using namespace caf;
// Type Aliases
using calc_atom = atom_constant<atom("calc")>;
behavior polynomial(std::array<double, 5> as) {
return {
[=](const calc_atom& _calc, const double x) -> double {
// Evaluate the polynomial.
// The accumulator variable
double result = 0;
// x^4, x^3, x^2, x^1, x^0
double exponent = as.size() - 1; // this is at generalized as it gets, it would also work for polynomials with a degree that is not 4.
// We are doing this with a for loop because C++11 doesn't support fold
for (double a : as) {
result += a * std::pow(x, exponent); //how does pow behave at x^0? // Apparently it returns 1.
exponent -= 1;
}
return result;
}
};
}
int main() {
// our CAF environment
actor_system_config cfg;
actor_system system{ cfg };
std::array<double, 5> as;
scoped_actor self{ system };
// system will wait until both actors are destroyed before leaving main
std::cout << std::pow(0, 0) << '\n';
}
<commit_msg>Polynomial Evaluator implemented.<commit_after>// C++ Actor Framework Exercices
// Christian Schirin, 2017-05-17
// Exercise 1: Polynomial Evaluator
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
#include "caf/all.hpp"
using std::endl;
using std::string;
using namespace caf;
// Type Aliases
using calc_atom = atom_constant<atom("calc")>;
behavior polynomial(std::array<double, 5> as) {
return {
// Lambda expression, pass parameters by value
[=](calc_atom, const double x) -> double {
// Evaluate the polynomial.
// The accumulator variable
double result = 0;
// x^4, x^3, x^2, x^1, x^0
double exponent = as.size() - 1; // This is at generalized as it gets, it would also work for polynomials with a degree that is not 4.
// Doing this with a for loop because C++11 doesn't support fold
for (double a : as) {
result += a * std::pow(x, exponent); //how does pow behave at x^0? // Apparently it returns 1.
exponent -= 1; // We need to go from size - 1 to 0 here.
}
return result;
}
};
}
int main() {
// our CAF environment
actor_system_config cfg;
actor_system system{ cfg };
std::array<double, 5> as;
// Let us use an plain old for loop here because I don't see the benefit over using foreach here.
// I do need the index here. Even if only to make the user prompt more understandable.
for (unsigned int i = 0; i < as.size() ; i++) {
// Prompt the user to input something
std::cout << "Please input a" << i << ": ";
// declare a temporary variable for the input
string input;
// read from cin
std::cin >> input;
//parse the doubles and write to the array
as[i] = std::stod(input);
// The obligatory newline
std::cout << endl;
}
std::cout << "Thank you! I'll spawn the polynomial evaluator now!" << endl;
scoped_actor self{ system };
// Spawn the actor.
// The signature of the spawn function doesn't look that straightforward,
// I think I'll go back to spawn/3 in Erlang, thanks. :-P
auto p = self->spawn(polynomial, as); //using type inference because I do not know the type.
// How would I even do this with the range based for loop?
// I would need an iterator that returns something forever.
// That is easy, but YAGNI, so a for (;;) will do.
for (;;) {
std::cout << "Please input an x: ";
// declare a temporary variable for the input
string input;
// read from cin
std::cin >> input;
// parse the x
double x = stod(input);
// send it to the actor
self->send(p, atom("calc"), x);
//receive from the actor
self->receive(
[&](double evaluatedPolynomial) {
// I'd love to write unit tests for this here instead of writing it to aout.
// Do you have something like eunit or common_test?
aout(self) << evaluatedPolynomial << endl;
}
);
// how do I make this receive synchronous?
// I don't like using sleep here.
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2009, Joacim Jacobsson ( j dot jacobsson at gmail dot com )
* All rights reserved.
*
* See LICENSE file for details
*
*/
#include <callback/callback.h>
#include <callback/instructions.h>
namespace callback
{
int run_program( CallbackProgram* info )
{
ProgramHeader* ph = (ProgramHeader*)(info->m_Program);
Instruction* i = (Instruction*)((char*)(info->m_Program) + sizeof(ProgramHeader));
char* bss = (char*)info->m_bss;
char* data = ((char*)(i)) + (sizeof(Instruction) * ph->m_IC);
BssHeader* bh = (BssHeader*)(bss);
callbackHandler ch = info->m_callback;
DebugHandler dh = info->m_Debug;
bool exit = false;
while( !exit )
{
const Instruction& inst = i[bh->m_IP];
++bh->m_IP;
++bh->m_IC;
switch( inst.m_I )
{
case INST_CALL_DEBUG_FN:
//if( dh )
// dh( info, ph, bh );
break;
case INST_CALL_CONS_FUN:
ch(
bh->m_R[inst.m_A1],
ACT_CONSTRUCT,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_EXEC_FUN:
bh->m_RE = ch(
bh->m_R[inst.m_A1],
ACT_EXECUTE,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_DEST_FUN:
ch(
bh->m_R[inst.m_A1],
ACT_DESTRUCT,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_PRUN_FUN:
bh->m_RE = ch(
bh->m_R[inst.m_A1],
ACT_PRUNE,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_MODI_FUN:
bh->m_RE = ch(
bh->m_R[inst.m_A1],
ACT_MODIFY,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_JABC_R_EQUA_C:
if( bh->m_RE == inst.m_A2 )
bh->m_IP = inst.m_A1;
break;
case INST_JABC_R_DIFF_C:
if( bh->m_RE != inst.m_A2 )
bh->m_IP = inst.m_A1;
break;
case INST_JABC_C_EQUA_B:
if( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )
bh->m_IP = inst.m_A1;
break;
case INST_JABC_C_DIFF_B:
if( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )
bh->m_IP = inst.m_A1;
break;
case INST_JABB_C_EQUA_B:
if( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABB_C_DIFF_B:
if( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABB_B_EQUA_B:
if( *((int*)&(bss[inst.m_A2])) == *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABB_B_DIFF_B:
if( *((int*)&(bss[inst.m_A2])) != *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABC_CONSTANT:
bh->m_IP = inst.m_A1;
break;
case INST_JREC_CONSTANT:
bh->m_IP += inst.m_A1;
break;
case INST_JABB_BSSVALUE:
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JREB_BSSVALUE:
bh->m_IP += *((int*)&(bss[inst.m_A1]));
break;
case INST_JABC_S_C_IN_B:
bh->m_IP = inst.m_A1;
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST_JREC_S_C_IN_B:
bh->m_IP += inst.m_A1;
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST_JABB_S_C_IN_B:
bh->m_IP = *((int*)&(bss[inst.m_A1]));
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST_JREB_S_C_IN_B:
bh->m_IP += *((int*)&(bss[inst.m_A1]));
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST__STORE_R_IN_B:
*((int*)&(bss[inst.m_A1])) = bh->m_RE;
break;
case INST__STORE_B_IN_R:
bh->m_RE = *((int*)&(bss[inst.m_A1]));
break;
case INST__STORE_C_IN_B:
*((int*)&(bss[inst.m_A1])) = inst.m_A2;
break;
case INST__STORE_B_IN_B:
*((int*)&(bss[inst.m_A1])) = *((int*)&(bss[inst.m_A2]));
break;
case INST__STORE_C_IN_R:
bh->m_RE = inst.m_A1;
break;
case INST_STORE_PD_IN_B:
*(int*)(&bss[inst.m_A1]) = (int)(&data[inst.m_A2]);
break;
case INST_STORE_PB_IN_R:
bh->m_R[inst.m_A1] = (int)(&bss[inst.m_A2]);
break;
case INST__INC_BSSVALUE:
*((int*)&(bss[inst.m_A1])) += inst.m_A2;
break;
case INST__DEC_BSSVALUE:
*((int*)&(bss[inst.m_A1])) += inst.m_A2;
break;
case INST_LOAD_REGISTRY:
bh->m_R[inst.m_A1] = (((int)inst.m_A2)<<16) + inst.m_A3;
break;
case INST_______SUSPEND:
bh->m_IP = 0;
exit = true;
break;
}
}
return bh->m_RE;
}
}
<commit_msg>Got rid of the outer "while" in the VM in favor of a goto. Yes. A goto. really.<commit_after>/*
*
* Copyright (C) 2009, Joacim Jacobsson ( j dot jacobsson at gmail dot com )
* All rights reserved.
*
* See LICENSE file for details
*
*/
#include <callback/callback.h>
#include <callback/instructions.h>
namespace callback
{
int run_program( CallbackProgram* info )
{
ProgramHeader* ph = (ProgramHeader*)(info->m_Program);
Instruction* i = (Instruction*)((char*)(info->m_Program) + sizeof(ProgramHeader));
char* bss = (char*)info->m_bss;
char* data = ((char*)(i)) + (sizeof(Instruction) * ph->m_IC);
BssHeader* bh = (BssHeader*)(bss);
callbackHandler ch = info->m_callback;
DebugHandler dh = info->m_Debug;
start:
const Instruction& inst = i[bh->m_IP];
++bh->m_IP;
++bh->m_IC;
switch( inst.m_I )
{
case INST_CALL_DEBUG_FN:
//if( dh )
// dh( info, ph, bh );
break;
case INST_CALL_CONS_FUN:
ch(
bh->m_R[inst.m_A1],
ACT_CONSTRUCT,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_EXEC_FUN:
bh->m_RE = ch(
bh->m_R[inst.m_A1],
ACT_EXECUTE,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_DEST_FUN:
ch(
bh->m_R[inst.m_A1],
ACT_DESTRUCT,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_PRUN_FUN:
bh->m_RE = ch(
bh->m_R[inst.m_A1],
ACT_PRUNE,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_CALL_MODI_FUN:
bh->m_RE = ch(
bh->m_R[inst.m_A1],
ACT_MODIFY,
(void*)bh->m_R[inst.m_A2],
(void**)bh->m_R[inst.m_A3],
info->m_UserData
);
bh->m_R[inst.m_A1] = 0;
bh->m_R[inst.m_A2] = 0;
bh->m_R[inst.m_A3] = 0;
break;
case INST_JABC_R_EQUA_C:
if( bh->m_RE == inst.m_A2 )
bh->m_IP = inst.m_A1;
break;
case INST_JABC_R_DIFF_C:
if( bh->m_RE != inst.m_A2 )
bh->m_IP = inst.m_A1;
break;
case INST_JABC_C_EQUA_B:
if( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )
bh->m_IP = inst.m_A1;
break;
case INST_JABC_C_DIFF_B:
if( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )
bh->m_IP = inst.m_A1;
break;
case INST_JABB_C_EQUA_B:
if( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABB_C_DIFF_B:
if( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABB_B_EQUA_B:
if( *((int*)&(bss[inst.m_A2])) == *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABB_B_DIFF_B:
if( *((int*)&(bss[inst.m_A2])) != *((int*)&(bss[inst.m_A3])) )
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JABC_CONSTANT:
bh->m_IP = inst.m_A1;
break;
case INST_JREC_CONSTANT:
bh->m_IP += inst.m_A1;
break;
case INST_JABB_BSSVALUE:
bh->m_IP = *((int*)&(bss[inst.m_A1]));
break;
case INST_JREB_BSSVALUE:
bh->m_IP += *((int*)&(bss[inst.m_A1]));
break;
case INST_JABC_S_C_IN_B:
bh->m_IP = inst.m_A1;
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST_JREC_S_C_IN_B:
bh->m_IP += inst.m_A1;
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST_JABB_S_C_IN_B:
bh->m_IP = *((int*)&(bss[inst.m_A1]));
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST_JREB_S_C_IN_B:
bh->m_IP += *((int*)&(bss[inst.m_A1]));
*((int*)&(bss[inst.m_A2])) = inst.m_A3;
break;
case INST__STORE_R_IN_B:
*((int*)&(bss[inst.m_A1])) = bh->m_RE;
break;
case INST__STORE_B_IN_R:
bh->m_RE = *((int*)&(bss[inst.m_A1]));
break;
case INST__STORE_C_IN_B:
*((int*)&(bss[inst.m_A1])) = inst.m_A2;
break;
case INST__STORE_B_IN_B:
*((int*)&(bss[inst.m_A1])) = *((int*)&(bss[inst.m_A2]));
break;
case INST__STORE_C_IN_R:
bh->m_RE = inst.m_A1;
break;
case INST_STORE_PD_IN_B:
*(int*)(&bss[inst.m_A1]) = (int)(&data[inst.m_A2]);
break;
case INST_STORE_PB_IN_R:
bh->m_R[inst.m_A1] = (int)(&bss[inst.m_A2]);
break;
case INST__INC_BSSVALUE:
*((int*)&(bss[inst.m_A1])) += inst.m_A2;
break;
case INST__DEC_BSSVALUE:
*((int*)&(bss[inst.m_A1])) += inst.m_A2;
break;
case INST_LOAD_REGISTRY:
bh->m_R[inst.m_A1] = (((int)inst.m_A2)<<16) + inst.m_A3;
break;
case INST_______SUSPEND:
bh->m_IP = 0;
goto exit;
break;
}
goto start;
exit:
return bh->m_RE;
}
}
<|endoftext|>
|
<commit_before>/*
ReflectaArduinoCore.cpp - Library for exposing the core Arduino library functions over Reflecta
*/
#include "Reflecta.h"
using namespace reflecta;
using namespace reflectaFunctions;
namespace reflectaArduinoCore
{
void pinMode()
{
::pinMode(pop(), pop());
}
void digitalRead()
{
push(::digitalRead(pop()));
}
void digitalWrite()
{
::digitalWrite(pop(), pop());
}
void analogRead()
{
push16(::analogRead(pop()));
}
void analogWrite()
{
::analogWrite(pop(), pop());
}
void wireBeginMaster()
{
Wire.begin();
}
void wireRequestFrom()
{
Wire.requestFrom(pop(), pop());
}
void wireRequestFromStart()
{
Wire.requestFrom(pop(), pop(), false);
}
void wireAvailable()
{
push(Wire.available());
}
void wireRead()
{
if (Wire.available())
push(Wire.read());
else
reflectaFrames::sendEvent(Error, WireNotAvailable);
}
void wireBeginTransmission()
{
Wire.beginTransmission(pop());
}
// TODO: Support variants write(string) and write(data, length)
void wireWrite()
{
Wire.write(pop());
}
void wireEndTransmission()
{
Wire.endTransmission();
}
Servo servos[MAX_SERVOS];
// TODO: Support variant attach(pin, min, max)
void servoAttach()
{
int8_t pin = pop();
servos[pin].attach(pin);
}
void servoDetach()
{
servos[pop()].detach();
}
void servoWrite()
{
servos[pop()].write(pop());
}
void servoWriteMicroseconds()
{
servos[pop()].writeMicroseconds(pop16());
}
// TODO: Support variant pulseIn(pin, value, timeout)
void pulseIn()
{
// BUGBUG: Broken, returns a 32 bit result
push(::pulseIn(pop(), pop()));
}
// Bind the Arduino core methods to the ardu1 interface
void setup()
{
reflectaFunctions::bind("ardu1", pinMode);
reflectaFunctions::bind("ardu1", digitalRead);
reflectaFunctions::bind("ardu1", digitalWrite);
reflectaFunctions::bind("ardu1", analogRead);
reflectaFunctions::bind("ardu1", analogWrite);
reflectaFunctions::bind("ardu1", wireBeginMaster);
reflectaFunctions::bind("ardu1", wireRequestFrom);
reflectaFunctions::bind("ardu1", wireRequestFromStart);
reflectaFunctions::bind("ardu1", wireAvailable);
reflectaFunctions::bind("ardu1", wireRead);
reflectaFunctions::bind("ardu1", wireBeginTransmission);
reflectaFunctions::bind("ardu1", wireWrite);
reflectaFunctions::bind("ardu1", wireEndTransmission);
reflectaFunctions::bind("ardu1", servoAttach);
reflectaFunctions::bind("ardu1", servoDetach);
reflectaFunctions::bind("ardu1", servoWrite);
reflectaFunctions::bind("ardu1", servoWriteMicroseconds);
reflectaFunctions::bind("ardu1", pulseIn);
}
};
<commit_msg>Fix behavior changes in compiler that broke functionality in Arduino 1.5.x+<commit_after>/*
ReflectaArduinoCore.cpp - Library for exposing the core Arduino library functions over Reflecta
*/
#include "Reflecta.h"
using namespace reflecta;
using namespace reflectaFunctions;
namespace reflectaArduinoCore
{
void pinMode()
{
int8_t pin = pop();
int8_t val = pop();
::pinMode(pin, val);
}
void digitalRead()
{
int8_t pin = pop();
push(::digitalRead(pin));
}
void digitalWrite()
{
int8_t pin = pop();
int8_t val = pop();
::digitalWrite(pin, val);
}
void analogRead()
{
int8_t pin = pop();
push16(::analogRead(pin));
}
void analogWrite()
{
int8_t pin = pop();
int8_t val = pop();
::analogWrite(pin, val);
}
void wireBeginMaster()
{
Wire.begin();
}
void wireRequestFrom()
{
int8_t address = pop();
int8_t quantity = pop();
Wire.requestFrom(address, quantity);
}
void wireRequestFromStart()
{
int8_t address = pop();
int8_t quantity = pop();
Wire.requestFrom(address, quantity, false);
}
void wireAvailable()
{
push(Wire.available());
}
void wireRead()
{
if (Wire.available())
push(Wire.read());
else
reflectaFrames::sendEvent(Error, WireNotAvailable);
}
void wireBeginTransmission()
{
int8_t address = pop();
Wire.beginTransmission(address);
}
// TODO: Support variants write(string) and write(data, length)
void wireWrite()
{
int8_t val = pop();
Wire.write(val);
}
void wireEndTransmission()
{
Wire.endTransmission();
}
Servo servos[MAX_SERVOS];
// TODO: Support variant attach(pin, min, max)
void servoAttach()
{
int8_t pin = pop();
servos[pin].attach(pin);
}
void servoDetach()
{
int8_t pin = pop();
servos[pin].detach();
}
void servoWrite()
{
int8_t pin = pop();
int8_t val = pop();
servos[pin].write(val);
}
void servoWriteMicroseconds()
{
int8_t pin = pop();
int8_t val = pop16();
servos[pin].writeMicroseconds(val);
}
// TODO: Support variant pulseIn(pin, value, timeout)
void pulseIn()
{
// BUGBUG: Broken, returns a 32 bit result
int8_t pin = pop();
int8_t val = pop();
push(::pulseIn(pin, val));
}
// Bind the Arduino core methods to the ardu1 interface
void setup()
{
reflectaFunctions::bind("ardu1", pinMode);
reflectaFunctions::bind("ardu1", digitalRead);
reflectaFunctions::bind("ardu1", digitalWrite);
reflectaFunctions::bind("ardu1", analogRead);
reflectaFunctions::bind("ardu1", analogWrite);
reflectaFunctions::bind("ardu1", wireBeginMaster);
reflectaFunctions::bind("ardu1", wireRequestFrom);
reflectaFunctions::bind("ardu1", wireRequestFromStart);
reflectaFunctions::bind("ardu1", wireAvailable);
reflectaFunctions::bind("ardu1", wireRead);
reflectaFunctions::bind("ardu1", wireBeginTransmission);
reflectaFunctions::bind("ardu1", wireWrite);
reflectaFunctions::bind("ardu1", wireEndTransmission);
reflectaFunctions::bind("ardu1", servoAttach);
reflectaFunctions::bind("ardu1", servoDetach);
reflectaFunctions::bind("ardu1", servoWrite);
reflectaFunctions::bind("ardu1", servoWriteMicroseconds);
reflectaFunctions::bind("ardu1", pulseIn);
}
};
<|endoftext|>
|
<commit_before>/*
LICENSE AND COPYRIGHT INFORMATION - Please read carefully.
Copyright (c) 2010-2013, davyjones <dj@pgxplorer.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "querymodel.h"
QueryModel::QueryModel()
{
this->rows_from = 1;
}
void QueryModel::setRowsFrom(int rows_from)
{
this->rows_from = rows_from;
}
int QueryModel::getPivotCol()
{
return this->pivot_col;
}
int QueryModel::getPivotCat()
{
return this->pivot_cat;
}
int QueryModel::getPivotVal()
{
return this->pivot_val;
}
void QueryModel::setPivotCol(int pivot_col)
{
this->pivot_col = pivot_col;
}
void QueryModel::setPivotCat(int pivot_cat)
{
this->pivot_cat = pivot_cat;
}
void QueryModel::setPivotVal(int pivot_val)
{
this->pivot_val = pivot_val;
}
void QueryModel::setColumnAggregate(QStringList aggs)
{
current_column_aggregates = aggs;
}
QVariant QueryModel::data(const QModelIndex &index, int role) const
{
//Store the index into item to call the sibling of index.
QModelIndex item = indexInQuery(index);
//Align integers to the right
if ((index.isValid() && role == Qt::TextAlignmentRole) && (index.data().type() != QMetaType::QString))
return (Qt::AlignVCenter + Qt::AlignRight);
if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_col)
return QColor(255, 0, 0, 100);
if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_cat)
return QColor(0, 255, 0, 100);
//Disable all roles except DisplayRole
if (!index.isValid() || (role != Qt::DisplayRole))
return QVariant();
//Return sibling of index
return QSqlQueryModel::data(index.sibling(item.row(), index.column()), role);
}
QVariant QueryModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Vertical && role == Qt::DisplayRole)
return QVariant(rows_from + section);
else
return QSqlQueryModel::headerData(section, orientation, role);
}
<commit_msg>Initialise pivot values for QueryModel.<commit_after>/*
LICENSE AND COPYRIGHT INFORMATION - Please read carefully.
Copyright (c) 2010-2013, davyjones <dj@pgxplorer.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "querymodel.h"
QueryModel::QueryModel()
{
this->rows_from = 1;
pivot_col = -1;
pivot_cat = -1;
pivot_val = -1;
}
void QueryModel::setRowsFrom(int rows_from)
{
this->rows_from = rows_from;
}
int QueryModel::getPivotCol()
{
return this->pivot_col;
}
int QueryModel::getPivotCat()
{
return this->pivot_cat;
}
int QueryModel::getPivotVal()
{
return this->pivot_val;
}
void QueryModel::setPivotCol(int pivot_col)
{
this->pivot_col = pivot_col;
}
void QueryModel::setPivotCat(int pivot_cat)
{
this->pivot_cat = pivot_cat;
}
void QueryModel::setPivotVal(int pivot_val)
{
this->pivot_val = pivot_val;
}
void QueryModel::setColumnAggregate(QStringList aggs)
{
current_column_aggregates = aggs;
}
QVariant QueryModel::data(const QModelIndex &index, int role) const
{
//Store the index into item to call the sibling of index.
QModelIndex item = indexInQuery(index);
//Align integers to the right
if ((index.isValid() && role == Qt::TextAlignmentRole) && (index.data().type() != QMetaType::QString))
return (Qt::AlignVCenter + Qt::AlignRight);
if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_col)
return QColor(255, 0, 0, 100);
if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_cat)
return QColor(0, 255, 0, 100);
//Disable all roles except DisplayRole
if (!index.isValid() || (role != Qt::DisplayRole))
return QVariant();
//Return sibling of index
return QSqlQueryModel::data(index.sibling(item.row(), index.column()), role);
}
QVariant QueryModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Vertical && role == Qt::DisplayRole)
return QVariant(rows_from + section);
else
return QSqlQueryModel::headerData(section, orientation, role);
}
<|endoftext|>
|
<commit_before>#include "core/stringutils.h"
#include <string>
#include <algorithm>
#include <cstring>
#include <vector>
#include <sstream>
#include <iterator>
#include <type_traits>
#include "core/assert.h"
namespace euphoria::core
{
std::pair<std::string, std::string>
last_strings(const std::string& str, char sep)
{
auto result = str.find(sep);
if(result == std::string::npos)
{
return std::make_pair(str, "");
}
const auto parent = str.substr(0, result);
const auto child = str.substr(result, str.length() - parent.length());
return std::make_pair(parent, child);
}
std::string
first_chars(const std::string& str, std::size_t count)
{
if(str.length() < count) { return str; }
else { return str.substr(0, count); }
}
std::string
first_chars_with_ellipsis(const std::string& str, unsigned int count)
{
if (str.length() > count)
{
return str.substr(0, count) + "...";
}
return str;
}
std::string
strip_last_string(const std::string& str, char sep)
{
auto result = str.find(sep);
if(result == std::string::npos)
{
return "";
}
return str.substr(0, result);
}
std::string
trim_right(const std::string& string_to_trim, const std::string& trim_characters)
{
return std::string(string_to_trim).erase(string_to_trim.find_last_not_of(trim_characters) + 1);
}
std::string
trim_left(const std::string& string_to_trim, const std::string& trim_characters)
{
return std::string(string_to_trim).erase(0, string_to_trim.find_first_not_of(trim_characters));
}
std::string
trim(const std::string& string_to_trim, const std::string& trim_characters)
{
return trim_right(trim_left(string_to_trim, trim_characters), trim_characters);
}
bool
starts_with(const std::string& string_to_test, const std::string& start)
{
const std::string::size_type length = start.length();
const std::string::size_type other_length = string_to_test.length();
if(other_length < length)
{
return false;
}
const std::string actual_start = string_to_test.substr(0, length);
return start == actual_start;
}
bool
ends_with(const std::string& string_to_test, const std::string& end)
{
const std::string::size_type length = end.length();
const std::string::size_type other_length = string_to_test.length();
if(other_length < length)
{
return false;
}
const std::string actual_end
= string_to_test.substr(other_length - length, length);
return end == actual_end;
}
char
to_lower_char(char b)
{
if(b >= 'A' && b <= 'Z')
{
return static_cast<char>((static_cast<int>(b) - 'A') + 'a');
}
else
{
return b;
}
}
char
to_upper_char(char b)
{
if(b >= 'a' && b <= 'z')
{
return static_cast<char>(b + ('A' - 'a'));
}
else
{
return b;
}
}
std::string
to_lower(const std::string& str)
{
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), to_lower_char);
return result;
}
std::vector<std::string>
to_lower(const std::vector<std::string>& str)
{
return to_string_vector(str, [](const std::string& s) { return to_lower(s); });
}
std::string
to_upper(const std::string& str)
{
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), to_upper_char);
return result;
}
std::string
char_to_string(char c, CharToStringStyle style)
{
constexpr std::string_view smart_characters =
"abcdefghijklmnopqrstuwxyz"
"ABCDEFGHIJKLMNOPQRSTUWXYZ"
" "
"~!@#$%^&*()_+"
"`123456790-="
",.<>/?"
"{}[]:;\"'\\|"
"\n\r\t"
;
std::ostringstream ss;
switch(c)
{
case 0:
ss << "<null>";
if(style == CharToStringStyle::smart)
{
return ss.str();
}
break;
case '\n':
ss << "<\\n>";
break;
case '\r':
ss << "<\\r>";
break;
case '\t':
ss << "<tab>";
break;
// source: http://www.asciitable.com/
case 1: ss << "<start of heading>"; break;
case 2: ss << "<start of text>"; break;
case 3: ss << "<end of text>"; break;
case 4: ss << "<end of transmission>"; break;
case 5: ss << "<enquiry>"; break;
case 6: ss << "<acknowledge>"; break;
case 7: ss << "<bell>"; break;
case 8: ss << "<backspace>"; break;
// case 9: ss << "<horizontal tab>"; break;
// case 10: ss << "<newline>"; break;
case 11: ss << "<vertical tab>"; break;
case 12: ss << "<new page>"; break;
// case 13: ss << "<carriage return>"; break;
case 14: ss << "<shift out>"; break;
case 15: ss << "<shift in>"; break;
case 16: ss << "<data link esqape>"; break;
case 17: ss << "<device control 1>"; break;
case 18: ss << "<device control 2>"; break;
case 19: ss << "<device control 3>"; break;
case 20: ss << "<device control 4>"; break;
case 21: ss << "<negative acknowledge>"; break;
case 22: ss << "<synchronous idle>"; break;
case 23: ss << "<end of trans. block>"; break;
case 24: ss << "<cancel>"; break;
case 25: ss << "<end of medium>"; break;
case 26: ss << "<substitute>"; break;
case 27: ss << "<escape>"; break;
case 28: ss << "<file separator>"; break;
case 29: ss << "<group separator>"; break;
case 30: ss << "<record separator>"; break;
case 31: ss << "<unit separator>"; break;
case 127: ss << "<DEL>"; break;
case ' ':
ss << "<space>";
break;
default:
ss << c;
break;
}
if(style == CharToStringStyle::include_hex || smart_characters.find(c) == std::string_view::npos)
{
ss << "(0x" << std::hex << static_cast<int>(c) << ")";
}
return ss.str();
}
std::string::size_type
find_first_index_of_mismatch(const std::string& lhs, const std::string& rhs)
{
const auto end = std::min(lhs.size(), rhs.size());
std::string::size_type index = 0;
for(; index < end; index+=1)
{
if(lhs[index]!=rhs[index])
{
return index;
}
}
if(index >= lhs.size() && index >= rhs.size())
{
return std::string::npos;
}
else
{
return end;
}
}
void
replace_all(std::string* string, const std::string& to_find, const std::string& to_replace)
{
std::size_t index = string->find(to_find);
const std::size_t find_length = to_find.length();
ASSERT(find_length > 0);
while(index != std::string::npos)
{
string->erase(index, find_length);
string->insert(index, to_replace);
index = string->find(to_find, index);
}
}
std::string
replace_all(const std::string& string, const std::string& to_find, const std::string& to_replace)
{
std::string temp = string;
replace_all(&temp, to_find, to_replace);
return temp;
}
void
copy(char* dst, const std::string& src, const std::string::size_type& count)
{
strncpy(dst, src.c_str(), count - 1);
dst[count - 1] = 0;
}
std::string
replace_with_character(const std::string& string, const std::string& to_find, char to_replace)
{
std::string s = string;
for(char c: to_find)
{
std::replace(s.begin(), s.end(), c, to_replace);
}
return s;
}
std::string
remove_from_end(const std::string& str, const std::string& end)
{
if(ends_with(str, end))
{
const auto new_length = str.length() - end.length();
if(new_length == 0)
{
return "";
}
ASSERT(new_length > 0);
return str.substr(0, new_length);
}
return str;
}
std::string
strip(const std::string& str, const std::string& ch)
{
std::stringstream ss;
for(const char c: str)
{
if(ch.find(c) == std::string::npos)
{
ss << c;
}
}
return ss.str();
}
// remove all characters in ch except the first one in a chain from str
std::string
remove_consecutive(const std::string& str, const std::string& ch)
{
std::stringstream ss;
bool skip = false;
for(const char c: str)
{
if(ch.find(c) == std::string::npos)
{
ss << c;
skip = false;
}
else
{
if(!skip)
{
ss << c;
skip = true;
}
}
}
return ss.str();
}
namespace
{
template<typename R, typename T>
struct SizeGetter
{
static R get(const T& t) { return t.size(); }
};
template<typename R>
struct SizeGetter<R, char>
{
static R get(char) { return 1; }
};
template<typename R, typename T>
R get_size(const T& t) { return SizeGetter<R, T>::get(t); }
template
<
typename ListType,
typename OffsetType,
typename StringType,
typename DelimType,
typename AddFunction
>
ListType
split_base(const StringType str, DelimType delim, bool add_final, AddFunction&& add_function)
{
ListType ret;
const OffsetType delim_length = get_size<OffsetType>(delim);
OffsetType search_start = 0;
OffsetType index = 0;
while(true)
{
const auto found_index = str.find(delim, search_start);
if(found_index == StringType::npos)
{
// abort... add last?
// todo(Gustav): add argument to specify how to handle split on empty input
if(add_final && str.empty() == false)
{
add_function(ret, index, str.substr(search_start));
}
return ret;
}
add_function(ret, index, str.substr(search_start, found_index - search_start));
index += 1;
search_start = found_index + delim_length;
}
}
}
std::vector<std::string>
split(const std::string& s, char c)
{
return split_base<std::vector<std::string>, std::size_t>
(
s, c, true, [](std::vector<std::string>& v, std::size_t, const std::string& s)
{
v.emplace_back(s);
}
);
}
std::vector<std::string>
split_on_spaces(const std::string& string)
{
std::istringstream iss(string);
return std::vector<std::string>
(
std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>()
);
}
std::string
optional_string(bool b, const std::string& str)
{
if(b)
{
return str;
}
else
{
return "";
}
}
bool
is_number(char b)
{
return b >= '0' && b <= '9';
}
int
parse_number(const char** aa)
{
const char*& a = *aa;
int result = *a - '0';
++a;
while(is_number(*a))
{
result *= 10;
result += *a - '0';
++a;
}
--a;
return result;
}
int
string_compare(const std::string& lhs, const std::string& rhs)
{
const char* a = lhs.c_str();
const char* b = rhs.c_str();
if(a == b) { return 0; }
if(a == nullptr) { return -1; }
if(b == nullptr) { return 1; }
while(*a != 0 && *b != 0)
{
// will contain either a number or a letter
const int a0 = is_number(*a) ? parse_number(&a) + 256 : to_lower_char(*a);
const int b0 = is_number(*b) ? parse_number(&b) + 256 : to_lower_char(*b);
if(a0 < b0) { return -1; }
if(a0 > b0) { return 1; }
++a;
++b;
}
if(*a != 0) { return 1; }
if(*b != 0) { return -1; }
return 0;
}
}
<commit_msg>fix: use auto to fix clang-tidy error<commit_after>#include "core/stringutils.h"
#include <string>
#include <algorithm>
#include <cstring>
#include <vector>
#include <sstream>
#include <iterator>
#include <type_traits>
#include "core/assert.h"
namespace euphoria::core
{
std::pair<std::string, std::string>
last_strings(const std::string& str, char sep)
{
auto result = str.find(sep);
if(result == std::string::npos)
{
return std::make_pair(str, "");
}
const auto parent = str.substr(0, result);
const auto child = str.substr(result, str.length() - parent.length());
return std::make_pair(parent, child);
}
std::string
first_chars(const std::string& str, std::size_t count)
{
if(str.length() < count) { return str; }
else { return str.substr(0, count); }
}
std::string
first_chars_with_ellipsis(const std::string& str, unsigned int count)
{
if (str.length() > count)
{
return str.substr(0, count) + "...";
}
return str;
}
std::string
strip_last_string(const std::string& str, char sep)
{
auto result = str.find(sep);
if(result == std::string::npos)
{
return "";
}
return str.substr(0, result);
}
std::string
trim_right(const std::string& string_to_trim, const std::string& trim_characters)
{
return std::string(string_to_trim).erase(string_to_trim.find_last_not_of(trim_characters) + 1);
}
std::string
trim_left(const std::string& string_to_trim, const std::string& trim_characters)
{
return std::string(string_to_trim).erase(0, string_to_trim.find_first_not_of(trim_characters));
}
std::string
trim(const std::string& string_to_trim, const std::string& trim_characters)
{
return trim_right(trim_left(string_to_trim, trim_characters), trim_characters);
}
bool
starts_with(const std::string& string_to_test, const std::string& start)
{
const std::string::size_type length = start.length();
const std::string::size_type other_length = string_to_test.length();
if(other_length < length)
{
return false;
}
const std::string actual_start = string_to_test.substr(0, length);
return start == actual_start;
}
bool
ends_with(const std::string& string_to_test, const std::string& end)
{
const std::string::size_type length = end.length();
const std::string::size_type other_length = string_to_test.length();
if(other_length < length)
{
return false;
}
const std::string actual_end
= string_to_test.substr(other_length - length, length);
return end == actual_end;
}
char
to_lower_char(char b)
{
if(b >= 'A' && b <= 'Z')
{
return static_cast<char>((static_cast<int>(b) - 'A') + 'a');
}
else
{
return b;
}
}
char
to_upper_char(char b)
{
if(b >= 'a' && b <= 'z')
{
return static_cast<char>(b + ('A' - 'a'));
}
else
{
return b;
}
}
std::string
to_lower(const std::string& str)
{
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), to_lower_char);
return result;
}
std::vector<std::string>
to_lower(const std::vector<std::string>& str)
{
return to_string_vector(str, [](const std::string& s) { return to_lower(s); });
}
std::string
to_upper(const std::string& str)
{
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), to_upper_char);
return result;
}
std::string
char_to_string(char c, CharToStringStyle style)
{
constexpr std::string_view smart_characters =
"abcdefghijklmnopqrstuwxyz"
"ABCDEFGHIJKLMNOPQRSTUWXYZ"
" "
"~!@#$%^&*()_+"
"`123456790-="
",.<>/?"
"{}[]:;\"'\\|"
"\n\r\t"
;
std::ostringstream ss;
switch(c)
{
case 0:
ss << "<null>";
if(style == CharToStringStyle::smart)
{
return ss.str();
}
break;
case '\n':
ss << "<\\n>";
break;
case '\r':
ss << "<\\r>";
break;
case '\t':
ss << "<tab>";
break;
// source: http://www.asciitable.com/
case 1: ss << "<start of heading>"; break;
case 2: ss << "<start of text>"; break;
case 3: ss << "<end of text>"; break;
case 4: ss << "<end of transmission>"; break;
case 5: ss << "<enquiry>"; break;
case 6: ss << "<acknowledge>"; break;
case 7: ss << "<bell>"; break;
case 8: ss << "<backspace>"; break;
// case 9: ss << "<horizontal tab>"; break;
// case 10: ss << "<newline>"; break;
case 11: ss << "<vertical tab>"; break;
case 12: ss << "<new page>"; break;
// case 13: ss << "<carriage return>"; break;
case 14: ss << "<shift out>"; break;
case 15: ss << "<shift in>"; break;
case 16: ss << "<data link esqape>"; break;
case 17: ss << "<device control 1>"; break;
case 18: ss << "<device control 2>"; break;
case 19: ss << "<device control 3>"; break;
case 20: ss << "<device control 4>"; break;
case 21: ss << "<negative acknowledge>"; break;
case 22: ss << "<synchronous idle>"; break;
case 23: ss << "<end of trans. block>"; break;
case 24: ss << "<cancel>"; break;
case 25: ss << "<end of medium>"; break;
case 26: ss << "<substitute>"; break;
case 27: ss << "<escape>"; break;
case 28: ss << "<file separator>"; break;
case 29: ss << "<group separator>"; break;
case 30: ss << "<record separator>"; break;
case 31: ss << "<unit separator>"; break;
case 127: ss << "<DEL>"; break;
case ' ':
ss << "<space>";
break;
default:
ss << c;
break;
}
if(style == CharToStringStyle::include_hex || smart_characters.find(c) == std::string_view::npos)
{
ss << "(0x" << std::hex << static_cast<int>(c) << ")";
}
return ss.str();
}
std::string::size_type
find_first_index_of_mismatch(const std::string& lhs, const std::string& rhs)
{
const auto end = std::min(lhs.size(), rhs.size());
std::string::size_type index = 0;
for(; index < end; index+=1)
{
if(lhs[index]!=rhs[index])
{
return index;
}
}
if(index >= lhs.size() && index >= rhs.size())
{
return std::string::npos;
}
else
{
return end;
}
}
void
replace_all(std::string* string, const std::string& to_find, const std::string& to_replace)
{
std::size_t index = string->find(to_find);
const std::size_t find_length = to_find.length();
ASSERT(find_length > 0);
while(index != std::string::npos)
{
string->erase(index, find_length);
string->insert(index, to_replace);
index = string->find(to_find, index);
}
}
std::string
replace_all(const std::string& string, const std::string& to_find, const std::string& to_replace)
{
std::string temp = string;
replace_all(&temp, to_find, to_replace);
return temp;
}
void
copy(char* dst, const std::string& src, const std::string::size_type& count)
{
strncpy(dst, src.c_str(), count - 1);
dst[count - 1] = 0;
}
std::string
replace_with_character(const std::string& string, const std::string& to_find, char to_replace)
{
std::string s = string;
for(char c: to_find)
{
std::replace(s.begin(), s.end(), c, to_replace);
}
return s;
}
std::string
remove_from_end(const std::string& str, const std::string& end)
{
if(ends_with(str, end))
{
const auto new_length = str.length() - end.length();
if(new_length == 0)
{
return "";
}
ASSERT(new_length > 0);
return str.substr(0, new_length);
}
return str;
}
std::string
strip(const std::string& str, const std::string& ch)
{
std::stringstream ss;
for(const char c: str)
{
if(ch.find(c) == std::string::npos)
{
ss << c;
}
}
return ss.str();
}
// remove all characters in ch except the first one in a chain from str
std::string
remove_consecutive(const std::string& str, const std::string& ch)
{
std::stringstream ss;
bool skip = false;
for(const char c: str)
{
if(ch.find(c) == std::string::npos)
{
ss << c;
skip = false;
}
else
{
if(!skip)
{
ss << c;
skip = true;
}
}
}
return ss.str();
}
namespace
{
template<typename R, typename T>
struct SizeGetter
{
static R get(const T& t) { return t.size(); }
};
template<typename R>
struct SizeGetter<R, char>
{
static R get(char) { return 1; }
};
template<typename R, typename T>
R get_size(const T& t) { return SizeGetter<R, T>::get(t); }
template
<
typename ListType,
typename OffsetType,
typename StringType,
typename DelimType,
typename AddFunction
>
ListType
split_base(const StringType str, DelimType delim, bool add_final, AddFunction&& add_function)
{
ListType ret;
const auto delim_length = get_size<OffsetType>(delim);
OffsetType search_start = 0;
OffsetType index = 0;
while(true)
{
const auto found_index = str.find(delim, search_start);
if(found_index == StringType::npos)
{
// abort... add last?
// todo(Gustav): add argument to specify how to handle split on empty input
if(add_final && str.empty() == false)
{
add_function(ret, index, str.substr(search_start));
}
return ret;
}
add_function(ret, index, str.substr(search_start, found_index - search_start));
index += 1;
search_start = found_index + delim_length;
}
}
}
std::vector<std::string>
split(const std::string& s, char c)
{
return split_base<std::vector<std::string>, std::size_t>
(
s, c, true, [](std::vector<std::string>& v, std::size_t, const std::string& s)
{
v.emplace_back(s);
}
);
}
std::vector<std::string>
split_on_spaces(const std::string& string)
{
std::istringstream iss(string);
return std::vector<std::string>
(
std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>()
);
}
std::string
optional_string(bool b, const std::string& str)
{
if(b)
{
return str;
}
else
{
return "";
}
}
bool
is_number(char b)
{
return b >= '0' && b <= '9';
}
int
parse_number(const char** aa)
{
const char*& a = *aa;
int result = *a - '0';
++a;
while(is_number(*a))
{
result *= 10;
result += *a - '0';
++a;
}
--a;
return result;
}
int
string_compare(const std::string& lhs, const std::string& rhs)
{
const char* a = lhs.c_str();
const char* b = rhs.c_str();
if(a == b) { return 0; }
if(a == nullptr) { return -1; }
if(b == nullptr) { return 1; }
while(*a != 0 && *b != 0)
{
// will contain either a number or a letter
const int a0 = is_number(*a) ? parse_number(&a) + 256 : to_lower_char(*a);
const int b0 = is_number(*b) ? parse_number(&b) + 256 : to_lower_char(*b);
if(a0 < b0) { return -1; }
if(a0 > b0) { return 1; }
++a;
++b;
}
if(*a != 0) { return 1; }
if(*b != 0) { return -1; }
return 0;
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkMapper.h"
#include "vtkLookupTable.h"
// Initialize static member that controls global immediate mode rendering
static int vtkMapperGlobalImmediateModeRendering = 0;
// Initialize static member that controls global coincidence resolution
static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;
// Construct with initial range (0,1).
vtkMapper::vtkMapper()
{
this->Colors = NULL;
this->LookupTable = NULL;
this->ScalarVisibility = 1;
this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;
this->UseLookupTableScalarRange = 0;
this->ImmediateModeRendering = 0;
this->ColorMode = VTK_COLOR_MODE_DEFAULT;
this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->RenderTime = 0.0;
strcpy(this->ArrayName, "");
this->ArrayId = -1;
this->ArrayComponent = -1;
this->ArrayAccessMode = -1;
}
vtkMapper::~vtkMapper()
{
if (this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
if ( this->Colors != NULL )
{
this->Colors->UnRegister(this);
}
}
// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->GetInput() )
{
return bounds;
}
else
{
this->Update();
this->GetInput()->GetBounds(this->Bounds);
return this->Bounds;
}
}
vtkDataSet *vtkMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkDataSet *)(this->Inputs[0]);
}
void vtkMapper::SetGlobalImmediateModeRendering(int val)
{
if (val == vtkMapperGlobalImmediateModeRendering)
{
return;
}
vtkMapperGlobalImmediateModeRendering = val;
}
int vtkMapper::GetGlobalImmediateModeRendering()
{
return vtkMapperGlobalImmediateModeRendering;
}
void vtkMapper::SetResolveCoincidentTopology(int val)
{
if (val == vtkMapperGlobalResolveCoincidentTopology)
{
return;
}
vtkMapperGlobalResolveCoincidentTopology = val;
}
int vtkMapper::GetResolveCoincidentTopology()
{
return vtkMapperGlobalResolveCoincidentTopology;
}
void vtkMapper::SetResolveCoincidentTopologyToDefault()
{
vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
}
void vtkMapper::SetResolveCoincidentTopologyZShift(double val)
{
if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyZShift = val;
}
double vtkMapper::GetResolveCoincidentTopologyZShift()
{
return vtkMapperGlobalResolveCoincidentTopologyZShift;
}
void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(
float factor, float units)
{
if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&
units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;
}
void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(
float& factor, float& units)
{
factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;
units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;
}
// Overload standard modified time function. If lookup table is modified,
// then this object is modified as well.
unsigned long vtkMapper::GetMTime()
{
unsigned long mTime=this->MTime.GetMTime();
unsigned long lutMTime;
if ( this->LookupTable != NULL )
{
lutMTime = this->LookupTable->GetMTime();
mTime = ( lutMTime > mTime ? lutMTime : mTime );
}
return mTime;
}
void vtkMapper::ShallowCopy(vtkMapper *m)
{
this->SetLookupTable(m->GetLookupTable());
this->SetClippingPlanes(m->GetClippingPlanes());
this->SetScalarVisibility(m->GetScalarVisibility());
this->SetScalarRange(m->GetScalarRange());
this->SetColorMode(m->GetColorMode());
this->SetScalarMode(m->GetScalarMode());
this->SetImmediateModeRendering(m->GetImmediateModeRendering());
}
// a side effect of this is that this->Colors is also set
// to the return value
vtkScalars *vtkMapper::GetColors()
{
vtkScalars *scalars = NULL;
vtkDataArray *dataArray=0;
vtkPointData *pd;
vtkCellData *cd;
vtkIdType i, numScalars;
// make sure we have an input
if (!this->GetInput())
{
return NULL;
}
// get and scalar data according to scalar mode
if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
if (!scalars)
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
pd = this->GetInput()->GetPointData();
if (pd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = pd->GetArray(this->ArrayId);
}
else
{
dataArray = pd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
cd = this->GetInput()->GetCellData();
if (cd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = cd->GetArray(this->ArrayId);
}
else
{
dataArray = cd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
}
// do we have any scalars ?
if (scalars && this->ScalarVisibility)
{
// if the scalars have a lookup table use it instead
if (scalars->GetLookupTable())
{
this->SetLookupTable(scalars->GetLookupTable());
}
else
{
// make sure we have a lookup table
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
this->LookupTable->Build();
}
// Setup mapper/scalar object for color generation
if (!this->UseLookupTableScalarRange)
{
this->LookupTable->SetRange(this->ScalarRange);
}
if (this->Colors)
{
this->Colors->UnRegister(this);
}
this->Colors = scalars;
this->Colors->Register(this);
this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);
}
else //scalars not visible
{
if ( this->Colors )
{
this->Colors->UnRegister(this);
}
this->Colors = NULL;
}
if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||
(this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&
scalars)
{
scalars->Delete();
}
return this->Colors;
}
void vtkMapper::ColorByArrayComponent(int arrayNum, int component)
{
if (this->ArrayId == arrayNum && component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
this->ArrayId = arrayNum;
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;
}
void vtkMapper::ColorByArrayComponent(char* arrayName, int component)
{
if (strcmp(this->ArrayName, arrayName) == 0 &&
component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
strcpy(this->ArrayName, arrayName);
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;
}
// Specify a lookup table for the mapper to use.
void vtkMapper::SetLookupTable(vtkScalarsToColors *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = lut;
if (lut)
{
lut->Register(this);
}
this->Modified();
}
}
vtkScalarsToColors *vtkMapper::GetLookupTable()
{
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
return this->LookupTable;
}
void vtkMapper::CreateDefaultLookupTable()
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = vtkLookupTable::New();
}
// Update the network connected to this mapper.
void vtkMapper::Update()
{
if ( this->GetInput() )
{
this->GetInput()->Update();
}
}
// Return the method of coloring scalar data.
const char *vtkMapper::GetColorModeAsString(void)
{
if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )
{
return "Luminance";
}
else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS )
{
return "MapScalars";
}
else
{
return "Default";
}
}
// Return the method for obtaining scalar data.
const char *vtkMapper::GetScalarModeAsString(void)
{
if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
return "UseCellData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
return "UsePointData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
return "UsePointFieldData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
return "UseCellFieldData";
}
else
{
return "Default";
}
}
void vtkMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkAbstractMapper3D::PrintSelf(os,indent);
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Lookup Table: (none)\n";
}
os << indent << "Immediate Mode Rendering: "
<< (this->ImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Global Immediate Mode Rendering: " <<
(vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Scalar Visibility: "
<< (this->ScalarVisibility ? "On\n" : "Off\n");
float *range = this->GetScalarRange();
os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n";
os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n";
os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;
os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl;
os << indent << "RenderTime: " << this->RenderTime << endl;
os << indent << "Resolve Coincident Topology: ";
if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )
{
os << "Off" << endl;
}
else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )
{
os << "Polygon Offset" << endl;
}
else
{
os << "Shift Z-Buffer" << endl;
}
}
<commit_msg>ENH:Notify the user that the indicated data array was not found when performing scalar coloring<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkMapper.h"
#include "vtkLookupTable.h"
// Initialize static member that controls global immediate mode rendering
static int vtkMapperGlobalImmediateModeRendering = 0;
// Initialize static member that controls global coincidence resolution
static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;
// Construct with initial range (0,1).
vtkMapper::vtkMapper()
{
this->Colors = NULL;
this->LookupTable = NULL;
this->ScalarVisibility = 1;
this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;
this->UseLookupTableScalarRange = 0;
this->ImmediateModeRendering = 0;
this->ColorMode = VTK_COLOR_MODE_DEFAULT;
this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->RenderTime = 0.0;
strcpy(this->ArrayName, "");
this->ArrayId = -1;
this->ArrayComponent = -1;
this->ArrayAccessMode = -1;
}
vtkMapper::~vtkMapper()
{
if (this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
if ( this->Colors != NULL )
{
this->Colors->UnRegister(this);
}
}
// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->GetInput() )
{
return bounds;
}
else
{
this->Update();
this->GetInput()->GetBounds(this->Bounds);
return this->Bounds;
}
}
vtkDataSet *vtkMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkDataSet *)(this->Inputs[0]);
}
void vtkMapper::SetGlobalImmediateModeRendering(int val)
{
if (val == vtkMapperGlobalImmediateModeRendering)
{
return;
}
vtkMapperGlobalImmediateModeRendering = val;
}
int vtkMapper::GetGlobalImmediateModeRendering()
{
return vtkMapperGlobalImmediateModeRendering;
}
void vtkMapper::SetResolveCoincidentTopology(int val)
{
if (val == vtkMapperGlobalResolveCoincidentTopology)
{
return;
}
vtkMapperGlobalResolveCoincidentTopology = val;
}
int vtkMapper::GetResolveCoincidentTopology()
{
return vtkMapperGlobalResolveCoincidentTopology;
}
void vtkMapper::SetResolveCoincidentTopologyToDefault()
{
vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
}
void vtkMapper::SetResolveCoincidentTopologyZShift(double val)
{
if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyZShift = val;
}
double vtkMapper::GetResolveCoincidentTopologyZShift()
{
return vtkMapperGlobalResolveCoincidentTopologyZShift;
}
void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(
float factor, float units)
{
if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&
units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;
}
void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(
float& factor, float& units)
{
factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;
units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;
}
// Overload standard modified time function. If lookup table is modified,
// then this object is modified as well.
unsigned long vtkMapper::GetMTime()
{
unsigned long mTime=this->MTime.GetMTime();
unsigned long lutMTime;
if ( this->LookupTable != NULL )
{
lutMTime = this->LookupTable->GetMTime();
mTime = ( lutMTime > mTime ? lutMTime : mTime );
}
return mTime;
}
void vtkMapper::ShallowCopy(vtkMapper *m)
{
this->SetLookupTable(m->GetLookupTable());
this->SetClippingPlanes(m->GetClippingPlanes());
this->SetScalarVisibility(m->GetScalarVisibility());
this->SetScalarRange(m->GetScalarRange());
this->SetColorMode(m->GetColorMode());
this->SetScalarMode(m->GetScalarMode());
this->SetImmediateModeRendering(m->GetImmediateModeRendering());
}
// a side effect of this is that this->Colors is also set
// to the return value
vtkScalars *vtkMapper::GetColors()
{
vtkScalars *scalars = NULL;
vtkDataArray *dataArray=0;
vtkPointData *pd;
vtkCellData *cd;
vtkIdType i, numScalars;
// make sure we have an input
if (!this->GetInput())
{
return NULL;
}
// get and scalar data according to scalar mode
if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
if (!scalars)
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
pd = this->GetInput()->GetPointData();
if (pd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = pd->GetArray(this->ArrayId);
}
else
{
dataArray = pd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
cd = this->GetInput()->GetCellData();
if (cd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = cd->GetArray(this->ArrayId);
}
else
{
dataArray = cd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
// do we have any scalars ?
if (scalars && this->ScalarVisibility)
{
// if the scalars have a lookup table use it instead
if (scalars->GetLookupTable())
{
this->SetLookupTable(scalars->GetLookupTable());
}
else
{
// make sure we have a lookup table
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
this->LookupTable->Build();
}
// Setup mapper/scalar object for color generation
if (!this->UseLookupTableScalarRange)
{
this->LookupTable->SetRange(this->ScalarRange);
}
if (this->Colors)
{
this->Colors->UnRegister(this);
}
this->Colors = scalars;
this->Colors->Register(this);
this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);
}
else //scalars not visible
{
if ( this->Colors )
{
this->Colors->UnRegister(this);
}
this->Colors = NULL;
}
if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||
(this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&
scalars)
{
scalars->Delete();
}
return this->Colors;
}
void vtkMapper::ColorByArrayComponent(int arrayNum, int component)
{
if (this->ArrayId == arrayNum && component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
this->ArrayId = arrayNum;
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;
}
void vtkMapper::ColorByArrayComponent(char* arrayName, int component)
{
if (strcmp(this->ArrayName, arrayName) == 0 &&
component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
strcpy(this->ArrayName, arrayName);
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;
}
// Specify a lookup table for the mapper to use.
void vtkMapper::SetLookupTable(vtkScalarsToColors *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = lut;
if (lut)
{
lut->Register(this);
}
this->Modified();
}
}
vtkScalarsToColors *vtkMapper::GetLookupTable()
{
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
return this->LookupTable;
}
void vtkMapper::CreateDefaultLookupTable()
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = vtkLookupTable::New();
}
// Update the network connected to this mapper.
void vtkMapper::Update()
{
if ( this->GetInput() )
{
this->GetInput()->Update();
}
}
// Return the method of coloring scalar data.
const char *vtkMapper::GetColorModeAsString(void)
{
if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )
{
return "Luminance";
}
else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS )
{
return "MapScalars";
}
else
{
return "Default";
}
}
// Return the method for obtaining scalar data.
const char *vtkMapper::GetScalarModeAsString(void)
{
if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
return "UseCellData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
return "UsePointData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
return "UsePointFieldData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
return "UseCellFieldData";
}
else
{
return "Default";
}
}
void vtkMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkAbstractMapper3D::PrintSelf(os,indent);
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Lookup Table: (none)\n";
}
os << indent << "Immediate Mode Rendering: "
<< (this->ImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Global Immediate Mode Rendering: " <<
(vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Scalar Visibility: "
<< (this->ScalarVisibility ? "On\n" : "Off\n");
float *range = this->GetScalarRange();
os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n";
os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n";
os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;
os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl;
os << indent << "RenderTime: " << this->RenderTime << endl;
os << indent << "Resolve Coincident Topology: ";
if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )
{
os << "Off" << endl;
}
else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )
{
os << "Polygon Offset" << endl;
}
else
{
os << "Shift Z-Buffer" << endl;
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cmath>
#include <iomanip>
#include <ios>
#include <locale>
#include "vast/logger.hpp"
#include <caf/all.hpp>
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/filesystem.hpp"
#include "vast/error.hpp"
#include "vast/system/accountant.hpp"
#include "vast/detail/coding.hpp"
#include "vast/detail/fill_status_map.hpp"
namespace vast {
namespace system {
namespace {
using accountant_actor = accountant_type::stateful_base<accountant_state>;
constexpr std::chrono::seconds overview_delay(3);
void init(accountant_actor* self, const path& filename) {
if (!exists(filename.parent())) {
auto t = mkdir(filename.parent());
if (!t) {
VAST_ERROR(self, to_string(t.error()));
self->quit(t.error());
return;
}
}
VAST_DEBUG(self, "opens log file:", filename.trim(-4));
auto& file = self->state.file;
file.open(filename.str());
if (!file.is_open()) {
VAST_ERROR(self, "failed to open file:", filename);
auto e = make_error(ec::filesystem_error, "failed to open file:", filename);
self->quit(e);
return;
}
file << "timestamp\thost\tpid\taid\tactor_name\tkey\tvalue\n";
if (!file)
self->quit(make_error(ec::filesystem_error));
VAST_DEBUG(self, "kicks off flush loop");
self->send(self, flush_atom::value);
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
self->delayed_send(self, overview_delay, telemetry_atom::value);
#endif
}
template <class T>
void record(accountant_actor* self, const std::string& key, T x,
time ts = std::chrono::system_clock::now()) {
using namespace std::chrono;
auto aid = self->current_sender()->id();
auto node = self->current_sender()->node();
auto& st = self->state;
st.file << to_string(ts) << '\t';
for (auto byte : node.host_id())
st.file << static_cast<int>(byte);
st.file << std::dec << '\t' << node.process_id() << '\t' << aid << '\t'
<< st.actor_map[aid] << '\t' << key << '\t' << std::setprecision(6)
<< x << '\n';
// Flush after at most 10 seconds.
if (!st.flush_pending) {
st.flush_pending = true;
self->delayed_send(self, 10s, flush_atom::value);
}
}
void record(accountant_actor* self, const std::string& key, duration x,
time ts = std::chrono::system_clock::now()) {
using namespace std::chrono;
auto us = duration_cast<microseconds>(x).count();
record(self, key, us, std::move(ts));
}
void record(accountant_actor* self, const std::string& key, time x,
time ts = std::chrono::system_clock::now()) {
record(self, key, x.time_since_epoch(), std::move(ts));
}
// Calculate rate in seconds resolution from nanosecond duration.
double calc_rate(const measurement& m) {
if (m.duration.count() > 0)
return m.events * 1'000'000'000 / m.duration.count();
else
return std::numeric_limits<double>::quiet_NaN();
}
} // namespace <anonymous>
accountant_state::accountant_state(accountant_actor* self) : self{self} {
// nop
}
void accountant_state::command_line_heartbeat() {
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO
&& accumulator.node.events > 0) {
std::ostringstream oss;
try {
oss.imbue(std::locale(""));
} catch (const std::exception& e) {
VAST_DEBUG(self,
"failed to set the locale for statistics output:", e.what());
}
auto node_rate = std::round(calc_rate(accumulator.node));
oss << "ingested " << accumulator.node.events << " events at a rate of "
<< node_rate << " events/sec";
VAST_INFO_ANON(oss.str());
}
accumulator = {};
}
accountant_type::behavior_type accountant(accountant_actor* self,
const path& filename) {
using namespace std::chrono;
init(self, filename);
self->set_exit_handler(
[=](const caf::exit_msg& msg) {
self->state.file.flush();
self->quit(msg.reason);
}
);
self->set_down_handler(
[=](const caf::down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
self->state.actor_map.erase(msg.source.id());
}
);
return {[=](announce_atom, const std::string& name) {
self->state.actor_map[self->current_sender()->id()] = name;
self->monitor(self->current_sender());
},
[=](const std::string& key, const std::string& value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
// Helpers to avoid to_string(..) in sender context.
[=](const std::string& key, duration value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, time value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, int64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, uint64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, double value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const report& r) {
VAST_TRACE(self, "received a report from", self->current_sender());
time ts = std::chrono::system_clock::now();
for (const auto& [key, value] : r) {
auto f = [&, key = key](const auto& x) {
record(self, key, x, ts);
};
caf::visit(f, value);
}
},
[=](const performance_report& r) {
VAST_TRACE(self, "received a performance report from",
self->current_sender());
time ts = std::chrono::system_clock::now();
for (const auto& [key, value] : r) {
record(self, key + ".events", value.events, ts);
record(self, key + ".duration", value.duration, ts);
auto rate = calc_rate(value);
if (std::isfinite(rate))
record(self, key + ".rate", static_cast<uint64_t>(rate), ts);
else
record(self, key + ".rate", "NaN", ts);
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO)
if (key == "node_throughput")
self->state.accumulator.node += value;
#endif
}
},
[=](flush_atom) {
if (self->state.file)
self->state.file.flush();
self->state.flush_pending = false;
},
[=](status_atom) {
using caf::put_dictionary;
caf::dictionary<caf::config_value> result;
result.emplace("log-file", filename.str());
auto& known = put_dictionary(result, "known-actors");
for (const auto& [aid, name] : self->state.actor_map)
known.emplace(name, aid);
detail::fill_status_map(result, self);
return result;
},
[=](telemetry_atom) {
self->state.command_line_heartbeat();
self->delayed_send(self, overview_delay, telemetry_atom::value);
}};
}
} // namespace system
} // namespace vast
<commit_msg>Port VAST to lastet node_id API<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <cmath>
#include <iomanip>
#include <ios>
#include <locale>
#include "vast/logger.hpp"
#include <caf/all.hpp>
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/filesystem.hpp"
#include "vast/error.hpp"
#include "vast/system/accountant.hpp"
#include "vast/detail/coding.hpp"
#include "vast/detail/fill_status_map.hpp"
namespace vast {
namespace system {
namespace {
using accountant_actor = accountant_type::stateful_base<accountant_state>;
constexpr std::chrono::seconds overview_delay(3);
void init(accountant_actor* self, const path& filename) {
if (!exists(filename.parent())) {
auto t = mkdir(filename.parent());
if (!t) {
VAST_ERROR(self, to_string(t.error()));
self->quit(t.error());
return;
}
}
VAST_DEBUG(self, "opens log file:", filename.trim(-4));
auto& file = self->state.file;
file.open(filename.str());
if (!file.is_open()) {
VAST_ERROR(self, "failed to open file:", filename);
auto e = make_error(ec::filesystem_error, "failed to open file:", filename);
self->quit(e);
return;
}
file << "timestamp\tnode\taid\tactor_name\tkey\tvalue\n";
if (!file)
self->quit(make_error(ec::filesystem_error));
VAST_DEBUG(self, "kicks off flush loop");
self->send(self, flush_atom::value);
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
self->delayed_send(self, overview_delay, telemetry_atom::value);
#endif
}
template <class T>
void record(accountant_actor* self, const std::string& key, T x,
time ts = std::chrono::system_clock::now()) {
using namespace std::chrono;
auto aid = self->current_sender()->id();
auto node = self->current_sender()->node();
auto& st = self->state;
st.file << to_string(ts) << '\t' << to_string(node) << '\t';
st.file << std::dec << aid << '\t' << st.actor_map[aid] << '\t' << key << '\t'
<< std::setprecision(6) << x << '\n';
// Flush after at most 10 seconds.
if (!st.flush_pending) {
st.flush_pending = true;
self->delayed_send(self, 10s, flush_atom::value);
}
}
void record(accountant_actor* self, const std::string& key, duration x,
time ts = std::chrono::system_clock::now()) {
using namespace std::chrono;
auto us = duration_cast<microseconds>(x).count();
record(self, key, us, std::move(ts));
}
void record(accountant_actor* self, const std::string& key, time x,
time ts = std::chrono::system_clock::now()) {
record(self, key, x.time_since_epoch(), std::move(ts));
}
// Calculate rate in seconds resolution from nanosecond duration.
double calc_rate(const measurement& m) {
if (m.duration.count() > 0)
return m.events * 1'000'000'000 / m.duration.count();
else
return std::numeric_limits<double>::quiet_NaN();
}
} // namespace <anonymous>
accountant_state::accountant_state(accountant_actor* self) : self{self} {
// nop
}
void accountant_state::command_line_heartbeat() {
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO
&& accumulator.node.events > 0) {
std::ostringstream oss;
try {
oss.imbue(std::locale(""));
} catch (const std::exception& e) {
VAST_DEBUG(self,
"failed to set the locale for statistics output:", e.what());
}
auto node_rate = std::round(calc_rate(accumulator.node));
oss << "ingested " << accumulator.node.events << " events at a rate of "
<< node_rate << " events/sec";
VAST_INFO_ANON(oss.str());
}
accumulator = {};
}
accountant_type::behavior_type accountant(accountant_actor* self,
const path& filename) {
using namespace std::chrono;
init(self, filename);
self->set_exit_handler(
[=](const caf::exit_msg& msg) {
self->state.file.flush();
self->quit(msg.reason);
}
);
self->set_down_handler(
[=](const caf::down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
self->state.actor_map.erase(msg.source.id());
}
);
return {[=](announce_atom, const std::string& name) {
self->state.actor_map[self->current_sender()->id()] = name;
self->monitor(self->current_sender());
},
[=](const std::string& key, const std::string& value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
// Helpers to avoid to_string(..) in sender context.
[=](const std::string& key, duration value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, time value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, int64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, uint64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, double value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const report& r) {
VAST_TRACE(self, "received a report from", self->current_sender());
time ts = std::chrono::system_clock::now();
for (const auto& [key, value] : r) {
auto f = [&, key = key](const auto& x) {
record(self, key, x, ts);
};
caf::visit(f, value);
}
},
[=](const performance_report& r) {
VAST_TRACE(self, "received a performance report from",
self->current_sender());
time ts = std::chrono::system_clock::now();
for (const auto& [key, value] : r) {
record(self, key + ".events", value.events, ts);
record(self, key + ".duration", value.duration, ts);
auto rate = calc_rate(value);
if (std::isfinite(rate))
record(self, key + ".rate", static_cast<uint64_t>(rate), ts);
else
record(self, key + ".rate", "NaN", ts);
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO)
if (key == "node_throughput")
self->state.accumulator.node += value;
#endif
}
},
[=](flush_atom) {
if (self->state.file)
self->state.file.flush();
self->state.flush_pending = false;
},
[=](status_atom) {
using caf::put_dictionary;
caf::dictionary<caf::config_value> result;
result.emplace("log-file", filename.str());
auto& known = put_dictionary(result, "known-actors");
for (const auto& [aid, name] : self->state.actor_map)
known.emplace(name, aid);
detail::fill_status_map(result, self);
return result;
},
[=](telemetry_atom) {
self->state.command_line_heartbeat();
self->delayed_send(self, overview_delay, telemetry_atom::value);
}};
}
} // namespace system
} // namespace vast
<|endoftext|>
|
<commit_before>// $Id: HINFile_test.C,v 1.8 2001/05/06 21:11:13 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/HINFile.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/PTE.h>
///////////////////////////
START_TEST(HINFile, "$Id: HINFile_test.C,v 1.8 2001/05/06 21:11:13 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
HINFile* ptr;
CHECK(HINFile::HINFile())
ptr = new HINFile;
TEST_NOT_EQUAL(ptr, 0)
RESULT
CHECK(HINFile::~HINFile())
delete ptr;
RESULT
HINFile hin;
CHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN))
hin = HINFile("data/HINFile_test.hin");
TEST_EQUAL(hin.isValid(), true)
RESULT
System system;
CHECK(HINFile::read(System& system))
hin.read(system);
hin.reopen();
Vector3 position(0.59038, -0.410275, -0.860515);
TEST_EQUAL(hin.isValid(), true)
TEST_EQUAL(system.countAtoms(), 648)
TEST_EQUAL(system.countMolecules(), 216)
TEST_EQUAL(system.getAtom(0)->getName(), "O")
TEST_EQUAL(system.getAtom(0)->getElement(), PTE["O"])
TEST_REAL_EQUAL(system.getAtom(0)->getCharge(), -0.834)
TEST_EQUAL(system.getAtom(0)->getPosition(), position)
TEST_NOT_EQUAL(system.getAtom(0)->getRadius(), 0.0)
TEST_EQUAL(system.getAtom(0)->countBonds(), 2)
RESULT
CHECK(HINFile::write(const System& system))
String filename;
NEW_TMP_FILE(filename)
HINFile hin2(filename, std::ios::out);
hin2.write(system);
TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false)
RESULT
CHECK(HINFile::HINFile& operator >> (System& system))
System system2;
hin >> system2;
TEST_EQUAL(system.countAtoms(), system2.countAtoms())
RESULT
CHECK(HINFile::HINFile& operator << (const System& system))
String filename;
NEW_TMP_FILE(filename)
HINFile hin2(filename, std::ios::out);
hin2 << system;
TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false)
RESULT
CHECK(HINFile::hasPeriodicBoundary() const )
TEST_EQUAL(hin.hasPeriodicBoundary(), true)
RESULT
CHECK(HINFile::getPeriodicBoundary() const )
Box3 box3(-9.35068, -9.35068, -9.35068, 9.35068, 9.35068, 9.35068);
TEST_EQUAL(hin.getPeriodicBoundary(), box3)
RESULT
CHECK(HINFile::getTemperature() const )
//BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added: in test for read now testing radius<commit_after>// $Id: HINFile_test.C,v 1.9 2001/05/10 22:16:47 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/HINFile.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/PTE.h>
///////////////////////////
START_TEST(HINFile, "$Id: HINFile_test.C,v 1.9 2001/05/10 22:16:47 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
HINFile* ptr;
CHECK(HINFile::HINFile())
ptr = new HINFile;
TEST_NOT_EQUAL(ptr, 0)
RESULT
CHECK(HINFile::~HINFile())
delete ptr;
RESULT
HINFile hin;
CHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN))
hin = HINFile("data/HINFile_test.hin");
TEST_EQUAL(hin.isValid(), true)
RESULT
System system;
CHECK(HINFile::read(System& system))
hin.read(system);
hin.reopen();
Vector3 position(0.59038, -0.410275, -0.860515);
TEST_EQUAL(hin.isValid(), true)
TEST_EQUAL(system.countAtoms(), 648)
TEST_EQUAL(system.countMolecules(), 216)
TEST_EQUAL(system.getAtom(0)->getName(), "O")
TEST_EQUAL(system.getAtom(0)->getElement(), PTE["O"])
TEST_REAL_EQUAL(system.getAtom(0)->getCharge(), -0.834)
TEST_EQUAL(system.getAtom(0)->getPosition(), position)
TEST_REAL_EQUAL(system.getAtom(0)->getRadius(), 1.4)
TEST_EQUAL(system.getAtom(0)->countBonds(), 2)
TEST_NOT_EQUAL(system.getAtom(1)->getRadius(), 0)
RESULT
CHECK(HINFile::write(const System& system))
String filename;
NEW_TMP_FILE(filename)
HINFile hin2(filename, std::ios::out);
hin2.write(system);
TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false)
RESULT
CHECK(HINFile::HINFile& operator >> (System& system))
System system2;
hin >> system2;
TEST_EQUAL(system.countAtoms(), system2.countAtoms())
RESULT
CHECK(HINFile::HINFile& operator << (const System& system))
String filename;
NEW_TMP_FILE(filename)
HINFile hin2(filename, std::ios::out);
hin2 << system;
TEST_FILE("data/HINFile_test2.hin", filename.c_str(), false)
RESULT
CHECK(HINFile::hasPeriodicBoundary() const )
TEST_EQUAL(hin.hasPeriodicBoundary(), true)
RESULT
CHECK(HINFile::getPeriodicBoundary() const )
Box3 box3(-9.35068, -9.35068, -9.35068, 9.35068, 9.35068, 9.35068);
TEST_EQUAL(hin.getPeriodicBoundary(), box3)
RESULT
CHECK(HINFile::getTemperature() const )
//BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: process_impl.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:59:24 $
*
* 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 "osl/process.h"
#ifndef INCLUDED_LIMITS_H
#include <limits.h>
#define INCLUDED_LIMITS_H
#endif
#ifndef INCLUDED_PTHREAD_H
#include <pthread.h>
#define INCLUDED_PTHREAD_H
#endif
#ifndef INCLUDED_STDLIB_H
#include <stdlib.h>
#define INCLUDED_STDLIB_H
#endif
#ifndef INCLUDED_STRING_H
#include <string.h>
#define INCLUDED_STRING_H
#endif
#ifndef _OSL_DIAGNOSE_H_
#include "osl/diagnose.h"
#endif
#ifndef _OSL_FILE_H_
#include <osl/file.h>
#endif
#ifndef _OSL_MODULE_H_
#include "osl/module.h"
#endif
#ifndef _OSL_THREAD_H_
#include "osl/thread.h"
#endif
#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif
#ifndef _OSL_FILE_PATH_HELPER_H_
#include "file_path_helper.h"
#endif
#ifndef _OSL_UUNXAPI_H_
#include "uunxapi.h"
#endif
/***************************************
osl_bootstrap_getExecutableFile_Impl().
@internal
@see rtl_bootstrap
@see #i37371#
**************************************/
extern "C" oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C();
#if defined(MACOSX)
#include <mach-o/dyld.h>
oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C()
{
oslProcessError result = osl_Process_E_NotFound;
char buffer[PATH_MAX];
size_t buflen = sizeof(buffer);
if (_NSGetExecutablePath (buffer, &buflen) == 0)
{
/* Determine absolute path. */
char abspath[PATH_MAX];
if (realpath (buffer, abspath) != 0)
{
/* Convert from utf8 to unicode. */
rtl_uString * pAbsPath = 0;
rtl_string2UString (
&(pAbsPath),
abspath, rtl_str_getLength (abspath),
RTL_TEXTENCODING_UTF8,
OSTRING_TO_OUSTRING_CVTFLAGS);
if (pAbsPath)
{
/* Convert from path to url. */
if (osl_getFileURLFromSystemPath (pAbsPath, ppFileURL) == osl_File_E_None)
{
/* Success. */
result = osl_Process_E_None;
}
rtl_uString_release (pAbsPath);
}
}
}
return (result);
}
#elif !defined(NO_DL_FUNCTIONS)
#include <dlfcn.h>
oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C()
{
oslProcessError result = osl_Process_E_NotFound;
/* Determine address of "main()" function. */
void * addr = dlsym (RTLD_DEFAULT, "main");
if (addr != 0)
{
/* Determine module URL. */
if (osl_getModuleURLFromAddress (addr, ppFileURL))
{
/* Success. */
result = osl_Process_E_None;
}
}
return (result);
}
#else /* NO_DL_FUNCTIONS */
oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C()
{
/* Fallback to ordinary osl_getExecutableFile(). */
return osl_getExecutableFile (ppFileURL);
}
#endif /* NO_DL_FUNCTIONS */
/***************************************
CommandArgs_Impl.
**************************************/
struct CommandArgs_Impl
{
pthread_mutex_t m_mutex;
sal_uInt32 m_nCount;
rtl_uString ** m_ppArgs;
};
static struct CommandArgs_Impl g_command_args =
{
PTHREAD_MUTEX_INITIALIZER,
0,
0
};
/***************************************
osl_getExecutableFile().
**************************************/
oslProcessError SAL_CALL osl_getExecutableFile (rtl_uString ** ppustrFile)
{
oslProcessError result = osl_Process_E_NotFound;
pthread_mutex_lock (&(g_command_args.m_mutex));
if (g_command_args.m_nCount > 0)
{
/* CommandArgs set. Obtain argv[0]. */
rtl_uString_assign (ppustrFile, g_command_args.m_ppArgs[0]);
result = osl_Process_E_None;
}
pthread_mutex_unlock (&(g_command_args.m_mutex));
return (result);
}
/***************************************
osl_getCommandArgCount().
**************************************/
sal_uInt32 SAL_CALL osl_getCommandArgCount (void)
{
sal_uInt32 result = 0;
pthread_mutex_lock (&(g_command_args.m_mutex));
if (g_command_args.m_nCount > 0)
result = g_command_args.m_nCount - 1;
pthread_mutex_unlock (&(g_command_args.m_mutex));
return (result);
}
/***************************************
osl_getCommandArg().
**************************************/
oslProcessError SAL_CALL osl_getCommandArg (sal_uInt32 nArg, rtl_uString ** strCommandArg)
{
oslProcessError result = osl_Process_E_NotFound;
pthread_mutex_lock (&(g_command_args.m_mutex));
if (g_command_args.m_nCount > (nArg + 1))
{
rtl_uString_assign (strCommandArg, g_command_args.m_ppArgs[nArg + 1]);
result = osl_Process_E_None;
}
pthread_mutex_unlock (&(g_command_args.m_mutex));
return (result);
}
/***************************************
osl_setCommandArgs().
**************************************/
void SAL_CALL osl_setCommandArgs (int argc, char ** argv)
{
pthread_mutex_lock (&(g_command_args.m_mutex));
OSL_ENSURE (g_command_args.m_nCount == 0, "osl_setCommandArgs(): CommandArgs already set.");
if (g_command_args.m_nCount == 0)
{
rtl_uString** ppArgs = (rtl_uString**)rtl_allocateZeroMemory (argc * sizeof(rtl_uString*));
if (ppArgs != 0)
{
rtl_TextEncoding encoding = osl_getThreadTextEncoding();
for (int i = 0; i < argc; i++)
{
rtl_string2UString (
&(ppArgs[i]),
argv[i], rtl_str_getLength (argv[i]), encoding,
OSTRING_TO_OUSTRING_CVTFLAGS);
}
if (ppArgs[0] != 0)
{
/* see @ osl_getExecutableFile(). */
if (rtl_ustr_indexOfChar (rtl_uString_getStr(ppArgs[0]), sal_Unicode('/')) == -1)
{
const rtl::OUString PATH (RTL_CONSTASCII_USTRINGPARAM("PATH"));
rtl_uString * pSearchPath = 0;
osl_getEnvironment (PATH.pData, &pSearchPath);
if (pSearchPath)
{
rtl_uString * pSearchResult = 0;
osl_searchPath (ppArgs[0], pSearchPath, &pSearchResult);
if (pSearchResult)
{
rtl_uString_assign (&(ppArgs[0]), pSearchResult);
rtl_uString_release (pSearchResult);
}
rtl_uString_release (pSearchPath);
}
}
rtl_uString * pArg0 = 0;
if (realpath_u (ppArgs[0], &pArg0))
{
osl_getFileURLFromSystemPath (pArg0, &(ppArgs[0]));
rtl_uString_release (pArg0);
}
}
g_command_args.m_nCount = argc;
g_command_args.m_ppArgs = ppArgs;
}
}
pthread_mutex_unlock (&(g_command_args.m_mutex));
}
/***************************************
osl_getEnvironment().
**************************************/
oslProcessError SAL_CALL osl_getEnvironment(rtl_uString* pustrEnvVar, rtl_uString** ppustrValue)
{
oslProcessError result = osl_Process_E_NotFound;
rtl_TextEncoding encoding = osl_getThreadTextEncoding();
rtl_String* pstr_env_var = 0;
OSL_PRECOND(pustrEnvVar, "osl_getEnvironment(): Invalid parameter");
OSL_PRECOND(ppustrValue, "osl_getEnvironment(): Invalid parameter");
rtl_uString2String(
&pstr_env_var,
rtl_uString_getStr(pustrEnvVar), rtl_uString_getLength(pustrEnvVar), encoding,
OUSTRING_TO_OSTRING_CVTFLAGS);
if (pstr_env_var != 0)
{
const char* p_env_var = getenv (rtl_string_getStr (pstr_env_var));
if (p_env_var != 0)
{
rtl_string2UString(
ppustrValue,
p_env_var, strlen(p_env_var), encoding,
OSTRING_TO_OUSTRING_CVTFLAGS);
OSL_ASSERT(*ppustrValue != NULL);
result = osl_Process_E_None;
}
rtl_string_release(pstr_env_var);
}
return (result);
}
/***************************************
osl_getProcessWorkingDir().
**************************************/
oslProcessError SAL_CALL osl_getProcessWorkingDir(rtl_uString **ppustrWorkingDir)
{
oslProcessError result = osl_Process_E_Unknown;
char buffer[PATH_MAX];
OSL_PRECOND(ppustrWorkingDir, "osl_getProcessWorkingDir(): Invalid parameter");
if (getcwd (buffer, sizeof(buffer)) != 0)
{
rtl_uString* ustrTmp = 0;
rtl_string2UString(
&ustrTmp,
buffer, strlen(buffer), osl_getThreadTextEncoding(),
OSTRING_TO_OUSTRING_CVTFLAGS);
if (ustrTmp != 0)
{
if (osl_getFileURLFromSystemPath (ustrTmp, ppustrWorkingDir) == osl_File_E_None)
result = osl_Process_E_None;
rtl_uString_release (ustrTmp);
}
}
return (result);
}
/******************************************************************************
*
* new functions to set/return the current process locale
*
*****************************************************************************/
struct ProcessLocale_Impl
{
pthread_mutex_t m_mutex;
rtl_Locale * m_pLocale;
};
static struct ProcessLocale_Impl g_process_locale =
{
PTHREAD_MUTEX_INITIALIZER,
0
};
extern "C" void _imp_getProcessLocale( rtl_Locale ** );
extern "C" int _imp_setProcessLocale( rtl_Locale * );
/**********************************************
osl_getProcessLocale().
*********************************************/
oslProcessError SAL_CALL osl_getProcessLocale( rtl_Locale ** ppLocale )
{
OSL_PRECOND(ppLocale, "osl_getProcessLocale(): Invalid parameter.");
pthread_mutex_lock(&(g_process_locale.m_mutex));
if (g_process_locale.m_pLocale == 0)
_imp_getProcessLocale (&(g_process_locale.m_pLocale));
*ppLocale = g_process_locale.m_pLocale;
pthread_mutex_unlock (&(g_process_locale.m_mutex));
return (osl_Process_E_None);
}
/**********************************************
osl_setProcessLocale().
*********************************************/
oslProcessError SAL_CALL osl_setProcessLocale( rtl_Locale * pLocale )
{
oslProcessError result = osl_Process_E_Unknown;
OSL_PRECOND(pLocale, "osl_setProcessLocale(): Invalid parameter.");
pthread_mutex_lock(&(g_process_locale.m_mutex));
if (_imp_setProcessLocale (pLocale) == 0)
{
g_process_locale.m_pLocale = pLocale;
result = osl_Process_E_None;
}
pthread_mutex_unlock (&(g_process_locale.m_mutex));
return (result);
}
<commit_msg>INTEGRATION: CWS macosxgcc4 (1.8.64); FILE MERGED 2005/09/20 03:34:38 fheckl 1.8.64.2: RESYNC: (1.8-1.9); FILE MERGED 2005/09/19 19:39:21 fheckl 1.8.64.1: Adding some casts necessary for compilation to succeed with gcc4 on MacOSX (i49046)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: process_impl.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-10-17 14:25:34 $
*
* 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 "osl/process.h"
#ifndef INCLUDED_LIMITS_H
#include <limits.h>
#define INCLUDED_LIMITS_H
#endif
#ifndef INCLUDED_PTHREAD_H
#include <pthread.h>
#define INCLUDED_PTHREAD_H
#endif
#ifndef INCLUDED_STDLIB_H
#include <stdlib.h>
#define INCLUDED_STDLIB_H
#endif
#ifndef INCLUDED_STRING_H
#include <string.h>
#define INCLUDED_STRING_H
#endif
#ifndef _OSL_DIAGNOSE_H_
#include "osl/diagnose.h"
#endif
#ifndef _OSL_FILE_H_
#include <osl/file.h>
#endif
#ifndef _OSL_MODULE_H_
#include "osl/module.h"
#endif
#ifndef _OSL_THREAD_H_
#include "osl/thread.h"
#endif
#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif
#ifndef _OSL_FILE_PATH_HELPER_H_
#include "file_path_helper.h"
#endif
#ifndef _OSL_UUNXAPI_H_
#include "uunxapi.h"
#endif
/***************************************
osl_bootstrap_getExecutableFile_Impl().
@internal
@see rtl_bootstrap
@see #i37371#
**************************************/
extern "C" oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C();
#if defined(MACOSX)
#include <mach-o/dyld.h>
oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C()
{
oslProcessError result = osl_Process_E_NotFound;
char buffer[PATH_MAX];
size_t buflen = sizeof(buffer);
#if __GNUC__ >= 4 && defined(MACOSX)
if (_NSGetExecutablePath (buffer, (uint32_t*)&buflen) == 0)
#else
if (_NSGetExecutablePath (buffer, &buflen) == 0)
#endif
{
/* Determine absolute path. */
char abspath[PATH_MAX];
if (realpath (buffer, abspath) != 0)
{
/* Convert from utf8 to unicode. */
rtl_uString * pAbsPath = 0;
rtl_string2UString (
&(pAbsPath),
abspath, rtl_str_getLength (abspath),
RTL_TEXTENCODING_UTF8,
OSTRING_TO_OUSTRING_CVTFLAGS);
if (pAbsPath)
{
/* Convert from path to url. */
if (osl_getFileURLFromSystemPath (pAbsPath, ppFileURL) == osl_File_E_None)
{
/* Success. */
result = osl_Process_E_None;
}
rtl_uString_release (pAbsPath);
}
}
}
return (result);
}
#elif !defined(NO_DL_FUNCTIONS)
#include <dlfcn.h>
oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C()
{
oslProcessError result = osl_Process_E_NotFound;
/* Determine address of "main()" function. */
void * addr = dlsym (RTLD_DEFAULT, "main");
if (addr != 0)
{
/* Determine module URL. */
if (osl_getModuleURLFromAddress (addr, ppFileURL))
{
/* Success. */
result = osl_Process_E_None;
}
}
return (result);
}
#else /* NO_DL_FUNCTIONS */
oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (
rtl_uString ** ppFileURL
) SAL_THROW_EXTERN_C()
{
/* Fallback to ordinary osl_getExecutableFile(). */
return osl_getExecutableFile (ppFileURL);
}
#endif /* NO_DL_FUNCTIONS */
/***************************************
CommandArgs_Impl.
**************************************/
struct CommandArgs_Impl
{
pthread_mutex_t m_mutex;
sal_uInt32 m_nCount;
rtl_uString ** m_ppArgs;
};
static struct CommandArgs_Impl g_command_args =
{
PTHREAD_MUTEX_INITIALIZER,
0,
0
};
/***************************************
osl_getExecutableFile().
**************************************/
oslProcessError SAL_CALL osl_getExecutableFile (rtl_uString ** ppustrFile)
{
oslProcessError result = osl_Process_E_NotFound;
pthread_mutex_lock (&(g_command_args.m_mutex));
if (g_command_args.m_nCount > 0)
{
/* CommandArgs set. Obtain argv[0]. */
rtl_uString_assign (ppustrFile, g_command_args.m_ppArgs[0]);
result = osl_Process_E_None;
}
pthread_mutex_unlock (&(g_command_args.m_mutex));
return (result);
}
/***************************************
osl_getCommandArgCount().
**************************************/
sal_uInt32 SAL_CALL osl_getCommandArgCount (void)
{
sal_uInt32 result = 0;
pthread_mutex_lock (&(g_command_args.m_mutex));
if (g_command_args.m_nCount > 0)
result = g_command_args.m_nCount - 1;
pthread_mutex_unlock (&(g_command_args.m_mutex));
return (result);
}
/***************************************
osl_getCommandArg().
**************************************/
oslProcessError SAL_CALL osl_getCommandArg (sal_uInt32 nArg, rtl_uString ** strCommandArg)
{
oslProcessError result = osl_Process_E_NotFound;
pthread_mutex_lock (&(g_command_args.m_mutex));
if (g_command_args.m_nCount > (nArg + 1))
{
rtl_uString_assign (strCommandArg, g_command_args.m_ppArgs[nArg + 1]);
result = osl_Process_E_None;
}
pthread_mutex_unlock (&(g_command_args.m_mutex));
return (result);
}
/***************************************
osl_setCommandArgs().
**************************************/
void SAL_CALL osl_setCommandArgs (int argc, char ** argv)
{
pthread_mutex_lock (&(g_command_args.m_mutex));
OSL_ENSURE (g_command_args.m_nCount == 0, "osl_setCommandArgs(): CommandArgs already set.");
if (g_command_args.m_nCount == 0)
{
rtl_uString** ppArgs = (rtl_uString**)rtl_allocateZeroMemory (argc * sizeof(rtl_uString*));
if (ppArgs != 0)
{
rtl_TextEncoding encoding = osl_getThreadTextEncoding();
for (int i = 0; i < argc; i++)
{
rtl_string2UString (
&(ppArgs[i]),
argv[i], rtl_str_getLength (argv[i]), encoding,
OSTRING_TO_OUSTRING_CVTFLAGS);
}
if (ppArgs[0] != 0)
{
/* see @ osl_getExecutableFile(). */
if (rtl_ustr_indexOfChar (rtl_uString_getStr(ppArgs[0]), sal_Unicode('/')) == -1)
{
const rtl::OUString PATH (RTL_CONSTASCII_USTRINGPARAM("PATH"));
rtl_uString * pSearchPath = 0;
osl_getEnvironment (PATH.pData, &pSearchPath);
if (pSearchPath)
{
rtl_uString * pSearchResult = 0;
osl_searchPath (ppArgs[0], pSearchPath, &pSearchResult);
if (pSearchResult)
{
rtl_uString_assign (&(ppArgs[0]), pSearchResult);
rtl_uString_release (pSearchResult);
}
rtl_uString_release (pSearchPath);
}
}
rtl_uString * pArg0 = 0;
if (realpath_u (ppArgs[0], &pArg0))
{
osl_getFileURLFromSystemPath (pArg0, &(ppArgs[0]));
rtl_uString_release (pArg0);
}
}
g_command_args.m_nCount = argc;
g_command_args.m_ppArgs = ppArgs;
}
}
pthread_mutex_unlock (&(g_command_args.m_mutex));
}
/***************************************
osl_getEnvironment().
**************************************/
oslProcessError SAL_CALL osl_getEnvironment(rtl_uString* pustrEnvVar, rtl_uString** ppustrValue)
{
oslProcessError result = osl_Process_E_NotFound;
rtl_TextEncoding encoding = osl_getThreadTextEncoding();
rtl_String* pstr_env_var = 0;
OSL_PRECOND(pustrEnvVar, "osl_getEnvironment(): Invalid parameter");
OSL_PRECOND(ppustrValue, "osl_getEnvironment(): Invalid parameter");
rtl_uString2String(
&pstr_env_var,
rtl_uString_getStr(pustrEnvVar), rtl_uString_getLength(pustrEnvVar), encoding,
OUSTRING_TO_OSTRING_CVTFLAGS);
if (pstr_env_var != 0)
{
const char* p_env_var = getenv (rtl_string_getStr (pstr_env_var));
if (p_env_var != 0)
{
rtl_string2UString(
ppustrValue,
p_env_var, strlen(p_env_var), encoding,
OSTRING_TO_OUSTRING_CVTFLAGS);
OSL_ASSERT(*ppustrValue != NULL);
result = osl_Process_E_None;
}
rtl_string_release(pstr_env_var);
}
return (result);
}
/***************************************
osl_getProcessWorkingDir().
**************************************/
oslProcessError SAL_CALL osl_getProcessWorkingDir(rtl_uString **ppustrWorkingDir)
{
oslProcessError result = osl_Process_E_Unknown;
char buffer[PATH_MAX];
OSL_PRECOND(ppustrWorkingDir, "osl_getProcessWorkingDir(): Invalid parameter");
if (getcwd (buffer, sizeof(buffer)) != 0)
{
rtl_uString* ustrTmp = 0;
rtl_string2UString(
&ustrTmp,
buffer, strlen(buffer), osl_getThreadTextEncoding(),
OSTRING_TO_OUSTRING_CVTFLAGS);
if (ustrTmp != 0)
{
if (osl_getFileURLFromSystemPath (ustrTmp, ppustrWorkingDir) == osl_File_E_None)
result = osl_Process_E_None;
rtl_uString_release (ustrTmp);
}
}
return (result);
}
/******************************************************************************
*
* new functions to set/return the current process locale
*
*****************************************************************************/
struct ProcessLocale_Impl
{
pthread_mutex_t m_mutex;
rtl_Locale * m_pLocale;
};
static struct ProcessLocale_Impl g_process_locale =
{
PTHREAD_MUTEX_INITIALIZER,
0
};
extern "C" void _imp_getProcessLocale( rtl_Locale ** );
extern "C" int _imp_setProcessLocale( rtl_Locale * );
/**********************************************
osl_getProcessLocale().
*********************************************/
oslProcessError SAL_CALL osl_getProcessLocale( rtl_Locale ** ppLocale )
{
OSL_PRECOND(ppLocale, "osl_getProcessLocale(): Invalid parameter.");
pthread_mutex_lock(&(g_process_locale.m_mutex));
if (g_process_locale.m_pLocale == 0)
_imp_getProcessLocale (&(g_process_locale.m_pLocale));
*ppLocale = g_process_locale.m_pLocale;
pthread_mutex_unlock (&(g_process_locale.m_mutex));
return (osl_Process_E_None);
}
/**********************************************
osl_setProcessLocale().
*********************************************/
oslProcessError SAL_CALL osl_setProcessLocale( rtl_Locale * pLocale )
{
oslProcessError result = osl_Process_E_Unknown;
OSL_PRECOND(pLocale, "osl_setProcessLocale(): Invalid parameter.");
pthread_mutex_lock(&(g_process_locale.m_mutex));
if (_imp_setProcessLocale (pLocale) == 0)
{
g_process_locale.m_pLocale = pLocale;
result = osl_Process_E_None;
}
pthread_mutex_unlock (&(g_process_locale.m_mutex));
return (result);
}
<|endoftext|>
|
<commit_before>#include "folder.h"
#include "exception.h"
#include "fileops.h"
#include "types.h"
#include <iterator>
namespace IO {
bool Folder::Path(const std::string& path) {
std::lock_guard<std::mutex> l(m_mxCall);
if (!IO::DoPathExist(path)) {
return false;
}
m_path = path;
return true;
}
std::string Folder::Path() const {
std::lock_guard<std::mutex> l(m_mxCall);
return m_path;
}
FileList Folder::CurrentContents() const {
auto iter = CreateIterator();
FileList files;
for (auto x = iter; x != boost::filesystem::directory_iterator(); x++) {
FolderEntry toRet;
if (boost::filesystem::is_directory(*x)) {
toRet.Type = TypeFolder;
}
if (boost::filesystem::is_regular_file(*x)) {
toRet.Type = TypeFile;
}
toRet.Name = x->path().filename().string();
files.push_back(toRet);
}
return files;
}
boost::filesystem::directory_iterator Folder::CreateIterator() const {
std::lock_guard<std::mutex> l(m_mxCall);
return boost::filesystem::directory_iterator(m_path);
}
}
<commit_msg>Avoid terminating if Pictus fails to iterate all files/subfolders<commit_after>#include "folder.h"
#include "exception.h"
#include "fileops.h"
#include "types.h"
#include <iterator>
namespace IO {
bool Folder::Path(const std::string& path) {
std::lock_guard<std::mutex> l(m_mxCall);
if (!IO::DoPathExist(path)) {
return false;
}
m_path = path;
return true;
}
std::string Folder::Path() const {
std::lock_guard<std::mutex> l(m_mxCall);
return m_path;
}
FileList Folder::CurrentContents() const {
auto iter = CreateIterator();
FileList files;
for (auto x = iter; x != boost::filesystem::directory_iterator(); x++) {
try
{
FolderEntry toRet;
if (boost::filesystem::is_directory(*x)) {
toRet.Type = TypeFolder;
}
if (boost::filesystem::is_regular_file(*x)) {
toRet.Type = TypeFile;
}
toRet.Name = x->path().filename().string();
files.push_back(toRet);
}
catch (boost::filesystem::filesystem_error& err)
{
// Boost can throw exceptions in is_directory and probably is_regular_file for various reasons that are
// entirely uninteresting to us. Try to do the best of the situation and ignore files/folders that
// are causing issues.
}
}
return files;
}
boost::filesystem::directory_iterator Folder::CreateIterator() const {
std::lock_guard<std::mutex> l(m_mxCall);
return boost::filesystem::directory_iterator(m_path);
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 "results.hpp"
#include <stdexcept>
using namespace realm;
#ifdef __has_cpp_attribute
#define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr)
#else
#define REALM_HAS_CCP_ATTRIBUTE(attr) 0
#endif
#if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough)
#define REALM_FALLTHROUGH [[clang::fallthrough]]
#else
#define REALM_FALLTHROUGH
#endif
Results::Results(SharedRealm r, Query q, SortOrder s)
: m_realm(std::move(r))
, m_query(std::move(q))
, m_table(m_query.get_table().get())
, m_sort(std::move(s))
, m_mode(Mode::Query)
{
}
Results::Results(SharedRealm r, Table& table)
: m_realm(std::move(r))
, m_table(&table)
, m_mode(Mode::Table)
{
}
void Results::validate_read() const
{
if (m_realm)
m_realm->verify_thread();
if (m_table && !m_table->is_attached())
throw InvalidatedException();
}
void Results::validate_write() const
{
validate_read();
if (!m_realm || !m_realm->is_in_transaction())
throw InvalidTransactionException("Must be in a write transaction");
}
size_t Results::size()
{
validate_read();
switch (m_mode) {
case Mode::Empty: return 0;
case Mode::Table: return m_table->size();
case Mode::Query: return m_query.count();
case Mode::TableView:
update_tableview();
return m_table_view.size();
}
REALM_UNREACHABLE();
}
RowExpr Results::get(size_t row_ndx)
{
validate_read();
switch (m_mode) {
case Mode::Empty: break;
case Mode::Table:
if (row_ndx < m_table->size())
return m_table->get(row_ndx);
break;
case Mode::Query:
case Mode::TableView:
update_tableview();
if (row_ndx < m_table_view.size())
return m_table_view.get(row_ndx);
break;
}
throw OutOfBoundsIndexException{row_ndx, size()};
}
util::Optional<RowExpr> Results::first()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return none;
case Mode::Table:
return m_table->size() == 0 ? util::none : util::make_optional(m_table->front());
case Mode::Query:
update_tableview();
REALM_FALLTHROUGH;
case Mode::TableView:
return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.front());
}
REALM_UNREACHABLE();
}
util::Optional<RowExpr> Results::last()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return none;
case Mode::Table:
return m_table->size() == 0 ? util::none : util::make_optional(m_table->back());
case Mode::Query:
update_tableview();
REALM_FALLTHROUGH;
case Mode::TableView:
return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.back());
}
REALM_UNREACHABLE();
}
void Results::update_tableview()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
case Mode::Table:
return;
case Mode::Query:
m_table_view = m_query.find_all();
if (m_sort) {
m_table_view.sort(m_sort.columnIndices, m_sort.ascending);
}
m_mode = Mode::TableView;
break;
case Mode::TableView:
m_table_view.sync_if_needed();
break;
}
}
size_t Results::index_of(Row const& row)
{
validate_read();
if (!row) {
throw DetatchedAccessorException{};
}
if (m_table && row.get_table() != m_table) {
throw IncorrectTableException{
ObjectStore::object_type_for_table_name(m_table->get_name()),
ObjectStore::object_type_for_table_name(row.get_table()->get_name())};
}
return index_of(row.get_index());
}
size_t Results::index_of(size_t row_ndx)
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return not_found;
case Mode::Table:
return row_ndx;
case Mode::Query:
if (!m_sort)
return m_query.count(row_ndx, row_ndx + 1) ? m_query.count(0, row_ndx) : not_found;
REALM_FALLTHROUGH;
case Mode::TableView:
update_tableview();
return m_table_view.find_by_source_ndx(row_ndx);
}
REALM_UNREACHABLE();
}
template<typename Int, typename Float, typename Double, typename DateTime>
util::Optional<Mixed> Results::aggregate(size_t column, bool return_none_for_empty,
Int agg_int, Float agg_float,
Double agg_double, DateTime agg_datetime)
{
validate_read();
if (!m_table)
return none;
if (column > m_table->get_column_count())
throw OutOfBoundsIndexException{column, m_table->get_column_count()};
auto do_agg = [&](auto const& getter) -> util::Optional<Mixed> {
switch (m_mode) {
case Mode::Empty:
return none;
case Mode::Table:
if (return_none_for_empty && m_table->size() == 0)
return none;
return util::Optional<Mixed>(getter(*m_table));
case Mode::Query:
case Mode::TableView:
this->update_tableview();
if (return_none_for_empty && m_table_view.size() == 0)
return none;
return util::Optional<Mixed>(getter(m_table_view));
}
REALM_UNREACHABLE();
};
switch (m_table->get_column_type(column))
{
case type_DateTime: return do_agg(agg_datetime);
case type_Double: return do_agg(agg_double);
case type_Float: return do_agg(agg_float);
case type_Int: return do_agg(agg_int);
default:
throw UnsupportedColumnTypeException{column, m_table};
}
}
util::Optional<Mixed> Results::max(size_t column)
{
return aggregate(column, true,
[=](auto const& table) { return table.maximum_int(column); },
[=](auto const& table) { return table.maximum_float(column); },
[=](auto const& table) { return table.maximum_double(column); },
[=](auto const& table) { return table.maximum_datetime(column); });
}
util::Optional<Mixed> Results::min(size_t column)
{
return aggregate(column, true,
[=](auto const& table) { return table.minimum_int(column); },
[=](auto const& table) { return table.minimum_float(column); },
[=](auto const& table) { return table.minimum_double(column); },
[=](auto const& table) { return table.minimum_datetime(column); });
}
util::Optional<Mixed> Results::sum(size_t column)
{
return aggregate(column, false,
[=](auto const& table) { return table.sum_int(column); },
[=](auto const& table) { return table.sum_float(column); },
[=](auto const& table) { return table.sum_double(column); },
[=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });
}
util::Optional<Mixed> Results::average(size_t column)
{
return aggregate(column, true,
[=](auto const& table) { return table.average_int(column); },
[=](auto const& table) { return table.average_float(column); },
[=](auto const& table) { return table.average_double(column); },
[=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });
}
void Results::clear()
{
switch (m_mode) {
case Mode::Empty:
return;
case Mode::Table:
validate_write();
m_table->clear();
break;
case Mode::Query:
// Not using Query:remove() because building the tableview and
// clearing it is actually significantly faster
case Mode::TableView:
validate_write();
update_tableview();
m_table_view.clear();
break;
}
}
Query Results::get_query() const
{
validate_read();
switch (m_mode) {
case Mode::Empty:
case Mode::Query:
case Mode::TableView:
return m_query;
case Mode::Table:
return m_table->where();
}
REALM_UNREACHABLE();
}
TableView Results::get_tableview()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return {};
case Mode::Query:
case Mode::TableView:
update_tableview();
return m_table_view;
case Mode::Table:
return m_table->where().find_all();
}
REALM_UNREACHABLE();
}
StringData Results::get_object_type() const noexcept
{
return ObjectStore::object_type_for_table_name(m_table->get_name());
}
Results Results::sort(realm::SortOrder&& sort) const
{
return Results(m_realm, get_query(), std::move(sort));
}
Results Results::filter(Query&& q) const
{
return Results(m_realm, get_query().and_query(std::move(q)), get_sort());
}
Results::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table) {
column_index = column;
column_name = table->get_column_name(column);
column_type = table->get_column_type(column);
}
<commit_msg>Update existing TableViews in first() and last()<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 "results.hpp"
#include <stdexcept>
using namespace realm;
#ifdef __has_cpp_attribute
#define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr)
#else
#define REALM_HAS_CCP_ATTRIBUTE(attr) 0
#endif
#if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough)
#define REALM_FALLTHROUGH [[clang::fallthrough]]
#else
#define REALM_FALLTHROUGH
#endif
Results::Results(SharedRealm r, Query q, SortOrder s)
: m_realm(std::move(r))
, m_query(std::move(q))
, m_table(m_query.get_table().get())
, m_sort(std::move(s))
, m_mode(Mode::Query)
{
}
Results::Results(SharedRealm r, Table& table)
: m_realm(std::move(r))
, m_table(&table)
, m_mode(Mode::Table)
{
}
void Results::validate_read() const
{
if (m_realm)
m_realm->verify_thread();
if (m_table && !m_table->is_attached())
throw InvalidatedException();
}
void Results::validate_write() const
{
validate_read();
if (!m_realm || !m_realm->is_in_transaction())
throw InvalidTransactionException("Must be in a write transaction");
}
size_t Results::size()
{
validate_read();
switch (m_mode) {
case Mode::Empty: return 0;
case Mode::Table: return m_table->size();
case Mode::Query: return m_query.count();
case Mode::TableView:
update_tableview();
return m_table_view.size();
}
REALM_UNREACHABLE();
}
RowExpr Results::get(size_t row_ndx)
{
validate_read();
switch (m_mode) {
case Mode::Empty: break;
case Mode::Table:
if (row_ndx < m_table->size())
return m_table->get(row_ndx);
break;
case Mode::Query:
case Mode::TableView:
update_tableview();
if (row_ndx < m_table_view.size())
return m_table_view.get(row_ndx);
break;
}
throw OutOfBoundsIndexException{row_ndx, size()};
}
util::Optional<RowExpr> Results::first()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return none;
case Mode::Table:
return m_table->size() == 0 ? util::none : util::make_optional(m_table->front());
case Mode::Query:
case Mode::TableView:
update_tableview();
return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.front());
}
REALM_UNREACHABLE();
}
util::Optional<RowExpr> Results::last()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return none;
case Mode::Table:
return m_table->size() == 0 ? util::none : util::make_optional(m_table->back());
case Mode::Query:
case Mode::TableView:
update_tableview();
return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.back());
}
REALM_UNREACHABLE();
}
void Results::update_tableview()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
case Mode::Table:
return;
case Mode::Query:
m_table_view = m_query.find_all();
if (m_sort) {
m_table_view.sort(m_sort.columnIndices, m_sort.ascending);
}
m_mode = Mode::TableView;
break;
case Mode::TableView:
m_table_view.sync_if_needed();
break;
}
}
size_t Results::index_of(Row const& row)
{
validate_read();
if (!row) {
throw DetatchedAccessorException{};
}
if (m_table && row.get_table() != m_table) {
throw IncorrectTableException{
ObjectStore::object_type_for_table_name(m_table->get_name()),
ObjectStore::object_type_for_table_name(row.get_table()->get_name())};
}
return index_of(row.get_index());
}
size_t Results::index_of(size_t row_ndx)
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return not_found;
case Mode::Table:
return row_ndx;
case Mode::Query:
if (!m_sort)
return m_query.count(row_ndx, row_ndx + 1) ? m_query.count(0, row_ndx) : not_found;
REALM_FALLTHROUGH;
case Mode::TableView:
update_tableview();
return m_table_view.find_by_source_ndx(row_ndx);
}
REALM_UNREACHABLE();
}
template<typename Int, typename Float, typename Double, typename DateTime>
util::Optional<Mixed> Results::aggregate(size_t column, bool return_none_for_empty,
Int agg_int, Float agg_float,
Double agg_double, DateTime agg_datetime)
{
validate_read();
if (!m_table)
return none;
if (column > m_table->get_column_count())
throw OutOfBoundsIndexException{column, m_table->get_column_count()};
auto do_agg = [&](auto const& getter) -> util::Optional<Mixed> {
switch (m_mode) {
case Mode::Empty:
return none;
case Mode::Table:
if (return_none_for_empty && m_table->size() == 0)
return none;
return util::Optional<Mixed>(getter(*m_table));
case Mode::Query:
case Mode::TableView:
this->update_tableview();
if (return_none_for_empty && m_table_view.size() == 0)
return none;
return util::Optional<Mixed>(getter(m_table_view));
}
REALM_UNREACHABLE();
};
switch (m_table->get_column_type(column))
{
case type_DateTime: return do_agg(agg_datetime);
case type_Double: return do_agg(agg_double);
case type_Float: return do_agg(agg_float);
case type_Int: return do_agg(agg_int);
default:
throw UnsupportedColumnTypeException{column, m_table};
}
}
util::Optional<Mixed> Results::max(size_t column)
{
return aggregate(column, true,
[=](auto const& table) { return table.maximum_int(column); },
[=](auto const& table) { return table.maximum_float(column); },
[=](auto const& table) { return table.maximum_double(column); },
[=](auto const& table) { return table.maximum_datetime(column); });
}
util::Optional<Mixed> Results::min(size_t column)
{
return aggregate(column, true,
[=](auto const& table) { return table.minimum_int(column); },
[=](auto const& table) { return table.minimum_float(column); },
[=](auto const& table) { return table.minimum_double(column); },
[=](auto const& table) { return table.minimum_datetime(column); });
}
util::Optional<Mixed> Results::sum(size_t column)
{
return aggregate(column, false,
[=](auto const& table) { return table.sum_int(column); },
[=](auto const& table) { return table.sum_float(column); },
[=](auto const& table) { return table.sum_double(column); },
[=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });
}
util::Optional<Mixed> Results::average(size_t column)
{
return aggregate(column, true,
[=](auto const& table) { return table.average_int(column); },
[=](auto const& table) { return table.average_float(column); },
[=](auto const& table) { return table.average_double(column); },
[=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });
}
void Results::clear()
{
switch (m_mode) {
case Mode::Empty:
return;
case Mode::Table:
validate_write();
m_table->clear();
break;
case Mode::Query:
// Not using Query:remove() because building the tableview and
// clearing it is actually significantly faster
case Mode::TableView:
validate_write();
update_tableview();
m_table_view.clear();
break;
}
}
Query Results::get_query() const
{
validate_read();
switch (m_mode) {
case Mode::Empty:
case Mode::Query:
case Mode::TableView:
return m_query;
case Mode::Table:
return m_table->where();
}
REALM_UNREACHABLE();
}
TableView Results::get_tableview()
{
validate_read();
switch (m_mode) {
case Mode::Empty:
return {};
case Mode::Query:
case Mode::TableView:
update_tableview();
return m_table_view;
case Mode::Table:
return m_table->where().find_all();
}
REALM_UNREACHABLE();
}
StringData Results::get_object_type() const noexcept
{
return ObjectStore::object_type_for_table_name(m_table->get_name());
}
Results Results::sort(realm::SortOrder&& sort) const
{
return Results(m_realm, get_query(), std::move(sort));
}
Results Results::filter(Query&& q) const
{
return Results(m_realm, get_query().and_query(std::move(q)), get_sort());
}
Results::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table) {
column_index = column;
column_name = table->get_column_name(column);
column_type = table->get_column_type(column);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
// void rowSum(int a[][4],int nRow){
// for(int i=0;i<nRow;i++){
// for(int j=0;j<4;j++){
// a[i][0] = a[i][j];
// }
// }
// }
// void splitFloat(float x,int *intPart, float *fracPart){
// *intPart = static_cast<int>(x);
// *fracPart = x - *intPart;
// }
// int* search(int* a, int num){
// for(int i=0;i<num;i++){
// if(a[i] == 0){
// return &a[i];
// }
// }
// }
// int compute(int a, int b,int(*func)(int,int)){
// return func(a,b);
// }
// int max(int a, int b){
// return((a>b)?a:b);
// }
// int min(int a, int b){
// return((a<b)?a:b);
// }
// int sum(int a, int b){
// return a+b;
// }
// class Point {
// public:
// Point(int x = 0, int y = 0) : x(x), y(y) { }
// int getX() const { return x; }
// int getY() const { return y; }
// private:
// int x, y;
// };
// double average(const vector<double> &arr){
// double sum = 0;
// for(unsigned i=0;i<arr.size();i++){
// sum += arr[i];
// }
// return sum/arr.size();
// }
class Base1{
public:
void display() const{
cout<<"Base1::display()"<<endl;
}
};
class Base2: public Base1{
public:
void display() const{
cout<<"Base2::display()"<<endl;
}
};
class Derived: public Base2{
public:
void display() const{
cout<<"Derived::display()"<<endl;
}
};
void func(Base1 *ptr){
ptr->display();
}
int main(){
Base1 base1;
Base2 base2;
Derived derived;
func(&base1);
func(&base2);
func(&derived);
// unsigned n;
// cout<<"n = ";
// cin>>n;
// vector<double> arr(n);
// cout<<"Please input "<<n<<" real numbers: "<<endl;
// for(int i=0;i<n;i++)
// cin>>arr[i];
// cout<<"Average = "<<average(arr)<<endl;
// int (*fp)[9][8] = new int[7][9][8];
// for (int i = 0; i < 7; i++)
// for (int j = 0; j < 9; j++)
// for (int k = 0; k < 8; k++)
// *(*(*(fp + i) + j) + k) = (i*100+j*10+k);
// for (int i = 0; i < 7; i++) {
// for (int j = 0; j < 9; j++) {
// for (int k = 0; k < 8; k++)
// cout<<fp[i][j][k]<<' ';
// cout<<endl;
// }
// cout<<endl;
// }
// delete[] fp;
// Point a(4,5);
// Point *ptr = &a;
// cout<<ptr->getX()<<endl;
// cout<<a.getX()<<endl;
// int a,b,res;
// cout<<"Please enter a: "; cin>>a;
// cout<<"Please enter b: "; cin>>b;
// res = compute(a,b,&max);
// cout<<"max of a and b is "<<res<<endl;
// res = compute(a,b,&min);
// cout<<"min of a and b is "<<res<<endl;
// res = compute(a,b,&sum);
// cout<<"sum of a and b is "<<res<<endl;
// int array[10];
// int* search(int* a, int num);
// for(int i=0;i<10;i++){
// cin>>array[i];
// }
// int* zeroptr = search(array, 10);
// cout<<"Enter 3 float point numbers: "<<endl;
// for(int i=0;i<3;i++){
// float x, f;
// int n;
// cin>>x;
// splitFloat(x, &n, &f);
// cout<<"Integer part: "<<n<<" Fraction part: "<<f<<endl;
// }
// int line1[] = {1,2,3};
// int line2[] = {4,5,6};
// int line3[] = {7,8,9};
// int *pline[] = {line1,line2,line3};
// cout<<"Matrix test: "<<endl;
// for(int i=0;i<3;i++){
// for(int j=0;j<3;j++){
// cout<<pline[i][j]<<",";
// }
// cout<<endl;
// }
// int array[3] = {1,2,3};
// for(int &e:array){
// e += 2;
// cout<<e<<endl;
// }
// int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 4; j++)
// cout << table[i][j] << " ";
// cout << endl;
// }
// rowSum(table, 3);
// for(int i=0;i<3;i++){
// cout << "Sum of row " << i << " is " << table[i][0] << endl;
// }
// const char key[] = {'a','c','b','a','d'};
// const int ques_num = 5;
// char usr_input;
// int ques = 0, correct_num = 0;
// cout<<"Enter the "<<ques_num<<" question tests:"<<endl;
// while(cin.get(usr_input)){
// if(usr_input != '\n'){
// if(usr_input == key[ques]){
// correct_num++;
// cout<<" ";
// }
// else{
// cout<<"*";
// }
// ques++;
// }
// else{
// cout<<"Score: "<<static_cast<float>(correct_num)/ques_num*100<<"%";
// ques = 0; correct_num = 0;cout<<endl;
// }
// }
// int f[20] = {1,1};
// for (int i=2;i<20;i++){
// f[i] = f[i-1] + f[i-2];
// }
// for (int i=0;i<20;i++){
// if(i%4 == 0)cout<<endl;
// cout.width(5);
// cout<<f[i];
// }
// cout<<endl;
// int a[10], b[10];
// for(int i = 0; i < 10; i++) {
// a[i] = i * 2 - 1;
// b[10 - i - 1] = a[i];
// }
// for(int i = 0; i < 10; i++) {
// cout << "a[" << i << "] = " << a[i] << " ";
// cout << "b[" << i << "] = " << b[i] << endl;
// }
return 0;
}
<commit_msg>to be added.<commit_after>#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
// void rowSum(int a[][4],int nRow){
// for(int i=0;i<nRow;i++){
// for(int j=0;j<4;j++){
// a[i][0] = a[i][j];
// }
// }
// }
// void splitFloat(float x,int *intPart, float *fracPart){
// *intPart = static_cast<int>(x);
// *fracPart = x - *intPart;
// }
// int* search(int* a, int num){
// for(int i=0;i<num;i++){
// if(a[i] == 0){
// return &a[i];
// }
// }
// }
// int compute(int a, int b,int(*func)(int,int)){
// return func(a,b);
// }
// int max(int a, int b){
// return((a>b)?a:b);
// }
// int min(int a, int b){
// return((a<b)?a:b);
// }
// int sum(int a, int b){
// return a+b;
// }
// class Point {
// public:
// Point(int x = 0, int y = 0) : x(x), y(y) { }
// int getX() const { return x; }
// int getY() const { return y; }
// private:
// int x, y;
// };
// double average(const vector<double> &arr){
// double sum = 0;
// for(unsigned i=0;i<arr.size();i++){
// sum += arr[i];
// }
// return sum/arr.size();
// }
// class Base1{
// public:
// void display() const{
// cout<<"Base1::display()"<<endl;
// }
// };
// class Base2: public Base1{
// public:
// void display() const{
// cout<<"Base2::display()"<<endl;
// }
// };
// class Derived: public Base2{
// public:
// void display() const{
// cout<<"Derived::display()"<<endl;
// }
// };
// void func(Base1 *ptr){
// ptr->display();
// }
int main(){
// Base1 base1;
// Base2 base2;
// Derived derived;
// func(&base1);
// func(&base2);
// func(&derived);
// unsigned n;
// cout<<"n = ";
// cin>>n;
// vector<double> arr(n);
// cout<<"Please input "<<n<<" real numbers: "<<endl;
// for(int i=0;i<n;i++)
// cin>>arr[i];
// cout<<"Average = "<<average(arr)<<endl;
// int (*fp)[9][8] = new int[7][9][8];
// for (int i = 0; i < 7; i++)
// for (int j = 0; j < 9; j++)
// for (int k = 0; k < 8; k++)
// *(*(*(fp + i) + j) + k) = (i*100+j*10+k);
// for (int i = 0; i < 7; i++) {
// for (int j = 0; j < 9; j++) {
// for (int k = 0; k < 8; k++)
// cout<<fp[i][j][k]<<' ';
// cout<<endl;
// }
// cout<<endl;
// }
// delete[] fp;
// Point a(4,5);
// Point *ptr = &a;
// cout<<ptr->getX()<<endl;
// cout<<a.getX()<<endl;
// int a,b,res;
// cout<<"Please enter a: "; cin>>a;
// cout<<"Please enter b: "; cin>>b;
// res = compute(a,b,&max);
// cout<<"max of a and b is "<<res<<endl;
// res = compute(a,b,&min);
// cout<<"min of a and b is "<<res<<endl;
// res = compute(a,b,&sum);
// cout<<"sum of a and b is "<<res<<endl;
// int array[10];
// int* search(int* a, int num);
// for(int i=0;i<10;i++){
// cin>>array[i];
// }
// int* zeroptr = search(array, 10);
// cout<<"Enter 3 float point numbers: "<<endl;
// for(int i=0;i<3;i++){
// float x, f;
// int n;
// cin>>x;
// splitFloat(x, &n, &f);
// cout<<"Integer part: "<<n<<" Fraction part: "<<f<<endl;
// }
// int line1[] = {1,2,3};
// int line2[] = {4,5,6};
// int line3[] = {7,8,9};
// int *pline[] = {line1,line2,line3};
// cout<<"Matrix test: "<<endl;
// for(int i=0;i<3;i++){
// for(int j=0;j<3;j++){
// cout<<pline[i][j]<<",";
// }
// cout<<endl;
// }
// int array[3] = {1,2,3};
// for(int &e:array){
// e += 2;
// cout<<e<<endl;
// }
// int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};
// for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 4; j++)
// cout << table[i][j] << " ";
// cout << endl;
// }
// rowSum(table, 3);
// for(int i=0;i<3;i++){
// cout << "Sum of row " << i << " is " << table[i][0] << endl;
// }
// const char key[] = {'a','c','b','a','d'};
// const int ques_num = 5;
// char usr_input;
// int ques = 0, correct_num = 0;
// cout<<"Enter the "<<ques_num<<" question tests:"<<endl;
// while(cin.get(usr_input)){
// if(usr_input != '\n'){
// if(usr_input == key[ques]){
// correct_num++;
// cout<<" ";
// }
// else{
// cout<<"*";
// }
// ques++;
// }
// else{
// cout<<"Score: "<<static_cast<float>(correct_num)/ques_num*100<<"%";
// ques = 0; correct_num = 0;cout<<endl;
// }
// }
// int f[20] = {1,1};
// for (int i=2;i<20;i++){
// f[i] = f[i-1] + f[i-2];
// }
// for (int i=0;i<20;i++){
// if(i%4 == 0)cout<<endl;
// cout.width(5);
// cout<<f[i];
// }
// cout<<endl;
// int a[10], b[10];
// for(int i = 0; i < 10; i++) {
// a[i] = i * 2 - 1;
// b[10 - i - 1] = a[i];
// }
// for(int i = 0; i < 10; i++) {
// cout << "a[" << i << "] = " << a[i] << " ";
// cout << "b[" << i << "] = " << b[i] << endl;
// }
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docfunc.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:21:03 $
*
* 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 SC_DOCFUNC_HXX
#define SC_DOCFUNC_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_POSTIT_HXX
#include "postit.hxx"
#endif
class ScEditEngineDefaulter;
class SfxUndoAction;
class ScAddress;
class ScDocShell;
class ScMarkData;
class ScPatternAttr;
class ScRange;
class ScRangeName;
class ScBaseCell;
struct ScTabOpParam;
// ---------------------------------------------------------------------------
class ScDocFunc
{
private:
ScDocShell& rDocShell;
BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE );
void CreateOneName( ScRangeName& rList,
SCCOL nPosX, SCROW nPosY, SCTAB nTab,
SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL& rCancel, BOOL bApi );
void NotifyInputHandler( const ScAddress& rPos );
public:
ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {}
~ScDocFunc() {}
DECL_LINK( NotifyDrawUndo, SfxUndoAction* );
BOOL DetectiveAddPred(const ScAddress& rPos);
BOOL DetectiveDelPred(const ScAddress& rPos);
BOOL DetectiveAddSucc(const ScAddress& rPos);
BOOL DetectiveDelSucc(const ScAddress& rPos);
BOOL DetectiveAddError(const ScAddress& rPos);
BOOL DetectiveMarkInvalid(SCTAB nTab);
BOOL DetectiveDelAll(SCTAB nTab);
BOOL DetectiveRefresh(BOOL bAutomatic = FALSE);
BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags,
BOOL bRecord, BOOL bApi );
BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType,
BOOL bRecord, BOOL bApi );
BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi );
BOOL PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine,
BOOL bInterpret, BOOL bApi );
BOOL SetCellText( const ScAddress& rPos, const String& rText,
BOOL bInterpret, BOOL bEnglish, BOOL bApi );
// creates a new cell for use with PutCell
ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText );
BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,
BOOL bRecord, BOOL bApi );
BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName,
BOOL bRecord, BOOL bApi );
BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi,
BOOL bPartOfPaste = FALSE );
BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi );
BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,
BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi );
BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi );
BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi );
BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi );
BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges,
SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips,
BOOL bRecord, BOOL bApi );
BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi );
BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi );
BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,
USHORT nFormatNo, BOOL bRecord, BOOL bApi );
BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,
const String& rString, BOOL bApi, BOOL bEnglish );
BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark,
const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi );
BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, BOOL bRecord, BOOL bApi );
BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,
double fStart, double fStep, double fMax,
BOOL bRecord, BOOL bApi );
// FillAuto: rRange wird von Source-Range auf Dest-Range angepasst
BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi );
BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi );
BOOL MergeCells( const ScRange& rRange, BOOL bContents,
BOOL bRecord, BOOL bApi );
BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi );
BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi );
BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi );
BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi );
BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi );
BOOL InsertAreaLink( const String& rFile, const String& rFilter,
const String& rOptions, const String& rSource,
const ScRange& rDestRange, ULONG nRefresh,
BOOL bFitBlock, BOOL bApi );
};
#endif
<commit_msg>INTEGRATION: CWS calc36 (1.12.156); FILE MERGED 2006/04/06 09:22:03 nn 1.12.156.1: #i63513# new method SetNewRangeNames to avoid extra copy of ScRangeName<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docfunc.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2006-05-05 09:44:58 $
*
* 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 SC_DOCFUNC_HXX
#define SC_DOCFUNC_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_POSTIT_HXX
#include "postit.hxx"
#endif
class ScEditEngineDefaulter;
class SfxUndoAction;
class ScAddress;
class ScDocShell;
class ScMarkData;
class ScPatternAttr;
class ScRange;
class ScRangeName;
class ScBaseCell;
struct ScTabOpParam;
// ---------------------------------------------------------------------------
class ScDocFunc
{
private:
ScDocShell& rDocShell;
BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE );
void CreateOneName( ScRangeName& rList,
SCCOL nPosX, SCROW nPosY, SCTAB nTab,
SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL& rCancel, BOOL bApi );
void NotifyInputHandler( const ScAddress& rPos );
public:
ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {}
~ScDocFunc() {}
DECL_LINK( NotifyDrawUndo, SfxUndoAction* );
BOOL DetectiveAddPred(const ScAddress& rPos);
BOOL DetectiveDelPred(const ScAddress& rPos);
BOOL DetectiveAddSucc(const ScAddress& rPos);
BOOL DetectiveDelSucc(const ScAddress& rPos);
BOOL DetectiveAddError(const ScAddress& rPos);
BOOL DetectiveMarkInvalid(SCTAB nTab);
BOOL DetectiveDelAll(SCTAB nTab);
BOOL DetectiveRefresh(BOOL bAutomatic = FALSE);
BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags,
BOOL bRecord, BOOL bApi );
BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType,
BOOL bRecord, BOOL bApi );
BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi );
BOOL PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine,
BOOL bInterpret, BOOL bApi );
BOOL SetCellText( const ScAddress& rPos, const String& rText,
BOOL bInterpret, BOOL bEnglish, BOOL bApi );
// creates a new cell for use with PutCell
ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText );
BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,
BOOL bRecord, BOOL bApi );
BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName,
BOOL bRecord, BOOL bApi );
BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi,
BOOL bPartOfPaste = FALSE );
BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi );
BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,
BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi );
BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi );
BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi );
BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi );
BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges,
SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips,
BOOL bRecord, BOOL bApi );
BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi );
BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi );
BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,
USHORT nFormatNo, BOOL bRecord, BOOL bApi );
BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,
const String& rString, BOOL bApi, BOOL bEnglish );
BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark,
const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi );
BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, BOOL bRecord, BOOL bApi );
BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,
double fStart, double fStep, double fMax,
BOOL bRecord, BOOL bApi );
// FillAuto: rRange wird von Source-Range auf Dest-Range angepasst
BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi );
BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi );
BOOL MergeCells( const ScRange& rRange, BOOL bContents,
BOOL bRecord, BOOL bApi );
BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi );
BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi );
BOOL SetNewRangeNames( ScRangeName* pNewRanges, BOOL bApi ); // takes ownership of pNewRanges
BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi );
BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi );
BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi );
BOOL InsertAreaLink( const String& rFile, const String& rFilter,
const String& rOptions, const String& rSource,
const ScRange& rDestRange, ULONG nRefresh,
BOOL bFitBlock, BOOL bApi );
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pivotsh.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:44:03 $
*
* 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 SC_PIVOTSH_HXX
#define SC_PIVOTSH_HXX
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
class ScTabViewShell;
class ScDPObject;
class ScPivotShell : public SfxShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SCID_PIVOT_SHELL);
ScPivotShell( ScTabViewShell* pView );
~ScPivotShell();
void Execute ( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
private:
ScTabViewShell* pViewShell;
ScDPObject* GetCurrDPObject();
};
#endif
<commit_msg>INTEGRATION: CWS calcwarnings (1.3.322); FILE MERGED 2006/12/14 17:57:13 nn 1.3.322.1: #i69284# warning-free: ui, unxsols4<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pivotsh.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-02-27 13:25:18 $
*
* 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 SC_PIVOTSH_HXX
#define SC_PIVOTSH_HXX
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
class ScTabViewShell;
class ScDPObject;
class ScPivotShell : public SfxShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SCID_PIVOT_SHELL)
ScPivotShell( ScTabViewShell* pView );
~ScPivotShell();
void Execute ( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
private:
ScTabViewShell* pViewShell;
ScDPObject* GetCurrDPObject();
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: target.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:38:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// System - Includes -----------------------------------------------------
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include "target.hxx"
// STATIC DATA -----------------------------------------------------------
TYPEINIT1(ScTabViewTarget, SfxRepeatTarget);
__EXPORT ScTabViewTarget::~ScTabViewTarget()
{
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.3.214); FILE MERGED 2006/07/12 10:02:52 kaib 1.3.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: target.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-07-21 14:25: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// System - Includes -----------------------------------------------------
// INCLUDE ---------------------------------------------------------------
#include "target.hxx"
// STATIC DATA -----------------------------------------------------------
TYPEINIT1(ScTabViewTarget, SfxRepeatTarget);
__EXPORT ScTabViewTarget::~ScTabViewTarget()
{
}
<|endoftext|>
|
<commit_before>//
// Aspia Project
// Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "relay/controller.h"
#include "base/logging.h"
#include "base/task_runner.h"
#include "base/peer/client_authenticator.h"
#include "proto/router_common.pb.h"
#include "relay/settings.h"
namespace relay {
namespace {
const std::chrono::seconds kReconnectTimeout{ 15 };
#if defined(OS_WIN)
const wchar_t kFirewallRuleName[] = L"Aspia Relay Service";
const wchar_t kFirewallRuleDecription[] = L"Allow incoming TCP connections";
#endif // defined(OS_WIN)
class KeyDeleter
{
public:
KeyDeleter(std::unique_ptr<SharedPool> pool, uint32_t key_id)
: pool_(std::move(pool)),
key_id_(key_id)
{
DCHECK(pool_);
}
~KeyDeleter() = default;
void deleteKey()
{
pool_->setKeyExpired(key_id_);
}
private:
std::unique_ptr<SharedPool> pool_;
const uint32_t key_id_;
DISALLOW_COPY_AND_ASSIGN(KeyDeleter);
};
} // namespace
Controller::Controller(std::shared_ptr<base::TaskRunner> task_runner)
: task_runner_(task_runner),
reconnect_timer_(base::WaitableTimer::Type::SINGLE_SHOT, task_runner),
shared_pool_(std::make_unique<SharedPool>(this))
{
Settings settings;
// Router settings.
router_address_ = settings.routerAddress();
router_port_ = settings.routerPort();
router_public_key_ = settings.routerPublicKey();
LOG(LS_INFO) << "Router address: " << router_address_;
LOG(LS_INFO) << "Router port: " << router_port_;
LOG(LS_INFO) << "Router public key: " << base::toHex(router_public_key_);
// Peers settings.
peer_address_ = settings.peerAddress();
peer_port_ = settings.peerPort();
peer_idle_timeout_ = settings.peerIdleTimeout();
max_peer_count_ = settings.maxPeerCount();
LOG(LS_INFO) << "Peer address: " << peer_address_;
LOG(LS_INFO) << "Peer port: " << peer_port_;
LOG(LS_INFO) << "Peer idle timeout: " << peer_idle_timeout_.count();
LOG(LS_INFO) << "Max peer count: " << max_peer_count_;
}
Controller::~Controller() = default;
bool Controller::start()
{
LOG(LS_INFO) << "Starting controller";
if (router_address_.empty())
{
LOG(LS_ERROR) << "Empty router address";
return false;
}
if (router_port_ == 0)
{
LOG(LS_ERROR) << "Invalid router port";
return false;
}
if (router_public_key_.empty())
{
LOG(LS_ERROR) << "Empty router public key";
return false;
}
if (peer_address_.empty())
{
LOG(LS_ERROR) << "Empty peer address";
return false;
}
if (peer_port_ == 0)
{
LOG(LS_ERROR) << "Invalid peer port";
return false;
}
if (peer_idle_timeout_ < std::chrono::minutes(1) || peer_idle_timeout_ > std::chrono::minutes(60))
{
LOG(LS_WARNING) << "Invalid peer idle specified";
return false;
}
sessions_worker_ = std::make_unique<SessionsWorker>(
peer_port_, peer_idle_timeout_, shared_pool_->share());
sessions_worker_->start(task_runner_, this);
connectToRouter();
return true;
}
void Controller::onConnected()
{
LOG(LS_INFO) << "Connection to the router is established";
channel_->setOwnKeepAlive(true);
channel_->setNoDelay(true);
authenticator_ = std::make_unique<base::ClientAuthenticator>(task_runner_);
authenticator_->setIdentify(proto::IDENTIFY_ANONYMOUS);
authenticator_->setPeerPublicKey(router_public_key_);
authenticator_->setSessionType(proto::ROUTER_SESSION_RELAY);
authenticator_->start(std::move(channel_),
[this](base::ClientAuthenticator::ErrorCode error_code)
{
if (error_code == base::ClientAuthenticator::ErrorCode::SUCCESS)
{
// The authenticator takes the listener on itself, we return the receipt of
// notifications.
channel_ = authenticator_->takeChannel();
channel_->setListener(this);
LOG(LS_INFO) << "Authentication complete";
// Now the session will receive incoming messages.
channel_->resume();
sendKeyPool(max_peer_count_);
}
else
{
LOG(LS_WARNING) << "Authentication failed: "
<< base::ClientAuthenticator::errorToString(error_code);
delayedConnectToRouter();
}
// Authenticator is no longer needed.
task_runner_->deleteSoon(std::move(authenticator_));
});
}
void Controller::onDisconnected(base::NetworkChannel::ErrorCode error_code)
{
LOG(LS_INFO) << "The connection to the router has been lost: "
<< base::NetworkChannel::errorToString(error_code);
// Clearing the key pool.
shared_pool_->clear();
// Retrying a connection at a time interval.
delayedConnectToRouter();
}
void Controller::onMessageReceived(const base::ByteArray& buffer)
{
std::unique_ptr<proto::RouterToRelay> message = std::make_unique<proto::RouterToRelay>();
if (!base::parse(buffer, message.get()))
{
LOG(LS_ERROR) << "Invalid message from router";
return;
}
if (message->has_key_used())
{
std::shared_ptr<KeyDeleter> key_deleter =
std::make_shared<KeyDeleter>(shared_pool_->share(), message->key_used().key_id());
// The router gave the key to the peers. They are required to use it within 30 seconds.
// If it is not used during this time, then it will be removed from the pool.
task_runner_->postDelayedTask(
std::bind(&KeyDeleter::deleteKey, key_deleter), std::chrono::seconds(30));
}
else
{
LOG(LS_WARNING) << "Unhandled message from router";
}
}
void Controller::onMessageWritten(size_t /* pending */)
{
// Nothing
}
void Controller::onSessionFinished()
{
// After disconnecting the peer, one key is released.
// Add a new key to the pool and send it to the router.
sendKeyPool(1);
}
void Controller::onPoolKeyExpired(uint32_t /* key_id */)
{
// The key has expired and has been removed from the pool.
// Add a new key to the pool and send it to the router.
sendKeyPool(1);
}
void Controller::connectToRouter()
{
LOG(LS_INFO) << "Connecting to router...";
// Create channel.
channel_ = std::make_unique<base::NetworkChannel>();
// Connect to router.
channel_->setListener(this);
channel_->connect(router_address_, router_port_);
}
void Controller::delayedConnectToRouter()
{
LOG(LS_INFO) << "Reconnect after " << kReconnectTimeout.count() << " seconds";
reconnect_timer_.start(kReconnectTimeout, std::bind(&Controller::connectToRouter, this));
}
void Controller::sendKeyPool(uint32_t key_count)
{
std::unique_ptr<proto::RelayToRouter> message = std::make_unique<proto::RelayToRouter>();
proto::RelayKeyPool* relay_key_pool = message->mutable_key_pool();
relay_key_pool->set_peer_host(base::utf8FromUtf16(peer_address_));
relay_key_pool->set_peer_port(peer_port_);
// Add the requested number of keys to the pool.
for (uint32_t i = 0; i < key_count; ++i)
{
SessionKey session_key = SessionKey::create();
if (!session_key.isValid())
return;
// Add the key to the outgoing message.
proto::RelayKey* key = relay_key_pool->add_key();
key->set_type(proto::RelayKey::TYPE_X25519);
key->set_encryption(proto::RelayKey::ENCRYPTION_CHACHA20_POLY1305);
key->set_public_key(base::toStdString(session_key.publicKey()));
key->set_iv(base::toStdString(session_key.iv()));
// Add the key to the pool.
key->set_key_id(shared_pool_->addKey(std::move(session_key)));
}
// Send a message to the router.
channel_->send(base::serialize(*message));
}
} // namespace relay
<commit_msg>Cleanup.<commit_after>//
// Aspia Project
// Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "relay/controller.h"
#include "base/logging.h"
#include "base/task_runner.h"
#include "base/peer/client_authenticator.h"
#include "proto/router_common.pb.h"
#include "relay/settings.h"
namespace relay {
namespace {
const std::chrono::seconds kReconnectTimeout{ 15 };
class KeyDeleter
{
public:
KeyDeleter(std::unique_ptr<SharedPool> pool, uint32_t key_id)
: pool_(std::move(pool)),
key_id_(key_id)
{
DCHECK(pool_);
}
~KeyDeleter() = default;
void deleteKey()
{
pool_->setKeyExpired(key_id_);
}
private:
std::unique_ptr<SharedPool> pool_;
const uint32_t key_id_;
DISALLOW_COPY_AND_ASSIGN(KeyDeleter);
};
} // namespace
Controller::Controller(std::shared_ptr<base::TaskRunner> task_runner)
: task_runner_(task_runner),
reconnect_timer_(base::WaitableTimer::Type::SINGLE_SHOT, task_runner),
shared_pool_(std::make_unique<SharedPool>(this))
{
Settings settings;
// Router settings.
router_address_ = settings.routerAddress();
router_port_ = settings.routerPort();
router_public_key_ = settings.routerPublicKey();
LOG(LS_INFO) << "Router address: " << router_address_;
LOG(LS_INFO) << "Router port: " << router_port_;
LOG(LS_INFO) << "Router public key: " << base::toHex(router_public_key_);
// Peers settings.
peer_address_ = settings.peerAddress();
peer_port_ = settings.peerPort();
peer_idle_timeout_ = settings.peerIdleTimeout();
max_peer_count_ = settings.maxPeerCount();
LOG(LS_INFO) << "Peer address: " << peer_address_;
LOG(LS_INFO) << "Peer port: " << peer_port_;
LOG(LS_INFO) << "Peer idle timeout: " << peer_idle_timeout_.count();
LOG(LS_INFO) << "Max peer count: " << max_peer_count_;
}
Controller::~Controller() = default;
bool Controller::start()
{
LOG(LS_INFO) << "Starting controller";
if (router_address_.empty())
{
LOG(LS_ERROR) << "Empty router address";
return false;
}
if (router_port_ == 0)
{
LOG(LS_ERROR) << "Invalid router port";
return false;
}
if (router_public_key_.empty())
{
LOG(LS_ERROR) << "Empty router public key";
return false;
}
if (peer_address_.empty())
{
LOG(LS_ERROR) << "Empty peer address";
return false;
}
if (peer_port_ == 0)
{
LOG(LS_ERROR) << "Invalid peer port";
return false;
}
if (peer_idle_timeout_ < std::chrono::minutes(1) || peer_idle_timeout_ > std::chrono::minutes(60))
{
LOG(LS_WARNING) << "Invalid peer idle specified";
return false;
}
sessions_worker_ = std::make_unique<SessionsWorker>(
peer_port_, peer_idle_timeout_, shared_pool_->share());
sessions_worker_->start(task_runner_, this);
connectToRouter();
return true;
}
void Controller::onConnected()
{
LOG(LS_INFO) << "Connection to the router is established";
channel_->setOwnKeepAlive(true);
channel_->setNoDelay(true);
authenticator_ = std::make_unique<base::ClientAuthenticator>(task_runner_);
authenticator_->setIdentify(proto::IDENTIFY_ANONYMOUS);
authenticator_->setPeerPublicKey(router_public_key_);
authenticator_->setSessionType(proto::ROUTER_SESSION_RELAY);
authenticator_->start(std::move(channel_),
[this](base::ClientAuthenticator::ErrorCode error_code)
{
if (error_code == base::ClientAuthenticator::ErrorCode::SUCCESS)
{
// The authenticator takes the listener on itself, we return the receipt of
// notifications.
channel_ = authenticator_->takeChannel();
channel_->setListener(this);
LOG(LS_INFO) << "Authentication complete";
// Now the session will receive incoming messages.
channel_->resume();
sendKeyPool(max_peer_count_);
}
else
{
LOG(LS_WARNING) << "Authentication failed: "
<< base::ClientAuthenticator::errorToString(error_code);
delayedConnectToRouter();
}
// Authenticator is no longer needed.
task_runner_->deleteSoon(std::move(authenticator_));
});
}
void Controller::onDisconnected(base::NetworkChannel::ErrorCode error_code)
{
LOG(LS_INFO) << "The connection to the router has been lost: "
<< base::NetworkChannel::errorToString(error_code);
// Clearing the key pool.
shared_pool_->clear();
// Retrying a connection at a time interval.
delayedConnectToRouter();
}
void Controller::onMessageReceived(const base::ByteArray& buffer)
{
std::unique_ptr<proto::RouterToRelay> message = std::make_unique<proto::RouterToRelay>();
if (!base::parse(buffer, message.get()))
{
LOG(LS_ERROR) << "Invalid message from router";
return;
}
if (message->has_key_used())
{
std::shared_ptr<KeyDeleter> key_deleter =
std::make_shared<KeyDeleter>(shared_pool_->share(), message->key_used().key_id());
// The router gave the key to the peers. They are required to use it within 30 seconds.
// If it is not used during this time, then it will be removed from the pool.
task_runner_->postDelayedTask(
std::bind(&KeyDeleter::deleteKey, key_deleter), std::chrono::seconds(30));
}
else
{
LOG(LS_WARNING) << "Unhandled message from router";
}
}
void Controller::onMessageWritten(size_t /* pending */)
{
// Nothing
}
void Controller::onSessionFinished()
{
// After disconnecting the peer, one key is released.
// Add a new key to the pool and send it to the router.
sendKeyPool(1);
}
void Controller::onPoolKeyExpired(uint32_t /* key_id */)
{
// The key has expired and has been removed from the pool.
// Add a new key to the pool and send it to the router.
sendKeyPool(1);
}
void Controller::connectToRouter()
{
LOG(LS_INFO) << "Connecting to router...";
// Create channel.
channel_ = std::make_unique<base::NetworkChannel>();
// Connect to router.
channel_->setListener(this);
channel_->connect(router_address_, router_port_);
}
void Controller::delayedConnectToRouter()
{
LOG(LS_INFO) << "Reconnect after " << kReconnectTimeout.count() << " seconds";
reconnect_timer_.start(kReconnectTimeout, std::bind(&Controller::connectToRouter, this));
}
void Controller::sendKeyPool(uint32_t key_count)
{
std::unique_ptr<proto::RelayToRouter> message = std::make_unique<proto::RelayToRouter>();
proto::RelayKeyPool* relay_key_pool = message->mutable_key_pool();
relay_key_pool->set_peer_host(base::utf8FromUtf16(peer_address_));
relay_key_pool->set_peer_port(peer_port_);
// Add the requested number of keys to the pool.
for (uint32_t i = 0; i < key_count; ++i)
{
SessionKey session_key = SessionKey::create();
if (!session_key.isValid())
return;
// Add the key to the outgoing message.
proto::RelayKey* key = relay_key_pool->add_key();
key->set_type(proto::RelayKey::TYPE_X25519);
key->set_encryption(proto::RelayKey::ENCRYPTION_CHACHA20_POLY1305);
key->set_public_key(base::toStdString(session_key.publicKey()));
key->set_iv(base::toStdString(session_key.iv()));
// Add the key to the pool.
key->set_key_id(shared_pool_->addKey(std::move(session_key)));
}
// Send a message to the router.
channel_->send(base::serialize(*message));
}
} // namespace relay
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "bucket.h"
#include <assert.h>
#include <map>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/visit_ranges.h>
namespace vespalib {
namespace metrics {
namespace {
template<typename T>
std::vector<typename T::aggregator_type>
mergeFromSamples(const StableStore<typename T::sample_type> &source)
{
using Aggregator = typename T::aggregator_type;
using Sample = typename T::sample_type;
using Key = std::pair<MetricId, Point>;
using Map = std::map<Key, Aggregator>;
using MapValue = typename Map::value_type;
Map map;
source.for_each([&map] (const Sample &sample) {
Key id = sample.idx;
auto iter_check = map.emplace(id, sample);
if (!iter_check.second) {
iter_check.first->second.merge(sample);
}
});
std::vector<typename T::aggregator_type> result;
for (const MapValue &entry : map) {
result.push_back(entry.second);
}
return result;
}
template<typename T>
struct IdxComparator {
bool operator() (const T& a, const T& b) { return a.idx < b.idx; }
};
template<typename T>
std::vector<T>
mergeVectors(const std::vector<T> &a,
const std::vector<T> &b)
{
std::vector<T> result;
visit_ranges(overload
{
[&result](visit_ranges_either, const T& x) { result.push_back(x); },
[&result](visit_ranges_both, const T& x, const T& y) {
result.push_back(x);
result.back().merge(y);
}
}, a.begin(), a.end(), b.begin(), b.end(), IdxComparator<T>());
return result;
}
template<typename T>
std::vector<T>
findMissing(const std::vector<T> &already,
const std::vector<T> &complete)
{
std::vector<T> result;
visit_ranges(overload
{
// missing from "complete", should not happen:
[&result](visit_ranges_first, const T&) { },
// missing this:
[&result](visit_ranges_second, const T& x) { result.push_back(x); },
// already have this:
[&result](visit_ranges_both, const T&, const T&) { }
},
already.begin(), already.end(),
complete.begin(), complete.end(),
IdxComparator<T>());
return result;
}
} // namespace <unnamed>
void Bucket::merge(const CurrentSamples &samples)
{
counters = mergeFromSamples<Counter>(samples.counterIncrements);
gauges = mergeFromSamples<Gauge>(samples.gaugeMeasurements);
}
void Bucket::merge(const Bucket &other)
{
assert(genCnt < other.genCnt);
genCnt = other.genCnt;
startTime = std::min(startTime, other.startTime);
endTime = std::max(endTime, other.endTime);
std::vector<CounterAggregator> nextCounters = mergeVectors(counters, other.counters);
counters = std::move(nextCounters);
std::vector<GaugeAggregator> nextGauges = mergeVectors(gauges, other.gauges);
gauges = std::move(nextGauges);
}
void Bucket::padMetrics(const Bucket &source)
{
std::vector<CounterAggregator> missingC = findMissing(counters, source.counters);
for (CounterAggregator aggr : missingC) {
aggr.count = 0;
counters.push_back(aggr);
}
std::vector<GaugeAggregator> missingG = findMissing(gauges, source.gauges);
for (GaugeAggregator aggr : missingG) {
aggr.observedCount = 0;
aggr.sumValue = 0;
aggr.minValue = 0;
aggr.maxValue = 0;
gauges.push_back(aggr);
}
}
} // namespace vespalib::metrics
} // namespace vespalib
<commit_msg>Remove unused lambda capture in findMissing function.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "bucket.h"
#include <assert.h>
#include <map>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/visit_ranges.h>
namespace vespalib {
namespace metrics {
namespace {
template<typename T>
std::vector<typename T::aggregator_type>
mergeFromSamples(const StableStore<typename T::sample_type> &source)
{
using Aggregator = typename T::aggregator_type;
using Sample = typename T::sample_type;
using Key = std::pair<MetricId, Point>;
using Map = std::map<Key, Aggregator>;
using MapValue = typename Map::value_type;
Map map;
source.for_each([&map] (const Sample &sample) {
Key id = sample.idx;
auto iter_check = map.emplace(id, sample);
if (!iter_check.second) {
iter_check.first->second.merge(sample);
}
});
std::vector<typename T::aggregator_type> result;
for (const MapValue &entry : map) {
result.push_back(entry.second);
}
return result;
}
template<typename T>
struct IdxComparator {
bool operator() (const T& a, const T& b) { return a.idx < b.idx; }
};
template<typename T>
std::vector<T>
mergeVectors(const std::vector<T> &a,
const std::vector<T> &b)
{
std::vector<T> result;
visit_ranges(overload
{
[&result](visit_ranges_either, const T& x) { result.push_back(x); },
[&result](visit_ranges_both, const T& x, const T& y) {
result.push_back(x);
result.back().merge(y);
}
}, a.begin(), a.end(), b.begin(), b.end(), IdxComparator<T>());
return result;
}
template<typename T>
std::vector<T>
findMissing(const std::vector<T> &already,
const std::vector<T> &complete)
{
std::vector<T> result;
visit_ranges(overload
{
// missing from "complete", should not happen:
[](visit_ranges_first, const T&) { },
// missing this:
[&result](visit_ranges_second, const T& x) { result.push_back(x); },
// already have this:
[](visit_ranges_both, const T&, const T&) { }
},
already.begin(), already.end(),
complete.begin(), complete.end(),
IdxComparator<T>());
return result;
}
} // namespace <unnamed>
void Bucket::merge(const CurrentSamples &samples)
{
counters = mergeFromSamples<Counter>(samples.counterIncrements);
gauges = mergeFromSamples<Gauge>(samples.gaugeMeasurements);
}
void Bucket::merge(const Bucket &other)
{
assert(genCnt < other.genCnt);
genCnt = other.genCnt;
startTime = std::min(startTime, other.startTime);
endTime = std::max(endTime, other.endTime);
std::vector<CounterAggregator> nextCounters = mergeVectors(counters, other.counters);
counters = std::move(nextCounters);
std::vector<GaugeAggregator> nextGauges = mergeVectors(gauges, other.gauges);
gauges = std::move(nextGauges);
}
void Bucket::padMetrics(const Bucket &source)
{
std::vector<CounterAggregator> missingC = findMissing(counters, source.counters);
for (CounterAggregator aggr : missingC) {
aggr.count = 0;
counters.push_back(aggr);
}
std::vector<GaugeAggregator> missingG = findMissing(gauges, source.gauges);
for (GaugeAggregator aggr : missingG) {
aggr.observedCount = 0;
aggr.sumValue = 0;
aggr.minValue = 0;
aggr.maxValue = 0;
gauges.push_back(aggr);
}
}
} // namespace vespalib::metrics
} // namespace vespalib
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestCellDistanceSelector.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware SAS 2012
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkExtractSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkCellDistanceSelector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridReader.h"
#include "vtkUnstructuredGridWriter.h"
#include <vtksys/ios/sstream>
// Reference values
vtkIdType cardCellDistanceSelection[] =
{
54,
54,
108,
45,
};
// ------------------------------------------------------------------------------------------------
static int CheckExtractedUGrid( vtkExtractSelection* extract,
const char* tag,
int testIdx,
bool writeGrid )
{
// Output must be a multiblock dataset
vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() );
if ( ! outputMB )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to multiblock dataset.");
return 1;
}
// First block must be an unstructured grid
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) );
if ( ! ugrid )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to unstructured grid.");
return 1;
}
// Initialize test status
int testStatus = 0;
cerr << endl;
// Verify selection cardinality
vtkIdType nCells = ugrid->GetNumberOfCells();
cout << tag
<< " contains "
<< nCells
<< " cells."
<< endl;
if ( nCells != cardCellDistanceSelection[testIdx] )
{
vtkGenericWarningMacro( "Incorrect cardinality: "
<< nCells
<< " != "
<< cardCellDistanceSelection[testIdx] );
testStatus = 1;
}
// Verify selection cells
cerr << "Original cell Ids (types): ";
ugrid->GetCellData()->SetActiveScalars( "vtkOriginalCellIds" );
vtkDataArray* oCellIds = ugrid->GetCellData()->GetScalars();
for ( vtkIdType i = 0; i < oCellIds->GetNumberOfTuples(); ++ i )
{
cerr << oCellIds->GetTuple1( i )
<< " ";
}
cerr << endl;
// If requested, write mesh
if ( writeGrid )
{
vtksys_ios::ostringstream fileNameSS;
fileNameSS << "./CellDistanceExtraction-"
<< testIdx
<< ".vtk";
vtkSmartPointer<vtkUnstructuredGridWriter> writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();
writer->SetFileName( fileNameSS.str().c_str() );
writer->SetInputData( ugrid );
writer->Write();
cerr << "Wrote file "
<< fileNameSS.str()
<< endl;
}
return testStatus;
}
//----------------------------------------------------------------------------
int TestCellDistanceSelector( int argc, char * argv [] )
{
// Initialize test value
int testIntValue = 0;
// Read 3D unstructured input mesh
char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk");
vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New();
reader->SetFileName( fileName );
reader->Update();
delete [] fileName;
// Create multi-block mesh for linear selector
vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New();
mesh->SetNumberOfBlocks( 1 );
mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" );
mesh->SetBlock( 0, reader->GetOutput() );
// *****************************************************************************
// 0. Selection along inner segment with endpoints (0,0,0) and (.23, 04,.04)
// *****************************************************************************
// Create selection along one line segment
vtkSmartPointer<vtkCellDistanceSelector> ls0 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls0->SetInputData( mesh );
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New();
es0->SetInputData( 0, mesh );
es0->SetInputConnection( 1, ls0->GetOutputPort() );
es0->Update();
testIntValue += CheckExtractedUGrid( es0, "Selection (0,0,0)-(0.23,0.04,0.04)", 0, true );
return testIntValue;
}
<commit_msg>A first test that corresponds to something real<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestCellDistanceSelector.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware SAS 2012
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkExtractSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkCellDistanceSelector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridReader.h"
#include "vtkUnstructuredGridWriter.h"
#include <vtksys/ios/sstream>
// Reference values
vtkIdType cardCellDistanceSelection[] =
{
125,
54,
108,
45,
};
// ------------------------------------------------------------------------------------------------
static int CheckExtractedUGrid( vtkExtractSelection* extract,
const char* tag,
int testIdx,
bool writeGrid )
{
// Output must be a multiblock dataset
vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() );
if ( ! outputMB )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to multiblock dataset.");
return 1;
}
// First block must be an unstructured grid
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) );
if ( ! ugrid )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to unstructured grid.");
return 1;
}
// Initialize test status
int testStatus = 0;
cerr << endl;
// Verify selection cardinality
vtkIdType nCells = ugrid->GetNumberOfCells();
cout << tag
<< " contains "
<< nCells
<< " cells."
<< endl;
if ( nCells != cardCellDistanceSelection[testIdx] )
{
vtkGenericWarningMacro( "Incorrect cardinality: "
<< nCells
<< " != "
<< cardCellDistanceSelection[testIdx] );
testStatus = 1;
}
// Verify selection cells
cerr << "Original cell Ids (types): ";
ugrid->GetCellData()->SetActiveScalars( "vtkOriginalCellIds" );
vtkDataArray* oCellIds = ugrid->GetCellData()->GetScalars();
for ( vtkIdType i = 0; i < oCellIds->GetNumberOfTuples(); ++ i )
{
cerr << oCellIds->GetTuple1( i )
<< " ";
}
cerr << endl;
// If requested, write mesh
if ( writeGrid )
{
vtksys_ios::ostringstream fileNameSS;
fileNameSS << "./CellDistanceExtraction-"
<< testIdx
<< ".vtk";
vtkSmartPointer<vtkUnstructuredGridWriter> writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();
writer->SetFileName( fileNameSS.str().c_str() );
writer->SetInputData( ugrid );
writer->Write();
cerr << "Wrote file "
<< fileNameSS.str()
<< endl;
}
return testStatus;
}
//----------------------------------------------------------------------------
int TestCellDistanceSelector( int argc, char * argv [] )
{
// Initialize test value
int testIntValue = 0;
// Read 3D unstructured input mesh
char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk");
vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New();
reader->SetFileName( fileName );
reader->Update();
delete [] fileName;
// Create multi-block mesh for linear selector
vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New();
mesh->SetNumberOfBlocks( 1 );
mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" );
mesh->SetBlock( 0, reader->GetOutput() );
// *****************************************************************************
// 0. Selection with distance of 2 from cell 7000
// *****************************************************************************
// Create a selection, sel0, of cell with index 7000
vtkSmartPointer<vtkIdTypeArray> selArr0 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr0->InsertNextValue( 7000 );
vtkSmartPointer<vtkSelectionNode> selNode0 = vtkSmartPointer<vtkSelectionNode>::New();
selNode0->SetContentType( vtkSelectionNode::INDICES );
selNode0->SetFieldType( vtkSelectionNode::CELL );
selNode0->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode0->SetSelectionList( selArr0 );
vtkSmartPointer<vtkSelection> sel0 = vtkSmartPointer<vtkSelection>::New();
sel0->AddNode( selNode0 );
// Create selection up to topological distance of 2
vtkSmartPointer<vtkCellDistanceSelector> ls0 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls0->SetInputData( 0, sel0 );
ls0->SetInputData( 1, mesh );
ls0->SetDistance( 2 );
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New();
es0->SetInputData( 0, mesh );
es0->SetInputConnection( 1, ls0->GetOutputPort() );
es0->Update();
testIntValue += CheckExtractedUGrid( es0, "Selection d({7000})<3", 0, true );
return testIntValue;
}
<|endoftext|>
|
<commit_before>/**
* Schulich Delta Hermes
* Copyright (C) 2015 University of Calgary Solar Car Team
*
* This file is part of Schulich Delta Hermes
*
* Schulich Delta Hermes is free software:
* you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Schulich Delta Hermes 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General
* Public License along with Schulich Delta Hermes.
* If not, see <http://www.gnu.org/licenses/>.
*
* For further contact, email <software@calgarysolarcar.ca>
*/
#include "DriverControlDetails.h"
#include "MessageDecodingHelpers.h"
#include "MessageDefines.h"
using namespace MessageDecodingHelpers;
namespace
{
const int motorVelocityIndex = 1;
const int motorVoltageIndex = 5;
const int motorCurrentRealIndex = 9;
const int backEmfIndex = 13;
const int dpsBoardTemperatureIndex = 17;
const int dcBusAmpHoursIndex = 21;
const int odometerIndex = 25;
}
DriverControlDetails::DriverControlDetails(
const QByteArray& messageData)
: messageData_(messageData)
{
}
float DriverControlDetails::motorVelocity() const
{
return getFloat(messageData_, motorVelocityIndex);
}
float DriverControlDetails::motorVoltage() const
{
return getFloat(messageData_, motorVoltageIndex);
}
float DriverControlDetails::motorCurrentReal() const
{
return getFloat(messageData_, motorCurrentRealIndex);
}
float DriverControlDetails::backEmf() const
{
return getFloat(messageData_, backEmfIndex);
}
float DriverControlDetails::dpsBoardTemperature() const
{
return getFloat(messageData_, dpsBoardTemperatureIndex);
}
float DriverControlDetails::dcBusAmpHours() const
{
return getFloat(messageData_, dcBusAmpHoursIndex);
}
float DriverControlDetails::odometer() const
{
return getFloat(messageData_, odometerIndex);
}
QString DriverControlDetails::toString() const
{
QString messageString;
messageString += QString::number(MessageDefines::DriverControlDetails) + ", ";
messageString += QString::number(motorVelocity()) + ", ";
messageString += QString::number(motorVoltage()) + ", ";
messageString += QString::number(motorCurrentReal()) + ", ";
messageString += QString::number(backEmf()) + ", ";
messageString += QString::number(dpsBoardTemperature()) + ", ";
messageString += QString::number(dcBusAmpHours()) + ", ";
return messageString;
}
<commit_msg>renamed driver control details to follow naming conventions<commit_after>/**
* Schulich Delta Hermes
* Copyright (C) 2015 University of Calgary Solar Car Team
*
* This file is part of Schulich Delta Hermes
*
* Schulich Delta Hermes is free software:
* you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Schulich Delta Hermes 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General
* Public License along with Schulich Delta Hermes.
* If not, see <http://www.gnu.org/licenses/>.
*
* For further contact, email <software@calgarysolarcar.ca>
*/
#include "DriverControlDetails.h"
#include "MessageDecodingHelpers.h"
#include "MessageDefines.h"
using namespace MessageDecodingHelpers;
namespace
{
const int MOTOR_VELOCITY_INDEX = 1;
const int MOTOR_VOLTAGE_INDEX = 5;
const int MOTOR_CURRENT_REAL_INDEX = 9;
const int BACK_EMF_INDEX = 13;
const int DSP_BOARD_TEMPERATURE_INDEX = 17;
const int DC_BUS_AMP_HOURS_INDEX = 21;
const int ODOMETER_INDEX = 25;
}
DriverControlDetails::DriverControlDetails(
const QByteArray& messageData)
: messageData_(messageData)
{
}
float DriverControlDetails::motorVelocity() const
{
return getFloat(messageData_, MOTOR_VELOCITY_INDEX);
}
float DriverControlDetails::motorVoltage() const
{
return getFloat(messageData_, MOTOR_VOLTAGE_INDEX);
}
float DriverControlDetails::motorCurrentReal() const
{
return getFloat(messageData_, MOTOR_CURRENT_REAL_INDEX);
}
float DriverControlDetails::backEmf() const
{
return getFloat(messageData_, BACK_EMF_INDEX);
}
float DriverControlDetails::dpsBoardTemperature() const
{
return getFloat(messageData_, DSP_BOARD_TEMPERATURE_INDEX);
}
float DriverControlDetails::dcBusAmpHours() const
{
return getFloat(messageData_, DC_BUS_AMP_HOURS_INDEX);
}
float DriverControlDetails::odometer() const
{
return getFloat(messageData_, ODOMETER_INDEX);
}
QString DriverControlDetails::toString() const
{
QString messageString;
messageString += QString::number(MessageDefines::DriverControlDetails) + ", ";
messageString += QString::number(motorVelocity()) + ", ";
messageString += QString::number(motorVoltage()) + ", ";
messageString += QString::number(motorCurrentReal()) + ", ";
messageString += QString::number(backEmf()) + ", ";
messageString += QString::number(dpsBoardTemperature()) + ", ";
messageString += QString::number(dcBusAmpHours()) + ", ";
return messageString;
}
<|endoftext|>
|
<commit_before>
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// Routines that generate pseudo-random numbers compatible
// with the standard erand48(), nrand48(), etc. functions.
//
//-----------------------------------------------------------------------------
#include "ImathRandom.h"
#include "ImathLimits.h"
namespace Imath {
#if ULONG_MAX == 18446744073709551615LU
typedef long unsigned int Int64;
#else
typedef long long unsigned int Int64;
#endif
namespace {
//
// Static state used by Imath::drand48(), Imath::lrand48() and Imath::srand48()
//
unsigned short staticState[3] = {0, 0, 0};
void
rand48Next (unsigned short state[3])
{
//
// drand48() and friends are all based
// on a linear congruential sequence,
//
// x[n+1] = (a * x[n] + c) % (m + 1),
//
// with a, c and m as specified below.
//
static const Int64 a = Int64 (0x5deece66dLL);
static const Int64 c = Int64 (0xbLL);
static const Int64 m = Int64 (0x0ffffffffffffLL);
//
// Assemble the 48-bit value x[n] from the
// three 16-bit values stored in state.
//
Int64 x = (Int64 (state[2]) << 32) |
(Int64 (state[1]) << 16) |
Int64 (state[0]);
//
// Compute x[n+1]
//
x = (a * x + c) & m;
//
// Disassemble x[n+1] into three 16-bit values.
// The code assumes that sizeof (unsigned short) == 2.
//
state[2] = x >> 32;
state[1] = x >> 16;
state[0] = x;
}
} // namespace
double
erand48 (unsigned short state[3])
{
//
// Generate a double-precision floating-point value between 0.0 and 1.0:
//
// The biased exponent for all doubles between 1.0 and 2.0 is 0x3ff.
// The 48 most significant bits of the significand (mantissa) are
// filled with pseudo-random bits generated by rand48Next(). The
// remaining 4 bits are set to 0. This results in a bit pattern
// between 0x3ff0000000000000 and 0x3ffffffffffffff0, which corresponds
// to a floating-point value between 1.0 and 1.9999999999999964.
// Subtracting 1.0 from this value produces a number between 0.0 and
// 0.9999999999999964.
//
rand48Next (state);
union {double d; Int64 i;} u;
u.i = (Int64 (0x3ff) << 52) | // sign and exponent
(Int64 (state[2]) << 36) | // significand
(Int64 (state[1]) << 20) |
(Int64 (state[0]) << 4);
return u.d - 1;
}
double
drand48 ()
{
return Imath::erand48 (staticState);
}
long int
nrand48 (unsigned short state[3])
{
//
// Generate an integer between 0 and 0x7fffffff.
//
rand48Next (state);
return ((long int) (state[2]) << 15) |
((long int) (state[1]) >> 1);
}
long int
lrand48 ()
{
return Imath::nrand48 (staticState);
}
void
srand48 (long int seed)
{
staticState[2] = seed >> 16;
staticState[1] = seed;
staticState[0] = 0x330e;
}
} // namespace Imath
<commit_msg>Fixed comments.<commit_after>
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// Routines that generate pseudo-random numbers compatible
// with the standard erand48(), nrand48(), etc. functions.
//
//-----------------------------------------------------------------------------
#include "ImathRandom.h"
#include "ImathLimits.h"
namespace Imath {
#if ULONG_MAX == 18446744073709551615LU
typedef long unsigned int Int64;
#else
typedef long long unsigned int Int64;
#endif
namespace {
//
// Static state used by Imath::drand48(), Imath::lrand48() and Imath::srand48()
//
unsigned short staticState[3] = {0, 0, 0};
void
rand48Next (unsigned short state[3])
{
//
// drand48() and friends are all based
// on a linear congruential sequence,
//
// x[n+1] = (a * x[n] + c) % (m + 1),
//
// with a, c and m as specified below.
//
static const Int64 a = Int64 (0x5deece66dLL);
static const Int64 c = Int64 (0xbLL);
static const Int64 m = Int64 (0x0ffffffffffffLL);
//
// Assemble the 48-bit value x[n] from the
// three 16-bit values stored in state.
//
Int64 x = (Int64 (state[2]) << 32) |
(Int64 (state[1]) << 16) |
Int64 (state[0]);
//
// Compute x[n+1]
//
x = (a * x + c) & m;
//
// Disassemble x[n+1] into three 16-bit values.
// The code assumes that sizeof (unsigned short) == 2.
//
state[2] = x >> 32;
state[1] = x >> 16;
state[0] = x;
}
} // namespace
double
erand48 (unsigned short state[3])
{
//
// Generate double-precision floating-point values between 0.0 and 1.0:
//
// The biased exponent for all doubles between 1.0 and 2.0 is 0x3ff.
// The 48 most significant bits of the significand (mantissa) are
// filled with pseudo-random bits generated by rand48Next().
// The remaining 4 bits are set to 0. This results in bit patterns
// between 0x3ff0000000000000 and 0x3ffffffffffffff0, which correspond
// to uniformly distributed floating-point values between 1.0 and
// 1.9999999999999964. Subtracting 1.0 from those values produces
// numbers between 0.0 and 0.9999999999999964.
//
rand48Next (state);
union {double d; Int64 i;} u;
u.i = (Int64 (0x3ff) << 52) | // sign and exponent
(Int64 (state[2]) << 36) | // significand
(Int64 (state[1]) << 20) |
(Int64 (state[0]) << 4);
return u.d - 1;
}
double
drand48 ()
{
return Imath::erand48 (staticState);
}
long int
nrand48 (unsigned short state[3])
{
//
// Generate uniformly distributed integers between 0 and 0x7fffffff.
//
rand48Next (state);
return ((long int) (state[2]) << 15) |
((long int) (state[1]) >> 1);
}
long int
lrand48 ()
{
return Imath::nrand48 (staticState);
}
void
srand48 (long int seed)
{
staticState[2] = seed >> 16;
staticState[1] = seed;
staticState[0] = 0x330e;
}
} // namespace Imath
<|endoftext|>
|
<commit_before>// RhoLaunch.cpp : Defines the entry point for the application.
//
#include "windows.h"
#include "RhoLaunch.h"
#define MAX_LOADSTRING 100
#define PB_WINDOW_RESTORE WM_USER + 10
// Global Functions:
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
COPYDATASTRUCT launchData;
//validate the command line
int iLen = wcslen(lpCmdLine);
if(iLen < 3){
return 1;
}
//LPWSTR pAppName = new WCHAR[iLen + 3];//allow space for the index
LPWSTR pAppName,pTabName,pTemp;
pAppName = pTemp= lpCmdLine;
int iLoop;
bool bStart,bTabStart,bAppName;
bStart = bTabStart = bAppName= false;
for(iLoop = 0;iLoop < iLen ;iLoop++)
{
if(lpCmdLine[iLoop] == L' '){
if(bStart){
if(!bAppName){
*pTemp = NULL;//terminate the app name
pTemp++;
bAppName = true;
pTabName = pTemp;
}
else if(bTabStart){
*pTemp = NULL;//terminate the tab name
break;//finished so exit loop
}
}
continue;//ignore spaces
}
if(lpCmdLine[iLoop] == L'/'){
if(!bStart){
bStart = !bStart;
continue;
}
if(!bAppName){
*pTemp= NULL;
bAppName = !bAppName;
bTabStart = true;
}
if(!bTabStart){
bTabStart = true;
continue;
}
}
*pTemp= lpCmdLine[iLoop];
pTemp++;
}
*pTemp = NULL;
HWND hwndRunningRE = FindWindow(NULL, pAppName);
if (hwndRunningRE){
// Found the running instance
//rhode expects a MultiByte string so convert
int ilen = wcslen(pTabName);
char *pTabNameMB = new char[ilen+1];
wcstombs(pTabNameMB, pTabName,ilen);
launchData.lpData = pTabNameMB;
launchData.cbData = (ilen+1);
ShowWindow(hwndRunningRE, SW_RESTORE);
SendMessage(hwndRunningRE,PB_WINDOW_RESTORE,(WPARAM) NULL,(LPARAM)TRUE);
//send a message to inform Rho of the requested index
SendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );
delete [] pTabNameMB;
// switch to it
SetForegroundWindow(hwndRunningRE);
}
else{
//no window handle, so try to start the app
//will only work if RhoLaunch is in the same directory as the app
//build the Rho app name
WCHAR pApp[MAX_PATH + 1];
int iIndex,iLen;
if(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){
return 1;//error could not find the path
}
//remove 'RhoLaunch' from the path
for(iIndex = iLen - 1;pApp[iIndex]!=L'\\';iIndex--);
pApp[iIndex+ 1] = NULL;
//LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];
wcscat(pApp,pAppName);
wcscat(pApp,L".exe");
LPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];
wsprintf(pTabCommand,L"/tabname=\"%s\"",pTabName);
LaunchProcess(pApp,pTabCommand);
delete [] pTabCommand;
}
return 0;
}
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)
{
STARTUPINFO StartInfo;
PROCESS_INFORMATION ProcessInfo;
BOOL bOk;
// Reset the contents of the 'Process Information' and 'Start Up' structures.
memset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));
memset( &StartInfo, 0, sizeof( STARTUPINFO));
StartInfo.cb = sizeof( STARTUPINFO);
// Create the 'browser' in a seperate process.
bOk = CreateProcess( pFilePath, // LPCTSTR lpApplicationName,//L"\\program files\\Neon\\BIN\\SVC_Controls.exe",
pCmdLine, // LPTSTR lpCommandLine,
NULL, // LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, // BOOL bInheritHandles,
0, // DWORD dwCreationFlags,
NULL, // LPVOID lpEnvironment,
NULL, // LPCTSTR lpCurrentDirectory,
&StartInfo, // LPSTARTUPINFO lpStartupInfo,
&ProcessInfo); // LPPROCESS_INFORMATION lpProcessInformation
//m_dwProcessID = ProcessInfo.dwProcessId;
// If all is Ok, then return '0' else return the last error code.
return bOk ? 0 : GetLastError();
}<commit_msg>Modifying RhoLaunch to look for Window's ClassName<commit_after>// RhoLaunch.cpp : Defines the entry point for the application.
//
#include "windows.h"
#include "RhoLaunch.h"
#define MAX_LOADSTRING 100
#define PB_WINDOW_RESTORE WM_USER + 10
// Global Functions:
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
COPYDATASTRUCT launchData;
//validate the command line
int iLen = wcslen(lpCmdLine);
if(iLen < 3){
return 1;
}
//LPWSTR pAppName = new WCHAR[iLen + 3];//allow space for the index
LPWSTR pAppName,pTabName,pTemp;
pAppName = pTemp= lpCmdLine;
int iLoop;
bool bStart,bTabStart,bAppName;
bStart = bTabStart = bAppName= false;
for(iLoop = 0;iLoop < iLen ;iLoop++)
{
if(lpCmdLine[iLoop] == L' '){
if(bStart){
if(!bAppName){
*pTemp = NULL;//terminate the app name
pTemp++;
bAppName = true;
pTabName = pTemp;
}
else if(bTabStart){
*pTemp = NULL;//terminate the tab name
break;//finished so exit loop
}
}
continue;//ignore spaces
}
if(lpCmdLine[iLoop] == L'/'){
if(!bStart){
bStart = !bStart;
continue;
}
if(!bAppName){
*pTemp= NULL;
bAppName = !bAppName;
bTabStart = true;
}
if(!bTabStart){
bTabStart = true;
continue;
}
}
*pTemp= lpCmdLine[iLoop];
pTemp++;
}
*pTemp = NULL;
// HWND hwndRunningRE = FindWindow(NULL, pAppName);
// DCC Main Window now has Classname <pAppName>.MainWindow
WCHAR* szClassName = new WCHAR[wcslen(pAppName) + wcslen(L".MainWindow") + 1];
wcscpy(szClassName, pAppName);
wcscat(szClassName, L".MainWindow");
HWND hwndRunningRE = FindWindow(szClassName, NULL);
delete[] szClassName;
if (hwndRunningRE){
// Found the running instance
//rhode expects a MultiByte string so convert
int ilen = wcslen(pTabName);
char *pTabNameMB = new char[ilen+1];
wcstombs(pTabNameMB, pTabName,ilen);
launchData.lpData = pTabNameMB;
launchData.cbData = (ilen+1);
ShowWindow(hwndRunningRE, SW_RESTORE);
SendMessage(hwndRunningRE,PB_WINDOW_RESTORE,(WPARAM) NULL,(LPARAM)TRUE);
//send a message to inform Rho of the requested index
SendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );
delete [] pTabNameMB;
// switch to it
SetForegroundWindow(hwndRunningRE);
}
else{
//no window handle, so try to start the app
//will only work if RhoLaunch is in the same directory as the app
//build the Rho app name
WCHAR pApp[MAX_PATH + 1];
int iIndex,iLen;
if(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){
return 1;//error could not find the path
}
//remove 'RhoLaunch' from the path
for(iIndex = iLen - 1;pApp[iIndex]!=L'\\';iIndex--);
pApp[iIndex+ 1] = NULL;
//LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];
wcscat(pApp,pAppName);
wcscat(pApp,L".exe");
LPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];
wsprintf(pTabCommand,L"/tabname=\"%s\"",pTabName);
LaunchProcess(pApp,pTabCommand);
delete [] pTabCommand;
}
return 0;
}
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)
{
STARTUPINFO StartInfo;
PROCESS_INFORMATION ProcessInfo;
BOOL bOk;
// Reset the contents of the 'Process Information' and 'Start Up' structures.
memset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));
memset( &StartInfo, 0, sizeof( STARTUPINFO));
StartInfo.cb = sizeof( STARTUPINFO);
// Create the 'browser' in a seperate process.
bOk = CreateProcess( pFilePath, // LPCTSTR lpApplicationName,//L"\\program files\\Neon\\BIN\\SVC_Controls.exe",
pCmdLine, // LPTSTR lpCommandLine,
NULL, // LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, // BOOL bInheritHandles,
0, // DWORD dwCreationFlags,
NULL, // LPVOID lpEnvironment,
NULL, // LPCTSTR lpCurrentDirectory,
&StartInfo, // LPSTARTUPINFO lpStartupInfo,
&ProcessInfo); // LPPROCESS_INFORMATION lpProcessInformation
//m_dwProcessID = ProcessInfo.dwProcessId;
// If all is Ok, then return '0' else return the last error code.
return bOk ? 0 : GetLastError();
}<|endoftext|>
|
<commit_before>/*
Steering macro for the Detector/<action> trending
//
// code to check consitency
//
gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/ -I$ALICE_ROOT/include -I$ALICE_ROOT/install/include -I$ALICE_ROOT/STEER\
-I$ALICE_ROOT/TPC -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TRD -I$ALICE_ROOT/TOF -I$ALICE_ROOT/RAW -I$ALICE_ROOT/STAT -I$ALICE_ROOT/TPC/TPCBase -I$ALICE_ROOT/TPC/TPCRec -I$ALICE_ROOT/TPC/TPCCalib -I$ALICE_PHYSICS/../src/PWGPP/TPC/");
.L $ALICE_PHYSICS/../src/PWGPP/QA/scripts/qaTrending.C+
period="LHC15o";
pass="cpass1_pass1";
detector="T0";
referenceDet="ITS;TPC;TRD;TOF";
treeQADet=InitTrees(detector,referenceDet);
treeQADet->SetAlias("tagID","run");
InitSummaryTrending(treeQADet);
*/
#include "TTree.h"
#include "TString.h"
#include "TStatToolkit.h"
#include "AliExternalInfo.h"
#include "TStyle.h"
#include "TROOT.h"
#include "TMultiGraph.h"
#include "TMath.h"
#include "TLegend.h"
TTree * InitTrees(const char * detector, const char * referenceDet); // load QA trees and Sttering tree <det> QA.<Det>, Logbook, Lo
void InitSummaryTrending(TTree * tree); // can be generic ?
void SetDrawStyle(); // setting Defaul draw style
TObjArray * GetTexDescription(TLatex *latex); // should go to base code
void logbookConfig(TTree * tree); // should go to base code
//
// Macro global variables:
//
char * year=0, *period=0, *pass=0;
TTree * treeQADet=0;
std::map<std::string,TTree*> qaMap;
TCanvas *canvasQA=0; // central canvas for QA plots
TObjArray * descriptionQA=0; // descriptionQA of process (time/aliroot/root/pariod/pass/user)
TObjArray* oaMultGr=0; // status bar multigraph
TString statusDescription[3]; // status bra description
//
//
// Drawing configuration can be changed
//
// colors & markers:
Int_t colPosA=kGreen+2; //kRed;
Int_t colPosC=kMagenta+1; //kAzure-4;
Int_t colNegA=kRed; //kRed;//kOrange;
Int_t colNegC=kAzure-4; //kAzure-4;//kGreen;
Int_t colSum=kBlack;
Int_t marA1=21;
Int_t marA2=24;
Int_t marC1=20;
Int_t marC2=25;
Int_t marSum=34;//full cross
Int_t marCorr=31;//snowflake
Float_t markerSize=0.9;
const char * defColors="1;2;4;3;856;616";
const char * defMarkers="21;22;25;26;27;28";
const char * bandColors="1;400;400;632;632;416;416"; // kBlack;kYellow;kYellow;kRed; kRed; kGreeen; kGreen
// shifting of graphs within one run for better visibility:
Float_t sh_gr0=-0.3;
Float_t sh_gr1=-0.1;
Float_t sh_gr2=+0.1;
Float_t sh_gr3=+0.3;
// maximal canvas width
Int_t kMaxCanvasWidth=2500;
// status bar height
Float_t statPadHeight=0.30; //fraction of canvas height (was 0.25 until Aug 2014)
Float_t statPadBotMar=0.40; //bottom margin of pad for run numbers
Int_t padRightMargin=0.07;
void qaTrending(){
}
TTree * InitTrees(const char * detector, const char *referenceDet){
//
// Init tree for given period
// all trees stored in qaMap
// FriendTree added to the master treeQADet
// Currentrly in the code we assume ID="run";
// Bug in root tree ? - in case more than one friend tree set - indeces looks corrupted
// 0.) QA tree per detector Raw+MC (if exist)
// 1.) QA trees per refernce detectors specified by string refDet e.g "TPC;TRD;TOF"
// 2.) Logbook tree per run
// 3.) Logbook tree per run/detector
// 3.) RCT table
// 4.) CPass table
//
// tree is created with addition of friend trees which can be used in queries
// queries as analog to the SQL statement
/*
period="LHC15o"; pass="cpass1_pass1"
*/
::Info("qaTrending::InitTrees::Begin","Detector %s, RefDet=%s",detector, referenceDet);
AliExternalInfo info;
Int_t treeCounter=0;
// Load trees
TObjArray * detArray=TString(referenceDet).Tokenize(";");
Int_t nrefDets=detArray->GetEntries();
TVectorF runCounter(5+nrefDets*2); // <QADet>, <Logbook>, <Logbook.Det>, <MonAlisa>, <CPass>, <QA.RefDet>xnrefDets, <Logbook.RefDet>xnrefDets
//
::Info("qaTrending::InitTrees::End","Laoding trees");
treeQADet = info.GetTreeDataQA(detector,period, pass);
if (!treeQADet){
::Error("qaTrending.InitTrees", "Input QA tree %s not available", detector);
return 0;
}
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
qaMap[TString::Format("QA.%s",detector).Data()]=treeQADet;
//
qaMap["Logbook"]=info.GetTree("Logbook",period,"");
qaMap["Logbook"]->AddFriend(treeQADet,"QADet");
treeQADet->AddFriend(qaMap["Logbook"],"Logbook");
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
//
qaMap["MonALISA.RCT"]=info.GetTree("MonALISA.RCT",period,pass);
qaMap["MonALISA.RCT"]->AddFriend(treeQADet,"QADet");
treeQADet->AddFriend(qaMap["MonALISA.RCT"],"MonALISA.RCT");
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
//
TTree *treeLogbookDetector =info.GetTree("Logbook.detector",period,"");
if (treeLogbookDetector){
if (detArray->GetEntries()>0){
for (Int_t idet=0; idet<detArray->GetEntries(); idet++){
// Load Logbook.RefDet
const char *detName=detArray->At(idet)->GetName();
TTree * treeLog =treeLogbookDetector->CopyTree(TString::Format("detector==\"%s\"",detName).Data());
if (treeLog->GetEntries()<=0){
::Error("qaTrending.InitTrees","Missing Tree Logbook. %s - check the syntax",detName);
}else{
treeLog->BuildIndex("run");
qaMap[TString::Format("Logbook.%s",detName).Data()]=treeLog;
treeLog->AddFriend(treeQADet, "QADet");
treeQADet->AddFriend(treeLog, TString::Format("Logbook.%s",detName).Data());
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
}
// Load QA.RefDet
TTree * treeQARefDet = info.GetTreeDataQA(detName,period, pass);
if (treeQARefDet){
qaMap[TString::Format("QA.%s",detName).Data()]=treeQARefDet;
treeQARefDet->AddFriend(treeQADet, "QADet");
treeQADet->AddFriend(treeQARefDet, TString::Format("QA.%s",detName).Data());
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
}else{
::Error("qaTrending.InitTrees","Missing Tree QA.%s - check the syntax",detName);
}
}
}
}
//
// Check consistency of data
//
::Info("qaTrending::InitTrees::End","Checking trees");
TList *arrFriends = treeQADet->GetListOfFriends();
for (Int_t ifriend=0; ifriend<arrFriends->GetEntries(); ifriend++){
Int_t entries = treeQADet->Draw(TString::Format("run-%s.run", arrFriends->At(ifriend)->GetName()).Data(),"1","goff");
Double_t mean=0;
if (entries>0) {
mean=TMath::Mean(entries, treeQADet->GetV1());
}
if (mean==0){
::Info("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
}else{
::Error("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
}
}
delete detArray;
::Info("qaTrending::InitTrees::End","Detector %s, RefDet=%s",detector, referenceDet);
return treeQADet;
}
void SetDrawStyle(){
//
// Standard drawing style
//
gROOT->SetStyle("Plain");
gStyle->SetPalette(1);
gStyle->SetLabelSize(0.04,"x");
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
}
TObjArray * GetTexDescription(TLatex *latex){
//
//
//
TObjArray * description= new TObjArray();
TString sTimestamp = TString::Format("Creation time:%s",gSystem->GetFromPipe("date").Data());
TString sUser=TString::Format("User:%s",gSystem->GetFromPipe("echo $USER").Data());
TString sPeriod=TString::Format("period:%s",period);
TString sPass=TString::Format("pass:%s",pass);
TString sAlirootVer;
TString sAliphysicsVer;
//TString runStat=
if (gSystem->GetFromPipe("echo $ALICE_VER") == "master" || gSystem->GetFromPipe("echo $ALICE_VER") == ""){
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_ROOT/../src; git describe; cd $wdir;");
}else {
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("echo $ALIROOT_VERSION");
}
if (gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == "master" || gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == ""){
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_PHYSICS/../src; git describe; cd $wdir;");
}else {
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("echo $ALIPHYSICS_VERSION");
}
//
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-2.2*latex->GetTextSize(),sPeriod.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-3.3*latex->GetTextSize(),sPass.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));
return description;
}
void logbookConfig(TTree * tree){
//
//
//
TStatToolkit::AddMetadata(tree,"totalEvents.Title","N_{events}");
TStatToolkit::AddMetadata(tree,"totalEvents.AxisTitle","N_{events}");
TStatToolkit::AddMetadata(tree,"totalEvents.Legend","logbook - N_{events}");
TStatToolkit::AddMetadata(tree,"totalEventsPhysics.Title","N_{phys.ev.}");
TStatToolkit::AddMetadata(tree,"totalEventsPhysics.AxisTitle","N_{phys.ev.}");
TStatToolkit::AddMetadata(tree,"totalEventsPhysics.Legend","logbook - N_{phys.ev.}");
//
TStatToolkit::AddMetadata(tree,"LogbookDet.eventCountPhysics.Title","T0 - N_{events}");
TStatToolkit::AddMetadata(tree,"LogbookT0.eventCountPhysics.AxisTitle","T0 - N_{events}");
TStatToolkit::AddMetadata(tree,"LogbookT0.eventCountPhysics.Legend","T0 - N_{events}");
TStatToolkit::AddMetadata(tree,"LogbookTPC.eventCountPhysics.Title","TPC - N_{events}");
TStatToolkit::AddMetadata(tree,"LogbookTPC.eventCountPhysics.AxisTitle","TPC - N_{events}");
TStatToolkit::AddMetadata(tree,"LogbookTPC.eventCountPhysics.Legend","TPC - N_{events}");
}
void InitSummaryTrending(TTree * tree){
//
// Init drawing for the <detector> QA
// Detector specific qaConfig() has to be called before invoking this function
// 0.) Make descriptor
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
// 3.) compute detector status graphs
//
// 0.) Make descriptor
//
TLatex *latex= new TLatex;
latex->SetX(0.11);
latex->SetY(0.8);
latex->SetTextSize(0.03);
descriptionQA = GetTexDescription(latex);
//
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
//
TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(tree,"resolution:tagID","");
Int_t numberOfTags = gr->GetN();
cout<<"number of graph entries: "<<numberOfTags<<endl;
double SpaceForLegend = 0.;
Int_t canvas_width = SpaceForLegend + (numberOfTags+5)*30;
Int_t canvas_height = 600;
if ( canvas_width>kMaxCanvasWidth) canvas_width=kMaxCanvasWidth;
canvasQA = new TCanvas("canvasQA","canvasQA",canvas_width,canvas_height);
canvasQA->SetGrid(3);
canvasQA->cd();
gPad->SetTicks(1,2);
// canvasQA->SetRightMargin(SpaceForLegend/canvas_width);
double leftlegend = 1 - 180./canvasQA->GetWw();
double rightlegend = 1 - 10./canvasQA->GetWw();
//
// 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
//
TString sStatusbarVars = statusDescription[0];
TString sStatusbarNames = statusDescription[1];
TString sCriteria = statusDescription[2];
cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
cout << "sCriteria = " << sCriteria.Data() << endl;
//
// 3.) compute detector status graphs
//
TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
oaMultGr = new TObjArray();
int igr=0;
for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
oaMultGr->Add( TStatToolkit::MakeStatusMultGr(tree, sVar.Data(), "", sCriteria.Data(), igr) );
TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
((TMultiGraph*) oaMultGr->At(igr))->SetTitle(sYtitle.Data());
igr++;
}
}
<commit_msg> ATO-360 - removing metdata part. Defined in another macro<commit_after>/*
Steering macro for the Detector/<action> trending
//
// code to check consitency
//
gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/ -I$ALICE_ROOT/include -I$ALICE_ROOT/install/include -I$ALICE_ROOT/STEER\
-I$ALICE_ROOT/TPC -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TRD -I$ALICE_ROOT/TOF -I$ALICE_ROOT/RAW -I$ALICE_ROOT/STAT -I$ALICE_ROOT/TPC/TPCBase -I$ALICE_ROOT/TPC/TPCRec -I$ALICE_ROOT/TPC/TPCCalib -I$ALICE_PHYSICS/../src/PWGPP/TPC/");
.L $ALICE_PHYSICS/../src/PWGPP/QA/scripts/qaTrending.C+
period="LHC15o";
pass="cpass1_pass1";
detector="T0";
referenceDet="ITS;TPC;TRD;TOF";
treeQADet=InitTrees(detector,referenceDet);
treeQADet->SetAlias("tagID","run");
InitSummaryTrending(treeQADet);
*/
#include "TTree.h"
#include "TString.h"
#include "TStatToolkit.h"
#include "AliExternalInfo.h"
#include "TStyle.h"
#include "TROOT.h"
#include "TMultiGraph.h"
#include "TMath.h"
#include "TLegend.h"
TTree * InitTrees(const char * detector, const char * referenceDet); // load QA trees and Sttering tree <det> QA.<Det>, Logbook, Lo
void InitSummaryTrending(TTree * tree); // can be generic ?
void SetDrawStyle(); // setting Default draw style
TObjArray * GetTexDescription(TLatex *latex); // should go to base code
//
// Macro global variables:
//
char * year=0, *period=0, *pass=0;
TTree * treeQADet=0;
std::map<std::string,TTree*> qaMap;
TCanvas *canvasQA=0; // central canvas for QA plots
TObjArray * descriptionQA=0; // descriptionQA of process (time/aliroot/root/pariod/pass/user)
TObjArray* oaMultGr=0; // status bar multigraph
TString statusDescription[3]; // status bar description
//
//
// Drawing configuration can be changed
//
// colors & markers:
Int_t colPosA=kGreen+2; //kRed;
Int_t colPosC=kMagenta+1; //kAzure-4;
Int_t colNegA=kRed; //kRed;//kOrange;
Int_t colNegC=kAzure-4; //kAzure-4;//kGreen;
Int_t colSum=kBlack;
Int_t marA1=21;
Int_t marA2=24;
Int_t marC1=20;
Int_t marC2=25;
Int_t marSum=34;//full cross
Int_t marCorr=31;//snowflake
Float_t markerSize=0.9;
const char * defColors="1;2;4;3;856;616";
const char * defMarkers="21;22;25;26;27;28";
const char * bandColors="1;400;400;632;632;416;416"; // kBlack;kYellow;kYellow;kRed; kRed; kGreeen; kGreen
// shifting of graphs within one run for better visibility:
Float_t sh_gr0=-0.3;
Float_t sh_gr1=-0.1;
Float_t sh_gr2=+0.1;
Float_t sh_gr3=+0.3;
// maximal canvas width
Int_t kMaxCanvasWidth=2500;
// status bar height
Float_t statPadHeight=0.30; //fraction of canvas height (was 0.25 until Aug 2014)
Float_t statPadBotMar=0.40; //bottom margin of pad for run numbers
Int_t padRightMargin=0.07;
void qaTrending(){
}
TTree * InitTrees(const char * detector, const char *referenceDet){
//
// Init tree for given period
// all trees stored in qaMap
// FriendTree added to the master treeQADet
// Currentrly in the code we assume ID="run";
// Bug in root tree ? - in case more than one friend tree set - indeces looks corrupted
// 0.) QA tree per detector Raw+MC (if exist)
// 1.) QA trees per refernce detectors specified by string refDet e.g "TPC;TRD;TOF"
// 2.) Logbook tree per run
// 3.) Logbook tree per run/detector
// 3.) RCT table
// 4.) CPass table
//
// tree is created with addition of friend trees which can be used in queries
// queries as analog to the SQL statement
/*
period="LHC15o"; pass="cpass1_pass1"
*/
::Info("qaTrending::InitTrees::Begin","Detector %s, RefDet=%s",detector, referenceDet);
AliExternalInfo info;
Int_t treeCounter=0;
// Load trees
TObjArray * detArray=TString(referenceDet).Tokenize(";");
Int_t nrefDets=detArray->GetEntries();
TVectorF runCounter(5+nrefDets*2); // <QADet>, <Logbook>, <Logbook.Det>, <MonAlisa>, <CPass>, <QA.RefDet>xnrefDets, <Logbook.RefDet>xnrefDets
//
::Info("qaTrending::InitTrees::End","Laoding trees");
treeQADet = info.GetTreeDataQA(detector,period, pass);
if (!treeQADet){
::Error("qaTrending.InitTrees", "Input QA tree %s not available", detector);
return 0;
}
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
qaMap[TString::Format("QA.%s",detector).Data()]=treeQADet;
//
qaMap["Logbook"]=info.GetTree("Logbook",period,"");
qaMap["Logbook"]->AddFriend(treeQADet,"QADet");
treeQADet->AddFriend(qaMap["Logbook"],"Logbook");
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
//
qaMap["MonALISA.RCT"]=info.GetTree("MonALISA.RCT",period,pass);
qaMap["MonALISA.RCT"]->AddFriend(treeQADet,"QADet");
treeQADet->AddFriend(qaMap["MonALISA.RCT"],"MonALISA.RCT");
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
//
TTree *treeLogbookDetector =info.GetTree("Logbook.detector",period,"");
if (treeLogbookDetector){
if (detArray->GetEntries()>0){
for (Int_t idet=0; idet<detArray->GetEntries(); idet++){
// Load Logbook.RefDet
const char *detName=detArray->At(idet)->GetName();
TTree * treeLog =treeLogbookDetector->CopyTree(TString::Format("detector==\"%s\"",detName).Data());
if (treeLog->GetEntries()<=0){
::Error("qaTrending.InitTrees","Missing Tree Logbook. %s - check the syntax",detName);
}else{
treeLog->BuildIndex("run");
qaMap[TString::Format("Logbook.%s",detName).Data()]=treeLog;
treeLog->AddFriend(treeQADet, "QADet");
treeQADet->AddFriend(treeLog, TString::Format("Logbook.%s",detName).Data());
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
}
// Load QA.RefDet
TTree * treeQARefDet = info.GetTreeDataQA(detName,period, pass);
if (treeQARefDet){
qaMap[TString::Format("QA.%s",detName).Data()]=treeQARefDet;
treeQARefDet->AddFriend(treeQADet, "QADet");
treeQADet->AddFriend(treeQARefDet, TString::Format("QA.%s",detName).Data());
runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
}else{
::Error("qaTrending.InitTrees","Missing Tree QA.%s - check the syntax",detName);
}
}
}
}
//
// Check consistency of data
//
::Info("qaTrending::InitTrees::End","Checking trees");
TList *arrFriends = treeQADet->GetListOfFriends();
for (Int_t ifriend=0; ifriend<arrFriends->GetEntries(); ifriend++){
Int_t entries = treeQADet->Draw(TString::Format("run-%s.run", arrFriends->At(ifriend)->GetName()).Data(),"1","goff");
Double_t mean=0;
if (entries>0) {
mean=TMath::Mean(entries, treeQADet->GetV1());
}
if (mean==0){
::Info("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
}else{
::Error("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
}
}
delete detArray;
::Info("qaTrending::InitTrees::End","Detector %s, RefDet=%s",detector, referenceDet);
return treeQADet;
}
void SetDrawStyle(){
//
// Standard drawing style
//
gROOT->SetStyle("Plain");
gStyle->SetPalette(1);
gStyle->SetLabelSize(0.04,"x");
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
}
TObjArray * GetTexDescription(TLatex *latex){
//
//
//
TObjArray * description= new TObjArray();
TString sTimestamp = TString::Format("Creation time:%s",gSystem->GetFromPipe("date").Data());
TString sUser=TString::Format("User:%s",gSystem->GetFromPipe("echo $USER").Data());
TString sPeriod=TString::Format("period:%s",period);
TString sPass=TString::Format("pass:%s",pass);
TString sAlirootVer;
TString sAliphysicsVer;
//TString runStat=
if (gSystem->GetFromPipe("echo $ALICE_VER") == "master" || gSystem->GetFromPipe("echo $ALICE_VER") == ""){
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_ROOT/../src; git describe; cd $wdir;");
}else {
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("echo $ALIROOT_VERSION");
}
if (gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == "master" || gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == ""){
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_PHYSICS/../src; git describe; cd $wdir;");
}else {
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("echo $ALIPHYSICS_VERSION");
}
//
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-2.2*latex->GetTextSize(),sPeriod.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-3.3*latex->GetTextSize(),sPass.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));
return description;
}
void InitSummaryTrending(TTree * tree){
//
// Init drawing for the <detector> QA
// Detector specific qaConfig() has to be called before invoking this function
// 0.) Make descriptor
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
// 3.) compute detector status graphs
//
// 0.) Make descriptor
//
TLatex *latex= new TLatex;
latex->SetX(0.11);
latex->SetY(0.8);
latex->SetTextSize(0.03);
descriptionQA = GetTexDescription(latex);
//
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
//
TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(tree,"resolution:tagID","");
Int_t numberOfTags = gr->GetN();
cout<<"number of graph entries: "<<numberOfTags<<endl;
double SpaceForLegend = 0.;
Int_t canvas_width = SpaceForLegend + (numberOfTags+5)*30;
Int_t canvas_height = 600;
if ( canvas_width>kMaxCanvasWidth) canvas_width=kMaxCanvasWidth;
canvasQA = new TCanvas("canvasQA","canvasQA",canvas_width,canvas_height);
canvasQA->SetGrid(3);
canvasQA->cd();
gPad->SetTicks(1,2);
// canvasQA->SetRightMargin(SpaceForLegend/canvas_width);
double leftlegend = 1 - 180./canvasQA->GetWw();
double rightlegend = 1 - 10./canvasQA->GetWw();
//
// 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
//
TString sStatusbarVars = statusDescription[0];
TString sStatusbarNames = statusDescription[1];
TString sCriteria = statusDescription[2];
cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
cout << "sCriteria = " << sCriteria.Data() << endl;
//
// 3.) compute detector status graphs
//
TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
oaMultGr = new TObjArray();
int igr=0;
for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
oaMultGr->Add( TStatToolkit::MakeStatusMultGr(tree, sVar.Data(), "", sCriteria.Data(), igr) );
TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
((TMultiGraph*) oaMultGr->At(igr))->SetTitle(sYtitle.Data());
igr++;
}
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*/
#ifndef PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_
#define PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_
#include "pcl/features/multiscale_feature_persistence.h"
template <typename PointSource, typename PointFeature>
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::MultiscaleFeaturePersistence ()
: distance_metric_ (MANHATTAN),
feature_estimator_ ()
{
feature_representation_.reset (new DefaultPointRepresentation<PointFeature>);
// No input is needed, hack around the initCompute () check from PCLBase
input_.reset (new PointCloud<PointSource> ());
};
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> bool
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::initCompute ()
{
if (!PCLBase<PointSource>::initCompute ())
{
PCL_ERROR ("[pcl::MultiscaleFeaturePersistence::initCompute] PCLBase::initCompute () failed - no input cloud was given.\n");
return false;
}
if (!feature_estimator_)
{
PCL_ERROR ("[pcl::MultiscaleFeaturePersistence::initCompute] No feature estimator was set\n");
return false;
}
if (scale_values_.empty ())
{
PCL_ERROR ("[pcl::MultiscaleFeaturePersistence::initCompute] No scale values were given\n");
return false;
}
mean_feature.resize (feature_representation_->getNumberOfDimensions ());
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeaturesAtAllScales ()
{
features_at_scale.resize (scale_values_.size ());
features_at_scale_vectorized.resize (scale_values_.size ());
for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i)
{
FeatureCloudPtr feature_cloud (new FeatureCloud ());
computeFeatureAtScale (scale_values_[scale_i], feature_cloud);
features_at_scale[scale_i] = feature_cloud;
// Vectorize each feature and insert it into the vectorized feature storage
std::vector<std::vector<float> > feature_cloud_vectorized (feature_cloud->points.size ());
for (size_t feature_i = 0; feature_i < feature_cloud->points.size (); ++feature_i)
{
std::vector<float> feature_vectorized (feature_representation_->getNumberOfDimensions ());
feature_representation_->vectorize (feature_cloud->points[feature_i], feature_vectorized);
feature_cloud_vectorized[feature_i] = feature_vectorized;
}
features_at_scale_vectorized[scale_i] = feature_cloud_vectorized;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeatureAtScale (float &scale,
FeatureCloudPtr &features)
{
feature_estimator_->setRadiusSearch (scale);
feature_estimator_->compute (*features);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> float
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::distanceBetweenFeatures (const std::vector<float> &a,
const std::vector<float> &b)
{
float dist = 0.0f;
switch (distance_metric_)
{
case (MANHATTAN):
{
for (size_t i = 0; i < a.size (); ++i)
dist += fabs (a[i] - b[i]);
break;
}
case (EUCLIDEAN):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (a[i] - b[i]) * (a[i] - b[i]);
dist = sqrt (dist);
break;
}
case (JEFFRIES_MATUSITA):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (sqrt ( fabs (a[i])) - sqrt ( fabs (b[i]))) * (sqrt (fabs (a[i])) - sqrt ( fabs (b[i])));
dist = sqrt (dist);
break;
}
case (BHATTACHARYYA):
{
for (size_t i = 0; i < a.size (); ++i)
dist += sqrt (fabs (a[i] - b[i]));
dist = -log (dist);
break;
}
case (CHI_SQUARE):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]);
break;
}
case (KL_DIVERGENCE):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (a[i] - b[i]) * log (a[i] / b[i]);
break;
}
}
return dist;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::calculateMeanFeature ()
{
// Reset mean feature
for (int i = 0; i < feature_representation_->getNumberOfDimensions (); ++i)
mean_feature[i] = 0.0f;
float normalization_factor = 0.0f;
for (std::vector<std::vector<std::vector<float> > >::iterator scale_it = features_at_scale_vectorized.begin (); scale_it != features_at_scale_vectorized.end(); ++scale_it) {
normalization_factor += scale_it->size ();
for (std::vector<std::vector<float> >::iterator feature_it = scale_it->begin (); feature_it != scale_it->end (); ++feature_it)
for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)
mean_feature[dim_i] += (*feature_it)[dim_i];
}
for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)
mean_feature[dim_i] /= normalization_factor;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::extractUniqueFeatures ()
{
unique_features_indices.resize (scale_values_.size ());
unique_features_table.resize (scale_values_.size ());
for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size (); ++scale_i)
{
// Calculate standard deviation within the scale
float standard_dev = 0.0;
std::vector<float> diff_vector (features_at_scale_vectorized[scale_i].size ());
for (size_t point_i = 0; point_i < features_at_scale_vectorized[scale_i].size (); ++point_i)
{
float diff = distanceBetweenFeatures (features_at_scale_vectorized[scale_i][point_i], mean_feature);
standard_dev += diff * diff;
diff_vector[point_i] = diff;
}
standard_dev = sqrt (standard_dev / features_at_scale_vectorized[scale_i].size ());
PCL_INFO("Standard deviation for scale %f is %f\n", scale_values_[scale_i], standard_dev);
// Select only points outside (mean +/- alpha * standard_dev)
std::list<size_t> indices_per_scale;
std::vector<bool> indices_table_per_scale (features_at_scale[scale_i]->points.size (), false);
for (size_t point_i = 0; point_i < features_at_scale[scale_i]->points.size (); ++point_i)
{
if (diff_vector[point_i] > alpha_ * standard_dev)
{
indices_per_scale.push_back (point_i);
indices_table_per_scale[point_i] = true;
}
}
unique_features_indices[scale_i] = indices_per_scale;
unique_features_table[scale_i] = indices_table_per_scale;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::determinePersistentFeatures (FeatureCloud &output_features,
boost::shared_ptr<std::vector<int> > &output_indices)
{
if (!initCompute ())
return;
// Compute the features for all scales with the given feature estimator
computeFeaturesAtAllScales ();
// Compute mean feature
calculateMeanFeature ();
// Get the 'unique' features at each scale
extractUniqueFeatures ();
// Determine persistent features between scales
/*
// Method 1: a feature is considered persistent if it is 'unique' in at least 2 different scales
for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size () - 1; ++scale_i)
for (std::list<size_t>::iterator feature_it = unique_features_indices[scale_i].begin (); feature_it != unique_features_indices[scale_i].end (); ++feature_it)
{
if (unique_features_table[scale_i][*feature_it] == true)
{
output_features.points.push_back (features_at_scale[scale_i]->points[*feature_it]);
output_indices->push_back (*feature_it);
}
}
*/
// Method 2: a feature is considered persistent if it is 'unique' in all the scales
for (std::list<size_t>::iterator feature_it = unique_features_indices.front ().begin (); feature_it != unique_features_indices.front ().end (); ++feature_it)
{
bool present_in_all = true;
for (size_t scale_i = 0; scale_i < features_at_scale.size (); ++scale_i)
present_in_all = present_in_all && unique_features_table[scale_i][*feature_it];
if (present_in_all)
{
output_features.points.push_back (features_at_scale.front ()->points[*feature_it]);
output_indices->push_back (*feature_it);
}
}
// Consider that output cloud is unorganized
output_features.header = feature_estimator_->getInputCloud ()->header;
output_features.is_dense = feature_estimator_->getInputCloud ()->is_dense;
output_features.width = output_features.points.size ();
output_features.height = 1;
}
#define PCL_INSTANTIATE_MultiscaleFeaturePersistence(InT, Feature) template class PCL_EXPORTS pcl::MultiscaleFeaturePersistence<InT, Feature>;
#endif /* PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_ */
<commit_msg>MSVC fix(?)<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*/
#ifndef PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_
#define PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_
#include "pcl/features/multiscale_feature_persistence.h"
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature>
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::MultiscaleFeaturePersistence ()
: distance_metric_ (MANHATTAN),
feature_estimator_ ()
{
feature_representation_.reset (new DefaultPointRepresentation<PointFeature>);
// No input is needed, hack around the initCompute () check from PCLBase
input_.reset (new pcl::PointCloud<PointSource> ());
};
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> bool
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::initCompute ()
{
if (!PCLBase<PointSource>::initCompute ())
{
PCL_ERROR ("[pcl::MultiscaleFeaturePersistence::initCompute] PCLBase::initCompute () failed - no input cloud was given.\n");
return false;
}
if (!feature_estimator_)
{
PCL_ERROR ("[pcl::MultiscaleFeaturePersistence::initCompute] No feature estimator was set\n");
return false;
}
if (scale_values_.empty ())
{
PCL_ERROR ("[pcl::MultiscaleFeaturePersistence::initCompute] No scale values were given\n");
return false;
}
mean_feature.resize (feature_representation_->getNumberOfDimensions ());
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeaturesAtAllScales ()
{
features_at_scale.resize (scale_values_.size ());
features_at_scale_vectorized.resize (scale_values_.size ());
for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i)
{
FeatureCloudPtr feature_cloud (new FeatureCloud ());
computeFeatureAtScale (scale_values_[scale_i], feature_cloud);
features_at_scale[scale_i] = feature_cloud;
// Vectorize each feature and insert it into the vectorized feature storage
std::vector<std::vector<float> > feature_cloud_vectorized (feature_cloud->points.size ());
for (size_t feature_i = 0; feature_i < feature_cloud->points.size (); ++feature_i)
{
std::vector<float> feature_vectorized (feature_representation_->getNumberOfDimensions ());
feature_representation_->vectorize (feature_cloud->points[feature_i], feature_vectorized);
feature_cloud_vectorized[feature_i] = feature_vectorized;
}
features_at_scale_vectorized[scale_i] = feature_cloud_vectorized;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeatureAtScale (float &scale,
FeatureCloudPtr &features)
{
feature_estimator_->setRadiusSearch (scale);
feature_estimator_->compute (*features);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> float
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::distanceBetweenFeatures (const std::vector<float> &a,
const std::vector<float> &b)
{
float dist = 0.0f;
switch (distance_metric_)
{
case (MANHATTAN):
{
for (size_t i = 0; i < a.size (); ++i)
dist += fabs (a[i] - b[i]);
break;
}
case (EUCLIDEAN):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (a[i] - b[i]) * (a[i] - b[i]);
dist = sqrt (dist);
break;
}
case (JEFFRIES_MATUSITA):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (sqrt ( fabs (a[i])) - sqrt ( fabs (b[i]))) * (sqrt (fabs (a[i])) - sqrt ( fabs (b[i])));
dist = sqrt (dist);
break;
}
case (BHATTACHARYYA):
{
for (size_t i = 0; i < a.size (); ++i)
dist += sqrt (fabs (a[i] - b[i]));
dist = -log (dist);
break;
}
case (CHI_SQUARE):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (a[i] - b[i]) * (a[i] - b[i]) / (a[i] + b[i]);
break;
}
case (KL_DIVERGENCE):
{
for (size_t i = 0; i < a.size (); ++i)
dist += (a[i] - b[i]) * log (a[i] / b[i]);
break;
}
}
return dist;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::calculateMeanFeature ()
{
// Reset mean feature
for (int i = 0; i < feature_representation_->getNumberOfDimensions (); ++i)
mean_feature[i] = 0.0f;
float normalization_factor = 0.0f;
for (std::vector<std::vector<std::vector<float> > >::iterator scale_it = features_at_scale_vectorized.begin (); scale_it != features_at_scale_vectorized.end(); ++scale_it) {
normalization_factor += scale_it->size ();
for (std::vector<std::vector<float> >::iterator feature_it = scale_it->begin (); feature_it != scale_it->end (); ++feature_it)
for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)
mean_feature[dim_i] += (*feature_it)[dim_i];
}
for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)
mean_feature[dim_i] /= normalization_factor;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::extractUniqueFeatures ()
{
unique_features_indices.resize (scale_values_.size ());
unique_features_table.resize (scale_values_.size ());
for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size (); ++scale_i)
{
// Calculate standard deviation within the scale
float standard_dev = 0.0;
std::vector<float> diff_vector (features_at_scale_vectorized[scale_i].size ());
for (size_t point_i = 0; point_i < features_at_scale_vectorized[scale_i].size (); ++point_i)
{
float diff = distanceBetweenFeatures (features_at_scale_vectorized[scale_i][point_i], mean_feature);
standard_dev += diff * diff;
diff_vector[point_i] = diff;
}
standard_dev = sqrt (standard_dev / features_at_scale_vectorized[scale_i].size ());
PCL_INFO("Standard deviation for scale %f is %f\n", scale_values_[scale_i], standard_dev);
// Select only points outside (mean +/- alpha * standard_dev)
std::list<size_t> indices_per_scale;
std::vector<bool> indices_table_per_scale (features_at_scale[scale_i]->points.size (), false);
for (size_t point_i = 0; point_i < features_at_scale[scale_i]->points.size (); ++point_i)
{
if (diff_vector[point_i] > alpha_ * standard_dev)
{
indices_per_scale.push_back (point_i);
indices_table_per_scale[point_i] = true;
}
}
unique_features_indices[scale_i] = indices_per_scale;
unique_features_table[scale_i] = indices_table_per_scale;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointFeature> void
pcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::determinePersistentFeatures (FeatureCloud &output_features,
boost::shared_ptr<std::vector<int> > &output_indices)
{
if (!initCompute ())
return;
// Compute the features for all scales with the given feature estimator
computeFeaturesAtAllScales ();
// Compute mean feature
calculateMeanFeature ();
// Get the 'unique' features at each scale
extractUniqueFeatures ();
// Determine persistent features between scales
/*
// Method 1: a feature is considered persistent if it is 'unique' in at least 2 different scales
for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size () - 1; ++scale_i)
for (std::list<size_t>::iterator feature_it = unique_features_indices[scale_i].begin (); feature_it != unique_features_indices[scale_i].end (); ++feature_it)
{
if (unique_features_table[scale_i][*feature_it] == true)
{
output_features.points.push_back (features_at_scale[scale_i]->points[*feature_it]);
output_indices->push_back (*feature_it);
}
}
*/
// Method 2: a feature is considered persistent if it is 'unique' in all the scales
for (std::list<size_t>::iterator feature_it = unique_features_indices.front ().begin (); feature_it != unique_features_indices.front ().end (); ++feature_it)
{
bool present_in_all = true;
for (size_t scale_i = 0; scale_i < features_at_scale.size (); ++scale_i)
present_in_all = present_in_all && unique_features_table[scale_i][*feature_it];
if (present_in_all)
{
output_features.points.push_back (features_at_scale.front ()->points[*feature_it]);
output_indices->push_back (*feature_it);
}
}
// Consider that output cloud is unorganized
output_features.header = feature_estimator_->getInputCloud ()->header;
output_features.is_dense = feature_estimator_->getInputCloud ()->is_dense;
output_features.width = output_features.points.size ();
output_features.height = 1;
}
#define PCL_INSTANTIATE_MultiscaleFeaturePersistence(InT, Feature) template class PCL_EXPORTS pcl::MultiscaleFeaturePersistence<InT, Feature>;
#endif /* PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_ */
<|endoftext|>
|
<commit_before>#include "systemGenerator.h"
#include <generatorBase/generatorCustomizer.h>
using namespace trik::simple;
using namespace generatorBase::simple;
SystemGenerator::SystemGenerator(qrRepo::RepoApi const &repo
, generatorBase::GeneratorCustomizer &customizer
, qReal::Id const &id
, QObject *parent)
: BindingGenerator(repo, customizer, id
, repo.property(id, "Code").toBool() ? "system.t" : "nativeCode.t"
, QList<Binding *>()
<< Binding::createDirect("@@COMMAND@@", "Command")
, parent)
{
}
<commit_msg>Fixed inverted "Code" value in System Call block<commit_after>#include "systemGenerator.h"
#include <generatorBase/generatorCustomizer.h>
using namespace trik::simple;
using namespace generatorBase::simple;
SystemGenerator::SystemGenerator(qrRepo::RepoApi const &repo
, generatorBase::GeneratorCustomizer &customizer
, qReal::Id const &id
, QObject *parent)
: BindingGenerator(repo, customizer, id
, repo.property(id, "Code").toBool() ? "nativeCode.t" : "system.t"
, QList<Binding *>()
<< Binding::createDirect("@@COMMAND@@", "Command")
, parent)
{
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/utilities.h>
#include <base/exceptions.h>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <cerrno>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#ifdef HAVE_STD_STRINGSTREAM
# include <sstream>
#else
# include <strstream>
#endif
#ifdef HAVE_STD_NUMERIC_LIMITS
# include <limits>
#else
# include <limits.h>
#endif
namespace Utilities
{
DeclException2 (ExcInvalidNumber2StringConversersion,
unsigned int, unsigned int,
<< "When trying to convert " << arg1
<< " to a string with " << arg2 << " digits");
DeclException1 (ExcInvalidNumber,
unsigned int,
<< "Invalid number " << arg1);
DeclException1 (ExcCantConvertString,
std::string,
<< "Can't convert the string " << arg1
<< " to the desired type");
std::string
int_to_string (const unsigned int i,
const unsigned int digits)
{
AssertThrow ( ! ((digits==1 && i>=10) ||
(digits==2 && i>=100) ||
(digits==3 && i>=1000) ||
(digits==4 && i>=10000)||
(i>=100000)),
ExcInvalidNumber2StringConversersion(i, digits));
std::string s;
switch (digits)
{
case 4:
s += '0' + i/1000;
case 3:
s += '0' + (i%1000)/100;
case 2:
s += '0' + (i%100)/10;
case 1:
s += '0' + i%10;
break;
default:
s += "invalid digits information";
};
return s;
}
unsigned int
needed_digits (const unsigned int max_number)
{
if (max_number < 10)
return 1;
if (max_number < 100)
return 2;
if (max_number < 1000)
return 3;
if (max_number < 10000)
return 4;
if (max_number < 100000)
return 5;
if (max_number < 1000000)
return 6;
AssertThrow (false, ExcInvalidNumber(max_number));
return 0;
}
int
string_to_int (const std::string &s)
{
#ifdef HAVE_STD_STRINGSTREAM
std::istringstream ss(s);
#else
std::ostrstream ss(s.c_str());
#endif
#ifdef HAVE_STD_NUMERIC_LIMITS
static const int max_int = std::numeric_limits<int>::max();
#else
static const int max_int = INT_MAX;
#endif
int i = max_int;
ss >> i;
// check for errors
AssertThrow (i != max_int, ExcCantConvertString (s));
return i;
}
std::vector<int>
string_to_int (const std::vector<std::string> &s)
{
std::vector<int> tmp (s.size());
for (unsigned int i=0; i<s.size(); ++i)
tmp[i] = string_to_int (s[i]);
return tmp;
}
std::vector<std::string>
split_string_list (const std::string &s,
const char delimiter)
{
std::string tmp = s;
std::vector<std::string> split_list;
split_list.reserve (std::count (tmp.begin(), tmp.end(), delimiter)+1);
// split the input list
while (tmp.length() != 0)
{
std::string name;
name = tmp;
if (name.find(delimiter) != std::string::npos)
{
name.erase (name.find(delimiter), std::string::npos);
tmp.erase (0, tmp.find(delimiter)+1);
}
else
tmp = "";
while ((name.length() != 0) &&
(name[0] == ' '))
name.erase (0,1);
while (name[name.length()-1] == ' ')
name.erase (name.length()-1, 1);
split_list.push_back (name);
}
return split_list;
}
double
generate_normal_random_number (const double a,
const double sigma)
{
// if no noise: return now
if (sigma == 0)
return a;
#ifdef HAVE_RAND_R
static unsigned int seed = 0xabcd1234;
const double y = 1.0*rand_r(&seed)/RAND_MAX;
#else
const double y = 1.0*rand()/RAND_MAX;
#endif
// find x such that y=erf(x). do so
// using a Newton method to find
// the zero of F(x)=erf(x)-y. start
// at x=0
double x = 0;
unsigned int iteration = 0;
while (true)
{
const double residual = 0.5+erf(x/std::sqrt(2.)/sigma)/2-y;
if (std::fabs(residual) < 1e-7)
break;
const double F_prime = 1./std::sqrt(2*3.1415926536)/sigma *
std::exp(-x*x/sigma/sigma/2);
x += -residual / F_prime;
// make sure that we don't
// recurse endlessly
++iteration;
Assert (iteration < 20, ExcInternalError());
};
return x+a;
}
namespace System
{
#if defined(__linux__)
double get_cpu_load ()
{
std::ifstream cpuinfo;
cpuinfo.open("/proc/loadavg");
AssertThrow(cpuinfo, ExcIO());
double load;
cpuinfo >> load;
return load;
}
#else
double get_cpu_load ()
{
return 0.;
}
#endif
std::string get_hostname ()
{
const unsigned int N=1024;
char hostname[N];
gethostname (&(hostname[0]), N-1);
return hostname;
}
std::string get_time ()
{
std::time_t time1= std::time (0);
std::tm *time = std::localtime(&time1);
#ifdef HAVE_STD_STRINGSTREAM
std::ostringstream o;
#else
std::ostrstream o;
#endif
o << time->tm_hour << ":"
<< (time->tm_min < 10 ? "0" : "") << time->tm_min << ":"
<< (time->tm_sec < 10 ? "0" : "") << time->tm_sec;
#ifndef HAVE_STD_STRINGSTREAM
o << std::ends;
#endif
return o.str();
}
}
}
<commit_msg>Use the has_documentation flag.<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/utilities.h>
#include <base/exceptions.h>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <cerrno>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#ifdef HAVE_STD_STRINGSTREAM
# include <sstream>
#else
# include <strstream>
#endif
#ifdef HAVE_STD_NUMERIC_LIMITS
# include <limits>
#else
# include <limits.h>
#endif
namespace Utilities
{
DeclException2 (ExcInvalidNumber2StringConversersion,
unsigned int, unsigned int,
<< "When trying to convert " << arg1
<< " to a string with " << arg2 << " digits");
DeclException1 (ExcInvalidNumber,
unsigned int,
<< "Invalid number " << arg1);
DeclException1 (ExcCantConvertString,
std::string,
<< "Can't convert the string " << arg1
<< " to the desired type");
std::string
int_to_string (const unsigned int i,
const unsigned int digits)
{
AssertThrow ( ! ((digits==1 && i>=10) ||
(digits==2 && i>=100) ||
(digits==3 && i>=1000) ||
(digits==4 && i>=10000)||
(i>=100000)),
ExcInvalidNumber2StringConversersion(i, digits));
std::string s;
switch (digits)
{
case 4:
s += '0' + i/1000;
case 3:
s += '0' + (i%1000)/100;
case 2:
s += '0' + (i%100)/10;
case 1:
s += '0' + i%10;
break;
default:
s += "invalid digits information";
};
return s;
}
unsigned int
needed_digits (const unsigned int max_number)
{
if (max_number < 10)
return 1;
if (max_number < 100)
return 2;
if (max_number < 1000)
return 3;
if (max_number < 10000)
return 4;
if (max_number < 100000)
return 5;
if (max_number < 1000000)
return 6;
AssertThrow (false, ExcInvalidNumber(max_number));
return 0;
}
int
string_to_int (const std::string &s)
{
#ifdef HAVE_STD_STRINGSTREAM
std::istringstream ss(s);
#else
std::ostrstream ss(s.c_str());
#endif
#ifdef HAVE_STD_NUMERIC_LIMITS
static const int max_int = std::numeric_limits<int>::max();
#else
static const int max_int = INT_MAX;
#endif
int i = max_int;
ss >> i;
// check for errors
AssertThrow (i != max_int, ExcCantConvertString (s));
return i;
}
std::vector<int>
string_to_int (const std::vector<std::string> &s)
{
std::vector<int> tmp (s.size());
for (unsigned int i=0; i<s.size(); ++i)
tmp[i] = string_to_int (s[i]);
return tmp;
}
std::vector<std::string>
split_string_list (const std::string &s,
const char delimiter)
{
std::string tmp = s;
std::vector<std::string> split_list;
split_list.reserve (std::count (tmp.begin(), tmp.end(), delimiter)+1);
// split the input list
while (tmp.length() != 0)
{
std::string name;
name = tmp;
if (name.find(delimiter) != std::string::npos)
{
name.erase (name.find(delimiter), std::string::npos);
tmp.erase (0, tmp.find(delimiter)+1);
}
else
tmp = "";
while ((name.length() != 0) &&
(name[0] == ' '))
name.erase (0,1);
while (name[name.length()-1] == ' ')
name.erase (name.length()-1, 1);
split_list.push_back (name);
}
return split_list;
}
std::vector<std::string>
break_text_into_lines (const std::string &original_text,
const unsigned int width)
{
std::string text = original_text;
std::vector<std::string> lines;
// remove trailing spaces
while ((text.length() != 0) && (text[text.length()-1] == ' '))
text.erase(text.length()-1,1);
// then split the text into lines
while (text.length() != 0)
{
// in each iteration, first remove
// leading spaces
while ((text.length() != 0) && (text[0] == ' '))
text.erase(0, 1);
// if we can fit everything into one
// line, then do so. otherwise, we have
// to keep breaking
if (text.length() < width)
{
lines.push_back (text);
text = "";
}
else
{
// starting at position width, find the
// location of the previous space, so
// that we can break around there
int location = std::min(width,text.length()-1);
for (; location>=0; --location)
if (text[location] == ' ')
break;
// if there are no spaces, then try if
// there are spaces coming up
if (location == 0)
for (location = std::min(width,text.length()-1);
location<static_cast<int>(text.length());
++location)
if (text[location] == ' ')
break;
// now take the text up to the found
// location and put it into a single
// line, and remove it from 'text'
lines.push_back (std::string (text, 0, location));
text.erase (0, location);
}
}
return lines;
}
double
generate_normal_random_number (const double a,
const double sigma)
{
// if no noise: return now
if (sigma == 0)
return a;
#ifdef HAVE_RAND_R
static unsigned int seed = 0xabcd1234;
const double y = 1.0*rand_r(&seed)/RAND_MAX;
#else
const double y = 1.0*rand()/RAND_MAX;
#endif
// find x such that y=erf(x). do so
// using a Newton method to find
// the zero of F(x)=erf(x)-y. start
// at x=0
double x = 0;
unsigned int iteration = 0;
while (true)
{
const double residual = 0.5+erf(x/std::sqrt(2.)/sigma)/2-y;
if (std::fabs(residual) < 1e-7)
break;
const double F_prime = 1./std::sqrt(2*3.1415926536)/sigma *
std::exp(-x*x/sigma/sigma/2);
x += -residual / F_prime;
// make sure that we don't
// recurse endlessly
++iteration;
Assert (iteration < 20, ExcInternalError());
};
return x+a;
}
namespace System
{
#if defined(__linux__)
double get_cpu_load ()
{
std::ifstream cpuinfo;
cpuinfo.open("/proc/loadavg");
AssertThrow(cpuinfo, ExcIO());
double load;
cpuinfo >> load;
return load;
}
#else
double get_cpu_load ()
{
return 0.;
}
#endif
std::string get_hostname ()
{
const unsigned int N=1024;
char hostname[N];
gethostname (&(hostname[0]), N-1);
return hostname;
}
std::string get_time ()
{
std::time_t time1= std::time (0);
std::tm *time = std::localtime(&time1);
#ifdef HAVE_STD_STRINGSTREAM
std::ostringstream o;
#else
std::ostrstream o;
#endif
o << time->tm_hour << ":"
<< (time->tm_min < 10 ? "0" : "") << time->tm_min << ":"
<< (time->tm_sec < 10 ? "0" : "") << time->tm_sec;
#ifndef HAVE_STD_STRINGSTREAM
o << std::ends;
#endif
return o.str();
}
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/framework/gradient_checker.h"
#include "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/framework/testutil.h"
#include "tensorflow/cc/gradients/grad_testutil.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
namespace {
using namespace ops; // NOLINT(build/namespaces)
class ResourceVariableGradTest : public ::testing::Test {
protected:
ResourceVariableGradTest() : scope_(Scope::NewRootScope()) {}
void RunTest(const Output& x, const TensorShape& x_shape, const Output& y,
const TensorShape& y_shape) {
TF_ASSERT_OK(scope_.status());
float max_error;
TF_ASSERT_OK((ComputeGradientError<float, float, float>(
scope_, {x}, {x_shape}, {y}, {y_shape}, &max_error)));
EXPECT_LT(max_error, 1e-3);
}
void RunTest(const OutputList& xs, const std::vector<TensorShape>& x_shapes,
const OutputList& ys, const std::vector<TensorShape>& y_shapes) {
TF_ASSERT_OK(scope_.status());
float max_error;
TF_ASSERT_OK((ComputeGradientError<float, float, float>(
scope_, xs, x_shapes, ys, y_shapes, &max_error)));
EXPECT_LT(max_error, 1e-3);
}
Scope scope_;
};
TEST_F(ResourceVariableGradTest, ReadVariableOpGrad) {
TensorShape shape({});
auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
auto var = VarHandleOp(scope_, DT_FLOAT, shape);
auto init = AssignVariableOp(scope_, var, Const(scope_, (float) 2, {}));
auto temp = ReadVariableOp(scope_, var, DT_FLOAT);
auto y = Mul(scope_, temp, x);
auto dy = ops::Cast(scope_, ops::Const(scope_, 1.0, shape), DT_FLOAT);
OutputList dxs;
TF_ASSERT_OK(AddSymbolicGradients(scope_, {y}, {var}, {dy}, &dxs));
ClientSession::FeedType feed_list;
feed_list.insert({x, (float) 5});
feed_list.insert({dy, (float) 1});
std::vector<Tensor> dxout;
ClientSession session(scope_);
TF_ASSERT_OK(session.Run(feed_list, dxs, &dxout));
auto grad = dxout[0].scalar<float>()();
EXPECT_EQ(grad, 5);
}
} // namespace
} // namespace tensorflow
<commit_msg>Fix test nits<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/framework/gradient_checker.h"
#include "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/framework/testutil.h"
#include "tensorflow/cc/gradients/grad_testutil.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
namespace {
using namespace ops; // NOLINT(build/namespaces)
TEST(ResourceVariableGradTest, ReadVariableOpGrad) {
TensorShape shape({});
auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
auto var = VarHandleOp(scope_, DT_FLOAT, shape);
auto init = AssignVariableOp(scope_, var, Const(scope_, (float) 2, shape));
auto temp = ReadVariableOp(scope_, var, DT_FLOAT);
auto y = Mul(scope_, temp, x);
auto dy = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
OutputList dxs;
TF_ASSERT_OK(AddSymbolicGradients(scope_, {y}, {var}, {dy}, &dxs));
ClientSession::FeedType feed_list;
feed_list.insert({x, (float) 5});
feed_list.insert({dy, (float) 1});
std::vector<Tensor> dxout;
ClientSession session(scope_);
TF_ASSERT_OK(session.Run(feed_list, dxs, &dxout));
auto grad = dxout[0].scalar<float>()();
EXPECT_EQ(grad, 5);
}
} // namespace
} // namespace tensorflow
<|endoftext|>
|
<commit_before><commit_msg>CR mode update for mode 3<commit_after><|endoftext|>
|
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "tablecountnode.h"
#include "common/common.h"
#include "expressions/abstractexpression.h"
#include "storage/table.h"
namespace voltdb {
TableCountPlanNode::~TableCountPlanNode() {
}
std::string TableCountPlanNode::debugInfo(const std::string &spacer) const {
std::ostringstream buffer;
buffer << this->AbstractScanPlanNode::debugInfo(spacer);
assert(m_predicate == NULL);
buffer << spacer << "TABLE COUNT Expression: <NULL>";
return (buffer.str());
}
}
<commit_msg>Resolve the valgrind memory leak problem<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "tablecountnode.h"
#include "common/common.h"
#include "expressions/abstractexpression.h"
#include "storage/table.h"
namespace voltdb {
TableCountPlanNode::~TableCountPlanNode() {
delete getOutputTable();
setOutputTable(NULL);
}
std::string TableCountPlanNode::debugInfo(const std::string &spacer) const {
std::ostringstream buffer;
buffer << this->AbstractScanPlanNode::debugInfo(spacer);
assert(m_predicate == NULL);
buffer << spacer << "TABLE COUNT Expression: <NULL>";
return (buffer.str());
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2001 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; 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 <string.h>
#include <iostream>
#ifdef HAVE_AV_CONFIG_H
#undef HAVE_AV_CONFIG_H
#endif
#include "gen_audio.hpp"
extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
#include <libavutil/common.h>
#include <libavutil/opt.h>
}
// this stuff makes me cranky!
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif
#define INBUF_SIZE 4096
#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096
using namespace std;
gen_audio::gen_audio() :
r{42}
{
}
vector<unsigned char> gen_audio::render_target( int datumNumber ) {
std::poisson_distribution<int> _word_count(3);
std::uniform_int_distribution<int> _word(0,vocab.size()-1);
vector<unsigned char> rc;
int word_count = _word_count(r)+1;
for(int i=0; i<word_count; i++) {
int word = _word(r);
string w = vocab[word];
if( i > 0 ) rc.push_back(' ');
rc.insert( rc.end(), w.begin(), w.end() );
}
// string result((char*)rc.data(),rc.size());
// cout << "'" << result << "'\n";
return rc;
}
vector<unsigned char> gen_audio::render_datum( int datumNumber ) {
int frequency = ((datumNumber % 7) + 1) * 1000;
return encode(frequency, 2000);
}
/*
* Audio encoding example
*/
vector<unsigned char> gen_audio::encode(float frequencyHz, int duration) {
AVCodec *codec;
AVCodecContext *c= nullptr;
int frame_size, i, j, out_size, outbuf_size;
short *samples;
float t, tincr;
uint8_t *outbuf;
vector<unsigned char> rc;
/* find the MP2 encoder */
codec = avcodec_find_encoder(CODEC_ID_MP2);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
c->sample_fmt = c->codec->sample_fmts[0];
/* put sample parameters */
c->bit_rate = 64000;
c->sample_rate = 44100;
c->channels = 2;
/* open it */
if (avcodec_open2(c, codec, nullptr) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
/* the codec gives us the frame size, in samples */
frame_size = c->frame_size;
float frame_duration = (float)(c->frame_size) / (float)(c->sample_rate);
int frames = ceil((float)duration / frame_duration / 1000.);
samples = (short*)malloc(frame_size * 2 * c->channels);
outbuf_size = 10000;
outbuf = (uint8_t*)malloc(outbuf_size);
/* encode a single tone sound */
t = 0;
tincr = 2 * M_PI * frequencyHz / c->sample_rate;
for(i=0;i<frames;i++) {
for(j=0;j<frame_size;j++) {
samples[2*j] = (int)(sin(t) * 10000);
samples[2*j+1] = samples[2*j];
t += tincr;
}
/* encode the samples */
out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
for(int i=0; i<out_size; i++) { rc.push_back(outbuf[i]); }
}
free(outbuf);
free(samples);
avcodec_close(c);
av_free(c);
return rc;
}
void gen_audio::encode(const std::string& filename, float frequencyHz, int duration)
{
FILE* f;
f = fopen(filename.c_str(), "wb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename.c_str());
exit(1);
}
vector<unsigned char> data = encode(frequencyHz,duration);
fwrite(data.data(), 1, data.size(), f);
fclose(f);
}
/*
* Audio decoding.
*/
void gen_audio::decode(const std::string& outfilename, const std::string& filename)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int out_size, len;
FILE *f, *outfile;
uint8_t *outbuf;
uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
AVPacket avpkt;
av_init_packet(&avpkt);
printf("Audio decoding\n");
/* find the mpeg audio decoder */
codec = avcodec_find_decoder(CODEC_ID_MP2);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c= avcodec_alloc_context3(codec);
/* open it */
if (avcodec_open2(c, codec, nullptr) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
outbuf = (uint8_t*)malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
f = fopen(filename.c_str(), "rb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename.c_str());
exit(1);
}
outfile = fopen(outfilename.c_str(), "wb");
if (!outfile) {
av_free(c);
exit(1);
}
/* decode until eof */
avpkt.data = inbuf;
avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
while (avpkt.size > 0) {
out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);
if (len < 0) {
fprintf(stderr, "Error while decoding\n");
exit(1);
}
if (out_size > 0) {
/* if a frame has been decoded, output it */
fwrite(outbuf, 1, out_size, outfile);
}
avpkt.size -= len;
avpkt.data += len;
if (avpkt.size < AUDIO_REFILL_THRESH) {
/* Refill the input buffer, to avoid trying to decode
* incomplete frames. Instead of this, one could also use
* a parser, or use a proper container format through
* libavformat. */
memmove(inbuf, avpkt.data, avpkt.size);
avpkt.data = inbuf;
len = fread(avpkt.data + avpkt.size, 1,
AUDIO_INBUF_SIZE - avpkt.size, f);
if (len > 0)
avpkt.size += len;
}
}
fclose(outfile);
fclose(f);
free(outbuf);
avcodec_close(c);
av_free(c);
}
vector<string> gen_audio::get_codec_list() {
vector<string> rc;
AVCodec* current_codec = av_codec_next(nullptr);
while (current_codec != NULL)
{
if (!av_codec_is_encoder(current_codec))
{
current_codec = av_codec_next(current_codec);
continue;
}
rc.push_back(string(current_codec->name));
current_codec = av_codec_next(current_codec);
}
return rc;
}
//int main(int argc, char **argv)
//{
// const char *filename;
// /* must be called before using avcodec lib */
//// avcodec_init();
// /* register all the codecs */
// avcodec_register_all();
// if (argc <= 1) {
// audio_encode_example("/tmp/test.mp2");
// audio_decode_example("/tmp/test.sw", "/tmp/test.mp2");
// video_encode_example("/tmp/test.mpg");
// filename = "/tmp/test.mpg";
// } else {
// filename = argv[1];
// }
// // audio_decode_example("/tmp/test.sw", filename);
// video_decode_example("/tmp/test%d.pgm", filename);
// return 0;
//}
<commit_msg>add more documentation to gen_audio.cpp<commit_after>/*
* Copyright (c) 2001 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; 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 <string.h>
#include <iostream>
#ifdef HAVE_AV_CONFIG_H
#undef HAVE_AV_CONFIG_H
#endif
#include "gen_audio.hpp"
extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
#include <libavutil/common.h>
#include <libavutil/opt.h>
}
// this stuff makes me cranky!
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif
#define INBUF_SIZE 4096
#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096
using namespace std;
gen_audio::gen_audio() :
r{42}
{
}
vector<unsigned char> gen_audio::render_target( int datumNumber ) {
std::poisson_distribution<int> _word_count(3);
std::uniform_int_distribution<int> _word(0,vocab.size()-1);
vector<unsigned char> rc;
int word_count = _word_count(r)+1;
for(int i=0; i<word_count; i++) {
int word = _word(r);
string w = vocab[word];
if( i > 0 ) rc.push_back(' ');
rc.insert( rc.end(), w.begin(), w.end() );
}
// string result((char*)rc.data(),rc.size());
// cout << "'" << result << "'\n";
return rc;
}
vector<unsigned char> gen_audio::render_datum( int datumNumber ) {
int frequency = ((datumNumber % 7) + 1) * 1000;
return encode(frequency, 2000);
}
/*
* Audio encoding example
*
* generate an mp2 encoded sin wave with `frequencyHz` and length `duration`
* in milliseconds.
*/
vector<unsigned char> gen_audio::encode(float frequencyHz, int duration) {
AVCodec *codec;
AVCodecContext *c= nullptr;
int frame_size, i, j, out_size, outbuf_size;
short *samples;
float t, tincr;
uint8_t *outbuf;
vector<unsigned char> rc;
/* find the MP2 encoder */
codec = avcodec_find_encoder(CODEC_ID_MP2);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
c->sample_fmt = c->codec->sample_fmts[0];
/* put sample parameters */
c->bit_rate = 64000;
c->sample_rate = 44100;
c->channels = 2;
/* open it */
if (avcodec_open2(c, codec, nullptr) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
/* the codec gives us the frame size, in samples */
frame_size = c->frame_size;
float frame_duration = (float)(c->frame_size) / (float)(c->sample_rate);
int frames = ceil((float)duration / frame_duration / 1000.);
samples = (short*)malloc(frame_size * 2 * c->channels);
outbuf_size = 10000;
outbuf = (uint8_t*)malloc(outbuf_size);
/* encode a single tone sound */
t = 0;
tincr = 2 * M_PI * frequencyHz / c->sample_rate;
for(i=0;i<frames;i++) {
for(j=0;j<frame_size;j++) {
samples[2*j] = (int)(sin(t) * 10000);
samples[2*j+1] = samples[2*j];
t += tincr;
}
/* encode the samples */
out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
for(int i=0; i<out_size; i++) { rc.push_back(outbuf[i]); }
}
free(outbuf);
free(samples);
avcodec_close(c);
av_free(c);
return rc;
}
/*
* Audio encoding example
*
* generate an mp2 encoded sin wave with `frequencyHz` and length `duration`
* in milliseconds. write audio file to `filename`.
*/
void gen_audio::encode(const std::string& filename, float frequencyHz, int duration)
{
FILE* f;
f = fopen(filename.c_str(), "wb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename.c_str());
exit(1);
}
vector<unsigned char> data = encode(frequencyHz,duration);
fwrite(data.data(), 1, data.size(), f);
fclose(f);
}
/*
* Audio decoding.
*/
void gen_audio::decode(const std::string& outfilename, const std::string& filename)
{
AVCodec *codec;
AVCodecContext *c= NULL;
int out_size, len;
FILE *f, *outfile;
uint8_t *outbuf;
uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
AVPacket avpkt;
av_init_packet(&avpkt);
printf("Audio decoding\n");
/* find the mpeg audio decoder */
codec = avcodec_find_decoder(CODEC_ID_MP2);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c= avcodec_alloc_context3(codec);
/* open it */
if (avcodec_open2(c, codec, nullptr) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
outbuf = (uint8_t*)malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
f = fopen(filename.c_str(), "rb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename.c_str());
exit(1);
}
outfile = fopen(outfilename.c_str(), "wb");
if (!outfile) {
av_free(c);
exit(1);
}
/* decode until eof */
avpkt.data = inbuf;
avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
while (avpkt.size > 0) {
out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);
if (len < 0) {
fprintf(stderr, "Error while decoding\n");
exit(1);
}
if (out_size > 0) {
/* if a frame has been decoded, output it */
fwrite(outbuf, 1, out_size, outfile);
}
avpkt.size -= len;
avpkt.data += len;
if (avpkt.size < AUDIO_REFILL_THRESH) {
/* Refill the input buffer, to avoid trying to decode
* incomplete frames. Instead of this, one could also use
* a parser, or use a proper container format through
* libavformat. */
memmove(inbuf, avpkt.data, avpkt.size);
avpkt.data = inbuf;
len = fread(avpkt.data + avpkt.size, 1,
AUDIO_INBUF_SIZE - avpkt.size, f);
if (len > 0)
avpkt.size += len;
}
}
fclose(outfile);
fclose(f);
free(outbuf);
avcodec_close(c);
av_free(c);
}
vector<string> gen_audio::get_codec_list() {
vector<string> rc;
AVCodec* current_codec = av_codec_next(nullptr);
while (current_codec != NULL)
{
if (!av_codec_is_encoder(current_codec))
{
current_codec = av_codec_next(current_codec);
continue;
}
rc.push_back(string(current_codec->name));
current_codec = av_codec_next(current_codec);
}
return rc;
}
//int main(int argc, char **argv)
//{
// const char *filename;
// /* must be called before using avcodec lib */
//// avcodec_init();
// /* register all the codecs */
// avcodec_register_all();
// if (argc <= 1) {
// audio_encode_example("/tmp/test.mp2");
// audio_decode_example("/tmp/test.sw", "/tmp/test.mp2");
// video_encode_example("/tmp/test.mpg");
// filename = "/tmp/test.mpg";
// } else {
// filename = argv[1];
// }
// // audio_decode_example("/tmp/test.sw", filename);
// video_decode_example("/tmp/test%d.pgm", filename);
// return 0;
//}
<|endoftext|>
|
<commit_before>/**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <gtest/gtest.h>
#include <vector>
#include <iostream>
#include <cmath>
#include <qi/transport/zeromq/zmqpublisher.hpp>
#include <qi/transport/zeromq/zmqsubscriber.hpp>
#include <qi/perf/sleep.hpp>
#include <boost/timer.hpp>
struct SubscribePerfHandler : qi::transport::ISubscribeHandler {
int fCount;
int fExpectedMessages;
boost::timer timer;
// conforms to ISubscriberHandler
void subscribeHandler(const std::string& msg) {
if (fCount == 0) {
timer.restart();
}
fCount++;
if (fCount != fExpectedMessages) {
return;
}
// print results
double elapsed = timer.elapsed();
double msgPerSecond = 1.0 /(elapsed / fExpectedMessages);
std::cout << "SUB: msg/s: " <<
std::setprecision(12) << msgPerSecond << std::endl;
}
int getCount() {
return fCount;
}
SubscribePerfHandler() : fCount(0) {}
SubscribePerfHandler(int expectedMessages) :
fCount(0),
fExpectedMessages(expectedMessages) {}
};
TEST(TransportZMQPublisher , MillionPerSecond)
{
int numMillions = 1;
int numMessages = numMillions * 1000000;
SubscribePerfHandler handler(numMessages);
qi::transport::ZMQPublisher publisher1("tcp://127.0.0.1:5556");
qi::transport::ZMQPublisher publisher("tcp://127.0.0.1:5555");
qi::transport::ZMQSubscriber subscriber("tcp://127.0.0.1:5555");
subscriber.setSubscribeHandler(&handler);
subscriber.subscribe();
std::string msg = "Hello";
sleep(1);
for (int i=0; i < numMessages; i++) {
publisher.publish(msg);
}
sleep(2);
int result = handler.getCount();
ASSERT_EQ( numMessages, result) << "Did not receive all messages";
}
TEST(TransportZMQPublisher , MultipleSubscribers)
{
int numMessages = 100000;
qi::transport::ZMQPublisher publisher("tcp://127.0.0.1:5555");
const int numSubscribers = 50;
std::vector<SubscribePerfHandler*> handlers;
std::vector< qi::transport::ZMQSubscriber*> subscribers;
boost::shared_ptr<zmq::context_t> subContext(new zmq::context_t(1));
for (unsigned int i = 0; i < numSubscribers; ++i) {
SubscribePerfHandler* hand = new SubscribePerfHandler(numMessages);
qi::transport::ZMQSubscriber* sub = new qi::transport::ZMQSubscriber(subContext, "tcp://127.0.0.1:5555");
sub->setSubscribeHandler(hand);
sub->subscribe();
handlers.push_back(hand);
subscribers.push_back(sub);
}
sleep(1);
std::string msg = "Hello";
std::cout << "Publishing...";
for (int i=0; i < numMessages; i++) {
publisher.publish(msg);
}
std::cout << " Done." << std::endl;
sleep(1);
int result = 0;
for(unsigned int i=0; i < numSubscribers; ++i) {
result += handlers[i]->getCount();
}
ASSERT_EQ( numMessages * numSubscribers, result) << "Did not receive all messages";
}
<commit_msg>publish test fixes for stash<commit_after>/**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <gtest/gtest.h>
#include <vector>
#include <iostream>
#include <cmath>
#include <qi/transport/zeromq/zmqpublisher.hpp>
#include <qi/transport/zeromq/zmqsubscriber.hpp>
#include <qi/perf/sleep.hpp>
#include <boost/timer.hpp>
struct SubscribePerfHandler : qi::transport::ISubscribeHandler {
int fCount;
int fExpectedMessages;
boost::timer timer;
// conforms to ISubscriberHandler
void subscribeHandler(const std::string& msg) {
if (fCount == 0) {
timer.restart();
}
fCount++;
if (fCount != fExpectedMessages) {
return;
}
// print results
double elapsed = timer.elapsed();
double msgPerSecond = 1.0 /(elapsed / fExpectedMessages);
std::cout << "SUB: msg/s: " <<
std::setprecision(12) << msgPerSecond << std::endl;
}
int getCount() {
return fCount;
}
SubscribePerfHandler() : fCount(0) {}
SubscribePerfHandler(int expectedMessages) :
fCount(0),
fExpectedMessages(expectedMessages) {}
};
TEST(TransportZMQPublisher , MillionPerSecond)
{
int numMillions = 1;
int numMessages = numMillions * 1000000;
SubscribePerfHandler handler(numMessages);
//qi::transport::ZMQPublisher publisher1("tcp://127.0.0.1:5556");
qi::transport::ZMQPublisher publisher("tcp://127.0.0.1:5555");
qi::transport::ZMQSubscriber subscriber("tcp://127.0.0.1:5555");
subscriber.setSubscribeHandler(&handler);
subscriber.subscribe();
std::string msg = "Hello";
sleep(1);
for (int i=0; i < numMessages; i++) {
publisher.publish(msg);
}
sleep(2);
int result = handler.getCount();
ASSERT_EQ( numMessages, result) << "Did not receive all messages";
}
TEST(TransportZMQPublisher , MultipleSubscribers)
{
int numMessages = 100000;
const int numSubscribers = 50;
std::vector<SubscribePerfHandler*> handlers;
std::vector< qi::transport::ZMQSubscriber*> subscribers;
//boost::shared_ptr<zmq::context_t> subContext(new zmq::context_t(1));
for (unsigned int i = 0; i < numSubscribers; ++i) {
SubscribePerfHandler* hand = new SubscribePerfHandler(numMessages);
qi::transport::ZMQSubscriber* sub = new qi::transport::ZMQSubscriber(/*subContext, */"tcp://127.0.0.1:5555");
sub->setSubscribeHandler(hand);
sub->subscribe();
handlers.push_back(hand);
subscribers.push_back(sub);
}
sleep(1);
qi::transport::ZMQPublisher publisher("tcp://127.0.0.1:5555");
sleep(1);
std::string msg = "Hello";
std::cout << "Publishing...";
for (int i=0; i < numMessages; i++) {
publisher.publish(msg);
}
std::cout << " Done." << std::endl;
sleep(1);
int result = 0;
for(unsigned int i=0; i < numSubscribers; ++i) {
result += handlers[i]->getCount();
}
ASSERT_EQ( numMessages * numSubscribers, result) << "Did not receive all messages";
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "base/logging.h"
#include "base/mutex.h"
using ::std::string;
DEFINE_int32(stderrthreshold,
LOGLEVEL_ERROR,
"log messages at or above this level are copied to stderr");
DEFINE_int32(minloglevel,
LOGLEVEL_INFO,
"Messages logged at a lower level than this don't actually get "
"logged anywhere");
namespace internal {
void DefaultLogHandler(LogLevel level, const char* filename, int line,
const string& message) {
static const char* level_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
// Only log errors above minloglevel.
if (level >= FLAGS_minloglevel) {
// We use fprintf() instead of cerr because we want this to work at static
// initialization time.
fprintf(stderr, "[lmctfy %s %s:%d] %s\n", level_names[level], filename,
line, message.c_str());
fflush(stderr); // Needed on MSVC.
}
}
void NullLogHandler(LogLevel level, const char* filename, int line,
const string& message) {
// Nothing.
}
static LogHandler* log_handler_ = &DefaultLogHandler;
static int log_silencer_count_ = 0;
static Mutex* log_silencer_count_mutex_ = nullptr;
Mutex *InitLogSilencerMutex() {
static Mutex *m = new Mutex();
return m;
}
void InitLogSilencerCount() {
log_silencer_count_mutex_ = InitLogSilencerMutex();
}
void InitLogSilencerCountOnce() {
log_silencer_count_mutex_ = new Mutex();
}
LogMessage& LogMessage::operator<<(const string& value) {
message_ += value;
return *this;
}
LogMessage& LogMessage::operator<<(const char* value) {
message_ += value;
return *this;
}
// Since this is just for logging, we don't care if the current locale changes
// the results -- in fact, we probably prefer that. So we use snprintf()
// instead of Simple*toa().
#undef DECLARE_STREAM_OPERATOR
#define DECLARE_STREAM_OPERATOR(TYPE, FORMAT) \
LogMessage& LogMessage::operator<<(TYPE value) { \
/* 128 bytes should be big enough for any of the primitive */ \
/* values which we print with this, but well use snprintf() */ \
/* anyway to be extra safe. */ \
char buffer[128]; \
snprintf(buffer, sizeof(buffer), FORMAT, value); \
/* Guard against broken MSVC snprintf(). */ \
buffer[sizeof(buffer)-1] = '\0'; \
message_ += buffer; \
return *this; \
}
DECLARE_STREAM_OPERATOR(char , "%c" )
DECLARE_STREAM_OPERATOR(int , "%d" )
DECLARE_STREAM_OPERATOR(uint , "%u" )
DECLARE_STREAM_OPERATOR(long , "%ld" )
DECLARE_STREAM_OPERATOR(long long , "%lld")
DECLARE_STREAM_OPERATOR(unsigned long , "%lu" )
DECLARE_STREAM_OPERATOR(unsigned long long, "%llu")
DECLARE_STREAM_OPERATOR(double , "%g" )
#undef DECLARE_STREAM_OPERATOR
LogMessage::LogMessage(LogLevel level, const char* filename, int line)
: level_(level), filename_(filename), line_(line) {}
LogMessage::~LogMessage() {}
void LogMessage::Finish() {
bool suppress = false;
if (level_ != LOGLEVEL_FATAL) {
InitLogSilencerCountOnce();
MutexLock lock(log_silencer_count_mutex_);
suppress = log_silencer_count_ > 0;
}
if (!suppress) {
log_handler_(level_, filename_, line_, message_);
}
if (level_ == LOGLEVEL_FATAL) {
#if PROTOBUF_USE_EXCEPTIONS
throw FatalException(filename_, line_, message_);
#else
abort();
#endif
}
}
void LogFinisher::operator=(LogMessage& other) {
other.Finish();
}
} // namespace internal
LogHandler* SetLogHandler(LogHandler* new_func) {
LogHandler* old = internal::log_handler_;
if (old == &internal::NullLogHandler) {
old = NULL;
}
if (new_func == NULL) {
internal::log_handler_ = &internal::NullLogHandler;
} else {
internal::log_handler_ = new_func;
}
return old;
}
LogSilencer::LogSilencer() {
internal::InitLogSilencerCountOnce();
MutexLock lock(internal::log_silencer_count_mutex_);
++internal::log_silencer_count_;
};
LogSilencer::~LogSilencer() {
internal::InitLogSilencerCountOnce();
MutexLock lock(internal::log_silencer_count_mutex_);
--internal::log_silencer_count_;
};
static int posix_strerror_r(int err, char *buf, size_t len) {
// Sanity check input parameters
if (buf == NULL || len <= 0) {
errno = EINVAL;
return -1;
}
// Reset buf and errno, and try calling whatever version of strerror_r()
// is implemented by glibc
buf[0] = '\000';
int old_errno = errno;
errno = 0;
char* rc = reinterpret_cast<char*>(strerror_r(err, buf, len));
// Both versions set errno on failure
if (errno) {
// Should already be there, but better safe than sorry
buf[0] = '\000';
return -1;
}
errno = old_errno;
// If the function succeeded, we can use its exit code to determine the
// semantics implemented by glibc
if (!rc) {
// POSIX is vague about whether the string will be terminated, although
// is indirectly implies that typically ERANGE will be returned, instead
// of truncating the string. This is different from the GNU implementation.
// We play it safe by always terminating the string explicitly.
buf[len - 1] = '\000';
return 0;
} else {
// GNU semantics detected
if (rc == buf) {
return 0;
} else {
buf[0] = '\000';
strncat(buf, rc, len - 1);
return 0;
}
}
}
string StrError(int err) {
char buf[100];
int rc = posix_strerror_r(err, buf, sizeof(buf));
if ((rc < 0) || (buf[0] == '\000')) {
snprintf(buf, sizeof(buf), "Error number %d", err);
}
return buf;
}
<commit_msg>Fix a memory leak in logging<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "base/logging.h"
#include "base/mutex.h"
using ::std::string;
DEFINE_int32(stderrthreshold,
LOGLEVEL_ERROR,
"log messages at or above this level are copied to stderr");
DEFINE_int32(minloglevel,
LOGLEVEL_INFO,
"Messages logged at a lower level than this don't actually get "
"logged anywhere");
namespace internal {
void DefaultLogHandler(LogLevel level, const char* filename, int line,
const string& message) {
static const char* level_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
// Only log errors above minloglevel.
if (level >= FLAGS_minloglevel) {
// We use fprintf() instead of cerr because we want this to work at static
// initialization time.
fprintf(stderr, "[lmctfy %s %s:%d] %s\n", level_names[level], filename,
line, message.c_str());
fflush(stderr); // Needed on MSVC.
}
}
void NullLogHandler(LogLevel level, const char* filename, int line,
const string& message) {
// Nothing.
}
static LogHandler* log_handler_ = &DefaultLogHandler;
static int log_silencer_count_ = 0;
static Mutex* log_silencer_count_mutex_ = nullptr;
Mutex *InitLogSilencerMutex() {
static Mutex *m = new Mutex();
return m;
}
void InitLogSilencerCount() {
log_silencer_count_mutex_ = InitLogSilencerMutex();
}
LogMessage& LogMessage::operator<<(const string& value) {
message_ += value;
return *this;
}
LogMessage& LogMessage::operator<<(const char* value) {
message_ += value;
return *this;
}
// Since this is just for logging, we don't care if the current locale changes
// the results -- in fact, we probably prefer that. So we use snprintf()
// instead of Simple*toa().
#undef DECLARE_STREAM_OPERATOR
#define DECLARE_STREAM_OPERATOR(TYPE, FORMAT) \
LogMessage& LogMessage::operator<<(TYPE value) { \
/* 128 bytes should be big enough for any of the primitive */ \
/* values which we print with this, but well use snprintf() */ \
/* anyway to be extra safe. */ \
char buffer[128]; \
snprintf(buffer, sizeof(buffer), FORMAT, value); \
/* Guard against broken MSVC snprintf(). */ \
buffer[sizeof(buffer)-1] = '\0'; \
message_ += buffer; \
return *this; \
}
DECLARE_STREAM_OPERATOR(char , "%c" )
DECLARE_STREAM_OPERATOR(int , "%d" )
DECLARE_STREAM_OPERATOR(uint , "%u" )
DECLARE_STREAM_OPERATOR(long , "%ld" )
DECLARE_STREAM_OPERATOR(long long , "%lld")
DECLARE_STREAM_OPERATOR(unsigned long , "%lu" )
DECLARE_STREAM_OPERATOR(unsigned long long, "%llu")
DECLARE_STREAM_OPERATOR(double , "%g" )
#undef DECLARE_STREAM_OPERATOR
LogMessage::LogMessage(LogLevel level, const char* filename, int line)
: level_(level), filename_(filename), line_(line) {}
LogMessage::~LogMessage() {}
void LogMessage::Finish() {
bool suppress = false;
if (level_ != LOGLEVEL_FATAL) {
InitLogSilencerCount();
MutexLock lock(log_silencer_count_mutex_);
suppress = log_silencer_count_ > 0;
}
if (!suppress) {
log_handler_(level_, filename_, line_, message_);
}
if (level_ == LOGLEVEL_FATAL) {
#if PROTOBUF_USE_EXCEPTIONS
throw FatalException(filename_, line_, message_);
#else
abort();
#endif
}
}
void LogFinisher::operator=(LogMessage& other) {
other.Finish();
}
} // namespace internal
LogHandler* SetLogHandler(LogHandler* new_func) {
LogHandler* old = internal::log_handler_;
if (old == &internal::NullLogHandler) {
old = NULL;
}
if (new_func == NULL) {
internal::log_handler_ = &internal::NullLogHandler;
} else {
internal::log_handler_ = new_func;
}
return old;
}
LogSilencer::LogSilencer() {
internal::InitLogSilencerCount();
MutexLock lock(internal::log_silencer_count_mutex_);
++internal::log_silencer_count_;
};
LogSilencer::~LogSilencer() {
internal::InitLogSilencerCount();
MutexLock lock(internal::log_silencer_count_mutex_);
--internal::log_silencer_count_;
};
static int posix_strerror_r(int err, char *buf, size_t len) {
// Sanity check input parameters
if (buf == NULL || len <= 0) {
errno = EINVAL;
return -1;
}
// Reset buf and errno, and try calling whatever version of strerror_r()
// is implemented by glibc
buf[0] = '\000';
int old_errno = errno;
errno = 0;
char* rc = reinterpret_cast<char*>(strerror_r(err, buf, len));
// Both versions set errno on failure
if (errno) {
// Should already be there, but better safe than sorry
buf[0] = '\000';
return -1;
}
errno = old_errno;
// If the function succeeded, we can use its exit code to determine the
// semantics implemented by glibc
if (!rc) {
// POSIX is vague about whether the string will be terminated, although
// is indirectly implies that typically ERANGE will be returned, instead
// of truncating the string. This is different from the GNU implementation.
// We play it safe by always terminating the string explicitly.
buf[len - 1] = '\000';
return 0;
} else {
// GNU semantics detected
if (rc == buf) {
return 0;
} else {
buf[0] = '\000';
strncat(buf, rc, len - 1);
return 0;
}
}
}
string StrError(int err) {
char buf[100];
int rc = posix_strerror_r(err, buf, sizeof(buf));
if ((rc < 0) || (buf[0] == '\000')) {
snprintf(buf, sizeof(buf), "Error number %d", err);
}
return buf;
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <iostream>
#include <ioa.hpp>
#include <queue>
#include <uuid/uuid.h>
#include <boost/type_traits.hpp>
struct uuid {
uuid_t u;
uuid () {
uuid_generate (u);
}
uuid (const uuid& x) {
uuid_copy (u, x.u);
}
uuid& operator= (const uuid& x) {
if (this != &x) {
uuid_copy (u, x.u);
}
return *this;
}
bool operator> (const uuid& x) const {
return uuid_compare (u, x.u) > 0;
}
bool operator== (const uuid& x) const {
return uuid_compare (u, x.u) == 0;
}
void print_on (std::ostream& os) const {
char s[37];
uuid_unparse (u, s);
os << s;
}
};
std::ostream& operator<< (std::ostream& strm,
const uuid& u) {
u.print_on (strm);
return strm;
}
/*
Channel I/O Automaton
Distributed Algorithms, p. 204.
*/
template <class T>
class channel_automaton :
public ioa::dispatching_automaton
{
private:
std::queue<T> m_queue;
V_UP_INPUT (channel_automaton, send, T, t) {
m_queue.push (t);
schedule ();
}
bool receive_precondition () const {
return !m_queue.empty () && receive.is_bound ();
}
V_UP_OUTPUT (channel_automaton, receive, T) {
std::pair<bool, T> retval;
if (receive_precondition ()) {
retval = std::make_pair (true, m_queue.front ());
m_queue.pop ();
}
schedule ();
return retval;
}
void schedule () {
if (receive_precondition ()) {
ioa::scheduler.schedule (this, &channel_automaton::receive);
}
}
public:
channel_automaton () :
ACTION (channel_automaton, send),
ACTION (channel_automaton, receive)
{ }
void init () { }
};
/*
AsyncLCR Automaton
Distributed Algorithms, p. 204.
*/
class asynch_lcr_automaton :
public ioa::dispatching_automaton
{
private:
typedef enum {
UNKNOWN,
CHOSEN,
REPORTED
} status_t;
uuid m_u;
std::queue<uuid> m_send;
status_t m_status;
V_UP_INPUT (asynch_lcr_automaton, receive, uuid, v) {
if (v > m_u) {
m_send.push (v);
}
else if (v == m_u) {
m_status = CHOSEN;
}
else {
// Do nothing.
}
schedule ();
}
bool send_precondition () const {
return !m_send.empty () && send.is_bound ();
}
V_UP_OUTPUT (asynch_lcr_automaton, send, uuid) {
std::pair<bool, uuid> retval;
if (send_precondition ()) {
retval = std::make_pair (true, m_send.front ());
m_send.pop ();
}
schedule ();
return retval;
}
bool leader_precondition () const {
return m_status == CHOSEN && leader.is_bound ();
}
UV_UP_OUTPUT (asynch_lcr_automaton, leader) {
bool retval = false;
if (leader_precondition ()) {
retval = true;
m_status = REPORTED;
}
schedule ();
return retval;
}
void schedule () {
if (send_precondition ()) {
ioa::scheduler.schedule (this, &asynch_lcr_automaton::send);
}
if (leader_precondition ()) {
ioa::scheduler.schedule (this, &asynch_lcr_automaton::leader);
}
}
public:
asynch_lcr_automaton () :
m_status (UNKNOWN),
ACTION (asynch_lcr_automaton, receive),
ACTION (asynch_lcr_automaton, send),
ACTION (asynch_lcr_automaton, leader)
{
m_send.push (m_u);
}
void init () {
schedule ();
}
};
template <size_t N>
class composer :
public ioa::dispatching_automaton
{
private:
UV_P_INPUT (composer, leader, size_t, i) {
std::cout << i << " is the leader." << std::endl;
}
typedef ioa::instance_generator<asynch_lcr_automaton> asynch_lcr_automaton_generator_type;
typedef ioa::instance_generator<channel_automaton<uuid> > channel_automaton_generator_type;
typedef ioa::automaton_helper<composer, asynch_lcr_automaton_generator_type> asynch_lcr_automaton_helper_type;
typedef ioa::automaton_helper<composer, channel_automaton_generator_type> channel_automaton_helper_type;
typedef ioa::self_helper<composer> composer_helper_type;
typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::send_type, channel_automaton_helper_type, channel_automaton<uuid>::send_type> send_bind_helper_type;
typedef ioa::bind_helper<composer, channel_automaton_helper_type, channel_automaton<uuid>::receive_type, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::receive_type> receive_bind_helper_type;
typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::leader_type, composer_helper_type, typename composer::leader_type> leader_bind_helper_type;
std::vector<asynch_lcr_automaton_helper_type*> asynch_lcr_automaton_helpers;
std::vector<channel_automaton_helper_type*> channel_automaton_helpers;
composer_helper_type composer_helper;
std::vector<send_bind_helper_type*> send_bind_helpers;
std::vector<receive_bind_helper_type*> receive_bind_helpers;
std::vector<leader_bind_helper_type*> leader_bind_helpers;
public:
composer () :
ACTION (composer, leader),
composer_helper (this)
{
for (size_t i = 0; i < N; ++i) {
asynch_lcr_automaton_helpers.push_back (new asynch_lcr_automaton_helper_type (this, asynch_lcr_automaton_generator_type ()));
channel_automaton_helpers.push_back (new channel_automaton_helper_type (this, channel_automaton_generator_type ()));
}
for (size_t i = 0; i < N; ++i) {
send_bind_helpers.push_back (new send_bind_helper_type (this,
asynch_lcr_automaton_helpers[i],
&asynch_lcr_automaton::send,
channel_automaton_helpers[i],
&channel_automaton<uuid>::send));
receive_bind_helpers.push_back (new receive_bind_helper_type (this,
channel_automaton_helpers[i],
&channel_automaton<uuid>::receive,
asynch_lcr_automaton_helpers[(i + 1) % N],
&asynch_lcr_automaton::receive));
leader_bind_helpers.push_back (new leader_bind_helper_type (this,
asynch_lcr_automaton_helpers[i],
&asynch_lcr_automaton::leader,
&composer_helper,
&composer::leader,
i));
}
}
void init () {
for (size_t i = 0; i < N; ++i) {
asynch_lcr_automaton_helpers[i]->create ();
channel_automaton_helpers[i]->create ();
send_bind_helpers[i]->bind ();
receive_bind_helpers[i]->bind ();
leader_bind_helpers[i]->bind ();
}
composer_helper.create ();
}
};
int
main () {
ioa::scheduler.run (ioa::instance_generator<composer<100> > ());
return 0;
}
<commit_msg>Minor changes.<commit_after>#include <ioa.hpp>
#include <queue>
#include <iostream>
#include <uuid/uuid.h>
struct uuid {
uuid_t u;
uuid () {
uuid_generate (u);
}
uuid (const uuid& x) {
uuid_copy (u, x.u);
}
uuid& operator= (const uuid& x) {
if (this != &x) {
uuid_copy (u, x.u);
}
return *this;
}
bool operator> (const uuid& x) const {
return uuid_compare (u, x.u) > 0;
}
bool operator== (const uuid& x) const {
return uuid_compare (u, x.u) == 0;
}
void print_on (std::ostream& os) const {
char s[37];
uuid_unparse (u, s);
os << s;
}
};
std::ostream& operator<< (std::ostream& strm,
const uuid& u) {
u.print_on (strm);
return strm;
}
/*
Channel I/O Automaton
Distributed Algorithms, p. 204.
*/
template <class T>
class channel_automaton :
public ioa::dispatching_automaton
{
private:
std::queue<T> m_queue;
V_UP_INPUT (channel_automaton, send, T, t) {
m_queue.push (t);
schedule ();
}
bool receive_precondition () const {
return !m_queue.empty () && receive.is_bound ();
}
V_UP_OUTPUT (channel_automaton, receive, T) {
std::pair<bool, T> retval;
if (receive_precondition ()) {
retval = std::make_pair (true, m_queue.front ());
m_queue.pop ();
}
schedule ();
return retval;
}
void schedule () {
if (receive_precondition ()) {
ioa::scheduler.schedule (this, &channel_automaton::receive);
}
}
public:
channel_automaton () :
ACTION (channel_automaton, send),
ACTION (channel_automaton, receive)
{ }
void init () { }
};
/*
AsyncLCR Automaton
Distributed Algorithms, p. 204.
*/
class asynch_lcr_automaton :
public ioa::dispatching_automaton
{
private:
typedef enum {
UNKNOWN,
CHOSEN,
REPORTED
} status_t;
uuid m_u;
std::queue<uuid> m_send;
status_t m_status;
V_UP_INPUT (asynch_lcr_automaton, receive, uuid, v) {
if (v > m_u) {
m_send.push (v);
}
else if (v == m_u) {
m_status = CHOSEN;
}
else {
// Do nothing.
}
schedule ();
}
bool send_precondition () const {
return !m_send.empty () && send.is_bound ();
}
V_UP_OUTPUT (asynch_lcr_automaton, send, uuid) {
std::pair<bool, uuid> retval;
if (send_precondition ()) {
retval = std::make_pair (true, m_send.front ());
m_send.pop ();
}
schedule ();
return retval;
}
bool leader_precondition () const {
return m_status == CHOSEN && leader.is_bound ();
}
UV_UP_OUTPUT (asynch_lcr_automaton, leader) {
bool retval = false;
if (leader_precondition ()) {
retval = true;
m_status = REPORTED;
}
schedule ();
return retval;
}
void schedule () {
if (send_precondition ()) {
ioa::scheduler.schedule (this, &asynch_lcr_automaton::send);
}
if (leader_precondition ()) {
ioa::scheduler.schedule (this, &asynch_lcr_automaton::leader);
}
}
public:
asynch_lcr_automaton () :
m_status (UNKNOWN),
ACTION (asynch_lcr_automaton, receive),
ACTION (asynch_lcr_automaton, send),
ACTION (asynch_lcr_automaton, leader)
{
m_send.push (m_u);
}
void init () {
schedule ();
}
};
template <size_t N>
class composer :
public ioa::dispatching_automaton
{
private:
UV_P_INPUT (composer, leader, size_t, i) {
std::cout << i << " is the leader." << std::endl;
}
typedef ioa::instance_generator<asynch_lcr_automaton> asynch_lcr_automaton_generator_type;
typedef ioa::instance_generator<channel_automaton<uuid> > channel_automaton_generator_type;
typedef ioa::automaton_helper<composer, asynch_lcr_automaton_generator_type> asynch_lcr_automaton_helper_type;
typedef ioa::automaton_helper<composer, channel_automaton_generator_type> channel_automaton_helper_type;
typedef ioa::self_helper<composer> composer_helper_type;
typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::send_type, channel_automaton_helper_type, channel_automaton<uuid>::send_type> send_bind_helper_type;
typedef ioa::bind_helper<composer, channel_automaton_helper_type, channel_automaton<uuid>::receive_type, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::receive_type> receive_bind_helper_type;
typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::leader_type, composer_helper_type, typename composer::leader_type> leader_bind_helper_type;
std::vector<asynch_lcr_automaton_helper_type*> asynch_lcr_automaton_helpers;
std::vector<channel_automaton_helper_type*> channel_automaton_helpers;
composer_helper_type composer_helper;
std::vector<send_bind_helper_type*> send_bind_helpers;
std::vector<receive_bind_helper_type*> receive_bind_helpers;
std::vector<leader_bind_helper_type*> leader_bind_helpers;
public:
composer () :
ACTION (composer, leader),
composer_helper (this)
{
for (size_t i = 0; i < N; ++i) {
asynch_lcr_automaton_helpers.push_back (new asynch_lcr_automaton_helper_type (this, asynch_lcr_automaton_generator_type ()));
channel_automaton_helpers.push_back (new channel_automaton_helper_type (this, channel_automaton_generator_type ()));
}
for (size_t i = 0; i < N; ++i) {
send_bind_helpers.push_back (new send_bind_helper_type (this,
asynch_lcr_automaton_helpers[i],
&asynch_lcr_automaton::send,
channel_automaton_helpers[i],
&channel_automaton<uuid>::send));
receive_bind_helpers.push_back (new receive_bind_helper_type (this,
channel_automaton_helpers[i],
&channel_automaton<uuid>::receive,
asynch_lcr_automaton_helpers[(i + 1) % N],
&asynch_lcr_automaton::receive));
leader_bind_helpers.push_back (new leader_bind_helper_type (this,
asynch_lcr_automaton_helpers[i],
&asynch_lcr_automaton::leader,
&composer_helper,
&composer::leader,
i));
}
}
void init () {
for (size_t i = 0; i < N; ++i) {
asynch_lcr_automaton_helpers[i]->create ();
channel_automaton_helpers[i]->create ();
send_bind_helpers[i]->bind ();
receive_bind_helpers[i]->bind ();
leader_bind_helpers[i]->bind ();
}
composer_helper.create ();
}
};
int
main () {
ioa::scheduler.run (ioa::instance_generator<composer<100> > ());
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImagePCAShapeModelEstimatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Insight classes
#include "itkImage.h"
#include "itkVector.h"
#include "vnl/vnl_matrix_fixed.h"
#include "vnl/vnl_math.h"
#include "itkImageRegionIterator.h"
#include "itkLightProcessObject.h"
#include "itkTextOutput.h"
#include "itkImagePCAShapeModelEstimator.h"
// class to support progress feeback
class ShowProgressObject
{
public:
ShowProgressObject(itk::LightProcessObject * o)
{m_Process = o;}
void ShowProgress()
{std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
itk::LightProcessObject::Pointer m_Process;
};
int itkImagePCAShapeModelEstimatorTest(int, char* [] )
{
//Data definitions
int IMGWIDTH = 2;
int IMGHEIGHT = 2;
const int NDIMENSION = 2;
int NUMTRAINIMAGES = 3;
int NUMLARGESTPC = 2;
itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());
//------------------------------------------------------
//Create 3 simple test images with
//------------------------------------------------------
typedef itk::Image<double,NDIMENSION> InputImageType;
typedef itk::Image<double,NDIMENSION> OutputImageType;
typedef itk::Image<double,NDIMENSION> MeanImageType;
typedef InputImageType::PixelType ImagePixelType;
typedef InputImageType::PixelType InputImagePixelType;
typedef
itk::ImageRegionIterator< InputImageType > InputImageIterator;
typedef
itk::ImageRegionIterator< OutputImageType > OutputImageIterator;
InputImageType::Pointer image1 = InputImageType::New();
InputImageType::Pointer image2 = InputImageType::New();
InputImageType::Pointer image3 = InputImageType::New();
InputImageType::SizeType inputImageSize = {{ IMGWIDTH, IMGHEIGHT }};
InputImageType::IndexType index;
index.Fill(0);
InputImageType::RegionType region;
region.SetSize( inputImageSize );
region.SetIndex( index );
//------------------------------------------------------------------------
// Set up Image 1 first
//------------------------------------------------------------------------
image1->SetLargestPossibleRegion( region );
image1->SetBufferedRegion( region );
image1->Allocate();
// setup the iterators
InputImageIterator image1It( image1, image1->GetBufferedRegion() );
//------------------------------------------------------------------------
// Set up Image 2 first
//------------------------------------------------------------------------
image2->SetLargestPossibleRegion( region );
image2->SetBufferedRegion( region );
image2->Allocate();
// setup the iterators
InputImageIterator image2It( image2, image2->GetBufferedRegion() );
//------------------------------------------------------------------------
// Set up Image 3 first
//------------------------------------------------------------------------
image3->SetLargestPossibleRegion( region );
image3->SetBufferedRegion( region );
image3->Allocate();
// setup the iterators
InputImageIterator image3It( image3, image3->GetBufferedRegion() );
//------------------------------------------------------------------------
//Manually create and store each vector
//------------------------------------------------------------------------
//Image no. 1
for( int i = 0; i< 4; i++ )
{
image1It.Set( 1 ); ++image1It;
}
//Image no. 2
image2It.Set( 2 ); ++image2It;
image2It.Set( 0 ); ++image2It;
image2It.Set( 0 ); ++image2It;
image2It.Set( 2 ); ++image2It;
//Image no. 3
image3It.Set( 0 ); ++image3It;
image3It.Set( 3 ); ++image3It;
image3It.Set( 3 ); ++image3It;
image3It.Set( 0 ); ++image3It;
//----------------------------------------------------------------------
// Test code for the Shape model estimator
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//Set the image model estimator
//----------------------------------------------------------------------
typedef itk::ImagePCAShapeModelEstimator<InputImageType, OutputImageType>
ImagePCAShapeModelEstimatorType;
ImagePCAShapeModelEstimatorType::Pointer
applyPCAShapeEstimator = ImagePCAShapeModelEstimatorType::New();
//----------------------------------------------------------------------
//Set the parameters of the clusterer
//----------------------------------------------------------------------
applyPCAShapeEstimator->SetNumberOfTrainingImages( NUMTRAINIMAGES );
applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC + 1 );
applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC );
applyPCAShapeEstimator->SetInput(0, image1);
applyPCAShapeEstimator->SetInput(1, image2);
applyPCAShapeEstimator->SetInput(2, image3);
applyPCAShapeEstimator->Update();
//Test the printself function to increase coverage
applyPCAShapeEstimator->Print(std::cout);
//Exercise TypeMacro in superclass
typedef ImagePCAShapeModelEstimatorType::Superclass GenericEstimatorType;
std::cout << applyPCAShapeEstimator->GenericEstimatorType::GetNameOfClass() << std::endl;
//Print out the number of training images and the number of principal
//components
std::cout << "The number of training images are: " <<
applyPCAShapeEstimator->GetNumberOfTrainingImages() << std::endl;
std::cout << "The number of principal components desired are: " <<
applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() << std::endl;
//Print the eigen vectors
vnl_vector<double> eigenValues =
applyPCAShapeEstimator->GetEigenValues();
unsigned int numEigVal = eigenValues.size();
std::cout << "Number of returned eign-values: " << numEigVal << std::endl;
std::cout << "The " <<
applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() <<
" largest eigen values are:" << std::endl;
for(unsigned int i= 0; i< vnl_math_min( numEigVal, (unsigned int)NUMLARGESTPC ); i++ )
{
std::cout << eigenValues[ i ] << std::endl;
}
std::cout << "" << std::endl;
std::cout << "" << std::endl;
//Print the MeanImage
OutputImageType::Pointer outImage = applyPCAShapeEstimator->GetOutput( 0 );
OutputImageIterator outImageIt( outImage, outImage->GetBufferedRegion() );
outImageIt.GoToBegin();
std::cout << "The mean image is:" << std::endl;
while(!outImageIt.IsAtEnd() )
{
std::cout << (double)(outImageIt.Get()) << ";" << std::endl;
++outImageIt;
}
std::cout << " " << std::endl;
//Print the largest two eigen vectors
for (unsigned int j=1; j< NUMLARGESTPC + 1; j++ )
{
OutputImageType::Pointer outImage2 = applyPCAShapeEstimator->GetOutput( j );
OutputImageIterator outImage2It( outImage2, outImage2->GetBufferedRegion() );
outImage2It.GoToBegin();
std::cout << "" << std::endl;
std::cout << "The eigen vector number: " << j << " is:" << std::endl;
while(!outImage2It.IsAtEnd() )
{
std::cout << (double) (outImage2It.Get()) << ";" << std::endl;
++outImage2It;
}
std::cout << " " << std::endl;
}
//Test for the eigen values for the test case precomputed using Matlab/Splus
std::cout << "" << std::endl;
if( (eigenValues[2] < 6 || eigenValues[2] > 6.1) || (eigenValues[1] >0.1) )
{
std::cout<< "Test Passed" << std::endl;
}
else
{
std::cout<< "Test failed" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>COMP: fix warning NUMLARGESTPC is an unsigned int<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImagePCAShapeModelEstimatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Insight classes
#include "itkImage.h"
#include "itkVector.h"
#include "vnl/vnl_matrix_fixed.h"
#include "vnl/vnl_math.h"
#include "itkImageRegionIterator.h"
#include "itkLightProcessObject.h"
#include "itkTextOutput.h"
#include "itkImagePCAShapeModelEstimator.h"
// class to support progress feeback
class ShowProgressObject
{
public:
ShowProgressObject(itk::LightProcessObject * o)
{m_Process = o;}
void ShowProgress()
{std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
itk::LightProcessObject::Pointer m_Process;
};
int itkImagePCAShapeModelEstimatorTest(int, char* [] )
{
//Data definitions
int IMGWIDTH = 2;
int IMGHEIGHT = 2;
const int NDIMENSION = 2;
unsigned int NUMTRAINIMAGES = 3;
unsigned int NUMLARGESTPC = 2;
itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());
//------------------------------------------------------
//Create 3 simple test images with
//------------------------------------------------------
typedef itk::Image<double,NDIMENSION> InputImageType;
typedef itk::Image<double,NDIMENSION> OutputImageType;
typedef itk::Image<double,NDIMENSION> MeanImageType;
typedef InputImageType::PixelType ImagePixelType;
typedef InputImageType::PixelType InputImagePixelType;
typedef
itk::ImageRegionIterator< InputImageType > InputImageIterator;
typedef
itk::ImageRegionIterator< OutputImageType > OutputImageIterator;
InputImageType::Pointer image1 = InputImageType::New();
InputImageType::Pointer image2 = InputImageType::New();
InputImageType::Pointer image3 = InputImageType::New();
InputImageType::SizeType inputImageSize = {{ IMGWIDTH, IMGHEIGHT }};
InputImageType::IndexType index;
index.Fill(0);
InputImageType::RegionType region;
region.SetSize( inputImageSize );
region.SetIndex( index );
//------------------------------------------------------------------------
// Set up Image 1 first
//------------------------------------------------------------------------
image1->SetLargestPossibleRegion( region );
image1->SetBufferedRegion( region );
image1->Allocate();
// setup the iterators
InputImageIterator image1It( image1, image1->GetBufferedRegion() );
//------------------------------------------------------------------------
// Set up Image 2 first
//------------------------------------------------------------------------
image2->SetLargestPossibleRegion( region );
image2->SetBufferedRegion( region );
image2->Allocate();
// setup the iterators
InputImageIterator image2It( image2, image2->GetBufferedRegion() );
//------------------------------------------------------------------------
// Set up Image 3 first
//------------------------------------------------------------------------
image3->SetLargestPossibleRegion( region );
image3->SetBufferedRegion( region );
image3->Allocate();
// setup the iterators
InputImageIterator image3It( image3, image3->GetBufferedRegion() );
//------------------------------------------------------------------------
//Manually create and store each vector
//------------------------------------------------------------------------
//Image no. 1
for( int i = 0; i< 4; i++ )
{
image1It.Set( 1 ); ++image1It;
}
//Image no. 2
image2It.Set( 2 ); ++image2It;
image2It.Set( 0 ); ++image2It;
image2It.Set( 0 ); ++image2It;
image2It.Set( 2 ); ++image2It;
//Image no. 3
image3It.Set( 0 ); ++image3It;
image3It.Set( 3 ); ++image3It;
image3It.Set( 3 ); ++image3It;
image3It.Set( 0 ); ++image3It;
//----------------------------------------------------------------------
// Test code for the Shape model estimator
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//Set the image model estimator
//----------------------------------------------------------------------
typedef itk::ImagePCAShapeModelEstimator<InputImageType, OutputImageType>
ImagePCAShapeModelEstimatorType;
ImagePCAShapeModelEstimatorType::Pointer
applyPCAShapeEstimator = ImagePCAShapeModelEstimatorType::New();
//----------------------------------------------------------------------
//Set the parameters of the clusterer
//----------------------------------------------------------------------
applyPCAShapeEstimator->SetNumberOfTrainingImages( NUMTRAINIMAGES );
applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC + 1 );
applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC );
applyPCAShapeEstimator->SetInput(0, image1);
applyPCAShapeEstimator->SetInput(1, image2);
applyPCAShapeEstimator->SetInput(2, image3);
applyPCAShapeEstimator->Update();
//Test the printself function to increase coverage
applyPCAShapeEstimator->Print(std::cout);
//Exercise TypeMacro in superclass
typedef ImagePCAShapeModelEstimatorType::Superclass GenericEstimatorType;
std::cout << applyPCAShapeEstimator->GenericEstimatorType::GetNameOfClass() << std::endl;
//Print out the number of training images and the number of principal
//components
std::cout << "The number of training images are: " <<
applyPCAShapeEstimator->GetNumberOfTrainingImages() << std::endl;
std::cout << "The number of principal components desired are: " <<
applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() << std::endl;
//Print the eigen vectors
vnl_vector<double> eigenValues =
applyPCAShapeEstimator->GetEigenValues();
unsigned int numEigVal = eigenValues.size();
std::cout << "Number of returned eign-values: " << numEigVal << std::endl;
std::cout << "The " <<
applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() <<
" largest eigen values are:" << std::endl;
for(unsigned int i= 0; i< vnl_math_min( numEigVal, NUMLARGESTPC ); i++ )
{
std::cout << eigenValues[ i ] << std::endl;
}
std::cout << "" << std::endl;
std::cout << "" << std::endl;
//Print the MeanImage
OutputImageType::Pointer outImage = applyPCAShapeEstimator->GetOutput( 0 );
OutputImageIterator outImageIt( outImage, outImage->GetBufferedRegion() );
outImageIt.GoToBegin();
std::cout << "The mean image is:" << std::endl;
while(!outImageIt.IsAtEnd() )
{
std::cout << (double)(outImageIt.Get()) << ";" << std::endl;
++outImageIt;
}
std::cout << " " << std::endl;
//Print the largest two eigen vectors
for (unsigned int j=1; j< NUMLARGESTPC + 1; j++ )
{
OutputImageType::Pointer outImage2 = applyPCAShapeEstimator->GetOutput( j );
OutputImageIterator outImage2It( outImage2, outImage2->GetBufferedRegion() );
outImage2It.GoToBegin();
std::cout << "" << std::endl;
std::cout << "The eigen vector number: " << j << " is:" << std::endl;
while(!outImage2It.IsAtEnd() )
{
std::cout << (double) (outImage2It.Get()) << ";" << std::endl;
++outImage2It;
}
std::cout << " " << std::endl;
}
//Test for the eigen values for the test case precomputed using Matlab/Splus
std::cout << "" << std::endl;
if( (eigenValues[2] < 6 || eigenValues[2] > 6.1) || (eigenValues[1] >0.1) )
{
std::cout<< "Test Passed" << std::endl;
}
else
{
std::cout<< "Test failed" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <Utility/MemoryManager/Include/Allocator/MemoryAllocator.hpp>
#include <exception>
namespace Utility
{
namespace MemoryManager
{
class ApplicationAllocator;
template <typename T> class PoolAllocator : public MemoryAllocator
{
PoolAllocator::PoolAllocator() {}
/**
Start the pool and allocate their own memory
*/
void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)
{
// TODORT move to cpp
MemoryAllocator::Initialize(p_memorySize, p_alignment, p_threadShared);
}
/**
Start the pool with our application allocator as base, distributes already allocated memory from "above".
*/
void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)
{
// TODORT move to cpp
MemoryAllocator::Initialize(p_memorySize, p_applicationAllocator, p_alignment, p_threadShared);
}
/**
TODORT docs
*/
void RawAllocator::InternalInitialize()
{
m_firstFree = m_raw;
if(m_alignment > m_headerSizeInBytes)
{
// TODORT fix freelist
}
else
{
// TODORT
throw std::runtime_error("m_alignment must be larger than m_headerSizeInBytes:" + m_headerSizeInBytes);
}
}
// void IncreasePoolSize(){} //TODORT
// void GetPossibleMemoryLeaks
// void GetOccupiedBlocks (Iterate through all blocks and check flags)
virtual PoolAllocator::~PoolAllocator() {}
T* Allocate()
{
if((m_numberOfTotalBlocks - m_numberOfOccupiedBlocks) > 0)
{
// Compute adjustment
const uint8_t mask = m_alignment - m_headerSizeInBytes;
const uint8_t misalignment = (reinterpret_cast<size_t>(m_raw) & mask);
const uint8_t adjustment = m_alignment - misalignment;
// Get next pointer
// Compute
// Compute start
m_currentFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) + adjustment);
// Set adjustment metadata
size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes);
AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);
// Set adjustment metadata
size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes + 1);
AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);
T* current = m_firstFree;
m_firstFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_firstFree) + sizeof(T) + m_alignment);
// TODORT alignment on each segment?
++m_numberOfOccupiedBlocks;
}
else
{
// TODORT logging
// TODORT could maybe return null instead, dangerous to throw exception if this is supposed to be threadsafe and the exceptions is
// not handled corretly
throw std::exception("pool is full"); // TODORT better message
}
}
T* Free(T* t)
{
delete t;
++m_numberOfOccupiedBlocks;
}
private:
void* m_start;
T* m_firstFree;
T* m_lastFree;
bool m_shared;
size_t m_numberOfOccupiedBlocks;
// Not sure about
uint8_t m_alignment;
uint8_t m_headerSizeInBytes = 3; // [next, flags, adjustment] data
};
}
}<commit_msg>Fixed bug which used the wrong operator<commit_after>#pragma once
#include <Utility/MemoryManager/Include/Allocator/MemoryAllocator.hpp>
#include <exception>
namespace Utility
{
namespace MemoryManager
{
class ApplicationAllocator;
template <typename T> class PoolAllocator : public MemoryAllocator
{
PoolAllocator::PoolAllocator() {}
/**
Start the pool and allocate their own memory
*/
void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)
{
// TODORT move to cpp
MemoryAllocator::Initialize(p_memorySize, p_alignment, p_threadShared);
}
/**
Start the pool with our application allocator as base, distributes already allocated memory from "above".
*/
void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)
{
// TODORT move to cpp
MemoryAllocator::Initialize(p_memorySize, p_applicationAllocator, p_alignment, p_threadShared);
}
/**
TODORT docs
*/
void RawAllocator::InternalInitialize()
{
m_firstFree = m_raw;
if(m_alignment > m_headerSizeInBytes)
{
// TODORT fix freelist
}
else
{
// TODORT
throw std::runtime_error("m_alignment must be larger than m_headerSizeInBytes:" + m_headerSizeInBytes);
}
}
// void IncreasePoolSize(){} //TODORT
// void GetPossibleMemoryLeaks
// void GetOccupiedBlocks (Iterate through all blocks and check flags)
virtual PoolAllocator::~PoolAllocator() {}
T* Allocate()
{
if((m_numberOfTotalBlocks - m_numberOfOccupiedBlocks) > 0)
{
// Compute adjustment
const uint8_t mask = m_alignment - m_headerSizeInBytes;
const uint8_t misalignment = (reinterpret_cast<size_t>(m_raw) & mask);
const uint8_t adjustment = m_alignment - misalignment;
// Get next pointer
// Compute
// Compute start
m_currentFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) + adjustment);
// Set adjustment metadata
size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes);
AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);
// Set adjustment metadata
size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes + 1);
AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);
T* current = m_firstFree;
m_firstFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_firstFree) + sizeof(T) + m_alignment);
// TODORT alignment on each segment?
++m_numberOfOccupiedBlocks;
}
else
{
// TODORT logging
// TODORT could maybe return null instead, dangerous to throw exception if this is supposed to be threadsafe and the exceptions is
// not handled corretly
throw std::exception("pool is full"); // TODORT better message
}
}
T* Free(T* t)
{
delete t;
--m_numberOfOccupiedBlocks;
}
private:
void* m_start;
T* m_firstFree;
T* m_lastFree;
bool m_shared;
size_t m_numberOfOccupiedBlocks;
// Not sure about
uint8_t m_alignment;
uint8_t m_headerSizeInBytes = 3; // [next, flags, adjustment] data
};
}
}<|endoftext|>
|
<commit_before>#include "StdTuvokDefines.h"
#include <algorithm>
#include <cstdarg>
#include <fstream>
#include <functional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "ShaderDescriptor.h"
#include "Basics/SysTools.h"
#include "Basics/SystemInfo.h"
#include "Controller/Controller.h"
namespace tuvok {
enum shader_type { SHADER_VERTEX_DISK, SHADER_VERTEX_STRING,
SHADER_FRAGMENT_DISK, SHADER_FRAGMENT_STRING };
struct ShaderDescriptor::sinfo {
std::vector<std::pair<std::string, enum shader_type> > vertex;
std::vector<std::pair<std::string, enum shader_type> > fragment;
bool operator==(const ShaderDescriptor::sinfo& sdi) const;
};
bool ShaderDescriptor::sinfo::operator==(const ShaderDescriptor::sinfo& sdi)
const {
return vertex.size() == sdi.vertex.size() &&
fragment.size() == sdi.fragment.size() &&
std::equal(vertex.begin(), vertex.end(), sdi.vertex.begin()) &&
std::equal(fragment.begin(), fragment.end(), sdi.fragment.begin());
}
ShaderDescriptor::ShaderDescriptor() : si(new struct sinfo()) { }
ShaderDescriptor::ShaderDescriptor(const ShaderDescriptor& sd) : si(sd.si) {}
ShaderDescriptor::ShaderDescriptor(const std::vector<std::string>& vertex,
const std::vector<std::string>& fragment) :
si(new struct sinfo())
{
typedef std::vector<std::string> sv;
for(sv::const_iterator v = vertex.begin(); v != vertex.end(); ++v) {
this->si->vertex.push_back(std::make_pair(*v, SHADER_VERTEX_DISK));
}
for(sv::const_iterator f = fragment.begin(); f != fragment.end(); ++f) {
this->si->fragment.push_back(std::make_pair(*f, SHADER_FRAGMENT_DISK));
}
}
// SysTools::FileExists can take a std::string OR a std::wstring. This makes
// it hard to use in a function composition, because the compiler cannot figure
// out which one we want, and it's not a template or anything so we cannot just
// be explicit.
// This serves to rename it to avoid the ambiguity.
static bool exists(std::string s) { return SysTools::FileExists(s); }
// we could technically achieve this by composing std::plus with
// std::plus, but my god is that a nightmare in c++03.
static std::string concat(std::string a, std::string b, std::string c) {
return a + b + c;
}
// Searches for the given filename in the given directories. Returns the fully
// qualified path of the file's location.
static std::string find_filename(std::vector<std::string> directories,
std::string filename)
{
// if we're on Mac, first try to see if the file is in our bundle.
#ifdef DETECTED_OS_APPLE
if (SysTools::FileExists(SysTools::GetFromResourceOnMac(filename))) {
filename = SysTools::GetFromResourceOnMac(filename);
MESSAGE("Found %s in bundle, using that.", filename.c_str());
return filename;
}
#endif
typedef std::vector<std::string> sv;
// check for garbage directories and warn the user about them
sv::iterator end = std::remove_if(directories.begin(), directories.end(),
std::not1(std::ptr_fun(exists)));
for(sv::const_iterator e = end; e != directories.end(); ++e) {
if (!e->empty())
WARNING("Directory %s does not exist!", e->c_str());
}
// also, we know they're junk, so don't search in them
directories.erase(end, directories.end());
// okay, now prepend each directory into our flename and see if we find a
// match.
using namespace std::placeholders;
const std::string dirsep = "/";
// the functor is a composition: 'exists(add(_1, dirsep, filename))'
sv::const_iterator fn =
std::find_if(directories.begin(), directories.end(),
std::bind(
std::ptr_fun(exists),
std::bind(concat, _1, dirsep, filename)
));
if(fn == directories.end()) { // file not found.
throw std::runtime_error("could not find file");
}
return *fn + dirsep + filename;
}
ShaderDescriptor ShaderDescriptor::Create(
std::vector<std::string> directories,
std::vector<std::pair<uint32_t, std::string> > fragmentDataBindings,
...
) {
ShaderDescriptor rv;
va_list args;
va_start(args, directories);
const char* filename;
// we expect two NULLs: first terminates vertex list, second fragment list.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->vertex.push_back(std::make_pair(std::string(filename),
SHADER_VERTEX_DISK));
}
} while(filename != NULL);
// now second: fragment shaders.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->fragment.push_back(std::make_pair(std::string(filename),
SHADER_FRAGMENT_DISK));
}
} while(filename != NULL);
va_end(args);
// now try to clean up all those paths.
// The user gave us some directories to search, but let's make sure we also
// search the location of our binary.
std::vector<std::string> dirs = SysTools::GetSubDirList(
Controller::Instance().SysInfo()->GetProgramPath()
);
directories.insert(directories.end(), dirs.begin(), dirs.end());
directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());
typedef std::vector<std::pair<std::string, enum shader_type> > sv;
for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {
v->first = find_filename(directories, v->first);
}
for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();
++f) {
f->first = find_filename(directories, f->first);
}
rv.fragmentDataBindings = fragmentDataBindings;
return rv;
}
ShaderDescriptor ShaderDescriptor::Create(
std::vector<std::string> directories, ...
) {
ShaderDescriptor rv;
va_list args;
va_start(args, directories);
const char* filename;
// we expect two NULLs: first terminates vertex list, second fragment list.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->vertex.push_back(std::make_pair(std::string(filename),
SHADER_VERTEX_DISK));
}
} while(filename != NULL);
// now second: fragment shaders.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->fragment.push_back(std::make_pair(std::string(filename),
SHADER_FRAGMENT_DISK));
}
} while(filename != NULL);
va_end(args);
// now try to clean up all those paths.
// The user gave us some directories to search, but let's make sure we also
// search the location of our binary.
std::vector<std::string> dirs = SysTools::GetSubDirList(
Controller::Instance().SysInfo()->GetProgramPath()
);
directories.insert(directories.end(), dirs.begin(), dirs.end());
directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());
typedef std::vector<std::pair<std::string, enum shader_type> > sv;
for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {
v->first = find_filename(directories, v->first);
}
for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();
++f) {
f->first = find_filename(directories, f->first);
}
return rv;
}
/// Adds a vertex shader in a string (i.e. not from a filename)
void ShaderDescriptor::AddVertexShaderString(const std::string shader) {
this->si->vertex.push_back(std::make_pair(shader, SHADER_VERTEX_STRING));
}
/// Adds a fragment shader in a string (i.e. not from a filename)
void ShaderDescriptor::AddFragmentShaderString(const std::string shader) {
this->si->fragment.push_back(std::make_pair(shader, SHADER_FRAGMENT_STRING));
}
/// Two shaders are equal if they utilize the same set of filenames/strings
/// to compose the shader.
bool ShaderDescriptor::operator ==(const ShaderDescriptor& sd) const
{
return this->si == sd.si;
}
static std::string readfile(const std::string& filename) {
// open in append mode so the file pointer will be at EOF and we can
// therefore easily/quickly figure out the file size.
std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::ate);
if(!ifs.is_open()) {
T_ERROR("Could not open shader '%s'", filename.c_str());
throw std::runtime_error("file could not be opened");
}
std::ifstream::pos_type len = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::vector<char> file(size_t(len+std::ifstream::pos_type(1)), 0);
size_t offset=0;
do {
std::streamsize length = std::streamsize(len) - std::streamsize(offset);
ifs.read(&file[offset], length);
offset += size_t(ifs.gcount());
} while(!ifs.eof() && std::ifstream::pos_type(offset) < len);
ifs.close();
return std::string(&file[0]);
}
typedef std::vector<std::pair<std::string, enum shader_type> > slist;
// internal implementation: we keep track of which object (ShaderDescriptor) we
// came from, the location within that object, and what type we are. The
// latter helps us with equality; no location in the vertex shader list is
// equal to any location in the fragment shader list.
struct ShaderDescriptor::SIterator::siterinfo {
const ShaderDescriptor* sd;
slist::const_iterator location;
enum VertFrag { ITER_VERTEX, ITER_FRAGMENT } vf;
siterinfo(const ShaderDescriptor* sdesc, slist::const_iterator loc,
enum VertFrag typ) : sd(sdesc), location(loc), vf(typ) { }
bool operator==(const siterinfo& sit) const {
return this->vf == sit.vf &&
this->location == sit.location;
}
};
ShaderDescriptor::SIterator::SIterator(const ShaderDescriptor::SIterator& sit) :
si(sit.si) { }
ShaderDescriptor::SIterator::SIterator(
struct ShaderDescriptor::SIterator::siterinfo sit
) : si(new ShaderDescriptor::SIterator::siterinfo(sit)) { }
ShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++() {
++this->si->location;
return *this;
}
ShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++(int n) {
std::advance(this->si->location, n);
return *this;
}
bool
ShaderDescriptor::SIterator::operator==(const ShaderDescriptor::SIterator& sit)
const {
return *(this->si) == (*sit.si);
}
bool
ShaderDescriptor::SIterator::operator!=(const ShaderDescriptor::SIterator& sit)
const {
return !(*this == sit);
}
std::pair<std::string, std::string>
ShaderDescriptor::SIterator::operator*() const {
std::pair<std::string, std::string> rv(
std::make_pair(this->si->location->first, "(in-memory)")
);
if(this->si->location->second == SHADER_VERTEX_DISK ||
this->si->location->second == SHADER_FRAGMENT_DISK) {
// load it from disk and replace those parameters.
rv.first = readfile(this->si->location->first);
rv.second = this->si->location->first;
}
return rv;
}
ShaderDescriptor::SIterator ShaderDescriptor::begin_vertex() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->vertex.begin(),
ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX
)
);
}
ShaderDescriptor::SIterator ShaderDescriptor::end_vertex() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->vertex.end(),
ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX
)
);
}
ShaderDescriptor::SIterator ShaderDescriptor::begin_fragment() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->fragment.begin(),
ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT
)
);
}
ShaderDescriptor::SIterator ShaderDescriptor::end_fragment() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->fragment.end(),
ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT
)
);
}
} // namespace tuvok
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Interactive Visualization and Data Analysis Group.
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.
*/
<commit_msg><commit_after>#include "StdTuvokDefines.h"
#include <algorithm>
#include <cstdarg>
#include <fstream>
#include <functional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "ShaderDescriptor.h"
#include "Basics/SysTools.h"
#include "Basics/SystemInfo.h"
#include "Controller/Controller.h"
namespace tuvok {
enum shader_type { SHADER_VERTEX_DISK, SHADER_VERTEX_STRING,
SHADER_FRAGMENT_DISK, SHADER_FRAGMENT_STRING };
struct ShaderDescriptor::sinfo {
std::vector<std::pair<std::string, enum shader_type> > vertex;
std::vector<std::pair<std::string, enum shader_type> > fragment;
bool operator==(const ShaderDescriptor::sinfo& sdi) const;
};
bool ShaderDescriptor::sinfo::operator==(const ShaderDescriptor::sinfo& sdi)
const {
return vertex.size() == sdi.vertex.size() &&
fragment.size() == sdi.fragment.size() &&
std::equal(vertex.begin(), vertex.end(), sdi.vertex.begin()) &&
std::equal(fragment.begin(), fragment.end(), sdi.fragment.begin());
}
ShaderDescriptor::ShaderDescriptor() : si(new struct sinfo()) { }
ShaderDescriptor::ShaderDescriptor(const ShaderDescriptor& sd) : si(sd.si) {}
ShaderDescriptor::ShaderDescriptor(const std::vector<std::string>& vertex,
const std::vector<std::string>& fragment) :
si(new struct sinfo())
{
typedef std::vector<std::string> sv;
for(sv::const_iterator v = vertex.begin(); v != vertex.end(); ++v) {
this->si->vertex.push_back(std::make_pair(*v, SHADER_VERTEX_DISK));
}
for(sv::const_iterator f = fragment.begin(); f != fragment.end(); ++f) {
this->si->fragment.push_back(std::make_pair(*f, SHADER_FRAGMENT_DISK));
}
}
// SysTools::FileExists can take a std::string OR a std::wstring. This makes
// it hard to use in a function composition, because the compiler cannot figure
// out which one we want, and it's not a template or anything so we cannot just
// be explicit.
// This serves to rename it to avoid the ambiguity.
static bool exists(std::string s) { return SysTools::FileExists(s); }
// we could technically achieve this by composing std::plus with
// std::plus, but my god is that a nightmare in c++03.
static std::string concat(std::string a, std::string b, std::string c) {
return a + b + c;
}
// Searches for the given filename in the given directories. Returns the fully
// qualified path of the file's location.
static std::string find_filename(std::vector<std::string> directories,
std::string filename)
{
// if we're on Mac, first try to see if the file is in our bundle.
#ifdef DETECTED_OS_APPLE
if (SysTools::FileExists(SysTools::GetFromResourceOnMac(filename))) {
filename = SysTools::GetFromResourceOnMac(filename);
MESSAGE("Found %s in bundle, using that.", filename.c_str());
return filename;
}
#endif
typedef std::vector<std::string> sv;
// check for garbage directories and warn the user about them
sv::iterator end = std::remove_if(directories.begin(), directories.end(),
std::not1(std::ptr_fun(exists)));
for(sv::const_iterator e = end; e != directories.end(); ++e) {
if (!e->empty())
WARNING("Directory %s does not exist!", e->c_str());
}
// also, we know they're junk, so don't search in them
directories.erase(end, directories.end());
// okay, now prepend each directory into our flename and see if we find a
// match.
using namespace std::placeholders;
const std::string dirsep = "/";
// the functor is a composition: 'exists(add(_1, dirsep, filename))'
sv::const_iterator fn =
std::find_if(directories.begin(), directories.end(),
std::bind(
std::ptr_fun(exists),
std::bind(concat, _1, dirsep, filename)
));
if(fn == directories.end()) { // file not found.
throw std::runtime_error("could not find file");
}
return *fn + dirsep + filename;
}
ShaderDescriptor ShaderDescriptor::Create(
std::vector<std::string> directories,
std::vector<std::pair<uint32_t, std::string> > fragmentDataBindings,
...
) {
ShaderDescriptor rv;
va_list args;
va_start(args, fragmentDataBindings);
const char* filename;
// we expect two NULLs: first terminates vertex list, second fragment list.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->vertex.push_back(std::make_pair(std::string(filename),
SHADER_VERTEX_DISK));
}
} while(filename != NULL);
// now second: fragment shaders.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->fragment.push_back(std::make_pair(std::string(filename),
SHADER_FRAGMENT_DISK));
}
} while(filename != NULL);
va_end(args);
// now try to clean up all those paths.
// The user gave us some directories to search, but let's make sure we also
// search the location of our binary.
std::vector<std::string> dirs = SysTools::GetSubDirList(
Controller::Instance().SysInfo()->GetProgramPath()
);
directories.insert(directories.end(), dirs.begin(), dirs.end());
directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());
typedef std::vector<std::pair<std::string, enum shader_type> > sv;
for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {
v->first = find_filename(directories, v->first);
}
for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();
++f) {
f->first = find_filename(directories, f->first);
}
rv.fragmentDataBindings = fragmentDataBindings;
return rv;
}
ShaderDescriptor ShaderDescriptor::Create(
std::vector<std::string> directories, ...
) {
ShaderDescriptor rv;
va_list args;
va_start(args, directories);
const char* filename;
// we expect two NULLs: first terminates vertex list, second fragment list.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->vertex.push_back(std::make_pair(std::string(filename),
SHADER_VERTEX_DISK));
}
} while(filename != NULL);
// now second: fragment shaders.
do {
filename = va_arg(args, const char*);
if(filename != NULL) {
rv.si->fragment.push_back(std::make_pair(std::string(filename),
SHADER_FRAGMENT_DISK));
}
} while(filename != NULL);
va_end(args);
// now try to clean up all those paths.
// The user gave us some directories to search, but let's make sure we also
// search the location of our binary.
std::vector<std::string> dirs = SysTools::GetSubDirList(
Controller::Instance().SysInfo()->GetProgramPath()
);
directories.insert(directories.end(), dirs.begin(), dirs.end());
directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());
typedef std::vector<std::pair<std::string, enum shader_type> > sv;
for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {
v->first = find_filename(directories, v->first);
}
for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();
++f) {
f->first = find_filename(directories, f->first);
}
return rv;
}
/// Adds a vertex shader in a string (i.e. not from a filename)
void ShaderDescriptor::AddVertexShaderString(const std::string shader) {
this->si->vertex.push_back(std::make_pair(shader, SHADER_VERTEX_STRING));
}
/// Adds a fragment shader in a string (i.e. not from a filename)
void ShaderDescriptor::AddFragmentShaderString(const std::string shader) {
this->si->fragment.push_back(std::make_pair(shader, SHADER_FRAGMENT_STRING));
}
/// Two shaders are equal if they utilize the same set of filenames/strings
/// to compose the shader.
bool ShaderDescriptor::operator ==(const ShaderDescriptor& sd) const
{
return this->si == sd.si;
}
static std::string readfile(const std::string& filename) {
// open in append mode so the file pointer will be at EOF and we can
// therefore easily/quickly figure out the file size.
std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::ate);
if(!ifs.is_open()) {
T_ERROR("Could not open shader '%s'", filename.c_str());
throw std::runtime_error("file could not be opened");
}
std::ifstream::pos_type len = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::vector<char> file(size_t(len+std::ifstream::pos_type(1)), 0);
size_t offset=0;
do {
std::streamsize length = std::streamsize(len) - std::streamsize(offset);
ifs.read(&file[offset], length);
offset += size_t(ifs.gcount());
} while(!ifs.eof() && std::ifstream::pos_type(offset) < len);
ifs.close();
return std::string(&file[0]);
}
typedef std::vector<std::pair<std::string, enum shader_type> > slist;
// internal implementation: we keep track of which object (ShaderDescriptor) we
// came from, the location within that object, and what type we are. The
// latter helps us with equality; no location in the vertex shader list is
// equal to any location in the fragment shader list.
struct ShaderDescriptor::SIterator::siterinfo {
const ShaderDescriptor* sd;
slist::const_iterator location;
enum VertFrag { ITER_VERTEX, ITER_FRAGMENT } vf;
siterinfo(const ShaderDescriptor* sdesc, slist::const_iterator loc,
enum VertFrag typ) : sd(sdesc), location(loc), vf(typ) { }
bool operator==(const siterinfo& sit) const {
return this->vf == sit.vf &&
this->location == sit.location;
}
};
ShaderDescriptor::SIterator::SIterator(const ShaderDescriptor::SIterator& sit) :
si(sit.si) { }
ShaderDescriptor::SIterator::SIterator(
struct ShaderDescriptor::SIterator::siterinfo sit
) : si(new ShaderDescriptor::SIterator::siterinfo(sit)) { }
ShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++() {
++this->si->location;
return *this;
}
ShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++(int n) {
std::advance(this->si->location, n);
return *this;
}
bool
ShaderDescriptor::SIterator::operator==(const ShaderDescriptor::SIterator& sit)
const {
return *(this->si) == (*sit.si);
}
bool
ShaderDescriptor::SIterator::operator!=(const ShaderDescriptor::SIterator& sit)
const {
return !(*this == sit);
}
std::pair<std::string, std::string>
ShaderDescriptor::SIterator::operator*() const {
std::pair<std::string, std::string> rv(
std::make_pair(this->si->location->first, "(in-memory)")
);
if(this->si->location->second == SHADER_VERTEX_DISK ||
this->si->location->second == SHADER_FRAGMENT_DISK) {
// load it from disk and replace those parameters.
rv.first = readfile(this->si->location->first);
rv.second = this->si->location->first;
}
return rv;
}
ShaderDescriptor::SIterator ShaderDescriptor::begin_vertex() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->vertex.begin(),
ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX
)
);
}
ShaderDescriptor::SIterator ShaderDescriptor::end_vertex() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->vertex.end(),
ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX
)
);
}
ShaderDescriptor::SIterator ShaderDescriptor::begin_fragment() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->fragment.begin(),
ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT
)
);
}
ShaderDescriptor::SIterator ShaderDescriptor::end_fragment() const {
return ShaderDescriptor::SIterator(
ShaderDescriptor::SIterator::siterinfo(
this, this->si->fragment.end(),
ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT
)
);
}
} // namespace tuvok
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Interactive Visualization and Data Analysis Group.
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.
*/
<|endoftext|>
|
<commit_before><commit_msg>Stopped messing with response<commit_after><|endoftext|>
|
<commit_before>#include "xchainer/memory.h"
#include <cassert>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/error.h"
namespace xchainer {
namespace internal {
bool IsPointerCudaMemory(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
cudaPointerAttributes attr = {};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
if (attr.isManaged) {
return true;
} else {
throw XchainerError("Non-managed GPU memory is not supported");
}
case cudaErrorInvalidValue:
return false;
default:
cuda::CheckError(status);
break;
}
assert(false); // should never be reached
#else
return false;
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> Allocate(const Device& device, size_t bytesize) {
if (device == MakeDevice("cpu")) {
return std::make_unique<uint8_t[]>(bytesize);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
void* raw_ptr = nullptr;
// Be careful to be exception-safe, i.e., do not throw before creating shared_ptr
cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);
if (status == cudaSuccess) {
return std::shared_ptr<void>{raw_ptr, cudaFree};
} else {
cuda::CheckError(status);
}
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);
bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);
if (is_dst_cuda_memory) {
if (is_src_cuda_memory) {
// Copy from device to device is faster even in unified memory
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));
} else {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));
}
} else {
if (is_src_cuda_memory) {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));
} else {
std::memcpy(dst_ptr, src_ptr, bytesize);
}
}
#else
std::memcpy(dst_ptr, src_ptr, bytesize);
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> MemoryFromBuffer(const Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
if (device == MakeDevice("cpu")) {
if (IsPointerCudaMemory(src_ptr.get())) {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));
return dst_ptr;
} else {
return src_ptr;
}
} else if (device == MakeDevice("cuda")) {
if (IsPointerCudaMemory(src_ptr.get())) {
return src_ptr;
} else {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
return dst_ptr;
}
} else {
throw DeviceError("invalid device");
}
#else
return src_ptr;
#endif // XCHAINER_ENABLE_CUDA
}
} // namespace internal
} // namespace xchainer
<commit_msg>Avoid warning: control reaches end of non-void function [-Wreturn-type]<commit_after>#include "xchainer/memory.h"
#include <cassert>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/error.h"
namespace xchainer {
namespace internal {
bool IsPointerCudaMemory(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
cudaPointerAttributes attr = {};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
if (attr.isManaged) {
return true;
} else {
throw XchainerError("Non-managed GPU memory is not supported");
}
case cudaErrorInvalidValue:
return false;
default:
cuda::CheckError(status);
break;
}
assert(false); // should never be reached
#else
return false;
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> Allocate(const Device& device, size_t bytesize) {
if (device == MakeDevice("cpu")) {
return std::make_unique<uint8_t[]>(bytesize);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
void* raw_ptr = nullptr;
// Be careful to be exception-safe, i.e., do not throw before creating shared_ptr
cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);
if (status == cudaSuccess) {
return std::shared_ptr<void>{raw_ptr, cudaFree};
} else {
cuda::CheckError(status);
}
assert(false); // should never be reached
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);
bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);
if (is_dst_cuda_memory) {
if (is_src_cuda_memory) {
// Copy from device to device is faster even in unified memory
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));
} else {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));
}
} else {
if (is_src_cuda_memory) {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));
} else {
std::memcpy(dst_ptr, src_ptr, bytesize);
}
}
#else
std::memcpy(dst_ptr, src_ptr, bytesize);
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> MemoryFromBuffer(const Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
if (device == MakeDevice("cpu")) {
if (IsPointerCudaMemory(src_ptr.get())) {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));
return dst_ptr;
} else {
return src_ptr;
}
} else if (device == MakeDevice("cuda")) {
if (IsPointerCudaMemory(src_ptr.get())) {
return src_ptr;
} else {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
return dst_ptr;
}
} else {
throw DeviceError("invalid device");
}
#else
return src_ptr;
#endif // XCHAINER_ENABLE_CUDA
}
} // namespace internal
} // namespace xchainer
<|endoftext|>
|
<commit_before>#include "Optimiser.h"
using namespace Moses;
using namespace std;
namespace Mira {
void MiraOptimiser::updateWeights(Moses::ScoreComponentCollection& weights,
const std::vector< std::vector<Moses::ScoreComponentCollection> >& scores,
const std::vector< std::vector<float> >& losses,
const Moses::ScoreComponentCollection& oracleScores) {
for(unsigned batch = 0; batch < scores.size(); batch++) {
for(unsigned analyseSentence = 0; analyseSentence < scores[batch].size(); analyseSentence++) {
float scoreChange = 0.0;
float norm = 0.0;
for(unsigned score = 0; score < scores[batch][analyseSentence].size(); score++) {
float currentScoreChange = oracleScores[score] - scores[batch][analyseSentence][score];
scoreChange += currentScoreChange * weights[score];
norm += currentScoreChange * currentScoreChange;
}
float delta;
if(norm == 0.0) //just in case... :-)
delta = 0.0;
else {
delta = (losses[batch][analyseSentence] - scoreChange) / norm;
cout << "scoreChange: " << scoreChange
<< "\ndelta: " << delta
<< "\nloss: " << losses[batch][analyseSentence] << endl;
}
//now get in shape
if(delta > upperBound_)
delta = upperBound_;
else if(delta < lowerBound_)
delta = lowerBound_;
// do this: weights += delta * (oracleScores - scores[batch][analyseSentence]);
Moses::ScoreComponentCollection tempColl = oracleScores;
tempColl.MinusEquals(scores[batch][analyseSentence]);
tempColl.MultiplyEquals(delta);
weights.MinusEquals(tempColl);
//StaticData::GetInstanceNonConst().SetWeightsScoreComponentCollection(weights);
//calculate max. for criterion
/*
float sumWeightedFeatures = 0.0;
for(unsigned score = 0; score < scores[analyseSentence]->size(); score++) {
sumWeightedFeatures += oracleScores[score]*newWeights[score];
}
if((losses[analyseSentence] - sumWeightedFeatures) > maxTranslation_) {
maxTranslation_ = losses[analyseSentence] - sumWeightedFeatures;
}
*/
}
}
}
}
<commit_msg>now i am using scoreComponentCollection :)<commit_after>#include "Optimiser.h"
using namespace Moses;
using namespace std;
namespace Mira {
void MiraOptimiser::updateWeights(Moses::ScoreComponentCollection& weights,
const std::vector< std::vector<Moses::ScoreComponentCollection> >& scores,
const std::vector< std::vector<float> >& losses,
const Moses::ScoreComponentCollection& oracleScores) {
for(unsigned batch = 0; batch < scores.size(); batch++) {
for(unsigned analyseSentence = 0; analyseSentence < scores[batch].size(); analyseSentence++) {
/* do this:
for(unsigned score = 0; score < scores[batch][analyseSentence].size(); score++) {
float currentScoreChange = oracleScores[score] - scores[batch][analyseSentence][score];
scoreChange += currentScoreChange * weights[score];
norm += currentScoreChange * currentScoreChange;
}
*/
Moses::ScoreComponentCollection currentScoreColl = oracleScores;
currentScoreColl.MinusEquals(scores[batch][analyseSentence]);
currentScoreColl.MultiplyEquals(weights);
float scoreChange = currentScoreChange.InnerProduct(weights);
float norm = currentScoreChange.InnerProduct(currentScoreChange);
float delta;
if(norm == 0.0) //just in case... :-)
delta = 0.0;
else {
delta = (losses[batch][analyseSentence] - scoreChange) / norm;
cout << "scoreChange: " << scoreChange
<< "\ndelta: " << delta
<< "\nloss: " << losses[batch][analyseSentence] << endl;
}
//now get in shape
if(delta > upperBound_)
delta = upperBound_;
else if(delta < lowerBound_)
delta = lowerBound_;
// do this: weights += delta * (oracleScores - scores[batch][analyseSentence])
Moses::ScoreComponentCollection tempColl = oracleScores;
tempColl.MinusEquals(scores[batch][analyseSentence]);
tempColl.MultiplyEquals(delta);
weights.MinusEquals(tempColl);
//calculate max. for criterion
/*
float sumWeightedFeatures = 0.0;
for(unsigned score = 0; score < scores[analyseSentence]->size(); score++) {
sumWeightedFeatures += oracleScores[score]*newWeights[score];
}
if((losses[analyseSentence] - sumWeightedFeatures) > maxTranslation_) {
maxTranslation_ = losses[analyseSentence] - sumWeightedFeatures;
}
*/
}
}
}
}
<|endoftext|>
|
<commit_before>/** \brief Implementation of writer classes for MARC files.
* \author Oliver Obenland (oliver.obenland@uni-tuebingen.de)
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MarcRecord.h"
#include "Compiler.h"
#include "FileUtil.h"
#include "MarcWriter.h"
#include "StringUtil.h"
#include "util.h"
#define DEBUG 1
static const size_t MAX_MARC_21_RECORD_LENGTH(99999);
static char write_buffer[MAX_MARC_21_RECORD_LENGTH]; // Possibly too big for the stack!
// Returns true if we can add the new field to our record w/o overflowing the maximum size of a binary
// MARC-21 record, o/w we return false.
static bool inline NewFieldDoesFit(const size_t base_address, const size_t current_record_length,
const size_t next_field_length)
{
return base_address + DirectoryEntry::DIRECTORY_ENTRY_LENGTH + current_record_length + next_field_length
+ 1 /* for the field terminator byte */ <= MAX_MARC_21_RECORD_LENGTH;
}
/**
* We determine the record dimensions by adding sizes of fields one-by-one (starting with the field represented by
* "directory_iter") while we do not overflow the maximum
* size of a binary MARC-21 record.
*/
static void inline DetermineRecordDimensions(const size_t control_number_field_length,
std::vector<DirectoryEntry>::const_iterator directory_iter,
const std::vector<DirectoryEntry>::const_iterator &end_iter,
size_t * const number_of_directory_entries, size_t * const base_address,
size_t * const record_length)
{
*number_of_directory_entries = 0;
*base_address = DirectoryEntry::DIRECTORY_ENTRY_LENGTH /* for the control number field */
+ Leader::LEADER_LENGTH + 1 /* for directory separator byte */;
*record_length = control_number_field_length + 1 /* for end of record byte */;
// Now we add fields one-by-one while taking care not to overflow the maximum record size:
for (/* empty */;
directory_iter < end_iter
and NewFieldDoesFit(*base_address, *record_length, directory_iter->getFieldLength());
++directory_iter)
{
*base_address += DirectoryEntry::DIRECTORY_ENTRY_LENGTH;
*record_length += directory_iter->getFieldLength();
++*number_of_directory_entries;
}
*record_length += *base_address;
}
static void inline WriteToBuffer(char *&dest, const std::string &data) {
#if DEBUG
if (unlikely(dest + data.size() > write_buffer + sizeof(write_buffer)))
logger->error("write past end of write_buffer! (1)");
#endif
std::memcpy(dest, data.data(), data.size());
dest += data.size();
}
static void inline WriteToBuffer(char *&dest, const char * const source, const size_t length) {
#if DEBUG
if (unlikely(dest + length > write_buffer + sizeof(write_buffer)))
logger->error("write past end of write_buffer! (2)");
#endif
std::memcpy(dest, source, length);
dest += length;
}
static void inline WriteDirEntryToBuffer(char *&directory_pointer, const DirectoryEntry &dir_entry) {
const MarcTag &tag(dir_entry.getTag());
WriteToBuffer(directory_pointer, tag.c_str(), DirectoryEntry::TAG_LENGTH);
WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldLength()), 4, '0'));
WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldOffset()), 5, '0'));
}
void BinaryMarcWriter::write(const MarcRecord &record) {
const std::string control_number(record.getControlNumber());
const size_t control_number_field_length(control_number.size() + 1);
auto dir_entry(record.directory_entries_.cbegin());
if (unlikely(dir_entry == record.directory_entries_.cend()))
logger->error("BinaryMarcWriter::write: can't write a record w/ an empty directory!");
if (unlikely(dir_entry->getTag() != "001"))
logger->error("BinaryMarcWriter::write: first directory entry has to be 001! Found: "
+ dir_entry->getTag().to_string() + " (Control number: " + record.getControlNumber() + ")");
++dir_entry;
while (dir_entry < record.directory_entries_.cend()) {
size_t number_of_directory_entries, record_length, base_address_of_data;
DetermineRecordDimensions(control_number_field_length, dir_entry, record.directory_entries_.cend(),
&number_of_directory_entries, &base_address_of_data, &record_length);
const std::vector<DirectoryEntry>::const_iterator end_iter(dir_entry + number_of_directory_entries);
char *leader_pointer(write_buffer);
record.leader_.setBaseAddressOfData(base_address_of_data);
record.leader_.setRecordLength(record_length);
// In the case of a multi-part records all but the last record need to have the multi-part flag set:
record.leader_.setMultiPartRecord(end_iter != record.directory_entries_.cend());
WriteToBuffer(leader_pointer, record.leader_.toString());
// Write a control number directory entry for each record as the first entry in the directory section:
char *directory_pointer(write_buffer + Leader::LEADER_LENGTH);
WriteDirEntryToBuffer(directory_pointer, record.directory_entries_.front());
char *field_data_pointer(write_buffer + base_address_of_data);
// Write the control number field data:
WriteToBuffer(field_data_pointer, record.field_data_.data(), control_number_field_length);
// Now write the field data for all fields after the 001-field:
for (; dir_entry < end_iter; ++dir_entry) {
WriteDirEntryToBuffer(directory_pointer, *dir_entry);
WriteToBuffer(field_data_pointer, record.field_data_.data() + dir_entry->getFieldOffset(),
dir_entry->getFieldLength());
}
WriteToBuffer(directory_pointer, "\x1E", 1); // End of directory.
WriteToBuffer(field_data_pointer, "\x1D", 1); // End of field data.
output_->write(write_buffer, record_length);
}
}
XmlMarcWriter::XmlMarcWriter(File * const output_file, const unsigned indent_amount,
const XmlWriter::TextConversionType text_conversion_type)
{
xml_writer_ = new MarcXmlWriter(output_file, indent_amount, text_conversion_type);
}
void XmlMarcWriter::write(const MarcRecord &record) {
xml_writer_->openTag("record");
record.leader_.setRecordLength(0);
record.leader_.setBaseAddressOfData(0);
xml_writer_->writeTagsWithData("leader", record.leader_.toString(), /* suppress_newline = */ true);
for (unsigned entry_no(0); entry_no < record.directory_entries_.size(); ++entry_no) {
const DirectoryEntry &dir_entry(record.directory_entries_[entry_no]);
if (dir_entry.isControlFieldEntry())
xml_writer_->writeTagsWithData("controlfield",
{ std::make_pair("tag", dir_entry.getTag().to_string()) },
record.getFieldData(entry_no),
/* suppress_newline = */ true);
else { // We have a data field.
const std::string data(record.getFieldData(entry_no));
xml_writer_->openTag("datafield",
{ std::make_pair("tag", dir_entry.getTag().to_string()),
std::make_pair("ind1", std::string(1, data[0])),
std::make_pair("ind2", std::string(1, data[1]))
});
std::string::const_iterator ch(data.cbegin() + 2 /* Skip over the indicators. */);
while (ch != data.cend()) {
if (*ch != '\x1F')
std::runtime_error("in XmlMarcWriter::write: expected subfield code delimiter not found! Found "
+ std::string(1, *ch) + "! (Control number is " + record.getControlNumber()
+ ".)");
++ch;
if (ch == data.cend())
std::runtime_error("in XmlMarcWriter::write: unexpected subfield data end while expecting a "
"subfield code!");
const std::string subfield_code(1, *ch++);
std::string subfield_data;
while (ch != data.cend() and *ch != '\x1F')
subfield_data += *ch++;
if (subfield_data.empty())
continue;
xml_writer_->writeTagsWithData("subfield", { std::make_pair("code", subfield_code) },
subfield_data, /* suppress_newline = */ true);
}
xml_writer_->closeTag(); // Close "datafield".
}
}
xml_writer_->closeTag(); // Close "record".
}
std::unique_ptr<MarcWriter> MarcWriter::Factory(const std::string &output_filename, WriterType writer_type,
const WriterMode writer_mode)
{
std::unique_ptr<File> output(writer_mode == WriterMode::OVERWRITE ? FileUtil::OpenOutputFileOrDie(output_filename)
: FileUtil::OpenForAppendingOrDie(output_filename));
if (writer_type == AUTO) {
if (StringUtil::EndsWith(output_filename, ".mrc") or StringUtil::EndsWith(output_filename, ".marc"))
writer_type = BINARY;
else if (StringUtil::EndsWith(output_filename, ".xml"))
writer_type = XML;
else
throw std::runtime_error("in MarcWriter::Factory: WriterType is AUTO but filename \""
+ output_filename + "\" does not end in \".mrc\" or \".xml\"!");
}
return (writer_type == XML) ? std::unique_ptr<MarcWriter>(new XmlMarcWriter(output.release()))
: std::unique_ptr<MarcWriter>(new BinaryMarcWriter(output.release()));
}
<commit_msg>Fixing naming conflict<commit_after>/** \brief Implementation of writer classes for MARC files.
* \author Oliver Obenland (oliver.obenland@uni-tuebingen.de)
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MarcRecord.h"
#include "Compiler.h"
#include "FileUtil.h"
#include "MarcWriter.h"
#include "StringUtil.h"
#include "util.h"
#define MARC_WRITER_DEBUG 1
static const size_t MAX_MARC_21_RECORD_LENGTH(99999);
static char write_buffer[MAX_MARC_21_RECORD_LENGTH]; // Possibly too big for the stack!
// Returns true if we can add the new field to our record w/o overflowing the maximum size of a binary
// MARC-21 record, o/w we return false.
static bool inline NewFieldDoesFit(const size_t base_address, const size_t current_record_length,
const size_t next_field_length)
{
return base_address + DirectoryEntry::DIRECTORY_ENTRY_LENGTH + current_record_length + next_field_length
+ 1 /* for the field terminator byte */ <= MAX_MARC_21_RECORD_LENGTH;
}
/**
* We determine the record dimensions by adding sizes of fields one-by-one (starting with the field represented by
* "directory_iter") while we do not overflow the maximum
* size of a binary MARC-21 record.
*/
static void inline DetermineRecordDimensions(const size_t control_number_field_length,
std::vector<DirectoryEntry>::const_iterator directory_iter,
const std::vector<DirectoryEntry>::const_iterator &end_iter,
size_t * const number_of_directory_entries, size_t * const base_address,
size_t * const record_length)
{
*number_of_directory_entries = 0;
*base_address = DirectoryEntry::DIRECTORY_ENTRY_LENGTH /* for the control number field */
+ Leader::LEADER_LENGTH + 1 /* for directory separator byte */;
*record_length = control_number_field_length + 1 /* for end of record byte */;
// Now we add fields one-by-one while taking care not to overflow the maximum record size:
for (/* empty */;
directory_iter < end_iter
and NewFieldDoesFit(*base_address, *record_length, directory_iter->getFieldLength());
++directory_iter)
{
*base_address += DirectoryEntry::DIRECTORY_ENTRY_LENGTH;
*record_length += directory_iter->getFieldLength();
++*number_of_directory_entries;
}
*record_length += *base_address;
}
static void inline WriteToBuffer(char *&dest, const std::string &data) {
#if MARC_WRITER_DEBUG
if (unlikely(dest + data.size() > write_buffer + sizeof(write_buffer)))
logger->error("write past end of write_buffer! (1)");
#endif
std::memcpy(dest, data.data(), data.size());
dest += data.size();
}
static void inline WriteToBuffer(char *&dest, const char * const source, const size_t length) {
#if MARC_WRITER_DEBUG
if (unlikely(dest + length > write_buffer + sizeof(write_buffer)))
logger->error("write past end of write_buffer! (2)");
#endif
std::memcpy(dest, source, length);
dest += length;
}
static void inline WriteDirEntryToBuffer(char *&directory_pointer, const DirectoryEntry &dir_entry) {
const MarcTag &tag(dir_entry.getTag());
WriteToBuffer(directory_pointer, tag.c_str(), DirectoryEntry::TAG_LENGTH);
WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldLength()), 4, '0'));
WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldOffset()), 5, '0'));
}
void BinaryMarcWriter::write(const MarcRecord &record) {
const std::string control_number(record.getControlNumber());
const size_t control_number_field_length(control_number.size() + 1);
auto dir_entry(record.directory_entries_.cbegin());
if (unlikely(dir_entry == record.directory_entries_.cend()))
logger->error("BinaryMarcWriter::write: can't write a record w/ an empty directory!");
if (unlikely(dir_entry->getTag() != "001"))
logger->error("BinaryMarcWriter::write: first directory entry has to be 001! Found: "
+ dir_entry->getTag().to_string() + " (Control number: " + record.getControlNumber() + ")");
++dir_entry;
while (dir_entry < record.directory_entries_.cend()) {
size_t number_of_directory_entries, record_length, base_address_of_data;
DetermineRecordDimensions(control_number_field_length, dir_entry, record.directory_entries_.cend(),
&number_of_directory_entries, &base_address_of_data, &record_length);
const std::vector<DirectoryEntry>::const_iterator end_iter(dir_entry + number_of_directory_entries);
char *leader_pointer(write_buffer);
record.leader_.setBaseAddressOfData(base_address_of_data);
record.leader_.setRecordLength(record_length);
// In the case of a multi-part records all but the last record need to have the multi-part flag set:
record.leader_.setMultiPartRecord(end_iter != record.directory_entries_.cend());
WriteToBuffer(leader_pointer, record.leader_.toString());
// Write a control number directory entry for each record as the first entry in the directory section:
char *directory_pointer(write_buffer + Leader::LEADER_LENGTH);
WriteDirEntryToBuffer(directory_pointer, record.directory_entries_.front());
char *field_data_pointer(write_buffer + base_address_of_data);
// Write the control number field data:
WriteToBuffer(field_data_pointer, record.field_data_.data(), control_number_field_length);
// Now write the field data for all fields after the 001-field:
for (; dir_entry < end_iter; ++dir_entry) {
WriteDirEntryToBuffer(directory_pointer, *dir_entry);
WriteToBuffer(field_data_pointer, record.field_data_.data() + dir_entry->getFieldOffset(),
dir_entry->getFieldLength());
}
WriteToBuffer(directory_pointer, "\x1E", 1); // End of directory.
WriteToBuffer(field_data_pointer, "\x1D", 1); // End of field data.
output_->write(write_buffer, record_length);
}
}
XmlMarcWriter::XmlMarcWriter(File * const output_file, const unsigned indent_amount,
const XmlWriter::TextConversionType text_conversion_type)
{
xml_writer_ = new MarcXmlWriter(output_file, indent_amount, text_conversion_type);
}
void XmlMarcWriter::write(const MarcRecord &record) {
xml_writer_->openTag("record");
record.leader_.setRecordLength(0);
record.leader_.setBaseAddressOfData(0);
xml_writer_->writeTagsWithData("leader", record.leader_.toString(), /* suppress_newline = */ true);
for (unsigned entry_no(0); entry_no < record.directory_entries_.size(); ++entry_no) {
const DirectoryEntry &dir_entry(record.directory_entries_[entry_no]);
if (dir_entry.isControlFieldEntry())
xml_writer_->writeTagsWithData("controlfield",
{ std::make_pair("tag", dir_entry.getTag().to_string()) },
record.getFieldData(entry_no),
/* suppress_newline = */ true);
else { // We have a data field.
const std::string data(record.getFieldData(entry_no));
xml_writer_->openTag("datafield",
{ std::make_pair("tag", dir_entry.getTag().to_string()),
std::make_pair("ind1", std::string(1, data[0])),
std::make_pair("ind2", std::string(1, data[1]))
});
std::string::const_iterator ch(data.cbegin() + 2 /* Skip over the indicators. */);
while (ch != data.cend()) {
if (*ch != '\x1F')
std::runtime_error("in XmlMarcWriter::write: expected subfield code delimiter not found! Found "
+ std::string(1, *ch) + "! (Control number is " + record.getControlNumber()
+ ".)");
++ch;
if (ch == data.cend())
std::runtime_error("in XmlMarcWriter::write: unexpected subfield data end while expecting a "
"subfield code!");
const std::string subfield_code(1, *ch++);
std::string subfield_data;
while (ch != data.cend() and *ch != '\x1F')
subfield_data += *ch++;
if (subfield_data.empty())
continue;
xml_writer_->writeTagsWithData("subfield", { std::make_pair("code", subfield_code) },
subfield_data, /* suppress_newline = */ true);
}
xml_writer_->closeTag(); // Close "datafield".
}
}
xml_writer_->closeTag(); // Close "record".
}
std::unique_ptr<MarcWriter> MarcWriter::Factory(const std::string &output_filename, WriterType writer_type,
const WriterMode writer_mode)
{
std::unique_ptr<File> output(writer_mode == WriterMode::OVERWRITE ? FileUtil::OpenOutputFileOrDie(output_filename)
: FileUtil::OpenForAppendingOrDie(output_filename));
if (writer_type == AUTO) {
if (StringUtil::EndsWith(output_filename, ".mrc") or StringUtil::EndsWith(output_filename, ".marc"))
writer_type = BINARY;
else if (StringUtil::EndsWith(output_filename, ".xml"))
writer_type = XML;
else
throw std::runtime_error("in MarcWriter::Factory: WriterType is AUTO but filename \""
+ output_filename + "\" does not end in \".mrc\" or \".xml\"!");
}
return (writer_type == XML) ? std::unique_ptr<MarcWriter>(new XmlMarcWriter(output.release()))
: std::unique_ptr<MarcWriter>(new BinaryMarcWriter(output.release()));
}
<|endoftext|>
|
<commit_before>// Parse test application
// Based upon: parsetest.cpp from xmlpp
// needed includes
#include <fstream>
#include <iostream>
#include <ctime>
#include <cppdom/cppdom.h>
// namespace includes
using namespace cppdom;
using namespace std;
// dumps the node
void dump_node( XMLNode &node, int level = 0 )
{
XMLString name = node.getName();
XMLNodeType type = node.getType();
XMLString c_data;
for(int i=0;i<level;i++) cout << " ";
char c = ' ';
switch(type)
{
case xml_nt_node:
c = '+';
break;
case xml_nt_leaf:
c = '-';
break;
case xml_nt_document:
c = '\\';
break;
case xml_nt_cdata:
c = '#';
c_data = node.getCdata();
break;
}
if(type == xml_nt_cdata)
cout << c << name.c_str() << "[" << c_data << "]" << endl;
else
cout << c << name.c_str() << endl;
XMLAttributes attr = node.getAttrmap();
// guru: added output of attributes
for (XMLAttributes::iterator j = attr.begin(); j!=attr.end(); j++)
{
for (int i=0; i<level; i++)
cout << " ";
cout << " ";
cout << j->first << ": " << j->second << endl;
}
XMLNodeList& nlist = node.getChildren();
XMLNodeList::const_iterator iter, stop;
iter = nlist.begin();
stop = nlist.end();
while (iter != stop)
{
XMLNodePtr node = *iter;
dump_node ( *node, level+1 );
++iter;
}
};
void process_xml( std::string filename )
{
cout << "processing [" << filename << "] ..." << endl;
XMLContextPtr context( new XMLContext );
XMLDocument node( context );
ifstream istr( filename.c_str() );
// Verify that file opened
if(!istr)
{
std::cerr << "Bad file: " << filename << std::endl;
return;
}
try
{
clock_t tstart = ::clock();
node.load( istr, context );
clock_t tstop = ::clock();
cout << " needed " <<
(tstop-tstart)/static_cast<float>(CLOCKS_PER_SEC)
<< " seconds." << endl;
dump_node( node );
ofstream ostr( "parsetest.xml" );
node.save( ostr );
ostr.close();
}
catch (xmlerror e)
{
XMLLocation where( context->get_location() );
XMLString errmsg;
e.getStrError(errmsg);
// print out where the error occured
cout << filename << ":" << where.getLine() << " ";
cout << "at position " << where.getPos();
cout << ": error: " << errmsg.c_str();
cout << endl;
// print out line where the error occured
ifstream errfile( filename.c_str() );
if(!errfile)
{
std::cerr << "Can't open file [" << filename << "] to output error" << std::endl;
}
int linenr = where.get_line();
char linebuffer[1024];
for(int i=0; i<linenr && !errfile.eof(); i++)
errfile.getline(linebuffer,1024);
int pos = where.get_pos();
if (pos>=80)
pos %= 80;
std::string err_line( linebuffer + (where.get_pos()-pos) );
if (err_line.length()>=79)
err_line.erase(79);
cout << err_line << std::flush;
cout << err_line.c_str() << std::endl;
cout << linebuffer << std::endl;
for(int j=2;j<pos;j++)
std::cout << " ";
cout << '^' << endl;
}
}
int main(int argc, char* argv[])
{
for(int i=1;i<argc;i++)
{
process_xml( std::string(argv[i]) );
}
return 0;
}
<commit_msg>updated to current cppdom api changes<commit_after>// Parse test application
// Based upon: parsetest.cpp from xmlpp
// needed includes
#include <fstream>
#include <iostream>
#include <ctime>
#include <cppdom/cppdom.h>
// namespace includes
using namespace cppdom;
using namespace std;
// dumps the node
void dump_node( XMLNode &node, int level = 0 )
{
XMLString name = node.getName();
XMLNodeType type = node.getType();
XMLString c_data;
for(int i=0;i<level;i++) cout << " ";
char c = ' ';
switch(type)
{
case xml_nt_node:
c = '+';
break;
case xml_nt_leaf:
c = '-';
break;
case xml_nt_document:
c = '\\';
break;
case xml_nt_cdata:
c = '#';
c_data = node.getCdata();
break;
}
if(type == xml_nt_cdata)
cout << c << name.c_str() << "[" << c_data << "]" << endl;
else
cout << c << name.c_str() << endl;
XMLAttributes attr = node.getAttrMap();
// guru: added output of attributes
for (XMLAttributes::iterator j = attr.begin(); j!=attr.end(); j++)
{
for (int i=0; i<level; i++)
cout << " ";
cout << " ";
cout << j->first << ": " << j->second << endl;
}
XMLNodeList& nlist = node.getChildren();
XMLNodeList::const_iterator iter, stop;
iter = nlist.begin();
stop = nlist.end();
while (iter != stop)
{
XMLNodePtr node = *iter;
dump_node ( *node, level+1 );
++iter;
}
};
void process_xml( std::string filename )
{
cout << "processing [" << filename << "] ..." << endl;
XMLContextPtr context( new XMLContext );
XMLDocument node( context );
ifstream istr( filename.c_str() );
// Verify that file opened
if(!istr)
{
std::cerr << "Bad file: " << filename << std::endl;
return;
}
try
{
clock_t tstart = ::clock();
node.load( istr, context );
clock_t tstop = ::clock();
cout << " needed " <<
(tstop-tstart)/static_cast<float>(CLOCKS_PER_SEC)
<< " seconds." << endl;
dump_node( node );
ofstream ostr( "parsetest.xml" );
node.save( ostr );
ostr.close();
}
catch (XMLError e)
{
XMLLocation where( context->getLocation() );
XMLString errmsg;
e.getStrError(errmsg);
// print out where the error occured
cout << filename << ":" << where.getLine() << " ";
cout << "at position " << where.getPos();
cout << ": error: " << errmsg.c_str();
cout << endl;
// print out line where the error occured
ifstream errfile( filename.c_str() );
if(!errfile)
{
std::cerr << "Can't open file [" << filename << "] to output error" << std::endl;
}
int linenr = where.getLine();
char linebuffer[1024];
for(int i=0; i<linenr && !errfile.eof(); i++)
errfile.getline( linebuffer,1024 );
int pos = where.getPos();
if (pos>=80)
pos %= 80;
std::string err_line( linebuffer + (where.getPos()-pos) );
if (err_line.length()>=79)
err_line.erase(79);
cout << err_line << std::flush;
cout << err_line.c_str() << std::endl;
cout << linebuffer << std::endl;
for(int j=2;j<pos;j++)
std::cout << " ";
cout << '^' << endl;
}
}
int main(int argc, char* argv[])
{
for(int i=1;i<argc;i++)
{
process_xml( std::string(argv[i]) );
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
*
* Author: Philipp Zschoche
* GitHub: https://github.com/zschoche
*
*/
#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
#ifndef __SYSLOG_LOGGERS_HPP__
#define __SYSLOG_LOGGERS_HPP__
#include <syslog.h>
#include "logger.hpp"
namespace mlog
{
class syslog_logger : public logger
{
public:
enum syslog_level {
EMERG = LOG_EMERG, /* system is unusable */
ALERT = LOG_ALERT, /* action must be taken immediately */
CRIT = LOG_CRIT, /* critical conditions */
ERR = LOG_ERR, /* error conditions */
WARNING = LOG_WARNING, /* warning conditions */
NOTICE = LOG_NOTICE, /* normal but significant condition */
INFO = LOG_INFO, /* informational */
DEBUG = LOG_DEBUG /* debug */
};
syslog_logger(const char* ident = nullptr, int option = LOG_CONS | LOG_PID | LOG_NDELAY, int facility = LOG_LOCAL1)
:level(syslog_level::NOTICE) {
setlogmask(LOG_UPTO(syslog_level::DEBUG)); // mlog handle that by its own.
openlog(ident, option, facility);
}
virtual ~syslog_logger() {
closelog();
logger::~logger();
}
void write_to_log(log_metadata &&metadata,
std::string &&log_text) {
syslog(level, "%s", metadata.to_string(log_text).c_str());
}
void write_to_log(const log_metadata& metadata,
const std::string& log_text) {
syslog(level, "%s", metadata.to_string(log_text).c_str());
}
syslog_level level;
};
} /* mlog */
#endif /* ___HPP__ */
#endif
<commit_msg>This wasn't a good idea. at all. -.-<commit_after>/*
*
* Author: Philipp Zschoche
* GitHub: https://github.com/zschoche
*
*/
#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
#ifndef __SYSLOG_LOGGERS_HPP__
#define __SYSLOG_LOGGERS_HPP__
#include <syslog.h>
#include "logger.hpp"
namespace mlog
{
class syslog_logger : public logger
{
public:
enum syslog_level {
EMERG = LOG_EMERG, /* system is unusable */
ALERT = LOG_ALERT, /* action must be taken immediately */
CRIT = LOG_CRIT, /* critical conditions */
ERR = LOG_ERR, /* error conditions */
WARNING = LOG_WARNING, /* warning conditions */
NOTICE = LOG_NOTICE, /* normal but significant condition */
INFO = LOG_INFO, /* informational */
DEBUG = LOG_DEBUG /* debug */
};
syslog_logger(const char* ident = nullptr, int option = LOG_CONS | LOG_PID | LOG_NDELAY, int facility = LOG_LOCAL1)
:level(syslog_level::NOTICE) {
setlogmask(LOG_UPTO(syslog_level::DEBUG)); // mlog handle that by its own.
openlog(ident, option, facility);
}
virtual ~syslog_logger() {
closelog();
}
void write_to_log(log_metadata &&metadata,
std::string &&log_text) {
syslog(level, "%s", metadata.to_string(log_text).c_str());
}
void write_to_log(const log_metadata& metadata,
const std::string& log_text) {
syslog(level, "%s", metadata.to_string(log_text).c_str());
}
syslog_level level;
};
} /* mlog */
#endif /* ___HPP__ */
#endif
<|endoftext|>
|
<commit_before>#include "backend.h"
#include <grpc/grpc.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/security/server_credentials.h>
#include <memory>
#include <mutex>
#include "action/action.h"
#include "action/action_service_impl.h"
#include "connection_initiator.h"
#include "core/corerpc_impl.h"
#include "dronecore.h"
#include "log.h"
#include "mission/mission.h"
#include "mission/mission_service_impl.h"
#include "telemetry/telemetry_service_impl.h"
namespace dronecore {
namespace backend {
class DroneCoreBackend::Impl
{
public:
Impl() {}
~Impl() {}
bool run(const int mavlink_listen_port)
{
_connection_initiator.start(_dc, 14540);
_connection_initiator.wait();
grpc::ServerBuilder builder;
setup_port(builder);
CoreServiceImpl core(_dc);
builder.RegisterService(&core);
Action action(_dc.system());
ActionServiceImpl<dronecore::Action> actionService(action);
builder.RegisterService(&actionService);
Mission mission(_dc.system());
MissionServiceImpl<dronecore::Mission> missionService(mission);
builder.RegisterService(&missionService);
Telemetry telemetry(_dc.system());
TelemetryServiceImpl<> telemetryService(telemetry);
builder.RegisterService(&telemetryService);
_server = builder.BuildAndStart();
LogInfo() << "Server started";
_server->Wait();
return true;
}
private:
void setup_port(grpc::ServerBuilder &builder)
{
std::string server_address("0.0.0.0:50051");
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
LogInfo() << "Server set to listen on " << server_address;
}
dronecore::DroneCore _dc;
dronecore::backend::ConnectionInitiator<dronecore::DroneCore> _connection_initiator;
std::unique_ptr<grpc::Server> _server;
};
DroneCoreBackend::DroneCoreBackend() : _impl(new Impl()) {}
DroneCoreBackend::~DroneCoreBackend() = default;
bool DroneCoreBackend::run(const int mavlink_listen_port) { return _impl->run(mavlink_listen_port); }
} // namespace backend
} // namespace dronecore
<commit_msg>backend: update mission proto file<commit_after>#include "backend.h"
#include <grpc/grpc.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/security/server_credentials.h>
#include <memory>
#include <mutex>
#include "action/action.h"
#include "action/action_service_impl.h"
#include "connection_initiator.h"
#include "core/corerpc_impl.h"
#include "dronecore.h"
#include "log.h"
#include "mission/mission_service_impl.h"
#include "telemetry/telemetry_service_impl.h"
namespace dronecore {
namespace backend {
class DroneCoreBackend::Impl
{
public:
Impl() {}
~Impl() {}
bool run(const int mavlink_listen_port)
{
_connection_initiator.start(_dc, 14540);
_connection_initiator.wait();
grpc::ServerBuilder builder;
setup_port(builder);
CoreServiceImpl core(_dc);
builder.RegisterService(&core);
Action action(_dc.system());
ActionServiceImpl<dronecore::Action> actionService(action);
builder.RegisterService(&actionService);
Mission mission(_dc.system());
MissionServiceImpl<dronecore::Mission> missionService(mission);
builder.RegisterService(&missionService);
Telemetry telemetry(_dc.system());
TelemetryServiceImpl<> telemetryService(telemetry);
builder.RegisterService(&telemetryService);
_server = builder.BuildAndStart();
LogInfo() << "Server started";
_server->Wait();
return true;
}
private:
void setup_port(grpc::ServerBuilder &builder)
{
std::string server_address("0.0.0.0:50051");
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
LogInfo() << "Server set to listen on " << server_address;
}
dronecore::DroneCore _dc;
dronecore::backend::ConnectionInitiator<dronecore::DroneCore> _connection_initiator;
std::unique_ptr<grpc::Server> _server;
};
DroneCoreBackend::DroneCoreBackend() : _impl(new Impl()) {}
DroneCoreBackend::~DroneCoreBackend() = default;
bool DroneCoreBackend::run(const int mavlink_listen_port) { return _impl->run(mavlink_listen_port); }
} // namespace backend
} // namespace dronecore
<|endoftext|>
|
<commit_before>#include "itkImageFileWriter.h"
#include "AnisotropicAnomalousDiffusionImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkPluginUtilities.h"
#include "AADDiffusionWeightedDataCLP.h"
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <class T>
int DoIt( int argc, char * argv[], T )
{
PARSE_ARGS;
typedef float InputPixelType;
typedef T OutputPixelType;
typedef itk::Image<InputPixelType, 3> InputImageType;
typedef itk::Image<OutputPixelType, 3> OutputImageType;
typedef itk::ImageFileReader<InputImageType> ReaderType;
typedef itk::ImageFileWriter<OutputImageType> WriterType;
typedef itk::CastImageFilter<InputImageType, OutputImageType> CastType;
typedef itk::AnisotropicAnomalousDiffusionImageFilter<InputImageType, InputImageType> FilterType;
typename ReaderType::Pointer reader = ReaderType::New();
itk::PluginFilterWatcher watchReader(reader, "Read Volume",CLPProcessInformation);
reader->SetFileName( inputVolume.c_str() );
typename FilterType::Pointer filter = FilterType::New();
itk::PluginFilterWatcher watchFilter(filter, "Anisotropic Anomalous Diffusion",CLPProcessInformation);
filter->SetInput( reader->GetOutput() );
filter->SetIterations(iterations);
filter->SetCondutance(condutance);
filter->SetTimeStep(timeStep);
filter->SetQ(q);
typename CastType::Pointer cast = CastType::New();
cast->SetInput( filter->GetOutput() );
typename WriterType::Pointer writer = WriterType::New();
itk::PluginFilterWatcher watchWriter(writer, "Write Volume",CLPProcessInformation);
writer->SetFileName( outputVolume.c_str() );
writer->SetInput( cast->GetOutput() );
writer->SetUseCompression(1);
writer->Update();
return EXIT_SUCCESS;
}
} // end of anonymous namespace
int main( int argc, char * argv[] )
{
PARSE_ARGS;
itk::ImageIOBase::IOPixelType pixelType;
itk::ImageIOBase::IOComponentType componentType;
try
{
itk::GetImageType(inputVolume, pixelType, componentType);
// This filter handles all types on input, but only produces
// signed types
switch( componentType )
{
case itk::ImageIOBase::UCHAR:
return DoIt( argc, argv, static_cast<unsigned char>(0) );
break;
case itk::ImageIOBase::CHAR:
return DoIt( argc, argv, static_cast<char>(0) );
break;
case itk::ImageIOBase::USHORT:
return DoIt( argc, argv, static_cast<unsigned short>(0) );
break;
case itk::ImageIOBase::SHORT:
return DoIt( argc, argv, static_cast<short>(0) );
break;
case itk::ImageIOBase::UINT:
return DoIt( argc, argv, static_cast<unsigned int>(0) );
break;
case itk::ImageIOBase::INT:
return DoIt( argc, argv, static_cast<int>(0) );
break;
case itk::ImageIOBase::ULONG:
return DoIt( argc, argv, static_cast<unsigned long>(0) );
break;
case itk::ImageIOBase::LONG:
return DoIt( argc, argv, static_cast<long>(0) );
break;
case itk::ImageIOBase::FLOAT:
return DoIt( argc, argv, static_cast<float>(0) );
break;
case itk::ImageIOBase::DOUBLE:
return DoIt( argc, argv, static_cast<double>(0) );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
std::cout << "unknown component type" << std::endl;
break;
}
}
catch( itk::ExceptionObject & excep )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Complete implementation of AAD filter on DWI data processing.<commit_after>#include "AnisotropicAnomalousDiffusionImageFilter.h"
#include "itkPluginUtilities.h"
#include <itkMetaDataObject.h>
#include <itkImageFileWriter.h>
#include <itkNrrdImageIO.h>
#include <itkCastImageFilter.h>
#if ITK_VERSION_MAJOR < 4
#include "itkCompose3DCovariantVectorImageFilter.h"
#else
#include "itkComposeImageFilter.h"
#endif
#include <itkDiffusionTensor3DReconstructionImageFilter.h>
#include <itkTensorFractionalAnisotropyImageFilter.h>
#include <itkTensorRelativeAnisotropyImageFilter.h>
#include "AADDiffusionWeightedDataCLP.h"
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <class T>
int DoIt( int argc, char * argv[], T )
{
PARSE_ARGS;
const unsigned int Dimension = 3;
unsigned int numberOfImages = 0;
unsigned int numberOfGradientImages = 0;
bool readb0 = false;
double b0 = 0;
typedef short PixelType;
typedef itk::VectorImage<PixelType, Dimension> VectorImageType;
typedef itk::Image< PixelType, Dimension > ScalarImageType;
itk::ImageFileReader<VectorImageType>::Pointer reader = itk::ImageFileReader<VectorImageType>::New();
VectorImageType::Pointer img;
typedef itk::AnisotropicAnomalousDiffusionImageFilter<ScalarImageType, ScalarImageType> AADFilterType;
// Set the properties for NrrdReader
reader->SetFileName( inputVolume.c_str());
// Read in the nrrd data. The file contains the reference image and the gradient
// images.
try
{
reader->Update();
img = reader->GetOutput();
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
// Here we instantiate the DiffusionTensor3DReconstructionImageFilter class.
// The class is templated over the pixel types of the reference, gradient
// and the to be created tensor pixel's precision. (We use double here). It
// takes as input the Reference (B0 image aquired in the absence of diffusion
// sensitizing gradients), 'n' Gradient images and their directions and produces
// as output an image of tensors with pixel-type DiffusionTensor3D.
//
typedef itk::DiffusionTensor3DReconstructionImageFilter<
PixelType, PixelType, double > TensorReconstructionImageFilterType;
// -------------------------------------------------------------------------
// Parse the Nrrd headers to get the B value and the gradient directions used
// for diffusion weighting.
//
// The Nrrd headers should look like :
// The tags specify the B value and the gradient directions. If gradient
// directions are (0,0,0), it indicates that it is a reference image.
//
// DWMRI_b-value:=800
// DWMRI_gradient_0000:= 0 0 0
// DWMRI_gradient_0001:=-1.000000 0.000000 0.000000
// DWMRI_gradient_0002:=-0.166000 0.986000 0.000000
// DWMRI_gradient_0003:=0.110000 0.664000 0.740000
// ...
//
itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary();
std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
std::string metaString;
TensorReconstructionImageFilterType::GradientDirectionType vect3d;
TensorReconstructionImageFilterType::GradientDirectionContainerType::Pointer
DiffusionVectors =
TensorReconstructionImageFilterType::GradientDirectionContainerType::New();
for (; itKey != imgMetaKeys.end(); ++itKey)
{
double x,y,z;
itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
if (itKey->find("DWMRI_gradient") != std::string::npos)
{
std::cout << *itKey << " ---> " << metaString << std::endl;
sscanf(metaString.c_str(), "%lf %lf %lf\n", &x, &y, &z);
vect3d[0] = x; vect3d[1] = y; vect3d[2] = z;
DiffusionVectors->InsertElement( numberOfImages, vect3d );
++numberOfImages;
// If the direction is 0.0, this is a reference image
if (vect3d[0] == 0.0 &&
vect3d[1] == 0.0 &&
vect3d[2] == 0.0)
{
continue;
}
++numberOfGradientImages;
}
else if (itKey->find("DWMRI_b-value") != std::string::npos)
{
std::cout << *itKey << " ---> " << metaString << std::endl;
readb0 = true;
b0 = atof(metaString.c_str());
}
}
std::cout << "Number of gradient images: "
<< numberOfGradientImages
<< " and Number of reference images: "
<< numberOfImages - numberOfGradientImages
<< std::endl;
if(!readb0)
{
std::cerr << "BValue not specified in header file" << std::endl;
return EXIT_FAILURE;
}
std::vector< ScalarImageType::Pointer > imageContainer;
// iterator to iterate over the DWI Vector image just read in.
typedef itk::ImageRegionConstIterator< VectorImageType > DWIIteratorType;
DWIIteratorType dwiit( img, img->GetBufferedRegion() );
typedef itk::ImageRegionIterator< ScalarImageType > IteratorType;
#if ITK_VERSION_MAJOR < 4
typedef itk::Compose3DCovariantVectorImageFilter<ScalarImageType,
VectorImageType> ScalarToVectorFilterType;
#else
typedef itk::ComposeImageFilter<ScalarImageType,
VectorImageType> ScalarToVectorFilterType;
#endif
typename ScalarToVectorFilterType::Pointer scalarToVectorImageFilter = ScalarToVectorFilterType::New();
for( unsigned int i = 0; i<numberOfImages; i++ )
{
ScalarImageType::Pointer image = ScalarImageType::New();
image->CopyInformation( img );
image->SetBufferedRegion( img->GetBufferedRegion() );
image->SetRequestedRegion( img->GetRequestedRegion() );
image->Allocate();
IteratorType it( image, image->GetBufferedRegion() );
dwiit.GoToBegin();
it.GoToBegin();
while (!it.IsAtEnd())
{
it.Set(dwiit.Get()[i]);
++it;
++dwiit;
}
imageContainer.push_back( image );
}
for(unsigned int countImage=0; countImage<numberOfImages; countImage++){
typename AADFilterType::Pointer filter = AADFilterType::New();
filter->SetInput( imageContainer[countImage] );
filter->SetIterations(iterations);
filter->SetCondutance(condutance);
filter->SetTimeStep(timeStep);
filter->SetQ(q);
filter->Update();
scalarToVectorImageFilter->SetInput(countImage, filter->GetOutput());
}
scalarToVectorImageFilter->Update();
VectorImageType::Pointer diffusionImage = scalarToVectorImageFilter->GetOutput();
// let's write it out
typename itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
itk::MetaDataDictionary metaDataDictionary;
metaDataDictionary = reader->GetMetaDataDictionary();
io->SetFileTypeToBinary();
io->SetMetaDataDictionary( metaDataDictionary );
typedef itk::ImageFileWriter<VectorImageType> WriterType;
typename WriterType::Pointer nrrdWriter = WriterType::New();
nrrdWriter->UseInputMetaDataDictionaryOff();
nrrdWriter->SetInput( diffusionImage );
nrrdWriter->SetImageIO(io);
nrrdWriter->SetFileName( outputVolume.c_str() );
nrrdWriter->UseCompressionOn();
try
{
nrrdWriter->Update();
}
catch( itk::ExceptionObject e )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // end of anonymous namespace
int main( int argc, char * argv[] )
{
PARSE_ARGS;
itk::ImageIOBase::IOPixelType pixelType;
itk::ImageIOBase::IOComponentType componentType;
try
{
itk::GetImageType(inputVolume, pixelType, componentType);
// This filter handles all types on input, but only produces
// signed types
switch( componentType )
{
case itk::ImageIOBase::UCHAR:
return DoIt( argc, argv, static_cast<unsigned char>(0) );
break;
case itk::ImageIOBase::CHAR:
return DoIt( argc, argv, static_cast<char>(0) );
break;
case itk::ImageIOBase::USHORT:
return DoIt( argc, argv, static_cast<unsigned short>(0) );
break;
case itk::ImageIOBase::SHORT:
return DoIt( argc, argv, static_cast<short>(0) );
break;
case itk::ImageIOBase::UINT:
return DoIt( argc, argv, static_cast<unsigned int>(0) );
break;
case itk::ImageIOBase::INT:
return DoIt( argc, argv, static_cast<int>(0) );
break;
case itk::ImageIOBase::ULONG:
return DoIt( argc, argv, static_cast<unsigned long>(0) );
break;
case itk::ImageIOBase::LONG:
return DoIt( argc, argv, static_cast<long>(0) );
break;
case itk::ImageIOBase::FLOAT:
return DoIt( argc, argv, static_cast<float>(0) );
break;
case itk::ImageIOBase::DOUBLE:
return DoIt( argc, argv, static_cast<double>(0) );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
std::cout << "unknown component type" << std::endl;
break;
}
}
catch( itk::ExceptionObject & excep )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|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 <vector>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_install_dialog.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/extensions/webstore_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "net/base/mock_host_resolver.h"
#include "ui/gfx/gl/gl_switches.h"
using namespace extension_function_test_utils;
namespace {
class WebstoreInstallListener : public WebstoreInstaller::Delegate {
public:
WebstoreInstallListener()
: received_failure_(false), received_success_(false), waiting_(false) {}
void OnExtensionInstallSuccess(const std::string& id) OVERRIDE;
void OnExtensionInstallFailure(const std::string& id,
const std::string& error) OVERRIDE;
void Wait();
bool received_failure() const { return received_failure_; }
bool received_success() const { return received_success_; }
const std::string& id() const { return id_; }
const std::string& error() const { return error_; }
private:
bool received_failure_;
bool received_success_;
bool waiting_;
std::string id_;
std::string error_;
};
void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) {
received_success_ = true;
id_ = id;
if (waiting_) {
waiting_ = false;
MessageLoopForUI::current()->Quit();
}
}
void WebstoreInstallListener::OnExtensionInstallFailure(
const std::string& id, const std::string& error) {
received_failure_ = true;
id_ = id;
error_ = error;
if (waiting_) {
waiting_ = false;
MessageLoopForUI::current()->Quit();
}
}
void WebstoreInstallListener::Wait() {
if (received_success_ || received_failure_)
return;
waiting_ = true;
ui_test_utils::RunMessageLoop();
}
} // namespace
// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
switches::kAppsGalleryURL, "http://www.example.com");
command_line->AppendSwitchASCII(
switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
}
void SetUpInProcessBrowserTestFixture() OVERRIDE {
// Start up the test server and get us ready for calling the install
// API functions.
host_resolver()->AddRule("www.example.com", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ExtensionInstallUI::DisableFailureUIForTests();
}
protected:
// Returns a test server URL, but with host 'www.example.com' so it matches
// the web store app's extent that we set up via command line flags.
GURL GetTestServerURL(const std::string& path) {
GURL url = test_server()->GetURL(
std::string("files/extensions/api_test/webstore_private/") + path);
// Replace the host with 'www.example.com' so it matches the web store
// app's extent.
GURL::Replacements replace_host;
std::string host_str("www.example.com");
replace_host.SetHostStr(host_str);
return url.ReplaceComponents(replace_host);
}
// Navigates to |page| and runs the Extension API test there. Any downloads
// of extensions will return the contents of |crx_file|.
bool RunInstallTest(const std::string& page, const std::string& crx_file) {
GURL crx_url = GetTestServerURL(crx_file);
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAppsGalleryUpdateURL, crx_url.spec());
GURL page_url = GetTestServerURL(page);
return RunPageTest(page_url.spec());
}
ExtensionService* service() {
return browser()->profile()->GetExtensionService();
}
};
class ExtensionWebstorePrivateBundleTest
: public ExtensionWebstorePrivateApiTest {
public:
void SetUpInProcessBrowserTestFixture() OVERRIDE {
ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture();
// The test server needs to have already started, so setup the switch here
// rather than in SetUpCommandLine.
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAppsGalleryDownloadURL,
GetTestServerURL("bundle/%s.crx").spec());
PackCRX("begfmnajjkbjdgmffnjaojchoncnmngg");
PackCRX("bmfoocgfinpmkmlbjhcbofejhkhlbchk");
PackCRX("mpneghmdnmaolkljkipbhaienajcflfe");
}
void TearDownInProcessBrowserTestFixture() OVERRIDE {
ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture();
for (size_t i = 0; i < test_crx_.size(); ++i)
ASSERT_TRUE(file_util::Delete(test_crx_[i], false));
}
private:
void PackCRX(const std::string& id) {
FilePath data_path = test_data_dir_.AppendASCII("webstore_private/bundle");
FilePath dir_path = data_path.AppendASCII(id);
FilePath pem_path = data_path.AppendASCII(id + ".pem");
FilePath crx_path = data_path.AppendASCII(id + ".crx");
FilePath destination = PackExtensionWithOptions(
dir_path, crx_path, pem_path, FilePath());
ASSERT_FALSE(destination.empty());
ASSERT_EQ(destination, crx_path);
test_crx_.push_back(destination);
}
std::vector<FilePath> test_crx_;
};
class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest {
public:
void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
// In linux, we need to launch GPU process to decide if WebGL is allowed.
// Run it on top of osmesa to avoid bot driver issues.
#if defined(OS_LINUX)
CHECK(test_launcher_utils::OverrideGLImplementation(
command_line, gfx::kGLImplementationOSMesaName)) <<
"kUseGL must not be set multiple times!";
#endif
}
protected:
void RunTest(bool webgl_allowed) {
static const char kEmptyArgs[] = "[]";
static const char kWebGLStatusAllowed[] = "webgl_allowed";
static const char kWebGLStatusBlocked[] = "webgl_blocked";
scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
new GetWebGLStatusFunction(), kEmptyArgs, browser()));
EXPECT_EQ(base::Value::TYPE_STRING, result->GetType());
StringValue* value = static_cast<StringValue*>(result.get());
std::string webgl_status = "";
EXPECT_TRUE(value && value->GetAsString(&webgl_status));
EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked,
webgl_status.c_str());
}
};
// Test cases where the user accepts the install confirmation dialog.
//
// flaky: http://crbug.com/111308
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FLAKY_InstallAccepted) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath temp_path = temp_dir.path();
WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);
ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
}
// Test having the default download directory missing.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) {
// Set a non-existent directory as the download path.
ScopedTempDir temp_dir;
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath missing_directory = temp_dir.Take();
EXPECT_TRUE(file_util::Delete(missing_directory, true));
WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory);
// Now run the install test, which should succeed.
ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
// Cleanup.
if (file_util::DirectoryExists(missing_directory))
EXPECT_TRUE(file_util::Delete(missing_directory, true));
}
// Tests passing a localized name.
//
// flaky: http://crbug.com/111308
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
FLAKY_InstallLocalized) {
ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx"));
}
// Now test the case where the user cancels the confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAppsGalleryInstallAutoConfirmForTests, "cancel");
ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx"));
}
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
IncorrectManifest1) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath temp_path = temp_dir.path();
WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);
WebstoreInstallListener listener;
WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx"));
listener.Wait();
ASSERT_TRUE(listener.received_failure());
ASSERT_EQ("Manifest file is invalid.", listener.error());
}
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
IncorrectManifest2) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath temp_path = temp_dir.path();
WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);
WebstoreInstallListener listener;
WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx"));
listener.Wait();
EXPECT_TRUE(listener.received_failure());
ASSERT_EQ("Manifest file is invalid.", listener.error());
}
// Tests that we can request an app installed bubble (instead of the default
// UI when an app is installed).
//
// flaky: http://crbug.com/111308
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
FLAKY_AppInstallBubble) {
WebstoreInstallListener listener;
WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx"));
listener.Wait();
ASSERT_TRUE(listener.received_success());
ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id());
}
// Tests using the iconUrl parameter to the install function.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
IconUrl) {
ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx"));
}
// Tests using silentlyInstall to install extensions.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest, SilentlyInstall) {
WebstorePrivateApi::SetTrustTestIDsForTesting(true);
ASSERT_TRUE(RunPageTest(GetTestServerURL("silently_install.html").spec()));
}
// Tests getWebGLStatus function when WebGL is allowed.
IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) {
bool webgl_allowed = true;
RunTest(webgl_allowed);
}
// Tests getWebGLStatus function when WebGL is blacklisted.
IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) {
static const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"webgl\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
GpuBlacklist* blacklist = new GpuBlacklist("1.0");
ASSERT_TRUE(blacklist->LoadGpuBlacklist(
json_blacklist, GpuBlacklist::kAllOs));
GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));
bool webgl_allowed = false;
RunTest(webgl_allowed);
}
<commit_msg>Mark ExtensionWebstorePrivateApiTest.SilentlyInstall as flaky.<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 <vector>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_install_dialog.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/extensions/webstore_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "net/base/mock_host_resolver.h"
#include "ui/gfx/gl/gl_switches.h"
using namespace extension_function_test_utils;
namespace {
class WebstoreInstallListener : public WebstoreInstaller::Delegate {
public:
WebstoreInstallListener()
: received_failure_(false), received_success_(false), waiting_(false) {}
void OnExtensionInstallSuccess(const std::string& id) OVERRIDE;
void OnExtensionInstallFailure(const std::string& id,
const std::string& error) OVERRIDE;
void Wait();
bool received_failure() const { return received_failure_; }
bool received_success() const { return received_success_; }
const std::string& id() const { return id_; }
const std::string& error() const { return error_; }
private:
bool received_failure_;
bool received_success_;
bool waiting_;
std::string id_;
std::string error_;
};
void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) {
received_success_ = true;
id_ = id;
if (waiting_) {
waiting_ = false;
MessageLoopForUI::current()->Quit();
}
}
void WebstoreInstallListener::OnExtensionInstallFailure(
const std::string& id, const std::string& error) {
received_failure_ = true;
id_ = id;
error_ = error;
if (waiting_) {
waiting_ = false;
MessageLoopForUI::current()->Quit();
}
}
void WebstoreInstallListener::Wait() {
if (received_success_ || received_failure_)
return;
waiting_ = true;
ui_test_utils::RunMessageLoop();
}
} // namespace
// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
switches::kAppsGalleryURL, "http://www.example.com");
command_line->AppendSwitchASCII(
switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
}
void SetUpInProcessBrowserTestFixture() OVERRIDE {
// Start up the test server and get us ready for calling the install
// API functions.
host_resolver()->AddRule("www.example.com", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ExtensionInstallUI::DisableFailureUIForTests();
}
protected:
// Returns a test server URL, but with host 'www.example.com' so it matches
// the web store app's extent that we set up via command line flags.
GURL GetTestServerURL(const std::string& path) {
GURL url = test_server()->GetURL(
std::string("files/extensions/api_test/webstore_private/") + path);
// Replace the host with 'www.example.com' so it matches the web store
// app's extent.
GURL::Replacements replace_host;
std::string host_str("www.example.com");
replace_host.SetHostStr(host_str);
return url.ReplaceComponents(replace_host);
}
// Navigates to |page| and runs the Extension API test there. Any downloads
// of extensions will return the contents of |crx_file|.
bool RunInstallTest(const std::string& page, const std::string& crx_file) {
GURL crx_url = GetTestServerURL(crx_file);
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAppsGalleryUpdateURL, crx_url.spec());
GURL page_url = GetTestServerURL(page);
return RunPageTest(page_url.spec());
}
ExtensionService* service() {
return browser()->profile()->GetExtensionService();
}
};
class ExtensionWebstorePrivateBundleTest
: public ExtensionWebstorePrivateApiTest {
public:
void SetUpInProcessBrowserTestFixture() OVERRIDE {
ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture();
// The test server needs to have already started, so setup the switch here
// rather than in SetUpCommandLine.
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAppsGalleryDownloadURL,
GetTestServerURL("bundle/%s.crx").spec());
PackCRX("begfmnajjkbjdgmffnjaojchoncnmngg");
PackCRX("bmfoocgfinpmkmlbjhcbofejhkhlbchk");
PackCRX("mpneghmdnmaolkljkipbhaienajcflfe");
}
void TearDownInProcessBrowserTestFixture() OVERRIDE {
ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture();
for (size_t i = 0; i < test_crx_.size(); ++i)
ASSERT_TRUE(file_util::Delete(test_crx_[i], false));
}
private:
void PackCRX(const std::string& id) {
FilePath data_path = test_data_dir_.AppendASCII("webstore_private/bundle");
FilePath dir_path = data_path.AppendASCII(id);
FilePath pem_path = data_path.AppendASCII(id + ".pem");
FilePath crx_path = data_path.AppendASCII(id + ".crx");
FilePath destination = PackExtensionWithOptions(
dir_path, crx_path, pem_path, FilePath());
ASSERT_FALSE(destination.empty());
ASSERT_EQ(destination, crx_path);
test_crx_.push_back(destination);
}
std::vector<FilePath> test_crx_;
};
class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest {
public:
void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
// In linux, we need to launch GPU process to decide if WebGL is allowed.
// Run it on top of osmesa to avoid bot driver issues.
#if defined(OS_LINUX)
CHECK(test_launcher_utils::OverrideGLImplementation(
command_line, gfx::kGLImplementationOSMesaName)) <<
"kUseGL must not be set multiple times!";
#endif
}
protected:
void RunTest(bool webgl_allowed) {
static const char kEmptyArgs[] = "[]";
static const char kWebGLStatusAllowed[] = "webgl_allowed";
static const char kWebGLStatusBlocked[] = "webgl_blocked";
scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
new GetWebGLStatusFunction(), kEmptyArgs, browser()));
EXPECT_EQ(base::Value::TYPE_STRING, result->GetType());
StringValue* value = static_cast<StringValue*>(result.get());
std::string webgl_status = "";
EXPECT_TRUE(value && value->GetAsString(&webgl_status));
EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked,
webgl_status.c_str());
}
};
// Test cases where the user accepts the install confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath temp_path = temp_dir.path();
WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);
ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
}
// Test having the default download directory missing.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) {
// Set a non-existent directory as the download path.
ScopedTempDir temp_dir;
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath missing_directory = temp_dir.Take();
EXPECT_TRUE(file_util::Delete(missing_directory, true));
WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory);
// Now run the install test, which should succeed.
ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
// Cleanup.
if (file_util::DirectoryExists(missing_directory))
EXPECT_TRUE(file_util::Delete(missing_directory, true));
}
// Tests passing a localized name.
//
// flaky: http://crbug.com/111308
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
FLAKY_InstallLocalized) {
ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx"));
}
// Now test the case where the user cancels the confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAppsGalleryInstallAutoConfirmForTests, "cancel");
ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx"));
}
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
IncorrectManifest1) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath temp_path = temp_dir.path();
WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);
WebstoreInstallListener listener;
WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx"));
listener.Wait();
ASSERT_TRUE(listener.received_failure());
ASSERT_EQ("Manifest file is invalid.", listener.error());
}
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
IncorrectManifest2) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath temp_path = temp_dir.path();
WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);
WebstoreInstallListener listener;
WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx"));
listener.Wait();
EXPECT_TRUE(listener.received_failure());
ASSERT_EQ("Manifest file is invalid.", listener.error());
}
// Tests that we can request an app installed bubble (instead of the default
// UI when an app is installed).
//
// flaky: http://crbug.com/111308
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
FLAKY_AppInstallBubble) {
WebstoreInstallListener listener;
WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx"));
listener.Wait();
ASSERT_TRUE(listener.received_success());
ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id());
}
// Tests using the iconUrl parameter to the install function.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
IconUrl) {
ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx"));
}
// Tests using silentlyInstall to install extensions.
//
// flaky: http://crbug.com/111308
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest,
FLAKY_SilentlyInstall) {
WebstorePrivateApi::SetTrustTestIDsForTesting(true);
ASSERT_TRUE(RunPageTest(GetTestServerURL("silently_install.html").spec()));
}
// Tests getWebGLStatus function when WebGL is allowed.
IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) {
bool webgl_allowed = true;
RunTest(webgl_allowed);
}
// Tests getWebGLStatus function when WebGL is blacklisted.
IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) {
static const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"webgl\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
GpuBlacklist* blacklist = new GpuBlacklist("1.0");
ASSERT_TRUE(blacklist->LoadGpuBlacklist(
json_blacklist, GpuBlacklist::kAllOs));
GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));
bool webgl_allowed = false;
RunTest(webgl_allowed);
}
<|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 "chrome/browser/notifications/notification_options_menu_model.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/notifications/balloon_collection.h"
#include "chrome/browser/notifications/balloon_host.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
// Menu commands
const int kTogglePermissionCommand = 0;
const int kToggleExtensionCommand = 1;
const int kOpenContentSettingsCommand = 2;
const int kCornerSelectionSubMenu = 3;
const int kCornerGroupId = 10;
const int kCornerUpperLeft = 11;
const int kCornerUpperRight = 12;
const int kCornerLowerLeft = 13;
const int kCornerLowerRight = 14;
const int kCornerDefault = 20;
CornerSelectionMenuModel::CornerSelectionMenuModel(Balloon* balloon)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
balloon_(balloon) {
AddRadioItem(kCornerDefault,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_DEFAULT),
kCornerGroupId);
AddSeparator();
AddRadioItem(kCornerUpperLeft,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_LEFT),
kCornerGroupId);
AddRadioItem(kCornerUpperRight,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_RIGHT),
kCornerGroupId);
AddRadioItem(kCornerLowerLeft,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_LEFT),
kCornerGroupId);
AddRadioItem(kCornerLowerRight,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_RIGHT),
kCornerGroupId);
}
CornerSelectionMenuModel::~CornerSelectionMenuModel() {
}
bool CornerSelectionMenuModel::IsCommandIdChecked(int command_id) const {
NotificationUIManager* ui = g_browser_process->notification_ui_manager();
BalloonCollection::PositionPreference current = ui->GetPositionPreference();
LOG(INFO) << "Current position preference: " << current;
if (command_id == kCornerUpperLeft)
return (current == BalloonCollection::UPPER_LEFT);
else if (command_id == kCornerUpperRight)
return (current == BalloonCollection::UPPER_RIGHT);
else if (command_id == kCornerLowerLeft)
return (current == BalloonCollection::LOWER_LEFT);
else if (command_id == kCornerLowerRight)
return (current == BalloonCollection::LOWER_RIGHT);
else if (command_id == kCornerDefault)
return (current == BalloonCollection::DEFAULT_POSITION);
NOTREACHED();
return false;
}
bool CornerSelectionMenuModel::IsCommandIdEnabled(int command_id) const {
// All the menu options are always enabled.
return true;
}
bool CornerSelectionMenuModel::GetAcceleratorForCommandId(
int command_id, ui::Accelerator* accelerator) {
// Currently no accelerators.
return false;
}
void CornerSelectionMenuModel::ExecuteCommand(int command_id) {
NotificationUIManager* ui = g_browser_process->notification_ui_manager();
LOG(INFO) << "Executing command: " << command_id;
if (command_id == kCornerUpperLeft)
ui->SetPositionPreference(BalloonCollection::UPPER_LEFT);
else if (command_id == kCornerUpperRight)
ui->SetPositionPreference(BalloonCollection::UPPER_RIGHT);
else if (command_id == kCornerLowerLeft)
ui->SetPositionPreference(BalloonCollection::LOWER_LEFT);
else if (command_id == kCornerLowerRight)
ui->SetPositionPreference(BalloonCollection::LOWER_RIGHT);
else if (command_id == kCornerDefault)
ui->SetPositionPreference(BalloonCollection::DEFAULT_POSITION);
else
NOTREACHED();
}
NotificationOptionsMenuModel::NotificationOptionsMenuModel(Balloon* balloon)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
balloon_(balloon) {
const Notification& notification = balloon->notification();
const GURL& origin = notification.origin_url();
if (origin.SchemeIs(chrome::kExtensionScheme)) {
const string16 disable_label = l10n_util::GetStringUTF16(
IDS_EXTENSIONS_DISABLE);
AddItem(kToggleExtensionCommand, disable_label);
} else {
const string16 disable_label = l10n_util::GetStringFUTF16(
IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,
notification.display_source());
AddItem(kTogglePermissionCommand, disable_label);
}
const string16 settings_label = l10n_util::GetStringUTF16(
IDS_NOTIFICATIONS_SETTINGS_BUTTON);
AddItem(kOpenContentSettingsCommand, settings_label);
corner_menu_model_.reset(new CornerSelectionMenuModel(balloon));
AddSubMenu(kCornerSelectionSubMenu,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_CHOOSE_POSITION),
corner_menu_model_.get());
}
NotificationOptionsMenuModel::~NotificationOptionsMenuModel() {
}
bool NotificationOptionsMenuModel::IsItemForCommandIdDynamic(int command_id)
const {
return command_id == kTogglePermissionCommand ||
command_id == kToggleExtensionCommand;
}
string16 NotificationOptionsMenuModel::GetLabelForCommandId(int command_id)
const {
// TODO(tfarina,johnnyg): Remove this code if we decide to close notifications
// after permissions are revoked.
if (command_id == kTogglePermissionCommand ||
command_id == kToggleExtensionCommand) {
const Notification& notification = balloon_->notification();
const GURL& origin = notification.origin_url();
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());
if (origin.SchemeIs(chrome::kExtensionScheme)) {
ExtensionService* ext_service =
balloon_->profile()->GetExtensionService();
const Extension* extension = ext_service->GetExtensionByURL(origin);
if (extension) {
ExtensionPrefs* extension_prefs = ext_service->extension_prefs();
const std::string& id = extension->id();
if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE);
else
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE);
}
} else {
if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) {
return l10n_util::GetStringFUTF16(
IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,
notification.display_source());
} else {
return l10n_util::GetStringFUTF16(
IDS_NOTIFICATION_BALLOON_ENABLE_MESSAGE,
notification.display_source());
}
}
} else if (command_id == kOpenContentSettingsCommand) {
return l10n_util::GetStringUTF16(IDS_NOTIFICATIONS_SETTINGS_BUTTON);
}
return string16();
}
bool NotificationOptionsMenuModel::IsCommandIdChecked(int /* command_id */)
const {
// Nothing in the menu is checked.
return false;
}
bool NotificationOptionsMenuModel::IsCommandIdEnabled(int /* command_id */)
const {
// All the menu options are always enabled.
return true;
}
bool NotificationOptionsMenuModel::GetAcceleratorForCommandId(
int /* command_id */, ui::Accelerator* /* accelerator */) {
// Currently no accelerators.
return false;
}
void NotificationOptionsMenuModel::ExecuteCommand(int command_id) {
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());
ExtensionService* ext_service =
balloon_->profile()->GetExtensionService();
const GURL& origin = balloon_->notification().origin_url();
switch (command_id) {
case kTogglePermissionCommand:
if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW)
service->DenyPermission(origin);
else
service->GrantPermission(origin);
break;
case kToggleExtensionCommand: {
const Extension* extension = ext_service->GetExtensionByURL(origin);
if (extension) {
ExtensionPrefs* extension_prefs = ext_service->extension_prefs();
const std::string& id = extension->id();
if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)
ext_service->DisableExtension(id);
else
ext_service->EnableExtension(id);
}
break;
}
case kOpenContentSettingsCommand: {
TabContents* tab_contents =
balloon_->view()->GetHost()->associated_tab_contents();
tab_contents->delegate()->ShowContentSettingsPage(
CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
break;
}
default:
NOTREACHED();
break;
}
}
<commit_msg>Fix opening settings page for balloons.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/notification_options_menu_model.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/notifications/balloon_collection.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents_delegate.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
// Menu commands
const int kTogglePermissionCommand = 0;
const int kToggleExtensionCommand = 1;
const int kOpenContentSettingsCommand = 2;
const int kCornerSelectionSubMenu = 3;
const int kCornerGroupId = 10;
const int kCornerUpperLeft = 11;
const int kCornerUpperRight = 12;
const int kCornerLowerLeft = 13;
const int kCornerLowerRight = 14;
const int kCornerDefault = 20;
CornerSelectionMenuModel::CornerSelectionMenuModel(Balloon* balloon)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
balloon_(balloon) {
AddRadioItem(kCornerDefault,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_DEFAULT),
kCornerGroupId);
AddSeparator();
AddRadioItem(kCornerUpperLeft,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_LEFT),
kCornerGroupId);
AddRadioItem(kCornerUpperRight,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_RIGHT),
kCornerGroupId);
AddRadioItem(kCornerLowerLeft,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_LEFT),
kCornerGroupId);
AddRadioItem(kCornerLowerRight,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_RIGHT),
kCornerGroupId);
}
CornerSelectionMenuModel::~CornerSelectionMenuModel() {
}
bool CornerSelectionMenuModel::IsCommandIdChecked(int command_id) const {
NotificationUIManager* ui = g_browser_process->notification_ui_manager();
BalloonCollection::PositionPreference current = ui->GetPositionPreference();
LOG(INFO) << "Current position preference: " << current;
if (command_id == kCornerUpperLeft)
return (current == BalloonCollection::UPPER_LEFT);
else if (command_id == kCornerUpperRight)
return (current == BalloonCollection::UPPER_RIGHT);
else if (command_id == kCornerLowerLeft)
return (current == BalloonCollection::LOWER_LEFT);
else if (command_id == kCornerLowerRight)
return (current == BalloonCollection::LOWER_RIGHT);
else if (command_id == kCornerDefault)
return (current == BalloonCollection::DEFAULT_POSITION);
NOTREACHED();
return false;
}
bool CornerSelectionMenuModel::IsCommandIdEnabled(int command_id) const {
// All the menu options are always enabled.
return true;
}
bool CornerSelectionMenuModel::GetAcceleratorForCommandId(
int command_id, ui::Accelerator* accelerator) {
// Currently no accelerators.
return false;
}
void CornerSelectionMenuModel::ExecuteCommand(int command_id) {
NotificationUIManager* ui = g_browser_process->notification_ui_manager();
LOG(INFO) << "Executing command: " << command_id;
if (command_id == kCornerUpperLeft)
ui->SetPositionPreference(BalloonCollection::UPPER_LEFT);
else if (command_id == kCornerUpperRight)
ui->SetPositionPreference(BalloonCollection::UPPER_RIGHT);
else if (command_id == kCornerLowerLeft)
ui->SetPositionPreference(BalloonCollection::LOWER_LEFT);
else if (command_id == kCornerLowerRight)
ui->SetPositionPreference(BalloonCollection::LOWER_RIGHT);
else if (command_id == kCornerDefault)
ui->SetPositionPreference(BalloonCollection::DEFAULT_POSITION);
else
NOTREACHED();
}
NotificationOptionsMenuModel::NotificationOptionsMenuModel(Balloon* balloon)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
balloon_(balloon) {
const Notification& notification = balloon->notification();
const GURL& origin = notification.origin_url();
if (origin.SchemeIs(chrome::kExtensionScheme)) {
const string16 disable_label = l10n_util::GetStringUTF16(
IDS_EXTENSIONS_DISABLE);
AddItem(kToggleExtensionCommand, disable_label);
} else {
const string16 disable_label = l10n_util::GetStringFUTF16(
IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,
notification.display_source());
AddItem(kTogglePermissionCommand, disable_label);
}
const string16 settings_label = l10n_util::GetStringUTF16(
IDS_NOTIFICATIONS_SETTINGS_BUTTON);
AddItem(kOpenContentSettingsCommand, settings_label);
corner_menu_model_.reset(new CornerSelectionMenuModel(balloon));
AddSubMenu(kCornerSelectionSubMenu,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_CHOOSE_POSITION),
corner_menu_model_.get());
}
NotificationOptionsMenuModel::~NotificationOptionsMenuModel() {
}
bool NotificationOptionsMenuModel::IsItemForCommandIdDynamic(int command_id)
const {
return command_id == kTogglePermissionCommand ||
command_id == kToggleExtensionCommand;
}
string16 NotificationOptionsMenuModel::GetLabelForCommandId(int command_id)
const {
// TODO(tfarina,johnnyg): Remove this code if we decide to close notifications
// after permissions are revoked.
if (command_id == kTogglePermissionCommand ||
command_id == kToggleExtensionCommand) {
const Notification& notification = balloon_->notification();
const GURL& origin = notification.origin_url();
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());
if (origin.SchemeIs(chrome::kExtensionScheme)) {
ExtensionService* ext_service =
balloon_->profile()->GetExtensionService();
const Extension* extension = ext_service->GetExtensionByURL(origin);
if (extension) {
ExtensionPrefs* extension_prefs = ext_service->extension_prefs();
const std::string& id = extension->id();
if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE);
else
return l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE);
}
} else {
if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) {
return l10n_util::GetStringFUTF16(
IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,
notification.display_source());
} else {
return l10n_util::GetStringFUTF16(
IDS_NOTIFICATION_BALLOON_ENABLE_MESSAGE,
notification.display_source());
}
}
} else if (command_id == kOpenContentSettingsCommand) {
return l10n_util::GetStringUTF16(IDS_NOTIFICATIONS_SETTINGS_BUTTON);
}
return string16();
}
bool NotificationOptionsMenuModel::IsCommandIdChecked(int /* command_id */)
const {
// Nothing in the menu is checked.
return false;
}
bool NotificationOptionsMenuModel::IsCommandIdEnabled(int /* command_id */)
const {
// All the menu options are always enabled.
return true;
}
bool NotificationOptionsMenuModel::GetAcceleratorForCommandId(
int /* command_id */, ui::Accelerator* /* accelerator */) {
// Currently no accelerators.
return false;
}
void NotificationOptionsMenuModel::ExecuteCommand(int command_id) {
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());
ExtensionService* ext_service =
balloon_->profile()->GetExtensionService();
const GURL& origin = balloon_->notification().origin_url();
switch (command_id) {
case kTogglePermissionCommand:
if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW)
service->DenyPermission(origin);
else
service->GrantPermission(origin);
break;
case kToggleExtensionCommand: {
const Extension* extension = ext_service->GetExtensionByURL(origin);
if (extension) {
ExtensionPrefs* extension_prefs = ext_service->extension_prefs();
const std::string& id = extension->id();
if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)
ext_service->DisableExtension(id);
else
ext_service->EnableExtension(id);
}
break;
}
case kOpenContentSettingsCommand: {
Browser* browser =
BrowserList::GetLastActiveWithProfile(balloon_->profile());
if (!browser) {
// It is possible that there is no browser window (e.g. when there are
// background pages, or for a chrome frame process on windows).
browser = Browser::Create(balloon_->profile());
}
static_cast<TabContentsDelegate*>(browser)->ShowContentSettingsPage(
CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
break;
}
default:
NOTREACHED();
break;
}
}
<|endoftext|>
|
<commit_before>/*
Reproducing xfstest generic/321 directory_test()
1. Create directory A and fsync it
After a crash, the directory should still be present.
https://github.com/kdave/xfstests/blob/master/tests/generic/321
*/
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <dirent.h>
#include <cstring>
#include <errno.h>
#include "BaseTestCase.h"
#include "../user_tools/api/workload.h"
#include "../user_tools/api/actions.h"
#define TEST_DIR_A "test_dir_a"
using fs_testing::tests::DataTestResult;
using fs_testing::user_tools::api::WriteData;
using fs_testing::user_tools::api::WriteDataMmap;
using fs_testing::user_tools::api::Checkpoint;
using std::string;
#define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO))
namespace fs_testing {
namespace tests {
class Generic321_1: public BaseTestCase {
public:
virtual int setup() override {
init_paths();
// Create test directory A.
int res = mkdir(dir_path.c_str(), 0777);
if (res < 0) {
return -1;
}
// fsync the directory
int dir = open(dir_path.c_str(), O_RDONLY, O_DIRECTORY);
if (dir < 0) {
return -4;
}
if (fsync(dir) < 0) {
return -5;
}
close(dir);
return 0;
}
virtual int run() override {
// nothing here since it's a simple test
if (Checkpoint() < 0){
return -5;
}
return 0;
}
virtual int check_test(unsigned int last_checkpoint,
DataTestResult *test_result) override {
init_paths();
struct stat stats;
const int stats_res = stat(dir_path.c_str(), &stats);
const int errno_stats = errno;
if (stats_res < 0 && errno_stats == ENOENT) {
test_result->SetError(DataTestResult::kFileMissing);
test_result->error_description = " : " + dir_path + " is missing";
return 0;
}
// If it is not a directory
if (!S_ISDIR(stats.st_mode)) {
test_result->SetError(DataTestResult::kFileMetadataCorrupted);
test_result->error_description = " : " + dir_path + " is not a directory";
return 0;
}
return 0;
}
private:
string dir_path;
void init_paths() {
dir_path = mnt_dir_ + "/" TEST_DIR_A;
}
};
} // namespace tests
} // namespace fs_testing
extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() {
return new fs_testing::tests::Generic321_1;
}
extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) {
delete tc;
}
<commit_msg>Moving create and fsync to run method in generic 321_1<commit_after>/*
Reproducing xfstest generic/321 directory_test()
1. Create directory A and fsync it
After a crash, the directory should still be present.
https://github.com/kdave/xfstests/blob/master/tests/generic/321
*/
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <dirent.h>
#include <cstring>
#include <errno.h>
#include "BaseTestCase.h"
#include "../user_tools/api/workload.h"
#include "../user_tools/api/actions.h"
#define TEST_DIR_A "test_dir_a"
using fs_testing::tests::DataTestResult;
using fs_testing::user_tools::api::WriteData;
using fs_testing::user_tools::api::WriteDataMmap;
using fs_testing::user_tools::api::Checkpoint;
using std::string;
#define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO))
namespace fs_testing {
namespace tests {
class Generic321_1: public BaseTestCase {
public:
virtual int setup() override {
return 0;
}
virtual int run() override {
// Create test directory A.
int res = mkdir(dir_path.c_str(), 0777);
if (res < 0) {
return -1;
}
// fsync the directory
int dir = open(dir_path.c_str(), O_RDONLY, O_DIRECTORY);
if (dir < 0) {
return -4;
}
if (fsync(dir) < 0) {
return -5;
}
if (Checkpoint() < 0){
return -5;
}
close(dir);
return 0;
}
virtual int check_test(unsigned int last_checkpoint,
DataTestResult *test_result) override {
init_paths();
struct stat stats;
const int stats_res = stat(dir_path.c_str(), &stats);
const int errno_stats = errno;
if (stats_res < 0 && errno_stats == ENOENT && last_checkpoint == 1) {
test_result->SetError(DataTestResult::kFileMissing);
test_result->error_description = " : " + dir_path + " is missing";
return 0;
}
// If it is not a directory
if (!S_ISDIR(stats.st_mode) && last_checkpoint == 1) {
test_result->SetError(DataTestResult::kFileMetadataCorrupted);
test_result->error_description = " : " + dir_path + " is not a directory";
return 0;
}
return 0;
}
private:
string dir_path;
void init_paths() {
dir_path = mnt_dir_ + "/" TEST_DIR_A;
}
};
} // namespace tests
} // namespace fs_testing
extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() {
return new fs_testing::tests::Generic321_1;
}
extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) {
delete tc;
}
<|endoftext|>
|
<commit_before>#include "eprosimartps/CDRMessage.h"
TEST(CDRMessage, constructor)
{
CDRMessage_t msg;
ASSERT_EQ(0,msg.pos);
ASSERT_EQ(0,msg.length);
ASSERT_EQ(RTPSMESSAGE_MAX_SIZE,msg.max_size);
ASSERT_TRUE(NULL != msg.buffer);
ASSERT_EQ(EPROSIMA_ENDIAN,msg.msg_endian);
}
TEST(CDRMessage, constructor_size)
{
CDRMessage_t msg2(20);
ASSERT_EQ(0,msg2.pos);
ASSERT_EQ(0,msg2.length);
ASSERT_EQ(20,msg2.max_size);
ASSERT_TRUE(NULL != msg2.buffer);
ASSERT_EQ(EPROSIMA_ENDIAN,msg2.msg_endian);
}
class CDRMessageTest: public ::testing::Test
{
protected:
void SetUp()
{
}
CDRMessage_t t_msg;
uint16_t t_length;
uint16_t t_pos;
void saveLengthPos()
{
t_length = t_msg.length;
t_pos = t_msg.pos;
}
bool checkLengthIncrement(uint16_t inc)
{
if(t_length+inc == t_msg.length)
return true;
else
return false;
}
bool checkPosIncrement(uint16_t inc)
{
if(t_pos+inc == t_msg.pos)
return true;
else
return false;
}
};
TEST_F(CDRMessageTest, octet)
{
octet o = 35;
saveLengthPos();
CDRMessage::addOctet(&t_msg,o);
EXPECT_TRUE(checkLengthIncrement(1));
EXPECT_TRUE(checkPosIncrement(1));
ASSERT_EQ(35,t_msg.buffer[t_msg.pos-1]) << "Octet not added correctly";
t_msg.pos--;
saveLengthPos();
CDRMessage::readOctet(&t_msg,&o);
EXPECT_FALSE(checkLengthIncrement(1));
EXPECT_TRUE(checkPosIncrement(1));
ASSERT_EQ(35,o) << "Octet not readed correctly";
}
TEST_F(CDRMessageTest, uint16)
{
uint16_t n = 645;
saveLengthPos();
CDRMessage::addUInt16(&t_msg,n);
EXPECT_TRUE(checkLengthIncrement(2));
EXPECT_TRUE(checkPosIncrement(2));
t_msg.pos-=2;
CDRMessage::readUInt16(&t_msg,&n);
ASSERT_EQ(645,n);
}
TEST_F(CDRMessageTest, uint32)
{
uint32_t n = 123456;
saveLengthPos();
CDRMessage::addUInt32(&t_msg,n);
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
CDRMessage::readUInt32(&t_msg,&n);
ASSERT_EQ(123456,n);
}
TEST_F(CDRMessageTest, int32)
{
int32_t n = 123456;
saveLengthPos();
EXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
EXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));
ASSERT_EQ(123456,n);
n = -123456;
saveLengthPos();
EXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
EXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));
ASSERT_EQ(-123456,n);
}
TEST_F(CDRMessageTest, SequenceNumber)
{
SequenceNumber_t seq;
seq.high = 10;
seq.low = 25;
saveLengthPos();
EXPECT_TRUE(CDRMessage::addSequenceNumber(&t_msg,&seq));
EXPECT_TRUE(checkLengthIncrement(8));
EXPECT_TRUE(checkPosIncrement(8));
t_msg.pos-=8;
CDRMessage::readSequenceNumber(&t_msg,&n);
ASSERT_EQ(123456,n);
n = -123456;
saveLengthPos();
CDRMessage::addInt32(&t_msg,n);
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
CDRMessage::readInt32(&t_msg,&n);
ASSERT_EQ(-123456,n);
}
<commit_msg>CDRMessage SeqNum unittest<commit_after>#include "eprosimartps/CDRMessage.h"
TEST(CDRMessage, constructor)
{
CDRMessage_t msg;
ASSERT_EQ(0,msg.pos);
ASSERT_EQ(0,msg.length);
ASSERT_EQ(RTPSMESSAGE_MAX_SIZE,msg.max_size);
ASSERT_TRUE(NULL != msg.buffer);
ASSERT_EQ(EPROSIMA_ENDIAN,msg.msg_endian);
}
TEST(CDRMessage, constructor_size)
{
CDRMessage_t msg2(20);
ASSERT_EQ(0,msg2.pos);
ASSERT_EQ(0,msg2.length);
ASSERT_EQ(20,msg2.max_size);
ASSERT_TRUE(NULL != msg2.buffer);
ASSERT_EQ(EPROSIMA_ENDIAN,msg2.msg_endian);
}
class CDRMessageTest: public ::testing::Test
{
protected:
void SetUp()
{
}
CDRMessage_t t_msg;
uint16_t t_length;
uint16_t t_pos;
void saveLengthPos()
{
t_length = t_msg.length;
t_pos = t_msg.pos;
}
bool checkLengthIncrement(uint16_t inc)
{
if(t_length+inc == t_msg.length)
return true;
else
return false;
}
bool checkPosIncrement(uint16_t inc)
{
if(t_pos+inc == t_msg.pos)
return true;
else
return false;
}
};
TEST_F(CDRMessageTest, octet)
{
octet o = 35;
saveLengthPos();
CDRMessage::addOctet(&t_msg,o);
EXPECT_TRUE(checkLengthIncrement(1));
EXPECT_TRUE(checkPosIncrement(1));
ASSERT_EQ(35,t_msg.buffer[t_msg.pos-1]) << "Octet not added correctly";
t_msg.pos--;
saveLengthPos();
CDRMessage::readOctet(&t_msg,&o);
EXPECT_FALSE(checkLengthIncrement(1));
EXPECT_TRUE(checkPosIncrement(1));
ASSERT_EQ(35,o) << "Octet not readed correctly";
}
TEST_F(CDRMessageTest, uint16)
{
uint16_t n = 645;
saveLengthPos();
CDRMessage::addUInt16(&t_msg,n);
EXPECT_TRUE(checkLengthIncrement(2));
EXPECT_TRUE(checkPosIncrement(2));
t_msg.pos-=2;
CDRMessage::readUInt16(&t_msg,&n);
ASSERT_EQ(645,n);
}
TEST_F(CDRMessageTest, uint32)
{
uint32_t n = 123456;
saveLengthPos();
CDRMessage::addUInt32(&t_msg,n);
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
CDRMessage::readUInt32(&t_msg,&n);
ASSERT_EQ(123456,n);
}
TEST_F(CDRMessageTest, int32)
{
int32_t n = 123456;
saveLengthPos();
EXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
EXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));
ASSERT_EQ(123456,n);
n = -123456;
saveLengthPos();
EXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));
EXPECT_TRUE(checkLengthIncrement(4));
EXPECT_TRUE(checkPosIncrement(4));
t_msg.pos-=4;
EXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));
ASSERT_EQ(-123456,n);
}
TEST_F(CDRMessageTest, SequenceNumber)
{
SequenceNumber_t seq;
seq.high = 10;
seq.low = 25;
saveLengthPos();
EXPECT_TRUE(CDRMessage::addSequenceNumber(&t_msg,&seq));
EXPECT_TRUE(checkLengthIncrement(8));
EXPECT_TRUE(checkPosIncrement(8));
t_msg.pos-=8;
CDRMessage::readSequenceNumber(&t_msg,&seq);
ASSERT_EQ(10,seq.high);
ASSERT_EQ(25,seq.low);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* 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 <znc/FileUtils.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <znc/ZNCDebug.h>
class CAdminDebugMod : public CModule {
private:
CString m_sEnabledBy;
public:
MODCONSTRUCTOR(CAdminDebugMod) {
AddHelpCommand();
AddCommand("Enable", "", t_d("Enable Debug Mode"),
[=](const CString& sLine) { CommandEnable(sLine); });
AddCommand("Disable", "", t_d("Disable Debug Mode"),
[=](const CString& sLine) { CommandDisable(sLine); });
AddCommand("Status", "", t_d("Show the Debug Mode status"),
[=](const CString& sLine) { CommandStatus(sLine); });
}
void CommandEnable(const CString& sCommand) {
if (GetUser()->IsAdmin() == false) {
PutModule(t_s("Access denied!"));
return;
}
ToggleDebug(true, GetUser()->GetNick());
}
void CommandDisable(const CString& sCommand) {
if (GetUser()->IsAdmin() == false) {
PutModule(t_s("Access denied!"));
return;
}
ToggleDebug(false, m_sEnabledBy);
}
bool ToggleDebug(bool bEnable, CString sEnabledBy) {
if (!CDebug::StdoutIsTTY()) {
PutModule(t_s("Failure. We need to be running with a TTY. (is ZNC running with --foreground?)"));
return false;
}
bool bValue = CDebug::Debug();
if (bEnable == bValue) {
if (bEnable) {
PutModule(t_s("Already enabled."));
} else {
PutModule(t_s("Already disabled."));
}
return false;
}
CDebug::SetDebug(bEnable);
CString sEnabled = CString(bEnable ? "on" : "off");
CZNC::Get().Broadcast(CString(
"An administrator has just turned Debug Mode \02" + sEnabled + "\02. It was enabled by \02" + sEnabledBy + "\02."
));
if (bEnable) {
CZNC::Get().Broadcast(
CString("Messages, credentials, and other sensitive data may"
" become exposed to the host during this period.")
);
m_sEnabledBy = sEnabledBy;
} else {
m_sEnabledBy = "";
}
return true;
}
void CommandStatus(const CString& sCommand) {
if (CDebug::Debug()) {
PutModule(t_s("Debugging mode is \02on\02."));
} else {
PutModule(t_s("Debugging mode is \02off\02."));
}
PutModule(t_s("Logging to: \02stdout\02."));
}
};
template <>
void TModInfo<CAdminDebugMod>(CModInfo& Info) {
Info.SetWikiPage("admindebug");
}
GLOBALMODULEDEFS(CAdminDebugMod, t_s("Enable Debug mode dynamically."))
<commit_msg>admindebug: language/style fixes<commit_after>/*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* 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 <znc/FileUtils.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <znc/ZNCDebug.h>
class CAdminDebugMod : public CModule {
private:
CString m_sEnabledBy;
public:
MODCONSTRUCTOR(CAdminDebugMod) {
AddHelpCommand();
AddCommand("Enable", "", t_d("Enable Debug Mode"),
[=](const CString& sLine) { CommandEnable(sLine); });
AddCommand("Disable", "", t_d("Disable Debug Mode"),
[=](const CString& sLine) { CommandDisable(sLine); });
AddCommand("Status", "", t_d("Show the Debug Mode status"),
[=](const CString& sLine) { CommandStatus(sLine); });
}
void CommandEnable(const CString& sCommand) {
if (!GetUser()->IsAdmin()) {
PutModule(t_s("Access denied!"));
return;
}
ToggleDebug(true, GetUser()->GetNick());
}
void CommandDisable(const CString& sCommand) {
if (!GetUser()->IsAdmin()) {
PutModule(t_s("Access denied!"));
return;
}
ToggleDebug(false, m_sEnabledBy);
}
bool ToggleDebug(bool bEnable, const CString& sEnabledBy) {
if (!CDebug::StdoutIsTTY()) {
PutModule(t_s("Failure. We need to be running with a TTY. (is ZNC running with --foreground?)"));
return false;
}
bool bValue = CDebug::Debug();
if (bEnable == bValue) {
if (bEnable) {
PutModule(t_s("Already enabled."));
} else {
PutModule(t_s("Already disabled."));
}
return false;
}
CDebug::SetDebug(bEnable);
CString sEnabled = bEnable ? "on" : "off";
CZNC::Get().Broadcast(
"An administrator has just turned Debug Mode \02" + sEnabled +
"\02. It was enabled by \02" + sEnabledBy + "\02.");
if (bEnable) {
CZNC::Get().Broadcast(
"Messages, credentials, and other sensitive data may become "
"exposed to the host during this period.");
m_sEnabledBy = sEnabledBy;
} else {
m_sEnabledBy = "";
}
return true;
}
void CommandStatus(const CString& sCommand) {
if (CDebug::Debug()) {
PutModule(t_s("Debugging mode is \02on\02."));
} else {
PutModule(t_s("Debugging mode is \02off\02."));
}
PutModule(t_s("Logging to: \02stdout\02."));
}
};
template <>
void TModInfo<CAdminDebugMod>(CModInfo& Info) {
Info.SetWikiPage("admindebug");
}
GLOBALMODULEDEFS(CAdminDebugMod, t_s("Enable Debug mode dynamically."))
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: MTypeConverter.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: fs $ $Date: 2002-05-17 12:08:41 $
*
* 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 EXPRESS 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): Willem van Dorp, Darren Kenny
*
*
************************************************************************/
#include <MNSInclude.hxx>
#ifndef _CONNECTIVITY_MAB_TYPECONVERTER_HXX_
#include "MTypeConverter.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
using namespace connectivity::mozab;
// -------------------------------------------------------------------------
void MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)
{
// Convert to ::rtl::OString (utf-8 encoding).
::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);
const char *cs = os.getStr();
PRUint32 csLen = os.getLength();
NS_ConvertUTF8toUCS2 mozString(cs, csLen);
//const PRUnichar* uniMozString = (const PRUnichar*) mozString;
nss = mozString; // temp.
}
// -------------------------------------------------------------------------
void MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)
{
// Get clone of buffer.
PRUnichar *uc = ToNewUnicode(nss);
sal_Int32 nssLen = nss.Length();
// TODO check if this is ok.
::rtl::OUString _ous(uc, nssLen);
ous = _ous;
nsMemory::Free(uc);
}
// -------------------------------------------------------------------------
void MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)
{
// TODO, specify length.
::rtl::OUString _ous(pru);
ous = _ous;
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)
{
// Convert to ::rtl::OString,
::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);
const char *cs = os.getStr();
return(strdup(cs));
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)
{
// Convert ::rtl::OUString to ::rtl::OString,
::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);
return(strdup(os.getStr()));
}
// -------------------------------------------------------------------------
char *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)
{
char cs[1024];
nss.ToCString(cs, 1024);
return(strdup(cs));
}
// -------------------------------------------------------------------------
::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)
{
// Convert ::rtl::OUString to ::rtl::OString.
::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);
return( ::std::string(os.getStr()));
}
#if 0
// -------------------------------------------------------------------------
::std::string MTypeConverter::nsStringToStlString(nsString const &nss)
{
return( ::std::string(nss.GetBuffer()));
}
#endif
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.332); FILE MERGED 2005/09/05 17:24:38 rt 1.4.332.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MTypeConverter.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:30: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
*
************************************************************************/
#include <MNSInclude.hxx>
#ifndef _CONNECTIVITY_MAB_TYPECONVERTER_HXX_
#include "MTypeConverter.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
using namespace connectivity::mozab;
// -------------------------------------------------------------------------
void MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)
{
// Convert to ::rtl::OString (utf-8 encoding).
::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);
const char *cs = os.getStr();
PRUint32 csLen = os.getLength();
NS_ConvertUTF8toUCS2 mozString(cs, csLen);
//const PRUnichar* uniMozString = (const PRUnichar*) mozString;
nss = mozString; // temp.
}
// -------------------------------------------------------------------------
void MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)
{
// Get clone of buffer.
PRUnichar *uc = ToNewUnicode(nss);
sal_Int32 nssLen = nss.Length();
// TODO check if this is ok.
::rtl::OUString _ous(uc, nssLen);
ous = _ous;
nsMemory::Free(uc);
}
// -------------------------------------------------------------------------
void MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)
{
// TODO, specify length.
::rtl::OUString _ous(pru);
ous = _ous;
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)
{
// Convert to ::rtl::OString,
::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);
const char *cs = os.getStr();
return(strdup(cs));
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)
{
// Convert ::rtl::OUString to ::rtl::OString,
::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);
return(strdup(os.getStr()));
}
// -------------------------------------------------------------------------
char *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)
{
char cs[1024];
nss.ToCString(cs, 1024);
return(strdup(cs));
}
// -------------------------------------------------------------------------
::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)
{
// Convert ::rtl::OUString to ::rtl::OString.
::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);
return( ::std::string(os.getStr()));
}
#if 0
// -------------------------------------------------------------------------
::std::string MTypeConverter::nsStringToStlString(nsString const &nss)
{
return( ::std::string(nss.GetBuffer()));
}
#endif
// -------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#ifndef MORDOR_BIN_READER
#define MORDOR_BIN_READER
#include <fstream>
#include <iostream>
using namespace std;
typedef unsigned char BYTE; // 1 byte
typedef unsigned short WORD; // 2 bytes wide
typedef signed short SWORD;
typedef unsigned long DWORD; // 4 bytes, or long word
typedef float CURRENCY;
void printLoc(ifstream *mdata, int offset, const char *prefix);
BYTE readByte(ifstream *mdata_input);
WORD readWord(ifstream *mdata_input);
WORD readWordByteOrder(ifstream *mdata_input);
SWORD readSWord(ifstream *mdata_input);
DWORD readDWord(ifstream *mdata_input);
int readInt(ifstream *mdata_input);
CURRENCY readCurrency(ifstream *mdata_input);
char* readVBString(ifstream *mdata_input);
char* seekTo(ifstream *mdata_input, int goal);
bool checkAlignment(ifstream *mdata_input);
bool checkByteAlignment(ifstream *mdata_input);
#endif
<commit_msg>currency is a double, not a float.<commit_after>#ifndef MORDOR_BIN_READER
#define MORDOR_BIN_READER
#include <fstream>
#include <iostream>
using namespace std;
typedef unsigned char BYTE; // 1 byte
typedef unsigned short WORD; // 2 bytes wide
typedef signed short SWORD;
typedef unsigned long DWORD; // 4 bytes, or long word
typedef double CURRENCY;
void printLoc(ifstream *mdata, int offset, const char *prefix);
BYTE readByte(ifstream *mdata_input);
WORD readWord(ifstream *mdata_input);
WORD readWordByteOrder(ifstream *mdata_input);
SWORD readSWord(ifstream *mdata_input);
DWORD readDWord(ifstream *mdata_input);
int readInt(ifstream *mdata_input);
CURRENCY readCurrency(ifstream *mdata_input);
char* readVBString(ifstream *mdata_input);
char* seekTo(ifstream *mdata_input, int goal);
bool checkAlignment(ifstream *mdata_input);
bool checkByteAlignment(ifstream *mdata_input);
#endif
<|endoftext|>
|
<commit_before><commit_msg>[RArrowDS] Fix compilation error<commit_after><|endoftext|>
|
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 <algorithm>
#include <stdlib.h>
#include "util/check.hh"
#include "util/exception.hh"
#include "util/tokenize_piece.hh"
#include "TargetPhrase.h"
#include "PhraseDictionaryMemory.h"
#include "GenerationDictionary.h"
#include "LM/Base.h"
#include "StaticData.h"
#include "LMList.h"
#include "ScoreComponentCollection.h"
#include "Util.h"
#include "DummyScoreProducers.h"
#include "AlignmentInfoCollection.h"
using namespace std;
namespace Moses
{
TargetPhrase::TargetPhrase( std::string out_string)
:Phrase(0), m_fullScore(0.0), m_sourcePhrase(0)
, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
{
//ACAT
const StaticData &staticData = StaticData::Instance();
CreateFromString(staticData.GetInputFactorOrder(), out_string, staticData.GetFactorDelimiter());
}
TargetPhrase::TargetPhrase()
:Phrase()
, m_fullScore(0.0)
,m_sourcePhrase()
, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
{
}
TargetPhrase::TargetPhrase(const Phrase &phrase)
: Phrase(phrase)
, m_fullScore(0.0)
, m_sourcePhrase()
, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
{
}
void TargetPhrase::SetScore(const TranslationSystem* system)
{
// used when creating translations of unknown words:
m_fullScore = - system->GetWeightWordPenalty();
}
#ifdef HAVE_PROTOBUF
void TargetPhrase::WriteToRulePB(hgmert::Rule* pb) const
{
pb->add_trg_words("[X,1]");
for (size_t pos = 0 ; pos < GetSize() ; pos++)
pb->add_trg_words(GetWord(pos)[0]->GetString());
}
#endif
void TargetPhrase::SetScore(float score)
{
//we use an existing score producer to figure out information for score setting (number of scores and weights)
//TODO: is this a good idea?
// Assume the default system.
const TranslationSystem& system = StaticData::Instance().GetTranslationSystem(TranslationSystem::DEFAULT);
const ScoreProducer* prod = system.GetPhraseDictionaries()[0];
vector<float> weights = StaticData::Instance().GetWeights(prod);
//find out how many items are in the score vector for this producer
size_t numScores = prod->GetNumScoreComponents();
//divide up the score among all of the score vectors
vector <float> scoreVector(numScores,score/numScores);
//Now we have what we need to call the full SetScore method
SetScore(prod, scoreVector, ScoreComponentCollection(), weights, system.GetWeightWordPenalty(), system.GetLanguageModels());
}
/**
* used for setting scores for unknown words with input link features (lattice/conf. nets)
* \param scoreVector input scores
*/
void TargetPhrase::SetScore(const TranslationSystem* system, const Scores &scoreVector)
{
//we use an existing score producer to figure out information for score setting (number of scores and weights)
const ScoreProducer* prod = system->GetPhraseDictionaries()[0];
vector<float> weights = StaticData::Instance().GetWeights(prod);
//expand the input weight vector
CHECK(scoreVector.size() <= prod->GetNumScoreComponents());
Scores sizedScoreVector = scoreVector;
sizedScoreVector.resize(prod->GetNumScoreComponents(),0.0f);
SetScore(prod,sizedScoreVector, ScoreComponentCollection(),weights,system->GetWeightWordPenalty(),system->GetLanguageModels());
}
void TargetPhrase::SetScore(const ScoreProducer* translationScoreProducer,
const Scores &scoreVector,
const ScoreComponentCollection &sparseScoreVector,
const vector<float> &weightT,
float weightWP, const LMList &languageModels)
{
CHECK(weightT.size() == scoreVector.size());
// calc average score if non-best
float transScore = std::inner_product(scoreVector.begin(), scoreVector.end(), weightT.begin(), 0.0f);
m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);
m_scoreBreakdown.PlusEquals(sparseScoreVector);
// Replicated from TranslationOptions.cpp
float totalNgramScore = 0;
float totalFullScore = 0;
float totalOOVScore = 0;
LMList::const_iterator lmIter;
for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {
const LanguageModel &lm = **lmIter;
if (lm.Useable(*this)) {
// contains factors used by this LM
const float weightLM = lm.GetWeight();
const float oovWeightLM = lm.GetOOVWeight();
float fullScore, nGramScore;
size_t oovCount;
lm.CalcScore(*this, fullScore, nGramScore, oovCount);
if (StaticData::Instance().GetLMEnableOOVFeature()) {
vector<float> scores(2);
scores[0] = nGramScore;
scores[1] = oovCount;
m_scoreBreakdown.Assign(&lm, scores);
totalOOVScore += oovCount * oovWeightLM;
} else {
m_scoreBreakdown.Assign(&lm, nGramScore);
}
// total LM score so far
totalNgramScore += nGramScore * weightLM;
totalFullScore += fullScore * weightLM;
}
}
m_fullScore = transScore + totalFullScore + totalOOVScore
- (this->GetSize() * weightWP); // word penalty
}
void TargetPhrase::SetScoreChart(const ScoreProducer* translationScoreProducer,
const Scores &scoreVector
,const vector<float> &weightT
,const LMList &languageModels
,const WordPenaltyProducer* wpProducer)
{
CHECK(weightT.size() == scoreVector.size());
// calc average score if non-best
m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);
// Replicated from TranslationOptions.cpp
float totalNgramScore = 0;
float totalFullScore = 0;
float totalOOVScore = 0;
LMList::const_iterator lmIter;
for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {
const LanguageModel &lm = **lmIter;
if (lm.Useable(*this)) {
// contains factors used by this LM
const float weightLM = lm.GetWeight();
const float oovWeightLM = lm.GetOOVWeight();
float fullScore, nGramScore;
size_t oovCount;
lm.CalcScore(*this, fullScore, nGramScore, oovCount);
fullScore = UntransformLMScore(fullScore);
nGramScore = UntransformLMScore(nGramScore);
if (StaticData::Instance().GetLMEnableOOVFeature()) {
vector<float> scores(2);
scores[0] = nGramScore;
scores[1] = oovCount;
m_scoreBreakdown.Assign(&lm, scores);
totalOOVScore += oovCount * oovWeightLM;
} else {
m_scoreBreakdown.Assign(&lm, nGramScore);
}
// total LM score so far
totalNgramScore += nGramScore * weightLM;
totalFullScore += fullScore * weightLM;
}
}
// word penalty
size_t wordCount = GetNumTerminals();
m_scoreBreakdown.Assign(wpProducer, - (float) wordCount * 0.434294482); // TODO log -> ln ??
m_fullScore = m_scoreBreakdown.GetWeightedScore() - totalNgramScore + totalFullScore + totalOOVScore;
}
void TargetPhrase::SetScore(const ScoreProducer* producer, const Scores &scoreVector)
{
// used when creating translations of unknown words (chart decoding)
m_scoreBreakdown.Assign(producer, scoreVector);
m_fullScore = m_scoreBreakdown.GetWeightedScore();
}
void TargetPhrase::SetWeights(const ScoreProducer* translationScoreProducer, const vector<float> &weightT)
{
// calling this function in case of confusion net input is undefined
CHECK(StaticData::Instance().GetInputType()==SentenceInput);
/* one way to fix this, you have to make sure the weightT contains (in
addition to the usual phrase translation scaling factors) the input
weight factor as last element
*/
}
void TargetPhrase::ResetScore()
{
m_fullScore = 0;
m_scoreBreakdown.ZeroAll();
}
TargetPhrase *TargetPhrase::MergeNext(const TargetPhrase &inputPhrase) const
{
if (! IsCompatible(inputPhrase)) {
return NULL;
}
// ok, merge
TargetPhrase *clone = new TargetPhrase(*this);
clone->m_sourcePhrase = m_sourcePhrase;
int currWord = 0;
const size_t len = GetSize();
for (size_t currPos = 0 ; currPos < len ; currPos++) {
const Word &inputWord = inputPhrase.GetWord(currPos);
Word &cloneWord = clone->GetWord(currPos);
cloneWord.Merge(inputWord);
currWord++;
}
return clone;
}
void TargetPhrase::SetAlignmentInfo(const StringPiece &alignString)
{
AlignmentInfo::CollType alignTerm, alignNonTerm;
for (util::TokenIter<util::AnyCharacter, true> token(alignString, util::AnyCharacter(" \t")); token; ++token) {
util::TokenIter<util::SingleCharacter, false> dash(*token, util::SingleCharacter('-'));
char *endptr;
size_t sourcePos = strtoul(dash->data(), &endptr, 10);
UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, "Error parsing alignment" << *dash);
++dash;
size_t targetPos = strtoul(dash->data(), &endptr, 10);
UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, "Error parsing alignment" << *dash);
UTIL_THROW_IF(++dash, util::Exception, "Extra gunk in alignment " << *token);
if (GetWord(targetPos).IsNonTerminal()) {
alignNonTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));
}
else {
alignTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));
}
}
SetAlignTerm(alignTerm);
SetAlignNonTerm(alignNonTerm);
}
void TargetPhrase::SetAlignTerm(const AlignmentInfo::CollType &coll)
{
const AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);
m_alignTerm = alignmentInfo;
}
void TargetPhrase::SetAlignNonTerm(const AlignmentInfo::CollType &coll)
{
const AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);
m_alignNonTerm = alignmentInfo;
}
TO_STRING_BODY(TargetPhrase);
std::ostream& operator<<(std::ostream& os, const TargetPhrase& tp)
{
os << static_cast<const Phrase&>(tp) << ":" << tp.GetAlignNonTerm();
os << ": c=" << tp.m_fullScore;
return os;
}
}
<commit_msg>added alignment output to n-best list<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 <algorithm>
#include <stdlib.h>
#include "util/check.hh"
#include "util/exception.hh"
#include "util/tokenize_piece.hh"
#include "TargetPhrase.h"
#include "PhraseDictionaryMemory.h"
#include "GenerationDictionary.h"
#include "LM/Base.h"
#include "StaticData.h"
#include "LMList.h"
#include "ScoreComponentCollection.h"
#include "Util.h"
#include "DummyScoreProducers.h"
#include "AlignmentInfoCollection.h"
using namespace std;
namespace Moses
{
TargetPhrase::TargetPhrase( std::string out_string)
:Phrase(0), m_fullScore(0.0), m_sourcePhrase(0)
, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
{
//ACAT
const StaticData &staticData = StaticData::Instance();
CreateFromString(staticData.GetInputFactorOrder(), out_string, staticData.GetFactorDelimiter());
}
TargetPhrase::TargetPhrase()
:Phrase()
, m_fullScore(0.0)
,m_sourcePhrase()
, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
{
}
TargetPhrase::TargetPhrase(const Phrase &phrase)
: Phrase(phrase)
, m_fullScore(0.0)
, m_sourcePhrase()
, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())
{
}
void TargetPhrase::SetScore(const TranslationSystem* system)
{
// used when creating translations of unknown words:
m_fullScore = - system->GetWeightWordPenalty();
}
#ifdef HAVE_PROTOBUF
void TargetPhrase::WriteToRulePB(hgmert::Rule* pb) const
{
pb->add_trg_words("[X,1]");
for (size_t pos = 0 ; pos < GetSize() ; pos++)
pb->add_trg_words(GetWord(pos)[0]->GetString());
}
#endif
void TargetPhrase::SetScore(float score)
{
//we use an existing score producer to figure out information for score setting (number of scores and weights)
//TODO: is this a good idea?
// Assume the default system.
const TranslationSystem& system = StaticData::Instance().GetTranslationSystem(TranslationSystem::DEFAULT);
const ScoreProducer* prod = system.GetPhraseDictionaries()[0];
vector<float> weights = StaticData::Instance().GetWeights(prod);
//find out how many items are in the score vector for this producer
size_t numScores = prod->GetNumScoreComponents();
//divide up the score among all of the score vectors
vector <float> scoreVector(numScores,score/numScores);
//Now we have what we need to call the full SetScore method
SetScore(prod, scoreVector, ScoreComponentCollection(), weights, system.GetWeightWordPenalty(), system.GetLanguageModels());
}
/**
* used for setting scores for unknown words with input link features (lattice/conf. nets)
* \param scoreVector input scores
*/
void TargetPhrase::SetScore(const TranslationSystem* system, const Scores &scoreVector)
{
//we use an existing score producer to figure out information for score setting (number of scores and weights)
const ScoreProducer* prod = system->GetPhraseDictionaries()[0];
vector<float> weights = StaticData::Instance().GetWeights(prod);
//expand the input weight vector
CHECK(scoreVector.size() <= prod->GetNumScoreComponents());
Scores sizedScoreVector = scoreVector;
sizedScoreVector.resize(prod->GetNumScoreComponents(),0.0f);
SetScore(prod,sizedScoreVector, ScoreComponentCollection(),weights,system->GetWeightWordPenalty(),system->GetLanguageModels());
}
void TargetPhrase::SetScore(const ScoreProducer* translationScoreProducer,
const Scores &scoreVector,
const ScoreComponentCollection &sparseScoreVector,
const vector<float> &weightT,
float weightWP, const LMList &languageModels)
{
CHECK(weightT.size() == scoreVector.size());
// calc average score if non-best
float transScore = std::inner_product(scoreVector.begin(), scoreVector.end(), weightT.begin(), 0.0f);
m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);
m_scoreBreakdown.PlusEquals(sparseScoreVector);
// Replicated from TranslationOptions.cpp
float totalNgramScore = 0;
float totalFullScore = 0;
float totalOOVScore = 0;
LMList::const_iterator lmIter;
for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {
const LanguageModel &lm = **lmIter;
if (lm.Useable(*this)) {
// contains factors used by this LM
const float weightLM = lm.GetWeight();
const float oovWeightLM = lm.GetOOVWeight();
float fullScore, nGramScore;
size_t oovCount;
lm.CalcScore(*this, fullScore, nGramScore, oovCount);
if (StaticData::Instance().GetLMEnableOOVFeature()) {
vector<float> scores(2);
scores[0] = nGramScore;
scores[1] = oovCount;
m_scoreBreakdown.Assign(&lm, scores);
totalOOVScore += oovCount * oovWeightLM;
} else {
m_scoreBreakdown.Assign(&lm, nGramScore);
}
// total LM score so far
totalNgramScore += nGramScore * weightLM;
totalFullScore += fullScore * weightLM;
}
}
m_fullScore = transScore + totalFullScore + totalOOVScore
- (this->GetSize() * weightWP); // word penalty
}
void TargetPhrase::SetScoreChart(const ScoreProducer* translationScoreProducer,
const Scores &scoreVector
,const vector<float> &weightT
,const LMList &languageModels
,const WordPenaltyProducer* wpProducer)
{
CHECK(weightT.size() == scoreVector.size());
// calc average score if non-best
m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);
// Replicated from TranslationOptions.cpp
float totalNgramScore = 0;
float totalFullScore = 0;
float totalOOVScore = 0;
LMList::const_iterator lmIter;
for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {
const LanguageModel &lm = **lmIter;
if (lm.Useable(*this)) {
// contains factors used by this LM
const float weightLM = lm.GetWeight();
const float oovWeightLM = lm.GetOOVWeight();
float fullScore, nGramScore;
size_t oovCount;
lm.CalcScore(*this, fullScore, nGramScore, oovCount);
fullScore = UntransformLMScore(fullScore);
nGramScore = UntransformLMScore(nGramScore);
if (StaticData::Instance().GetLMEnableOOVFeature()) {
vector<float> scores(2);
scores[0] = nGramScore;
scores[1] = oovCount;
m_scoreBreakdown.Assign(&lm, scores);
totalOOVScore += oovCount * oovWeightLM;
} else {
m_scoreBreakdown.Assign(&lm, nGramScore);
}
// total LM score so far
totalNgramScore += nGramScore * weightLM;
totalFullScore += fullScore * weightLM;
}
}
// word penalty
size_t wordCount = GetNumTerminals();
m_scoreBreakdown.Assign(wpProducer, - (float) wordCount * 0.434294482); // TODO log -> ln ??
m_fullScore = m_scoreBreakdown.GetWeightedScore() - totalNgramScore + totalFullScore + totalOOVScore;
}
void TargetPhrase::SetScore(const ScoreProducer* producer, const Scores &scoreVector)
{
// used when creating translations of unknown words (chart decoding)
m_scoreBreakdown.Assign(producer, scoreVector);
m_fullScore = m_scoreBreakdown.GetWeightedScore();
}
void TargetPhrase::SetWeights(const ScoreProducer* translationScoreProducer, const vector<float> &weightT)
{
// calling this function in case of confusion net input is undefined
CHECK(StaticData::Instance().GetInputType()==SentenceInput);
/* one way to fix this, you have to make sure the weightT contains (in
addition to the usual phrase translation scaling factors) the input
weight factor as last element
*/
}
void TargetPhrase::ResetScore()
{
m_fullScore = 0;
m_scoreBreakdown.ZeroAll();
}
TargetPhrase *TargetPhrase::MergeNext(const TargetPhrase &inputPhrase) const
{
if (! IsCompatible(inputPhrase)) {
return NULL;
}
// ok, merge
TargetPhrase *clone = new TargetPhrase(*this);
clone->m_sourcePhrase = m_sourcePhrase;
int currWord = 0;
const size_t len = GetSize();
for (size_t currPos = 0 ; currPos < len ; currPos++) {
const Word &inputWord = inputPhrase.GetWord(currPos);
Word &cloneWord = clone->GetWord(currPos);
cloneWord.Merge(inputWord);
currWord++;
}
return clone;
}
void TargetPhrase::SetAlignmentInfo(const StringPiece &alignString)
{
AlignmentInfo::CollType alignTerm, alignNonTerm;
for (util::TokenIter<util::AnyCharacter, true> token(alignString, util::AnyCharacter(" \t")); token; ++token) {
util::TokenIter<util::SingleCharacter, false> dash(*token, util::SingleCharacter('-'));
char *endptr;
size_t sourcePos = strtoul(dash->data(), &endptr, 10);
UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, "Error parsing alignment" << *dash);
++dash;
size_t targetPos = strtoul(dash->data(), &endptr, 10);
UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, "Error parsing alignment" << *dash);
UTIL_THROW_IF(++dash, util::Exception, "Extra gunk in alignment " << *token);
if (GetWord(targetPos).IsNonTerminal()) {
alignNonTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));
}
else {
alignTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));
}
}
SetAlignTerm(alignTerm);
SetAlignNonTerm(alignNonTerm);
}
void TargetPhrase::SetAlignTerm(const AlignmentInfo::CollType &coll)
{
const AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);
m_alignTerm = alignmentInfo;
}
void TargetPhrase::SetAlignNonTerm(const AlignmentInfo::CollType &coll)
{
const AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);
m_alignNonTerm = alignmentInfo;
}
TO_STRING_BODY(TargetPhrase);
std::ostream& operator<<(std::ostream& os, const TargetPhrase& tp)
{
os << static_cast<const Phrase&>(tp) << ":" << tp.GetAlignNonTerm();
os << ": c=" << tp.m_fullScore;
return os;
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
* @brief: Implementation of PiecewiseLinearConstraint class
**/
#include "modules/planning/math/smoothing_spline/piecewise_linear_constraint.h"
#include <limits>
namespace apollo {
namespace planning {
namespace {
Eigen::MatrixXd MergeMaxtrices(const std::vector<Eigen::MatrixXd> matrices) {
int32_t d = 0;
for (const auto& mat : matrices) {
d += mat.rows();
}
int32_t col = matrices.front().cols();
Eigen::MatrixXd res = Eigen::MatrixXd::Zero(d, col);
int32_t index = 0;
for (const auto& mat : matrices) {
res.block(index, 0, mat.rows(), mat.cols()) = mat;
index += mat.rows();
}
return res;
}
}
PiecewiseLinearConstraint::PiecewiseLinearConstraint(const uint32_t dimension)
: dimension_(dimension) {}
Eigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_matrix()
const {
return MergeMaxtrices(inequality_matrices_);
}
Eigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_boundary()
const {
return MergeMaxtrices(inequality_boundaries_);
}
Eigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_matrix() const {
return MergeMaxtrices(equality_matrices_);
}
Eigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_boundary()
const {
return MergeMaxtrices(equality_boundaries_);
}
bool PiecewiseLinearConstraint::AddBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddDerivativeBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddSecondDerivativeBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddThirdDerivativeBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointConstraint(const double x,
const double fx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointDerivativeConstraint(const double x,
const double dfx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointSecondDerivativeConstraint(
const double x, const double ddfx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointThirdDerivativeConstraint(
const double x, const double dddfx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddMonotoneInequalityConstraint() {
// TODO(Liangliang): implement this function
Eigen::MatrixXd inequality_matrix =
Eigen::MatrixXd::Zero(dimension_ - 1, dimension_ - 1);
Eigen::MatrixXd inequality_boundary =
Eigen::MatrixXd::Zero(dimension_ - 1, 1);
for (uint32_t i = 1; i < dimension_; ++i) {
inequality_matrix(i, i - 1) = -1.0;
inequality_matrix(i, i) = 1.0;
}
inequality_matrices_.push_back(inequality_matrix);
inequality_boundaries_.push_back(inequality_boundary);
return true;
}
} // namespace planning
} // namespace apollo
<commit_msg>Planning: added boundary constraint implementation in piecewise linear constraint.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
* @brief: Implementation of PiecewiseLinearConstraint class
**/
#include "modules/planning/math/smoothing_spline/piecewise_linear_constraint.h"
#include <limits>
namespace apollo {
namespace planning {
namespace {
Eigen::MatrixXd MergeMaxtrices(const std::vector<Eigen::MatrixXd> matrices) {
int32_t d = 0;
for (const auto& mat : matrices) {
d += mat.rows();
}
int32_t col = matrices.front().cols();
Eigen::MatrixXd res = Eigen::MatrixXd::Zero(d, col);
int32_t index = 0;
for (const auto& mat : matrices) {
res.block(index, 0, mat.rows(), mat.cols()) = mat;
index += mat.rows();
}
return res;
}
}
PiecewiseLinearConstraint::PiecewiseLinearConstraint(const uint32_t dimension)
: dimension_(dimension) {}
Eigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_matrix()
const {
return MergeMaxtrices(inequality_matrices_);
}
Eigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_boundary()
const {
return MergeMaxtrices(inequality_boundaries_);
}
Eigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_matrix() const {
return MergeMaxtrices(equality_matrices_);
}
Eigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_boundary()
const {
return MergeMaxtrices(equality_boundaries_);
}
bool PiecewiseLinearConstraint::AddBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
if (index_list.size() != lower_bound.size() ||
index_list.size() != upper_bound.size()) {
return false;
}
Eigen::MatrixXd inequality_matrix =
Eigen::MatrixXd::Zero(2 * index_list.size(), dimension_);
Eigen::MatrixXd inequality_boundary =
Eigen::MatrixXd::Zero(2 * index_list.size(), 1);
for (uint32_t i = 0; i < index_list.size(); ++i) {
uint32_t index = index_list[i];
inequality_matrix(i, index) = -1.0;
inequality_boundary(i, 0) = -upper_bound[i];
inequality_matrix(i + 1, index) = 1.0;
inequality_boundary(i + 1, 0) = lower_bound[i];
}
return true;
}
bool PiecewiseLinearConstraint::AddDerivativeBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddSecondDerivativeBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddThirdDerivativeBoundary(
const std::vector<uint32_t>& index_list,
const std::vector<double>& lower_bound,
const std::vector<double>& upper_bound) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointConstraint(const double x,
const double fx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointDerivativeConstraint(const double x,
const double dfx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointSecondDerivativeConstraint(
const double x, const double ddfx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddPointThirdDerivativeConstraint(
const double x, const double dddfx) {
// TODO(Liangliang): implement this function
return true;
}
bool PiecewiseLinearConstraint::AddMonotoneInequalityConstraint() {
Eigen::MatrixXd inequality_matrix =
Eigen::MatrixXd::Zero(dimension_ - 1, dimension_ - 1);
Eigen::MatrixXd inequality_boundary =
Eigen::MatrixXd::Zero(dimension_ - 1, 1);
for (uint32_t i = 1; i < dimension_; ++i) {
inequality_matrix(i, i - 1) = -1.0;
inequality_matrix(i, i) = 1.0;
}
inequality_matrices_.push_back(inequality_matrix);
inequality_boundaries_.push_back(inequality_boundary);
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file qp_spline_path_generator.cc
**/
#include <algorithm>
#include <utility>
#include <vector>
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_generator.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/log.h"
#include "modules/common/macro.h"
#include "modules/common/util/file.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/sl_analytic_transformation.h"
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_sampler.h"
namespace apollo {
namespace planning {
bool QpSplinePathGenerator::Init(const std::string& config_file) {
if (!common::util::GetProtoFromFile(config_file, &_qp_spline_path_config)) {
AERROR << "Failed to load config file " << config_file;
return false;
}
return true;
}
bool QpSplinePathGenerator::generate(const ReferenceLine& reference_line,
const DecisionData& decision_data,
const SpeedData& speed_data,
const common::TrajectoryPoint& init_point,
PathData* const path_data) {
if (!calculate_sl_point(reference_line, init_point, &_init_point)) {
AERROR << "Fail to map init point: " << init_point.ShortDebugString();
return false;
}
double start_s = _init_point.s();
double end_s = std::min(reference_line.length(),
_init_point.s() + FLAGS_planning_distance);
QpFrenetFrame qp_frenet_frame(reference_line, decision_data, speed_data,
_init_point, start_s, end_s,
_qp_spline_path_config.time_resolution());
if (!qp_frenet_frame.Init(_qp_spline_path_config.num_output())) {
AERROR << "Fail to initialize qp frenet frame";
return false;
}
if (!init_coord_range(qp_frenet_frame, &start_s, &end_s)) {
AERROR << "Measure natural coord system with s range failed!";
return false;
}
AINFO << "pss path start with " << start_s << ", end with " << end_s;
if (!init_smoothing_spline(reference_line, start_s, end_s)) {
AERROR << "Init smoothing spline failed with (" << start_s << ", end_s "
<< end_s;
return false;
}
if (!setup_constraint(qp_frenet_frame)) {
AERROR << "Fail to setup pss path constraint.";
return false;
}
if (!setup_kernel()) {
AERROR << "Fail to setup pss path kernel.";
return false;
}
if (!solve()) {
AERROR << "Fail to solve the qp problem.";
return false;
}
AINFO << common::util::StrCat("Spline dl:", _init_point.dl(), ", ddl:",
_init_point.ddl());
// extract data
const Spline1d& spline = _spline_generator->spline();
double s_resolution =
(end_s - _init_point.s()) / _qp_spline_path_config.num_output();
std::vector<common::PathPoint> path_points;
double start_l = spline(_init_point.s());
ReferencePoint ref_point =
reference_line.get_reference_point(_init_point.s());
common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
start_l);
double x_diff = xy_point.x() - init_point.path_point().x();
double y_diff = xy_point.y() - init_point.path_point().y();
double s = _init_point.s();
for (std::uint32_t i = 0;
i <= _qp_spline_path_config.num_output() && s <= end_s; ++i) {
double l = spline(s);
double dl = spline.derivative(s);
double ddl = spline.second_order_derivative(s);
ReferencePoint ref_point = reference_line.get_reference_point(s);
common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
l);
xy_point.set_x(xy_point.x() - x_diff);
xy_point.set_y(xy_point.y() - y_diff);
double theta = SLAnalyticTransformation::calculate_theta(
ref_point.heading(), ref_point.kappa(), l, dl);
double kappa = SLAnalyticTransformation::calculate_kappa(
ref_point.kappa(), ref_point.dkappa(), l, dl, ddl);
common::PathPoint path_point = common::util::MakePathPoint(
xy_point.x(), xy_point.y(), 0.0, theta, kappa, 0.0, 0.0);
if (path_points.size() != 0) {
double distance =
common::util::Distance2D(path_points.back(), path_point);
path_point.set_s(path_points.back().s() + distance);
}
path_points.push_back(std::move(path_point));
s = _init_point.s() + (i + 1) * s_resolution;
}
path_data->set_discretized_path(path_points);
return true;
}
bool QpSplinePathGenerator::calculate_sl_point(
const ReferenceLine& reference_line,
const common::TrajectoryPoint& traj_point,
common::FrenetFramePoint* const frenet_frame_point) {
common::SLPoint sl_point;
if (!reference_line.get_point_in_frenet_frame(
{traj_point.path_point().x(), traj_point.path_point().y()},
&sl_point)) {
return false;
}
frenet_frame_point->set_s(sl_point.s());
frenet_frame_point->set_l(sl_point.l());
const double theta = traj_point.path_point().theta();
const double kappa = traj_point.path_point().kappa();
const double l = frenet_frame_point->l();
ReferencePoint ref_point =
reference_line.get_reference_point(frenet_frame_point->s());
const double theta_ref = ref_point.heading();
const double kappa_ref = ref_point.kappa();
const double dkappa_ref = ref_point.dkappa();
const double dl = SLAnalyticTransformation::calculate_lateral_derivative(
theta_ref, theta, l, kappa_ref);
const double ddl =
SLAnalyticTransformation::calculate_second_order_lateral_derivative(
theta_ref, theta, kappa_ref, kappa, dkappa_ref, l);
frenet_frame_point->set_dl(dl);
frenet_frame_point->set_ddl(ddl);
return true;
}
bool QpSplinePathGenerator::init_coord_range(
const QpFrenetFrame& qp_frenet_frame, double* const start_s,
double* const end_s) {
// TODO(all): step 1 get current sl coordinate - with init coordinate point
double start_point = std::max(_init_point.s() - 5.0, 0.0);
const ReferenceLine& reference_line = qp_frenet_frame.GetReferenceLine();
double end_point =
std::min(reference_line.length(), *start_s + FLAGS_planning_distance);
end_point =
std::min(qp_frenet_frame.feasible_longitudinal_upper_bound(), end_point);
*start_s = start_point;
*end_s = end_point;
return true;
}
bool QpSplinePathGenerator::init_smoothing_spline(
const ReferenceLine& reference_line, const double start_s,
const double end_s) {
QpSplinePathSampler sampler(_qp_spline_path_config);
// TODO(all): refine here, add end_s tolorence here
std::vector<double> sampling_point;
if (!sampler.Sample(_init_point, reference_line, start_s, end_s - 0.1,
&sampling_point)) {
AERROR << "Qp spline sampler failed!";
return false;
}
_spline_generator.reset(new Spline1dGenerator(
sampling_point, _qp_spline_path_config.spline_order()));
return true;
}
bool QpSplinePathGenerator::setup_constraint(
const QpFrenetFrame& qp_frenet_frame) {
Spline1dConstraint* spline_constraint =
_spline_generator->mutable_spline_constraint();
// add init status constraint
spline_constraint->add_point_fx_constraint(_init_point.s(), _init_point.l());
spline_constraint->add_point_derivative_constraint(_init_point.s(),
_init_point.dl());
spline_constraint->add_point_second_derivative_constraint(_init_point.s(),
_init_point.ddl());
AINFO << "init frenet point: " << _init_point.ShortDebugString();
// add end point constraint
const std::vector<double> spline_knots =
_spline_generator->spline().x_knots();
if (spline_knots.size() < 2) {
AERROR << common::util::StrCat("Smoothing spline knot size(",
spline_knots.size(), ") < 2");
return false;
}
double s_length = spline_knots.back() - spline_knots.front();
if (s_length <= 0) {
AERROR << common::util::StrCat("Smoothing spline knot length(", s_length,
") <= 0");
return false;
}
std::pair<double, double> boundary = std::make_pair(0.0, 0.0);
double end_ref_l = (boundary.first + boundary.second) / 2.0;
spline_constraint->add_point_fx_constraint(spline_knots.back(), end_ref_l);
spline_constraint->add_point_derivative_constraint(spline_knots.back(), 0.0);
spline_constraint->add_point_second_derivative_constraint(spline_knots.back(),
0.0);
AINFO << "end frenet point:" << s_length << ", " << end_ref_l
<< ", 0.0, 0.0.";
const std::vector<double> sampling_knots = spline_knots;
if (sampling_knots.size() <= 2) {
return false;
}
std::uint32_t num_fx_bound =
_qp_spline_path_config.number_of_fx_constraint_knots();
std::vector<double> boundary_low;
std::vector<double> boundary_high;
std::vector<double> fx_knots;
if (num_fx_bound > 1) {
double ds = (sampling_knots.back() - sampling_knots.front()) / num_fx_bound;
double s = sampling_knots.front();
for (std::uint32_t i = 0; i < num_fx_bound + 1; ++i) {
fx_knots.push_back(s);
std::pair<double, double> boundary = std::make_pair(0.0, 0.0);
qp_frenet_frame.get_map_bound(s, &boundary);
boundary_low.push_back(boundary.first);
boundary_high.push_back(boundary.second);
s += ds;
// calculate boundary here
}
if (!spline_constraint->add_fx_boundary(fx_knots, boundary_low,
boundary_high)) {
AERROR << "Add boundary constraint failed";
return false;
}
}
// add smooth jointness constraint
if (!spline_constraint->add_third_derivative_smooth_constraint()) {
AERROR << "Add spline jointness constraint failed!";
return false;
}
return true;
}
bool QpSplinePathGenerator::setup_kernel() {
Spline1dKernel* spline_kernel = _spline_generator->mutable_spline_kernel();
if (_qp_spline_path_config.regularization_weight() > 0) {
spline_kernel->add_regularization(
_qp_spline_path_config.regularization_weight());
}
if (_qp_spline_path_config.derivative_weight() > 0) {
spline_kernel->add_derivative_kernel_matrix(
_qp_spline_path_config.derivative_weight());
}
if (_qp_spline_path_config.second_derivative_weight() > 0) {
spline_kernel->add_second_order_derivative_matrix(
_qp_spline_path_config.second_derivative_weight());
}
if (_qp_spline_path_config.third_derivative_weight() > 0) {
spline_kernel->add_third_order_derivative_matrix(
_qp_spline_path_config.third_derivative_weight());
}
// TODO(all): Add reference line kernel here
return true;
}
bool QpSplinePathGenerator::solve() {
if (!_spline_generator->solve()) {
AERROR << "Could not solve the qp problem in spline path generator.";
return false;
}
return true;
}
} // namespace planning
} // namespace apollo
<commit_msg>fixed a bug which can cause path length exceed reference line.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file qp_spline_path_generator.cc
**/
#include <algorithm>
#include <utility>
#include <vector>
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_generator.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/log.h"
#include "modules/common/macro.h"
#include "modules/common/util/file.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/double.h"
#include "modules/planning/math/sl_analytic_transformation.h"
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_sampler.h"
namespace apollo {
namespace planning {
bool QpSplinePathGenerator::Init(const std::string& config_file) {
if (!common::util::GetProtoFromFile(config_file, &_qp_spline_path_config)) {
AERROR << "Failed to load config file " << config_file;
return false;
}
return true;
}
bool QpSplinePathGenerator::generate(const ReferenceLine& reference_line,
const DecisionData& decision_data,
const SpeedData& speed_data,
const common::TrajectoryPoint& init_point,
PathData* const path_data) {
if (!calculate_sl_point(reference_line, init_point, &_init_point)) {
AERROR << "Fail to map init point: " << init_point.ShortDebugString();
return false;
}
double start_s = _init_point.s();
double end_s = std::min(reference_line.length(),
_init_point.s() + FLAGS_planning_distance);
QpFrenetFrame qp_frenet_frame(reference_line, decision_data, speed_data,
_init_point, start_s, end_s,
_qp_spline_path_config.time_resolution());
if (!qp_frenet_frame.Init(_qp_spline_path_config.num_output())) {
AERROR << "Fail to initialize qp frenet frame";
return false;
}
if (!init_coord_range(qp_frenet_frame, &start_s, &end_s)) {
AERROR << "Measure natural coord system with s range failed!";
return false;
}
AINFO << "pss path start with " << start_s << ", end with " << end_s;
if (!init_smoothing_spline(reference_line, start_s, end_s)) {
AERROR << "Init smoothing spline failed with (" << start_s << ", end_s "
<< end_s;
return false;
}
if (!setup_constraint(qp_frenet_frame)) {
AERROR << "Fail to setup pss path constraint.";
return false;
}
if (!setup_kernel()) {
AERROR << "Fail to setup pss path kernel.";
return false;
}
if (!solve()) {
AERROR << "Fail to solve the qp problem.";
return false;
}
AINFO << common::util::StrCat("Spline dl:", _init_point.dl(), ", ddl:",
_init_point.ddl());
// extract data
const Spline1d& spline = _spline_generator->spline();
std::vector<common::PathPoint> path_points;
double start_l = spline(_init_point.s());
ReferencePoint ref_point =
reference_line.get_reference_point(_init_point.s());
common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
start_l);
double x_diff = xy_point.x() - init_point.path_point().x();
double y_diff = xy_point.y() - init_point.path_point().y();
double s = _init_point.s();
double s_resolution =
(end_s - _init_point.s()) / _qp_spline_path_config.num_output();
while (Double::compare(s, end_s) < 0) {
double l = spline(s);
double dl = spline.derivative(s);
double ddl = spline.second_order_derivative(s);
ReferencePoint ref_point = reference_line.get_reference_point(s);
common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(
ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),
l);
xy_point.set_x(xy_point.x() - x_diff);
xy_point.set_y(xy_point.y() - y_diff);
double theta = SLAnalyticTransformation::calculate_theta(
ref_point.heading(), ref_point.kappa(), l, dl);
double kappa = SLAnalyticTransformation::calculate_kappa(
ref_point.kappa(), ref_point.dkappa(), l, dl, ddl);
common::PathPoint path_point = common::util::MakePathPoint(
xy_point.x(), xy_point.y(), 0.0, theta, kappa, 0.0, 0.0);
if (path_points.size() != 0) {
double distance =
common::util::Distance2D(path_points.back(), path_point);
path_point.set_s(path_points.back().s() + distance);
}
if (Double::compare(path_point.s(), end_s) >= 0) {
break;
}
path_points.push_back(path_point);
s += s_resolution;
}
path_data->set_discretized_path(path_points);
return true;
}
bool QpSplinePathGenerator::calculate_sl_point(
const ReferenceLine& reference_line,
const common::TrajectoryPoint& traj_point,
common::FrenetFramePoint* const frenet_frame_point) {
common::SLPoint sl_point;
if (!reference_line.get_point_in_frenet_frame(
{traj_point.path_point().x(), traj_point.path_point().y()},
&sl_point)) {
return false;
}
frenet_frame_point->set_s(sl_point.s());
frenet_frame_point->set_l(sl_point.l());
const double theta = traj_point.path_point().theta();
const double kappa = traj_point.path_point().kappa();
const double l = frenet_frame_point->l();
ReferencePoint ref_point =
reference_line.get_reference_point(frenet_frame_point->s());
const double theta_ref = ref_point.heading();
const double kappa_ref = ref_point.kappa();
const double dkappa_ref = ref_point.dkappa();
const double dl = SLAnalyticTransformation::calculate_lateral_derivative(
theta_ref, theta, l, kappa_ref);
const double ddl =
SLAnalyticTransformation::calculate_second_order_lateral_derivative(
theta_ref, theta, kappa_ref, kappa, dkappa_ref, l);
frenet_frame_point->set_dl(dl);
frenet_frame_point->set_ddl(ddl);
return true;
}
bool QpSplinePathGenerator::init_coord_range(
const QpFrenetFrame& qp_frenet_frame, double* const start_s,
double* const end_s) {
// TODO(all): step 1 get current sl coordinate - with init coordinate point
double start_point = std::max(_init_point.s() - 5.0, 0.0);
const ReferenceLine& reference_line = qp_frenet_frame.GetReferenceLine();
double end_point =
std::min(reference_line.length(), *start_s + FLAGS_planning_distance);
end_point =
std::min(qp_frenet_frame.feasible_longitudinal_upper_bound(), end_point);
*start_s = start_point;
*end_s = end_point;
return true;
}
bool QpSplinePathGenerator::init_smoothing_spline(
const ReferenceLine& reference_line, const double start_s,
const double end_s) {
QpSplinePathSampler sampler(_qp_spline_path_config);
// TODO(all): refine here, add end_s tolorence here
std::vector<double> sampling_point;
if (!sampler.Sample(_init_point, reference_line, start_s, end_s - 0.1,
&sampling_point)) {
AERROR << "Qp spline sampler failed!";
return false;
}
_spline_generator.reset(new Spline1dGenerator(
sampling_point, _qp_spline_path_config.spline_order()));
return true;
}
bool QpSplinePathGenerator::setup_constraint(
const QpFrenetFrame& qp_frenet_frame) {
Spline1dConstraint* spline_constraint =
_spline_generator->mutable_spline_constraint();
// add init status constraint
spline_constraint->add_point_fx_constraint(_init_point.s(), _init_point.l());
spline_constraint->add_point_derivative_constraint(_init_point.s(),
_init_point.dl());
spline_constraint->add_point_second_derivative_constraint(_init_point.s(),
_init_point.ddl());
AINFO << "init frenet point: " << _init_point.ShortDebugString();
// add end point constraint
const std::vector<double> spline_knots =
_spline_generator->spline().x_knots();
if (spline_knots.size() < 2) {
AERROR << common::util::StrCat("Smoothing spline knot size(",
spline_knots.size(), ") < 2");
return false;
}
double s_length = spline_knots.back() - spline_knots.front();
if (s_length <= 0) {
AERROR << common::util::StrCat("Smoothing spline knot length(", s_length,
") <= 0");
return false;
}
std::pair<double, double> boundary = std::make_pair(0.0, 0.0);
double end_ref_l = (boundary.first + boundary.second) / 2.0;
spline_constraint->add_point_fx_constraint(spline_knots.back(), end_ref_l);
spline_constraint->add_point_derivative_constraint(spline_knots.back(), 0.0);
spline_constraint->add_point_second_derivative_constraint(spline_knots.back(),
0.0);
AINFO << "end frenet point:" << s_length << ", " << end_ref_l
<< ", 0.0, 0.0.";
const std::vector<double> sampling_knots = spline_knots;
if (sampling_knots.size() <= 2) {
return false;
}
std::uint32_t num_fx_bound =
_qp_spline_path_config.number_of_fx_constraint_knots();
std::vector<double> boundary_low;
std::vector<double> boundary_high;
std::vector<double> fx_knots;
if (num_fx_bound > 1) {
double ds = (sampling_knots.back() - sampling_knots.front()) / num_fx_bound;
double s = sampling_knots.front();
for (std::uint32_t i = 0; i < num_fx_bound + 1; ++i) {
fx_knots.push_back(s);
std::pair<double, double> boundary = std::make_pair(0.0, 0.0);
qp_frenet_frame.get_map_bound(s, &boundary);
boundary_low.push_back(boundary.first);
boundary_high.push_back(boundary.second);
s += ds;
// calculate boundary here
}
if (!spline_constraint->add_fx_boundary(fx_knots, boundary_low,
boundary_high)) {
AERROR << "Add boundary constraint failed";
return false;
}
}
// add smooth jointness constraint
if (!spline_constraint->add_third_derivative_smooth_constraint()) {
AERROR << "Add spline jointness constraint failed!";
return false;
}
return true;
}
bool QpSplinePathGenerator::setup_kernel() {
Spline1dKernel* spline_kernel = _spline_generator->mutable_spline_kernel();
if (_qp_spline_path_config.regularization_weight() > 0) {
spline_kernel->add_regularization(
_qp_spline_path_config.regularization_weight());
}
if (_qp_spline_path_config.derivative_weight() > 0) {
spline_kernel->add_derivative_kernel_matrix(
_qp_spline_path_config.derivative_weight());
}
if (_qp_spline_path_config.second_derivative_weight() > 0) {
spline_kernel->add_second_order_derivative_matrix(
_qp_spline_path_config.second_derivative_weight());
}
if (_qp_spline_path_config.third_derivative_weight() > 0) {
spline_kernel->add_third_order_derivative_matrix(
_qp_spline_path_config.third_derivative_weight());
}
// TODO(all): Add reference line kernel here
return true;
}
bool QpSplinePathGenerator::solve() {
if (!_spline_generator->solve()) {
AERROR << "Could not solve the qp problem in spline path generator.";
return false;
}
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>/*
Copyright 2011, Jernej Kovacic
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.
*/
/**
@file NumericUtil.cpp
Implementation of the class NumericUtil, a collection of some useful
numerical utilities. This is a templated class and must not be compiled.
Instead it must be included after the class declaration in the .h file
@author Jernej Kovacic
*/
// Delibarately there is no #include "NumericUtil.h"
#include "Rational.h"
// Note that the optimal EPS depends on application requirements
/*
* Definition of EPS for type float
*/
template<>
float NumericUtil<float>::EPS = 1e-9f;
/*
* Double is a more accurate type...
*/
template<>
double NumericUtil<double>::EPS = 1e-16;
/*
* In int and other types, EPS doesn't make sense, so set it to 0
*/
template<class T>
T NumericUtil<T>::EPS = (T) 0;
/*
* The implementation for integers et al. where the == operator
* does make sense and no comparison to EPS is necessary.
*/
template<class T>
bool NumericUtil<T>::isZero(T value)
{
bool retVal = ( 0==value ? true : false );
return retVal;
}
/*
* Two specialized implementations for float and double.
* In case of these two types, the equality operator (==) is useless.
* In numerical mathematics, two numbers are considered "equal", when
* absolute value of their difference does not exceed a reasonably set EPS.
* Both specializations are very similar and only differ in types of an input value.
* TODO: would it make sense using #define ???
*/
// float:
template<>
bool NumericUtil<float>::isZero(float value)
{
bool retVal = false;
// quick definition of an absolute value
float absValue = ( value>=0 ? value : -value );
retVal = (absValue < EPS ? true : false );
return retVal;
}
// and double:
template<>
bool NumericUtil<double>::isZero(double value)
{
bool retVal = false;
// quick definition of an absolute value
double absValue = ( value>=0 ? value : -value );
retVal = (absValue < EPS ? true : false );
return retVal;
}
/*
* Implementation for Rational
*/
template<>
bool NumericUtil<Rational>::isZero(Rational value)
{
// Rational already contains its own isZero()...
return value.isZero();
}
<commit_msg>arg. passing<commit_after>/*
Copyright 2011, Jernej Kovacic
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.
*/
/**
@file NumericUtil.cpp
Implementation of the class NumericUtil, a collection of some useful
numerical utilities. This is a templated class and must not be compiled.
Instead it must be included after the class declaration in the .h file
@author Jernej Kovacic
*/
// Delibarately there is no #include "NumericUtil.h"
#include "Rational.h"
// Note that the optimal EPS depends on application requirements
/*
* Definition of EPS for type float
*/
template<>
float NumericUtil<float>::EPS = 1e-9f;
/*
* Double is a more accurate type...
*/
template<>
double NumericUtil<double>::EPS = 1e-16;
/*
* In int and other types, EPS doesn't make sense, so set it to 0
*/
template<class T>
T NumericUtil<T>::EPS = (T) 0;
/*
* The implementation for integers et al. where the == operator
* does make sense and no comparison to EPS is necessary.
*/
template<class T>
bool NumericUtil<T>::isZero(const T& value)
{
bool retVal = ( 0==value ? true : false );
return retVal;
}
/*
* Two specialized implementations for float and double.
* In case of these two types, the equality operator (==) is useless.
* In numerical mathematics, two numbers are considered "equal", when
* absolute value of their difference does not exceed a reasonably set EPS.
* Both specializations are very similar and only differ in types of an input value.
* TODO: would it make sense using #define ???
*/
// float:
template<>
bool NumericUtil<float>::isZero(const float& value)
{
bool retVal = false;
// quick definition of an absolute value
float absValue = ( value>=0 ? value : -value );
retVal = (absValue < EPS ? true : false );
return retVal;
}
// and double:
template<>
bool NumericUtil<double>::isZero(const double& value)
{
bool retVal = false;
// quick definition of an absolute value
double absValue = ( value>=0 ? value : -value );
retVal = (absValue < EPS ? true : false );
return retVal;
}
/*
* Implementation for Rational
*/
template<>
bool NumericUtil<Rational>::isZero(const Rational& value)
{
// Rational already contains its own isZero()...
return value.isZero();
}
<|endoftext|>
|
<commit_before>// Copyright 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <windows.h>
#include <string>
#include "base/icu_util.h"
#include "base/logging.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "unicode/udata.h"
namespace icu_util {
bool Initialize() {
// Assert that we are not called more than once. Even though calling this
// function isn't harmful (ICU can handle it), being called twice probably
// indicates a programming error.
#ifndef DEBUG
static bool called_once = false;
DCHECK(!called_once);
called_once = true;
#endif
// We expect to find the ICU data module alongside the current module.
std::wstring data_path;
PathService::Get(base::DIR_MODULE, &data_path);
file_util::AppendToPath(&data_path, L"icudt38.dll");
HMODULE module = LoadLibrary(data_path.c_str());
if (!module)
return false;
FARPROC addr = GetProcAddress(module, "icudt38_dat");
if (!addr)
return false;
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
}
} // namespace icu_util
<commit_msg>ICU isn't packaged on the Mac as it is on Windows. Review URL: http://chrome-reviews.prom.corp.google.com/1092<commit_after>// Copyright 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "build/build_config.h"
#ifdef OS_WIN
#include <windows.h>
#endif
#include <string>
#include "base/icu_util.h"
#include "base/logging.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "unicode/udata.h"
namespace icu_util {
bool Initialize() {
#ifdef OS_WIN
// Assert that we are not called more than once. Even though calling this
// function isn't harmful (ICU can handle it), being called twice probably
// indicates a programming error.
#ifndef NDEBUG
static bool called_once = false;
DCHECK(!called_once);
called_once = true;
#endif
// We expect to find the ICU data module alongside the current module.
std::wstring data_path;
PathService::Get(base::DIR_MODULE, &data_path);
file_util::AppendToPath(&data_path, L"icudt38.dll");
HMODULE module = LoadLibrary(data_path.c_str());
if (!module)
return false;
FARPROC addr = GetProcAddress(module, "icudt38_dat");
if (!addr)
return false;
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
#else
// Windows ships ICU's data separate, so it needs to link the code to data
// here. Other platforms don't need this.
return true;
#endif // OS_WIN
}
} // namespace icu_util
<|endoftext|>
|
<commit_before>// key.cc
#include "stdsneezy.h"
#include "obj_open_container.h"
#include "obj_keyring.h"
#include "obj_key.h"
TKey::TKey() :
TObj()
{
}
TKey::TKey(const TKey &a)
: TObj(a)
{
}
TKey & TKey::operator=(const TKey &a)
{
if (this == &a) return *this;
TObj::operator=(a);
return *this;
}
TKey::~TKey()
{
}
void TKey::assignFourValues(int, int, int, int)
{
}
void TKey::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = 0;
*x2 = 0;
*x3 = 0;
*x4 = 0;
}
sstring TKey::statObjInfo() const
{
char buf[256];
sprintf(buf, "It is a key to %s", what_does_it_open(this));
sstring a(buf);
return a;
}
void TKey::lowCheck()
{
if ((obj_flags.cost >= 0) && isRentable() &&
(obj_flags.decay_time <= 0))
vlogf(LOG_LOW, fmt("rentable key (%s)!") % getName());
TObj::lowCheck();
}
bool TKey::objectRepair(TBeing *ch, TMonster *repair, silentTypeT silent)
{
if (!silent) {
repair->doTell(fname(ch->name), "Does this look like a locksmithery to you?");
}
return TRUE;
}
int TKey::stealModifier()
{
return 77; // make keys tough to steal
}
int TKey::putMeInto(TBeing *ch, TOpenContainer *container)
{
TObj *o;
TThing *t;
char buf[256];
for(t=container->getStuff(); t; t=t->nextThing){
o = dynamic_cast<TObj *>(t);
if (!o)
continue;
if (dynamic_cast<TKeyring *>(container) &&
obj_index[getItemIndex()].virt == obj_index[o->getItemIndex()].virt) {
sprintf(buf, "You already have one of those keys in your %s.\n\r",
fname(container->name).c_str());
ch->sendTo(buf);
return TRUE;
}
}
return FALSE;
}
<commit_msg>Rentable keys with the [housekey] keyword won't generate LOW errors.<commit_after>// key.cc
#include "stdsneezy.h"
#include "obj_open_container.h"
#include "obj_keyring.h"
#include "obj_key.h"
TKey::TKey() :
TObj()
{
}
TKey::TKey(const TKey &a)
: TObj(a)
{
}
TKey & TKey::operator=(const TKey &a)
{
if (this == &a) return *this;
TObj::operator=(a);
return *this;
}
TKey::~TKey()
{
}
void TKey::assignFourValues(int, int, int, int)
{
}
void TKey::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = 0;
*x2 = 0;
*x3 = 0;
*x4 = 0;
}
sstring TKey::statObjInfo() const
{
char buf[256];
sprintf(buf, "It is a key to %s", what_does_it_open(this));
sstring a(buf);
return a;
}
void TKey::lowCheck()
{
if ((obj_flags.cost >= 0) && isRentable() &&
isname("[housekey]", getName()) &&
(obj_flags.decay_time <= 0))
vlogf(LOG_LOW, fmt("rentable key (%s)!") % getName());
TObj::lowCheck();
}
bool TKey::objectRepair(TBeing *ch, TMonster *repair, silentTypeT silent)
{
if (!silent) {
repair->doTell(fname(ch->name), "Does this look like a locksmithery to you?");
}
return TRUE;
}
int TKey::stealModifier()
{
return 77; // make keys tough to steal
}
int TKey::putMeInto(TBeing *ch, TOpenContainer *container)
{
TObj *o;
TThing *t;
char buf[256];
for(t=container->getStuff(); t; t=t->nextThing){
o = dynamic_cast<TObj *>(t);
if (!o)
continue;
if (dynamic_cast<TKeyring *>(container) &&
obj_index[getItemIndex()].virt == obj_index[o->getItemIndex()].virt) {
sprintf(buf, "You already have one of those keys in your %s.\n\r",
fname(container->name).c_str());
ch->sendTo(buf);
return TRUE;
}
}
return FALSE;
}
<|endoftext|>
|
<commit_before>/** @file distributed_table_test.cc
*
* @author Dongryeol Lee (dongryel@cc.gatech.edu)
*/
#include "core/metric_kernels/lmetric.h"
#include "core/table/distributed_table.h"
#include "core/table/mailbox.h"
#include "core/tree/gen_kdtree.h"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
typedef core::tree::GeneralBinarySpaceTree < core::tree::GenKdTree > TreeType;
typedef core::table::Table<TreeType> TableType;
bool CheckDistributedTableIntegrity(
const core::table::DistributedTable &table_in,
const boost::mpi::communicator &world,
const boost::mpi::communicator &table_outbox_group,
const boost::mpi::communicator &table_inbox_group) {
for(int i = 0; i < world.size(); i++) {
printf(
"Process %d thinks Process %d owns %d points of dimensionality %d.\n",
world.rank(), i, table_in.local_n_entries(i % (world.size() / 3)),
table_in.n_attributes());
}
return true;
}
core::table::DistributedTable *InitDistributedTable(
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
std::pair< core::table::DistributedTable *, std::size_t >
distributed_table_pair =
core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();
core::table::DistributedTable *distributed_table =
distributed_table_pair.first;
if(distributed_table == NULL) {
printf("Process %d: TableOutbox.\n", world.rank());
// Each process generates its own random data, dumps it to the file,
// and read its own file back into its own distributed table.
core::table::Table<TreeType> random_dataset;
const int num_dimensions = 5;
int num_points = core::math::RandInt(10, 20);
random_dataset.Init(5, num_points);
for(int j = 0; j < num_points; j++) {
core::table::DensePoint point;
random_dataset.get(j, &point);
for(int i = 0; i < num_dimensions; i++) {
point[i] = core::math::Random(0.1, 1.0);
}
}
printf("Process %d generated %d points...\n", world.rank(), num_points);
std::stringstream file_name_sstr;
file_name_sstr << "random_dataset_" << world.rank() << ".csv";
std::string file_name = file_name_sstr.str();
random_dataset.Save(file_name);
std::stringstream distributed_table_name_sstr;
distributed_table_name_sstr << "distributed_table_" << world.rank() << "\n";
distributed_table = core::table::global_m_file_->UniqueConstruct <
core::table::DistributedTable > ();
distributed_table->Init(
file_name, table_outbox_group);
printf(
"Process %d read in %d points...\n",
world.rank(), distributed_table->local_n_entries());
}
return distributed_table;
}
void TableOutboxProcess(
core::table::DistributedTable *distributed_table,
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
printf("Process %d: TableOutbox.\n", world.rank());
distributed_table->RunOutbox(
table_outbox_group, table_inbox_group, computation_group);
}
void TableInboxProcess(
core::table::DistributedTable *distributed_table,
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
printf("Process %d: TableInbox.\n", world.rank());
distributed_table->RunInbox(
table_outbox_group, table_inbox_group, computation_group);
}
void ComputationProcess(
core::table::DistributedTable *distributed_table,
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
printf("Process %d: Computation.\n", world.rank());
// Do a test where each computation process requests a random point
// from a randomly chosen process.
int num_points = core::math::RandInt(10, 30);
for(int n = 0; n < num_points; n++) {
core::table::DenseConstPoint point;
int random_request_rank = core::math::RandInt(0, table_outbox_group.size());
int random_request_point_id =
core::math::RandInt(
0, distributed_table->local_n_entries(random_request_rank));
distributed_table->get(
table_outbox_group, table_inbox_group,
random_request_rank, random_request_point_id, &point);
// Print the point.
point.Print();
// Tell the inbox that we are done using the point.
distributed_table->UnlockPointinTableInbox();
}
}
int main(int argc, char *argv[]) {
// Initialize boost MPI.
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
if(world.size() <= 1 || world.size() % 3 != 0) {
std::cout << "Please specify a process number greater than 1 and "
"a multiple of 3.\n";
return 0;
}
// Delete the teporary files and put a barrier.
std::stringstream temporary_file_name;
temporary_file_name << "tmp_file" << world.rank();
remove(temporary_file_name.str().c_str());
world.barrier();
// Initialize the memory allocator.
core::table::global_m_file_ = new core::table::MemoryMappedFile();
core::table::global_m_file_->Init(
std::string("tmp_file"), world.rank(),
world.rank() % (world.size() / 3), 5000000);
// Seed the random number.
srand(time(NULL) + world.rank());
if(world.rank() == 0) {
printf("%d processes are present...\n", world.size());
}
// If the process ID is less than half of the size of the
// communicator, make it a table process. Otherwise, make it a
// computation process. This assignment depends heavily on the
// round-robin assignment of mpirun.
boost::mpi::communicator table_outbox_group = world.split(
(world.rank() < world.size() / 3) ? 1 : 0);
boost::mpi::communicator table_inbox_group = world.split(
(world.rank() >= world.size() / 3 &&
world.rank() < world.size() / 3 * 2) ? 1 : 0);
boost::mpi::communicator computation_group = world.split(
(world.rank() >= world.size() / 3 * 2) ? 1 : 0);
printf("Check: %d %d %d %d\n", world.rank(), table_outbox_group.size(),
table_inbox_group.size(), computation_group.size());
return 0;
core::table::DistributedTable *distributed_table = NULL;
// Wait until the memory allocator is in synch.
world.barrier();
// Read the distributed table once per each compute node, and put a
// barrier.
if(world.rank() < world.size() / 3) {
distributed_table =
InitDistributedTable(
world, table_outbox_group, table_inbox_group, computation_group);
}
world.barrier();
// Attach the distributed table for all the processes and put a
// barrier.
std::pair< core::table::DistributedTable *, std::size_t >
distributed_table_pair =
core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();
distributed_table = distributed_table_pair.first;
// Check the integrity of the distributed table.
CheckDistributedTableIntegrity(
*distributed_table, world, table_outbox_group, table_inbox_group);
// The main computation loop.
if(world.rank() < world.size() / 3) {
TableOutboxProcess(
distributed_table, world, table_outbox_group,
table_inbox_group, computation_group);
}
else if(world.rank() < world.size() / 3 * 2) {
TableInboxProcess(
distributed_table, world, table_outbox_group,
table_inbox_group, computation_group);
}
else {
ComputationProcess(
distributed_table, world,
table_outbox_group, table_inbox_group, computation_group);
}
return 0;
}
<commit_msg>Trying to get communicator (inter) working.<commit_after>/** @file distributed_table_test.cc
*
* @author Dongryeol Lee (dongryel@cc.gatech.edu)
*/
#include "core/metric_kernels/lmetric.h"
#include "core/table/distributed_table.h"
#include "core/table/mailbox.h"
#include "core/tree/gen_kdtree.h"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
typedef core::tree::GeneralBinarySpaceTree < core::tree::GenKdTree > TreeType;
typedef core::table::Table<TreeType> TableType;
bool CheckDistributedTableIntegrity(
const core::table::DistributedTable &table_in,
const boost::mpi::communicator &world,
const boost::mpi::communicator &table_outbox_group,
const boost::mpi::communicator &table_inbox_group) {
for(int i = 0; i < world.size(); i++) {
printf(
"Process %d thinks Process %d owns %d points of dimensionality %d.\n",
world.rank(), i, table_in.local_n_entries(i % (world.size() / 3)),
table_in.n_attributes());
}
return true;
}
core::table::DistributedTable *InitDistributedTable(
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group) {
std::pair< core::table::DistributedTable *, std::size_t >
distributed_table_pair =
core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();
core::table::DistributedTable *distributed_table =
distributed_table_pair.first;
if(distributed_table == NULL) {
printf("Process %d: TableOutbox.\n", world.rank());
// Each process generates its own random data, dumps it to the file,
// and read its own file back into its own distributed table.
core::table::Table<TreeType> random_dataset;
const int num_dimensions = 5;
int num_points = core::math::RandInt(10, 20);
random_dataset.Init(5, num_points);
for(int j = 0; j < num_points; j++) {
core::table::DensePoint point;
random_dataset.get(j, &point);
for(int i = 0; i < num_dimensions; i++) {
point[i] = core::math::Random(0.1, 1.0);
}
}
printf("Process %d generated %d points...\n", world.rank(), num_points);
std::stringstream file_name_sstr;
file_name_sstr << "random_dataset_" << world.rank() << ".csv";
std::string file_name = file_name_sstr.str();
random_dataset.Save(file_name);
std::stringstream distributed_table_name_sstr;
distributed_table_name_sstr << "distributed_table_" << world.rank() << "\n";
distributed_table = core::table::global_m_file_->UniqueConstruct <
core::table::DistributedTable > ();
distributed_table->Init(
file_name, table_outbox_group);
printf(
"Process %d read in %d points...\n",
world.rank(), distributed_table->local_n_entries());
}
return distributed_table;
}
void TableOutboxProcess(
core::table::DistributedTable *distributed_table,
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
printf("Process %d: TableOutbox.\n", world.rank());
distributed_table->RunOutbox(
table_outbox_group, table_inbox_group, computation_group);
}
void TableInboxProcess(
core::table::DistributedTable *distributed_table,
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
printf("Process %d: TableInbox.\n", world.rank());
distributed_table->RunInbox(
table_outbox_group, table_inbox_group, computation_group);
}
void ComputationProcess(
core::table::DistributedTable *distributed_table,
boost::mpi::communicator &world,
boost::mpi::communicator &table_outbox_group,
boost::mpi::communicator &table_inbox_group,
boost::mpi::communicator &computation_group) {
printf("Process %d: Computation.\n", world.rank());
// Do a test where each computation process requests a random point
// from a randomly chosen process.
int num_points = core::math::RandInt(10, 30);
for(int n = 0; n < num_points; n++) {
core::table::DenseConstPoint point;
int random_request_rank = core::math::RandInt(0, table_outbox_group.size());
int random_request_point_id =
core::math::RandInt(
0, distributed_table->local_n_entries(random_request_rank));
distributed_table->get(
table_outbox_group, table_inbox_group,
random_request_rank, random_request_point_id, &point);
// Print the point.
point.Print();
// Tell the inbox that we are done using the point.
distributed_table->UnlockPointinTableInbox();
}
}
int main(int argc, char *argv[]) {
// Initialize boost MPI.
boost::mpi::environment env(argc, argv);
boost::mpi::communicator world;
if(world.size() <= 1 || world.size() % 3 != 0) {
std::cout << "Please specify a process number greater than 1 and "
"a multiple of 3.\n";
return 0;
}
// Delete the teporary files and put a barrier.
std::stringstream temporary_file_name;
temporary_file_name << "tmp_file" << world.rank();
remove(temporary_file_name.str().c_str());
world.barrier();
// Initialize the memory allocator.
core::table::global_m_file_ = new core::table::MemoryMappedFile();
core::table::global_m_file_->Init(
std::string("tmp_file"), world.rank(),
world.rank() % (world.size() / 3), 5000000);
// Seed the random number.
srand(time(NULL) + world.rank());
if(world.rank() == 0) {
printf("%d processes are present...\n", world.size());
}
// If the process ID is less than half of the size of the
// communicator, make it a table process. Otherwise, make it a
// computation process. This assignment depends heavily on the
// round-robin assignment of mpirun.
boost::mpi::group world_group = world.group();
std::vector<int> table_outbox_group_vector(world.size() / 3, 0);
std::vector<int> table_inbox_group_vector(world.size() / 3, 0);
std::vector<int> computation_group_vector(world.size() / 3, 0);
for(int i = 0; i < world.size() / 3; i++) {
table_outbox_group_vector[i] = i;
table_inbox_group_vector[i] = i + world.size() / 3;
computation_group_vector[i] = i + world.size() / 3 * 2;
}
boost::mpi::group table_outbox_group =
world_group.include(
table_outbox_group_vector.begin(), table_outbox_group_vector.end());
boost::mpi::communicator table_outbox_group_comm(world, table_outbox_group);
boost::mpi::group table_inbox_group =
world_group.include(
table_inbox_group_vector.begin(), table_inbox_group_vector.end());
boost::mpi::communicator table_inbox_group_comm(world, table_inbox_group);
boost::mpi::group computation_group =
world_group.include(
computation_group_vector.begin(), computation_group_vector.end());
boost::mpi::communicator computation_group_comm(world, computation_group);
// Create the intercommunicator between the current process and each
// of the subgroups.
// if(world.rank() >= world.size() / 3) {
table_outbox_group_vector.push_back(world.rank());
//}
//if( world.rank() < world.size() / 3 ||
// world.rank() >= world.size() / 3 * 2 ) {
table_inbox_group_vector.push_back(world.rank());
//}
//if( world.rank() < world.size() / 3 * 2) {
computation_group_vector.push_back(world.rank());
// }
boost::mpi::group table_outbox_inter_group =
world_group.include(
table_outbox_group_vector.begin(), table_outbox_group_vector.end());
boost::mpi::communicator table_outbox_group_inter_comm(
world, table_outbox_inter_group);
boost::mpi::group table_inbox_inter_group =
world_group.include(
table_inbox_group_vector.begin(), table_inbox_group_vector.end());
boost::mpi::communicator table_inbox_group_inter_comm(
world, table_inbox_inter_group);
boost::mpi::group computation_inter_group =
world_group.include(
computation_group_vector.begin(), computation_group_vector.end());
boost::mpi::communicator computation_group_inter_comm(
world, computation_inter_group);
// Declare the distributed table.
core::table::DistributedTable *distributed_table = NULL;
// Wait until the memory allocator is in synch.
world.barrier();
// Read the distributed table once per each compute node, and put a
// barrier.
if(world.rank() < world.size() / 3) {
distributed_table =
InitDistributedTable(world, table_outbox_group_comm);
}
world.barrier();
// Attach the distributed table for all the processes and put a
// barrier.
std::pair< core::table::DistributedTable *, std::size_t >
distributed_table_pair =
core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();
distributed_table = distributed_table_pair.first;
// Check the integrity of the distributed table.
CheckDistributedTableIntegrity(
*distributed_table, world,
table_outbox_group_inter_comm, table_inbox_group_inter_comm);
// The main computation loop.
if(world.rank() < world.size() / 3) {
TableOutboxProcess(
distributed_table, world, table_outbox_group_inter_comm,
table_inbox_group_inter_comm, computation_group_inter_comm);
}
else if(world.rank() < world.size() / 3 * 2) {
TableInboxProcess(
distributed_table, world, table_outbox_group_inter_comm,
table_inbox_group_inter_comm, computation_group_inter_comm);
}
else {
ComputationProcess(
distributed_table, world,
table_outbox_group_inter_comm, table_inbox_group_inter_comm,
computation_group_inter_comm);
}
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.