text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file
* Simple PCI IDE controller with bus mastering capability and UDMA
* modeled after controller in the Intel PIIX4 chip
*/
#ifndef __IDE_CTRL_HH__
#define __IDE_CTRL_HH__
#include "dev/pcidev.hh"
#include "dev/pcireg.h"
#include "dev/io_device.hh"
#define BMIC0 0x0 // Bus master IDE command register
#define BMIS0 0x2 // Bus master IDE status register
#define BMIDTP0 0x4 // Bus master IDE descriptor table pointer register
#define BMIC1 0x8 // Bus master IDE command register
#define BMIS1 0xa // Bus master IDE status register
#define BMIDTP1 0xc // Bus master IDE descriptor table pointer register
// Bus master IDE command register bit fields
#define RWCON 0x08 // Bus master read/write control
#define SSBM 0x01 // Start/stop bus master
// Bus master IDE status register bit fields
#define DMA1CAP 0x40 // Drive 1 DMA capable
#define DMA0CAP 0x20 // Drive 0 DMA capable
#define IDEINTS 0x04 // IDE Interrupt Status
#define IDEDMAE 0x02 // IDE DMA error
#define BMIDEA 0x01 // Bus master IDE active
// IDE Command byte fields
#define IDE_SELECT_OFFSET (6)
#define IDE_SELECT_DEV_BIT 0x10
#define IDE_FEATURE_OFFSET IDE_ERROR_OFFSET
#define IDE_COMMAND_OFFSET IDE_STATUS_OFFSET
// PCI device specific register byte offsets
#define PCI_IDE_TIMING 0x40
#define PCI_SLAVE_TIMING 0x44
#define PCI_UDMA33_CTRL 0x48
#define PCI_UDMA33_TIMING 0x4a
#define IDETIM (0)
#define SIDETIM (4)
#define UDMACTL (5)
#define UDMATIM (6)
typedef enum RegType {
COMMAND_BLOCK = 0,
CONTROL_BLOCK,
BMI_BLOCK
} RegType_t;
class BaseInterface;
class Bus;
class HierParams;
class IdeDisk;
class IntrControl;
class PciConfigAll;
class PhysicalMemory;
class Platform;
/**
* Device model for an Intel PIIX4 IDE controller
*/
class IdeController : public PciDev
{
friend class IdeDisk;
private:
/** Primary command block registers */
Addr pri_cmd_addr;
Addr pri_cmd_size;
/** Primary control block registers */
Addr pri_ctrl_addr;
Addr pri_ctrl_size;
/** Secondary command block registers */
Addr sec_cmd_addr;
Addr sec_cmd_size;
/** Secondary control block registers */
Addr sec_ctrl_addr;
Addr sec_ctrl_size;
/** Bus master interface (BMI) registers */
Addr bmi_addr;
Addr bmi_size;
private:
/** Registers used for bus master interface */
uint8_t bmi_regs[16];
/** Shadows of the device select bit */
uint8_t dev[2];
/** Registers used in PCI configuration */
uint8_t pci_regs[8];
// Internal management variables
bool io_enabled;
bool bm_enabled;
bool cmd_in_progress[4];
private:
/** IDE disks connected to controller */
IdeDisk *disks[4];
private:
/** Parse the access address to pass on to device */
void parseAddr(const Addr &addr, Addr &offset, bool &primary,
RegType_t &type);
/** Select the disk based on the channel and device bit */
int getDisk(bool primary);
/** Select the disk based on a pointer */
int getDisk(IdeDisk *diskPtr);
public:
/** See if a disk is selected based on its pointer */
bool isDiskSelected(IdeDisk *diskPtr);
public:
struct Params : public PciDev::Params
{
/** Array of disk objects */
std::vector<IdeDisk *> disks;
Bus *host_bus;
Tick pio_latency;
HierParams *hier;
};
const Params *params() const { return (const Params *)_params; }
public:
IdeController(Params *p);
~IdeController();
virtual void WriteConfig(int offset, int size, uint32_t data);
virtual void ReadConfig(int offset, int size, uint8_t *data);
void intrPost();
void intrClear();
void setDmaComplete(IdeDisk *disk);
/**
* Read a done field for a given target.
* @param req Contains the address of the field to read.
* @param data Return the field read.
* @return The fault condition of the access.
*/
virtual Fault read(MemReqPtr &req, uint8_t *data);
/**
* Write to the mmapped I/O control registers.
* @param req Contains the address to write to.
* @param data The data to write.
* @return The fault condition of the access.
*/
virtual Fault write(MemReqPtr &req, const uint8_t *data);
/**
* Serialize this object to the given output stream.
* @param os The stream to serialize to.
*/
virtual void serialize(std::ostream &os);
/**
* Reconstruct the state of this object from a checkpoint.
* @param cp The checkpoint use.
* @param section The section name of this object
*/
virtual void unserialize(Checkpoint *cp, const std::string §ion);
/**
* Return how long this access will take.
* @param req the memory request to calcuate
* @return Tick when the request is done
*/
Tick cacheAccess(MemReqPtr &req);
};
#endif // __IDE_CTRL_HH_
<commit_msg>forgot a change in the previous commit. the ide controller doesn't have its own interrupt functions<commit_after>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file
* Simple PCI IDE controller with bus mastering capability and UDMA
* modeled after controller in the Intel PIIX4 chip
*/
#ifndef __IDE_CTRL_HH__
#define __IDE_CTRL_HH__
#include "dev/pcidev.hh"
#include "dev/pcireg.h"
#include "dev/io_device.hh"
#define BMIC0 0x0 // Bus master IDE command register
#define BMIS0 0x2 // Bus master IDE status register
#define BMIDTP0 0x4 // Bus master IDE descriptor table pointer register
#define BMIC1 0x8 // Bus master IDE command register
#define BMIS1 0xa // Bus master IDE status register
#define BMIDTP1 0xc // Bus master IDE descriptor table pointer register
// Bus master IDE command register bit fields
#define RWCON 0x08 // Bus master read/write control
#define SSBM 0x01 // Start/stop bus master
// Bus master IDE status register bit fields
#define DMA1CAP 0x40 // Drive 1 DMA capable
#define DMA0CAP 0x20 // Drive 0 DMA capable
#define IDEINTS 0x04 // IDE Interrupt Status
#define IDEDMAE 0x02 // IDE DMA error
#define BMIDEA 0x01 // Bus master IDE active
// IDE Command byte fields
#define IDE_SELECT_OFFSET (6)
#define IDE_SELECT_DEV_BIT 0x10
#define IDE_FEATURE_OFFSET IDE_ERROR_OFFSET
#define IDE_COMMAND_OFFSET IDE_STATUS_OFFSET
// PCI device specific register byte offsets
#define PCI_IDE_TIMING 0x40
#define PCI_SLAVE_TIMING 0x44
#define PCI_UDMA33_CTRL 0x48
#define PCI_UDMA33_TIMING 0x4a
#define IDETIM (0)
#define SIDETIM (4)
#define UDMACTL (5)
#define UDMATIM (6)
typedef enum RegType {
COMMAND_BLOCK = 0,
CONTROL_BLOCK,
BMI_BLOCK
} RegType_t;
class BaseInterface;
class Bus;
class HierParams;
class IdeDisk;
class IntrControl;
class PciConfigAll;
class PhysicalMemory;
class Platform;
/**
* Device model for an Intel PIIX4 IDE controller
*/
class IdeController : public PciDev
{
friend class IdeDisk;
private:
/** Primary command block registers */
Addr pri_cmd_addr;
Addr pri_cmd_size;
/** Primary control block registers */
Addr pri_ctrl_addr;
Addr pri_ctrl_size;
/** Secondary command block registers */
Addr sec_cmd_addr;
Addr sec_cmd_size;
/** Secondary control block registers */
Addr sec_ctrl_addr;
Addr sec_ctrl_size;
/** Bus master interface (BMI) registers */
Addr bmi_addr;
Addr bmi_size;
private:
/** Registers used for bus master interface */
uint8_t bmi_regs[16];
/** Shadows of the device select bit */
uint8_t dev[2];
/** Registers used in PCI configuration */
uint8_t pci_regs[8];
// Internal management variables
bool io_enabled;
bool bm_enabled;
bool cmd_in_progress[4];
private:
/** IDE disks connected to controller */
IdeDisk *disks[4];
private:
/** Parse the access address to pass on to device */
void parseAddr(const Addr &addr, Addr &offset, bool &primary,
RegType_t &type);
/** Select the disk based on the channel and device bit */
int getDisk(bool primary);
/** Select the disk based on a pointer */
int getDisk(IdeDisk *diskPtr);
public:
/** See if a disk is selected based on its pointer */
bool isDiskSelected(IdeDisk *diskPtr);
public:
struct Params : public PciDev::Params
{
/** Array of disk objects */
std::vector<IdeDisk *> disks;
Bus *host_bus;
Tick pio_latency;
HierParams *hier;
};
const Params *params() const { return (const Params *)_params; }
public:
IdeController(Params *p);
~IdeController();
virtual void WriteConfig(int offset, int size, uint32_t data);
virtual void ReadConfig(int offset, int size, uint8_t *data);
void setDmaComplete(IdeDisk *disk);
/**
* Read a done field for a given target.
* @param req Contains the address of the field to read.
* @param data Return the field read.
* @return The fault condition of the access.
*/
virtual Fault read(MemReqPtr &req, uint8_t *data);
/**
* Write to the mmapped I/O control registers.
* @param req Contains the address to write to.
* @param data The data to write.
* @return The fault condition of the access.
*/
virtual Fault write(MemReqPtr &req, const uint8_t *data);
/**
* Serialize this object to the given output stream.
* @param os The stream to serialize to.
*/
virtual void serialize(std::ostream &os);
/**
* Reconstruct the state of this object from a checkpoint.
* @param cp The checkpoint use.
* @param section The section name of this object
*/
virtual void unserialize(Checkpoint *cp, const std::string §ion);
/**
* Return how long this access will take.
* @param req the memory request to calcuate
* @return Tick when the request is done
*/
Tick cacheAccess(MemReqPtr &req);
};
#endif // __IDE_CTRL_HH_
<|endoftext|>
|
<commit_before>/** @example user_touche.cpp
Touche example.
*/
#include <ESP.h>
BinaryIntArraySerialStream stream(0, 115200, 160);
GestureRecognitionPipeline pipeline;
void setup()
{
useInputStream(stream);
pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160));
pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2));
usePipeline(pipeline);
}<commit_msg>Remove Touche feature extraction module.<commit_after>/** @example user_touche.cpp
Touche example.
*/
#include <ESP.h>
BinaryIntArraySerialStream stream(0, 115200, 160);
GestureRecognitionPipeline pipeline;
void setup()
{
useInputStream(stream);
pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2));
usePipeline(pipeline);
}<|endoftext|>
|
<commit_before>/*
* ext.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/background/gmodel/creator.h>
#include <dials/algorithms/background/gmodel/model.h>
namespace dials { namespace algorithms { namespace background {
namespace boost_python {
using namespace boost::python;
struct StaticBackgroundModelPickleSuite : boost::python::pickle_suite {
static
boost::python::tuple getstate(const StaticBackgroundModel &obj)
{
boost::python::list data;
for (std::size_t i = 0; i < obj.size(); ++i) {
data.append(obj.data(i));
}
return boost::python::make_tuple(data);
}
static
void setstate(StaticBackgroundModel &obj, boost::python::tuple state)
{
DIALS_ASSERT(boost::python::len(state) == 1);
boost::python::list data = boost::python::extract<boost::python::list>(state[0]);
for (std::size_t i = 0; i < boost::python::len(data); ++i) {
af::const_ref< double, af::c_grid<2> > arr = boost::python::extract<
af::const_ref< double, af::c_grid<2> > >(data[i]);
obj.add(arr);
}
}
};
BOOST_PYTHON_MODULE(dials_algorithms_background_gmodel_ext)
{
class_<BackgroundModel, boost::noncopyable, boost::shared_ptr<BackgroundModel> >("BackgroundModel", no_init)
.def("extract", pure_virtual(&BackgroundModel::extract))
;
class_< StaticBackgroundModel, bases<BackgroundModel> >("StaticBackgroundModel")
.def("add", &StaticBackgroundModel::add)
.def("__len__", &StaticBackgroundModel::size)
.def("data", &StaticBackgroundModel::data)
.def_pickle(StaticBackgroundModelPickleSuite())
;
class_<Creator> creator("Creator", no_init);
creator
.def(init<
boost::shared_ptr<BackgroundModel>,
bool,
double,
std::size_t>((
arg("model"),
arg("robust"),
arg("tuning_constant"),
arg("max_iter"))))
.def("__call__", &Creator::shoebox)
.def("__call__", &Creator::volume)
;
}
}}}} // namespace = dials::algorithms::background::boost_python
<commit_msg>Expose dispersion thershold class<commit_after>/*
* ext.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/background/gmodel/creator.h>
#include <dials/algorithms/background/gmodel/model.h>
namespace dials { namespace algorithms { namespace background {
namespace boost_python {
using namespace boost::python;
struct StaticBackgroundModelPickleSuite : boost::python::pickle_suite {
static
boost::python::tuple getstate(const StaticBackgroundModel &obj)
{
boost::python::list data;
for (std::size_t i = 0; i < obj.size(); ++i) {
data.append(obj.data(i));
}
return boost::python::make_tuple(data);
}
static
void setstate(StaticBackgroundModel &obj, boost::python::tuple state)
{
DIALS_ASSERT(boost::python::len(state) == 1);
boost::python::list data = boost::python::extract<boost::python::list>(state[0]);
for (std::size_t i = 0; i < boost::python::len(data); ++i) {
af::const_ref< double, af::c_grid<2> > arr = boost::python::extract<
af::const_ref< double, af::c_grid<2> > >(data[i]);
obj.add(arr);
}
}
};
BOOST_PYTHON_MODULE(dials_algorithms_background_gmodel_ext)
{
class_<BackgroundModel, boost::noncopyable, boost::shared_ptr<BackgroundModel> >("BackgroundModel", no_init)
.def("extract", pure_virtual(&BackgroundModel::extract))
;
class_< StaticBackgroundModel, bases<BackgroundModel> >("StaticBackgroundModel")
.def("add", &StaticBackgroundModel::add)
.def("__len__", &StaticBackgroundModel::size)
.def("data", &StaticBackgroundModel::data)
.def_pickle(StaticBackgroundModelPickleSuite())
;
class_<Creator> creator("Creator", no_init);
creator
.def(init<
boost::shared_ptr<BackgroundModel>,
bool,
double,
std::size_t>((
arg("model"),
arg("robust"),
arg("tuning_constant"),
arg("max_iter"))))
.def("__call__", &Creator::shoebox)
.def("__call__", &Creator::volume)
;
class_<DispersionThreshold>("DispersionThreshold", no_init)
.def(init< std::size_t,
std::size_t,
double,
double,
double,
int >())
.def("__call__", &DispersionThreshold::threshold<int>)
.def("__call__", &DispersionThreshold::threshold<double>)
;
}
}}}} // namespace = dials::algorithms::background::boost_python
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "pnm_image.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Helper functions
//
template <typename AssignFunc>
static void load_ascii(
uint8_t* dst,
std::ifstream& file,
size_t pitch,
size_t height,
int max_value,
AssignFunc assign_func // specifies how to handle color components
)
{
assert(max_value < 256); // TODO: 16-bit
for (size_t y = 0; y < height; ++y)
{
std::string line;
std::getline(file, line);
std::vector<std::string> tokens;
boost::algorithm::split(
tokens,
line,
boost::algorithm::is_any_of(" \t")
);
// Remove empty tokens and spaces
tokens.erase(
std::remove_if(
tokens.begin(),
tokens.end(),
[](std::string str) { return str.empty() || std::isspace(str[0]); }
),
tokens.end()
);
assert(tokens.size() == pitch);
for (size_t x = 0; x < pitch; ++x)
{
int val = std::stoi(tokens[x]);
if (max_value != 255)
{
double n = val / static_cast<double>(max_value); // scale down to [0..1]
val = static_cast<int>(n * 255); // scale up to [0..255]
}
dst[y * pitch + x] = assign_func(val);
}
}
}
static void load_binary_rgb(
uint8_t* dst,
std::ifstream& file,
size_t pitch,
size_t height,
int max_value
)
{
assert(max_value < 256); // TODO: 16-bit
file.read(reinterpret_cast<char*>(dst), pitch * height);
if (max_value != 255)
{
double scale = (1.0 / max_value) * 255;
size_t size = height * pitch;
for (size_t i = 0; i < size; ++i)
{
dst[i] = static_cast<uint8_t>(dst[i] * scale);
}
}
}
//-------------------------------------------------------------------------------------------------
// pnm_image
//
bool pnm_image::load(std::string const& filename)
{
enum format { P1 = 1, P2, P3, P4, P5, P6 };
std::ifstream file(filename);
std::string line;
//
// First line determines format:
// P1: ASCII BW | P4: binary BW
// P2: ASCII gray scale | P5: binary gray scale
// P3: ASCII RGB | P6: binary RGB
//
std::getline(file, line);
if (line.size() < 2 || line[0] != 'P' || line[1] < '0' || line[1] > '6')
{
std::cerr << "Invalid file format: " << line << '\n';
return false;
}
format fmt = static_cast<format>(line[1] - '0');
// Header
int header[3]; // width, height, max. value
int index = 0;
bool is_bitmap = (fmt == P1 || fmt == P4);
for (;;)
{
std::getline(file, line);
if (line[0] == '#')
{
// Skip comments
continue;
}
else
{
std::vector<std::string> tokens;
boost::algorithm::split(
tokens,
line,
boost::algorithm::is_any_of(" \t")
);
if (tokens.size() > 3)
{
std::cerr << "Invalid pnm file header\n";
return false;
}
for (auto t : tokens)
{
header[index++] = std::stoi(t);
if ((is_bitmap && index > 2) || (!is_bitmap && index > 3))
{
std::cerr << "Invalid pnm file header\n";
return false;
}
}
// BitMap: width and height read ==> break
if (is_bitmap && index == 2)
{
break;
}
// GrayMap/PixMap: width, height and max_value read ==> break
if (!is_bitmap && index == 3)
{
break;
}
}
}
if (header[0] <= 0 || header[1] <= 0)
{
std::cerr << "Invalid image dimensions: " << header[0] << ' ' << header[1] << '\n';
return false;
}
width_ = static_cast<size_t>(header[0]);
height_ = static_cast<size_t>(header[1]);
int max_value = header[2];
switch (fmt)
{
default:
std::cerr << "Unsupported PNM image type: P" << std::to_string(static_cast<int>(fmt)) << '\n';
width_ = 0;
height_ = 0;
format_ = PF_UNSPECIFIED;
data_.resize(0);
return false;
case P1:
format_ = PF_R8;
data_.resize(width_ * height_);
// black or white
load_ascii(
data_.data(),
file,
width_,
height_,
max_value,
[](int val)
{
assert( val == 0 || val == 1);
return val ? 0U : 255U;
}
);
return true;
case P2:
format_ = PF_R8;
data_.resize(width_ * height_);
// single gray component
load_ascii(
data_.data(),
file,
width_,
height_,
max_value,
[](int val)
{
return static_cast<uint8_t>(val);
}
);
return true;
case P3:
assert(max_value < 256);
assert(max_value == 255);
format_ = PF_RGB8;
data_.resize(width_ * height_ * 3);
// RGB color components
load_ascii(
data_.data(),
file,
width_ * 3,
height_,
max_value,
[](int val)
{
return static_cast<uint8_t>(val);
}
);
return true;
case P6:
assert(max_value < 256);
assert(max_value == 255);
format_ = PF_RGB8;
data_.resize(width_ * height_ * 3);
load_binary_rgb(
data_.data(),
file,
width_ * 3,
height_,
max_value
);
return true;
}
return true;
}
}
<commit_msg>Support binary gray-scale pnm images (P5)<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "pnm_image.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Helper functions
//
template <typename AssignFunc>
static void load_ascii(
uint8_t* dst,
std::ifstream& file,
size_t pitch,
size_t height,
int max_value,
AssignFunc assign_func // specifies how to handle color components
)
{
assert(max_value < 256); // TODO: 16-bit
for (size_t y = 0; y < height; ++y)
{
std::string line;
std::getline(file, line);
std::vector<std::string> tokens;
boost::algorithm::split(
tokens,
line,
boost::algorithm::is_any_of(" \t")
);
// Remove empty tokens and spaces
tokens.erase(
std::remove_if(
tokens.begin(),
tokens.end(),
[](std::string str) { return str.empty() || std::isspace(str[0]); }
),
tokens.end()
);
assert(tokens.size() == pitch);
for (size_t x = 0; x < pitch; ++x)
{
int val = std::stoi(tokens[x]);
if (max_value != 255)
{
double n = val / static_cast<double>(max_value); // scale down to [0..1]
val = static_cast<int>(n * 255); // scale up to [0..255]
}
dst[y * pitch + x] = assign_func(val);
}
}
}
static void load_binary(
uint8_t* dst,
std::ifstream& file,
size_t pitch,
size_t height,
int max_value
)
{
assert(max_value < 256); // TODO: 16-bit
file.read(reinterpret_cast<char*>(dst), pitch * height);
if (max_value != 255)
{
double scale = (1.0 / max_value) * 255;
size_t size = height * pitch;
for (size_t i = 0; i < size; ++i)
{
dst[i] = static_cast<uint8_t>(dst[i] * scale);
}
}
}
//-------------------------------------------------------------------------------------------------
// pnm_image
//
bool pnm_image::load(std::string const& filename)
{
enum format { P1 = 1, P2, P3, P4, P5, P6 };
std::ifstream file(filename);
std::string line;
//
// First line determines format:
// P1: ASCII BW | P4: binary BW
// P2: ASCII gray scale | P5: binary gray scale
// P3: ASCII RGB | P6: binary RGB
//
std::getline(file, line);
if (line.size() < 2 || line[0] != 'P' || line[1] < '0' || line[1] > '6')
{
std::cerr << "Invalid file format: " << line << '\n';
return false;
}
format fmt = static_cast<format>(line[1] - '0');
// Header
int header[3]; // width, height, max. value
int index = 0;
bool is_bitmap = (fmt == P1 || fmt == P4);
for (;;)
{
std::getline(file, line);
if (line[0] == '#')
{
// Skip comments
continue;
}
else
{
std::vector<std::string> tokens;
boost::algorithm::split(
tokens,
line,
boost::algorithm::is_any_of(" \t")
);
if (tokens.size() > 3)
{
std::cerr << "Invalid pnm file header\n";
return false;
}
for (auto t : tokens)
{
header[index++] = std::stoi(t);
if ((is_bitmap && index > 2) || (!is_bitmap && index > 3))
{
std::cerr << "Invalid pnm file header\n";
return false;
}
}
// BitMap: width and height read ==> break
if (is_bitmap && index == 2)
{
break;
}
// GrayMap/PixMap: width, height and max_value read ==> break
if (!is_bitmap && index == 3)
{
break;
}
}
}
if (header[0] <= 0 || header[1] <= 0)
{
std::cerr << "Invalid image dimensions: " << header[0] << ' ' << header[1] << '\n';
return false;
}
width_ = static_cast<size_t>(header[0]);
height_ = static_cast<size_t>(header[1]);
int max_value = header[2];
switch (fmt)
{
default:
std::cerr << "Unsupported PNM image type: P" << std::to_string(static_cast<int>(fmt)) << '\n';
width_ = 0;
height_ = 0;
format_ = PF_UNSPECIFIED;
data_.resize(0);
return false;
case P1:
format_ = PF_R8;
data_.resize(width_ * height_);
// black or white
load_ascii(
data_.data(),
file,
width_,
height_,
max_value,
[](int val)
{
assert( val == 0 || val == 1);
return val ? 0U : 255U;
}
);
return true;
case P2:
format_ = PF_R8;
data_.resize(width_ * height_);
// single gray component
load_ascii(
data_.data(),
file,
width_,
height_,
max_value,
[](int val)
{
return static_cast<uint8_t>(val);
}
);
return true;
case P3:
assert(max_value < 256);
assert(max_value == 255);
format_ = PF_RGB8;
data_.resize(width_ * height_ * 3);
// RGB color components
load_ascii(
data_.data(),
file,
width_ * 3,
height_,
max_value,
[](int val)
{
return static_cast<uint8_t>(val);
}
);
return true;
case P5:
format_ = PF_R8;
data_.resize(width_ * height_);
load_binary(
data_.data(),
file,
width_,
height_,
max_value
);
return true;
case P6:
assert(max_value < 256);
assert(max_value == 255);
format_ = PF_RGB8;
data_.resize(width_ * height_ * 3);
load_binary(
data_.data(),
file,
width_ * 3,
height_,
max_value
);
return true;
}
return true;
}
}
<|endoftext|>
|
<commit_before>//---------------------------- trilinos_vector_equality_4.cc ---------------------------
// $Id: vector_equality_4.cc 17992 2008-12-18 03:03:20Z bangerth $
// Version: $Name$
//
// Copyright (C) 2004, 2005, 2008, 2010 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.
//
//---------------------------- trilinos_vector_equality_4.cc ---------------------------
// check correct behaviour of Trilinos ghosted vectors and l2_norm(). The
// test now checks that l2_norm() is disabled.
#include "../tests.h"
#include <base/utilities.h>
#include <base/index_set.h>
#include <lac/trilinos_vector.h>
#include <fstream>
#include <iostream>
#include <vector>
void test ()
{
unsigned int myid = Utilities::System::get_this_mpi_process (MPI_COMM_WORLD);
unsigned int numproc = Utilities::System::get_n_mpi_processes (MPI_COMM_WORLD);
if (myid==0) deallog << "numproc=" << numproc << std::endl;
// each processor owns 2 indices and all
// are ghosting element 1 (the second)
IndexSet local_active(numproc*2);
local_active.add_range(myid*2,myid*2+2);
IndexSet local_relevant(numproc*2);
local_relevant = local_active;
local_relevant.add_range(1,2);
TrilinosWrappers::MPI::Vector v(local_active, MPI_COMM_WORLD);
TrilinosWrappers::MPI::Vector v_tmp(local_relevant, MPI_COMM_WORLD);
// set local values
v(myid*2)=1.0;
v(myid*2+1)=1.0;
v.compress();
v_tmp.reinit(v,false,true);
deal_II_exceptions::disable_abort_on_exception();
bool exc = false;
try
{
v_tmp.l2_norm();
}
catch (TrilinosWrappers::VectorBase::ExcTrilinosError e)
{
exc = true;
}
Assert (exc == true, ExcInternalError());
if (Utilities::System::get_this_mpi_process (MPI_COMM_WORLD) == 0)
deallog << "OK" << std::endl;
}
int main (int argc, char **argv)
{
Utilities::System::MPI_InitFinalize mpi_initialization(argc, argv);
unsigned int myid = Utilities::System::get_this_mpi_process (MPI_COMM_WORLD);
deallog.push(Utilities::int_to_string(myid));
if (myid == 0)
{
std::ofstream logfile(output_file_for_mpi("trilinos_ghost_03").c_str());
deallog.attach(logfile);
deallog << std::setprecision(4);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test();
}
else
test();
}
<commit_msg>Adjust comment.<commit_after>//---------------------------- trilinos_ghost_03.cc ---------------------------
// $Id: vector_equality_4.cc 17992 2008-12-18 03:03:20Z bangerth $
// Version: $Name$
//
// Copyright (C) 2004, 2005, 2008, 2010 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.
//
//---------------------------- trilinos_ghost_03.cc ---------------------------
// check correct behaviour of Trilinos ghosted vectors and l2_norm(). The
// test now checks that l2_norm() is disabled.
#include "../tests.h"
#include <base/utilities.h>
#include <base/index_set.h>
#include <lac/trilinos_vector.h>
#include <fstream>
#include <iostream>
#include <vector>
void test ()
{
unsigned int myid = Utilities::System::get_this_mpi_process (MPI_COMM_WORLD);
unsigned int numproc = Utilities::System::get_n_mpi_processes (MPI_COMM_WORLD);
if (myid==0) deallog << "numproc=" << numproc << std::endl;
// each processor owns 2 indices and all
// are ghosting element 1 (the second)
IndexSet local_active(numproc*2);
local_active.add_range(myid*2,myid*2+2);
IndexSet local_relevant(numproc*2);
local_relevant = local_active;
local_relevant.add_range(1,2);
TrilinosWrappers::MPI::Vector v(local_active, MPI_COMM_WORLD);
TrilinosWrappers::MPI::Vector v_tmp(local_relevant, MPI_COMM_WORLD);
// set local values
v(myid*2)=1.0;
v(myid*2+1)=1.0;
v.compress();
v_tmp.reinit(v,false,true);
deal_II_exceptions::disable_abort_on_exception();
bool exc = false;
try
{
v_tmp.l2_norm();
}
catch (TrilinosWrappers::VectorBase::ExcTrilinosError e)
{
exc = true;
}
Assert (exc == true, ExcInternalError());
if (Utilities::System::get_this_mpi_process (MPI_COMM_WORLD) == 0)
deallog << "OK" << std::endl;
}
int main (int argc, char **argv)
{
Utilities::System::MPI_InitFinalize mpi_initialization(argc, argv);
unsigned int myid = Utilities::System::get_this_mpi_process (MPI_COMM_WORLD);
deallog.push(Utilities::int_to_string(myid));
if (myid == 0)
{
std::ofstream logfile(output_file_for_mpi("trilinos_ghost_03").c_str());
deallog.attach(logfile);
deallog << std::setprecision(4);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test();
}
else
test();
}
<|endoftext|>
|
<commit_before>#include "Arduino.h"
#include "String.h"
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include "configs.h"
#ifdef ONLINE_MODE
//#include <ESP8266WebServer.h>
//#include <ESP8266mDNS.h>
#include "Ambient7Wifi.h"
#endif
#include <DHT.h>
#include <MHZ19_uart.h>
#ifdef SEND_TO_INFLUXDB
#include <InfluxDb.h>
#endif
unsigned long startTime = millis();
MHZ19_uart mhz19;
DHT dht;
#ifdef SEND_TO_INFLUXDB
Influxdb influxDbClient(INFLUXDB_HOST, INFLUXDB_PORT);
#endif
void setup()
{
Serial.begin(9600);
Serial.println(""); Serial.println("");
Serial.println("Ambient7");
Serial.println("https://github.com/maizy/ambient7/");
Serial.println("");
Serial.println("Configs: ");
Serial.print(" CO2 RX Pin: "); Serial.println(CO2_RX);
Serial.print(" CO2 TX Pin: "); Serial.println(CO2_TX);
Serial.print(" DHT22 1wire Pin: "); Serial.println(DTH22_1WIRE);
#ifdef ONLINE_MODE
Serial.print(" Wifi network: "); Serial.println(WIFI_NETWORK);
Serial.print(" Wifi password: ");
for (unsigned int i = 0; i < strlen(WIFI_PASSWORD); i++) {
Serial.print('*');
}
#else
Serial.println(" Offline mode");
#endif
Serial.println("");
Serial.println("");
Serial.print("Setup DHT22: ...");
dht.setup(DTH22_1WIRE);
Serial.println(" done");
Serial.print("Setup MH-Z19 ...");
mhz19.begin(CO2_RX, CO2_TX);
mhz19.setAutoCalibration(false);
Serial.println(" done");
#ifdef ONLINE_MODE
setupWifi(WIFI_NETWORK, WIFI_PASSWORD);
Serial.println("");
#ifdef SEND_TO_INFLUXDB
Serial.println("Setup InfluxDB ... ");
Serial.print(" InfluxDB host: "); Serial.print(INFLUXDB_HOST);
Serial.print(":"); Serial.print(INFLUXDB_PORT); Serial.println("");
Serial.print(" InfluxDB database: "); Serial.println(INFLUXDB_DATABASE);
if (strlen(INFLUXDB_USER) > 0) {
influxDbClient.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD);
Serial.print(" InfluxDB user: "); Serial.println(INFLUXDB_USER);
Serial.print(" InfluxDB password: ");
for (unsigned int i = 0; i < strlen(INFLUXDB_PASSWORD); i++) {
Serial.print('*');
}
Serial.println("");
} else {
influxDbClient.setDb(INFLUXDB_DATABASE);
}
Serial.println("Done");
#endif
#else
WiFi.mode(WIFI_OFF);
#endif
Serial.println("");
Serial.println("");
}
void loop()
{
unsigned long uptime = millis() - startTime;
Serial.print("DATA: uptime="); Serial.print(uptime / 1000); Serial.println("s");
int mhZ19Status = mhz19.getStatus();
Serial.print("DATA: mh_z19_status="); Serial.println(mhZ19Status);
int co2Ppm = mhz19.getPPM();
if (co2Ppm < 0) {
Serial.println("ERROR: failed to read from Co2 sensor");
} else {
Serial.print("DATA: co2="); Serial.print(co2Ppm); Serial.println("PPM");
}
// TODO: to separete thread
float humidity = dht.getHumidity();
float tempCelsius = dht.getTemperature();
if (isnan(humidity) || isnan(tempCelsius)) {
Serial.println("ERROR: failed to read from DHT sensor");
} else {
Serial.print("DATA: humidity="); Serial.print(humidity); Serial.println("%");
Serial.print("DATA: temperature="); Serial.print(tempCelsius); Serial.println("C");
}
#ifdef SEND_TO_INFLUXDB
String data = String("");
data += "uptime,device=" + String(INFLUXDB_DEVICE_NAME);
data += " millis=" + String(uptime, DEC) + "i";
if (!isnan(humidity)) {
data += "\nhumidity,device=" + String(INFLUXDB_DEVICE_NAME);
data += " relative=" + String(humidity);
}
if (!isnan(tempCelsius)) {
data += "\ntemperature,device=" + String(INFLUXDB_DEVICE_NAME);
data += " celsius=" + String(tempCelsius);
}
data += "\nco2,device=" + String(INFLUXDB_DEVICE_NAME);
data += " status=" + String(mhZ19Status) + "i";
if (co2Ppm > 0) {
data += ",ppm=" + String(co2Ppm, DEC)+"i";
}
influxDbClient.write(data);
#endif
delay(5000);
Serial.println("");
}
<commit_msg>arduino: increase update delay to 15s<commit_after>#include "Arduino.h"
#include "String.h"
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include "configs.h"
#ifdef ONLINE_MODE
//#include <ESP8266WebServer.h>
//#include <ESP8266mDNS.h>
#include "Ambient7Wifi.h"
#endif
#include <DHT.h>
#include <MHZ19_uart.h>
#ifdef SEND_TO_INFLUXDB
#include <InfluxDb.h>
#endif
unsigned long startTime = millis();
MHZ19_uart mhz19;
DHT dht;
#ifdef SEND_TO_INFLUXDB
Influxdb influxDbClient(INFLUXDB_HOST, INFLUXDB_PORT);
#endif
void setup()
{
Serial.begin(9600);
Serial.println(""); Serial.println("");
Serial.println("Ambient7");
Serial.println("https://github.com/maizy/ambient7/");
Serial.println("");
Serial.println("Configs: ");
Serial.print(" CO2 RX Pin: "); Serial.println(CO2_RX);
Serial.print(" CO2 TX Pin: "); Serial.println(CO2_TX);
Serial.print(" DHT22 1wire Pin: "); Serial.println(DTH22_1WIRE);
#ifdef ONLINE_MODE
Serial.print(" Wifi network: "); Serial.println(WIFI_NETWORK);
Serial.print(" Wifi password: ");
for (unsigned int i = 0; i < strlen(WIFI_PASSWORD); i++) {
Serial.print('*');
}
#else
Serial.println(" Offline mode");
#endif
Serial.println("");
Serial.println("");
Serial.print("Setup DHT22: ...");
dht.setup(DTH22_1WIRE);
Serial.println(" done");
Serial.print("Setup MH-Z19 ...");
mhz19.begin(CO2_RX, CO2_TX);
mhz19.setAutoCalibration(false);
Serial.println(" done");
#ifdef ONLINE_MODE
setupWifi(WIFI_NETWORK, WIFI_PASSWORD);
Serial.println("");
#ifdef SEND_TO_INFLUXDB
Serial.println("Setup InfluxDB ... ");
Serial.print(" InfluxDB host: "); Serial.print(INFLUXDB_HOST);
Serial.print(":"); Serial.print(INFLUXDB_PORT); Serial.println("");
Serial.print(" InfluxDB database: "); Serial.println(INFLUXDB_DATABASE);
if (strlen(INFLUXDB_USER) > 0) {
influxDbClient.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD);
Serial.print(" InfluxDB user: "); Serial.println(INFLUXDB_USER);
Serial.print(" InfluxDB password: ");
for (unsigned int i = 0; i < strlen(INFLUXDB_PASSWORD); i++) {
Serial.print('*');
}
Serial.println("");
} else {
influxDbClient.setDb(INFLUXDB_DATABASE);
}
Serial.println("Done");
#endif
#else
WiFi.mode(WIFI_OFF);
#endif
Serial.println("");
Serial.println("");
}
void loop()
{
unsigned long uptime = millis() - startTime;
Serial.print("DATA: uptime="); Serial.print(uptime / 1000); Serial.println("s");
int mhZ19Status = mhz19.getStatus();
Serial.print("DATA: mh_z19_status="); Serial.println(mhZ19Status);
int co2Ppm = mhz19.getPPM();
if (co2Ppm < 0) {
Serial.println("ERROR: failed to read from Co2 sensor");
} else {
Serial.print("DATA: co2="); Serial.print(co2Ppm); Serial.println("PPM");
}
// TODO: to separete thread
float humidity = dht.getHumidity();
float tempCelsius = dht.getTemperature();
if (isnan(humidity) || isnan(tempCelsius)) {
Serial.println("ERROR: failed to read from DHT sensor");
} else {
Serial.print("DATA: humidity="); Serial.print(humidity); Serial.println("%");
Serial.print("DATA: temperature="); Serial.print(tempCelsius); Serial.println("C");
}
#ifdef SEND_TO_INFLUXDB
String data = String("");
data += "uptime,device=" + String(INFLUXDB_DEVICE_NAME);
data += " millis=" + String(uptime, DEC) + "i";
if (!isnan(humidity)) {
data += "\nhumidity,device=" + String(INFLUXDB_DEVICE_NAME);
data += " relative=" + String(humidity);
}
if (!isnan(tempCelsius)) {
data += "\ntemperature,device=" + String(INFLUXDB_DEVICE_NAME);
data += " celsius=" + String(tempCelsius);
}
data += "\nco2,device=" + String(INFLUXDB_DEVICE_NAME);
data += " status=" + String(mhZ19Status) + "i";
if (co2Ppm > 0) {
data += ",ppm=" + String(co2Ppm, DEC)+"i";
}
influxDbClient.write(data);
#endif
delay(15000);
Serial.println("");
}
<|endoftext|>
|
<commit_before>#ifndef ITER_FILTER_H_
#define ITER_FILTER_H_
#include "internal/iterator_wrapper.hpp"
#include "internal/iterbase.hpp"
#include <initializer_list>
#include <iterator>
#include <utility>
namespace iter {
namespace impl {
template <typename FilterFunc, typename Container>
class Filtered;
struct BoolTester {
template <typename T>
constexpr bool operator()(const T& item_) const {
return bool(item_);
}
};
using FilterFn = IterToolFnOptionalBindFirst<Filtered, BoolTester>;
}
constexpr impl::FilterFn filter{};
}
template <typename FilterFunc, typename Container>
class iter::impl::Filtered {
private:
Container container_;
FilterFunc filter_func_;
friend FilterFn;
protected:
// Value constructor for use only in the filter function
Filtered(FilterFunc filter_func, Container&& container)
: container_(std::forward<Container>(container)),
filter_func_(filter_func) {}
public:
Filtered(Filtered&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>> {
protected:
using Holder = DerefHolder<iterator_deref<Container>>;
IteratorWrapper<Container> sub_iter_;
IteratorWrapper<Container> sub_end_;
Holder item_;
FilterFunc* filter_func_;
void inc_sub_iter() {
++sub_iter_;
if (sub_iter_ != sub_end_) {
item_.reset(*sub_iter_);
}
}
// increment until the iterator points to is true on the
// predicate. Called by constructor and operator++
void skip_failures() {
while (sub_iter_ != sub_end_ && !(*filter_func_)(item_.get())) {
inc_sub_iter();
}
}
public:
Iterator(IteratorWrapper<Container>&& sub_iter,
IteratorWrapper<Container>&& sub_end, FilterFunc& filter_func)
: sub_iter_{std::move(sub_iter)},
sub_end_{std::move(sub_end)},
filter_func_(&filter_func) {
if (sub_iter_ != sub_end_) {
item_.reset(*sub_iter_);
}
skip_failures();
}
typename Holder::reference operator*() {
return item_.get();
}
typename Holder::pointer operator->() {
return item_.get_ptr();
}
Iterator& operator++() {
inc_sub_iter();
skip_failures();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return sub_iter_ != other.sub_iter_;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {get_begin(container_), get_end(container_), filter_func_};
}
Iterator end() {
return {get_end(container_), get_end(container_), filter_func_};
}
};
#endif
<commit_msg>Adds support for const iteration to filter<commit_after>#ifndef ITER_FILTER_H_
#define ITER_FILTER_H_
#include "internal/iterator_wrapper.hpp"
#include "internal/iterbase.hpp"
#include <initializer_list>
#include <iterator>
#include <utility>
namespace iter {
namespace impl {
template <typename FilterFunc, typename Container>
class Filtered;
struct BoolTester {
template <typename T>
constexpr bool operator()(const T& item_) const {
return bool(item_);
}
};
using FilterFn = IterToolFnOptionalBindFirst<Filtered, BoolTester>;
}
constexpr impl::FilterFn filter{};
}
template <typename FilterFunc, typename Container>
class iter::impl::Filtered {
private:
Container container_;
mutable FilterFunc filter_func_;
friend FilterFn;
protected:
// Value constructor for use only in the filter function
Filtered(FilterFunc filter_func, Container&& container)
: container_(std::forward<Container>(container)),
filter_func_(filter_func) {}
public:
Filtered(Filtered&&) = default;
template <typename ContainerT>
class Iterator : public std::iterator<std::input_iterator_tag,
iterator_traits_deref<ContainerT>> {
protected:
template <typename>
friend class Iterator;
using Holder = DerefHolder<iterator_deref<ContainerT>>;
IteratorWrapper<ContainerT> sub_iter_;
IteratorWrapper<ContainerT> sub_end_;
Holder item_;
FilterFunc* filter_func_;
void inc_sub_iter() {
++sub_iter_;
if (sub_iter_ != sub_end_) {
item_.reset(*sub_iter_);
}
}
// increment until the iterator points to is true on the
// predicate. Called by constructor and operator++
void skip_failures() {
while (sub_iter_ != sub_end_ && !(*filter_func_)(item_.get())) {
inc_sub_iter();
}
}
public:
Iterator(IteratorWrapper<ContainerT>&& sub_iter,
IteratorWrapper<ContainerT>&& sub_end, FilterFunc& filter_func)
: sub_iter_{std::move(sub_iter)},
sub_end_{std::move(sub_end)},
filter_func_(&filter_func) {
if (sub_iter_ != sub_end_) {
item_.reset(*sub_iter_);
}
skip_failures();
}
typename Holder::reference operator*() {
return item_.get();
}
typename Holder::pointer operator->() {
return item_.get_ptr();
}
Iterator& operator++() {
inc_sub_iter();
skip_failures();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
template <typename T>
bool operator!=(const Iterator<T>& other) const {
return sub_iter_ != other.sub_iter_;
}
template <typename T>
bool operator==(const Iterator<T>& other) const {
return !(*this != other);
}
};
Iterator<Container> begin() {
return {get_begin(container_), get_end(container_), filter_func_};
}
Iterator<Container> end() {
return {get_end(container_), get_end(container_), filter_func_};
}
Iterator<AsConst<Container>> begin() const {
return {get_begin(as_const(container_)), get_end(as_const(container_)),
filter_func_};
}
Iterator<AsConst<Container>> end() const {
return {get_end(as_const(container_)), get_end(as_const(container_)),
filter_func_};
}
};
#endif
<|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 "remoting/protocol/jingle_session.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "base/test/test_timeouts.h"
#include "net/socket/socket.h"
#include "net/socket/stream_socket.h"
#include "remoting/base/constants.h"
#include "remoting/protocol/authenticator.h"
#include "remoting/protocol/channel_authenticator.h"
#include "remoting/protocol/connection_tester.h"
#include "remoting/protocol/fake_authenticator.h"
#include "remoting/protocol/jingle_session_manager.h"
#include "remoting/protocol/libjingle_transport_factory.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/fake_signal_strategy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::AtMost;
using testing::DeleteArg;
using testing::DoAll;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::SaveArg;
using testing::SetArgumentPointee;
using testing::WithArg;
namespace remoting {
namespace protocol {
namespace {
const char kHostJid[] = "host1@gmail.com/123";
const char kClientJid[] = "host2@gmail.com/321";
// Send 100 messages 1024 bytes each. UDP messages are sent with 10ms delay
// between messages (about 1 second for 100 messages).
const int kMessageSize = 1024;
const int kMessages = 100;
const char kChannelName[] = "test_channel";
void QuitCurrentThread() {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
ACTION(QuitThread) {
QuitCurrentThread();
}
ACTION_P(QuitThreadOnCounter, counter) {
--(*counter);
EXPECT_GE(*counter, 0);
if (*counter == 0)
QuitCurrentThread();
}
class MockSessionManagerListener : public SessionManager::Listener {
public:
MOCK_METHOD0(OnSessionManagerReady, void());
MOCK_METHOD2(OnIncomingSession,
void(Session*,
SessionManager::IncomingSessionResponse*));
};
class MockSessionEventHandler : public Session::EventHandler {
public:
MOCK_METHOD1(OnSessionStateChange, void(Session::State));
MOCK_METHOD2(OnSessionRouteChange, void(const std::string& channel_name,
const TransportRoute& route));
};
class MockStreamChannelCallback {
public:
MOCK_METHOD1(OnDone, void(net::StreamSocket* socket));
};
} // namespace
class JingleSessionTest : public testing::Test {
public:
JingleSessionTest() {
talk_base::ThreadManager::Instance()->WrapCurrentThread();
message_loop_.reset(
new JingleThreadMessageLoop(talk_base::Thread::Current()));
}
// Helper method that handles OnIncomingSession().
void SetHostSession(Session* session) {
DCHECK(session);
host_session_.reset(session);
host_session_->SetEventHandler(&host_session_event_handler_);
session->set_config(SessionConfig::GetDefault());
}
void OnClientChannelCreated(scoped_ptr<net::StreamSocket> socket) {
client_channel_callback_.OnDone(socket.get());
client_socket_ = socket.Pass();
}
void OnHostChannelCreated(scoped_ptr<net::StreamSocket> socket) {
host_channel_callback_.OnDone(socket.get());
host_socket_ = socket.Pass();
}
protected:
virtual void SetUp() {
}
virtual void TearDown() {
CloseSessions();
CloseSessionManager();
message_loop_->RunAllPending();
}
void CloseSessions() {
host_socket_.reset();
host_session_.reset();
client_socket_.reset();
client_session_.reset();
}
void CreateSessionManagers(int auth_round_trips,
FakeAuthenticator::Action auth_action) {
host_signal_strategy_.reset(new FakeSignalStrategy(kHostJid));
client_signal_strategy_.reset(new FakeSignalStrategy(kClientJid));
FakeSignalStrategy::Connect(host_signal_strategy_.get(),
client_signal_strategy_.get());
EXPECT_CALL(host_server_listener_, OnSessionManagerReady())
.Times(1);
host_server_.reset(new JingleSessionManager(
scoped_ptr<TransportFactory>(new LibjingleTransportFactory()),
false));
host_server_->Init(host_signal_strategy_.get(), &host_server_listener_);
scoped_ptr<AuthenticatorFactory> factory(
new FakeHostAuthenticatorFactory(auth_round_trips, auth_action, true));
host_server_->set_authenticator_factory(factory.Pass());
EXPECT_CALL(client_server_listener_, OnSessionManagerReady())
.Times(1);
client_server_.reset(new JingleSessionManager(
scoped_ptr<TransportFactory>(new LibjingleTransportFactory()), false));
client_server_->Init(client_signal_strategy_.get(),
&client_server_listener_);
}
void CloseSessionManager() {
if (host_server_.get()) {
host_server_->Close();
host_server_.reset();
}
if (client_server_.get()) {
client_server_->Close();
client_server_.reset();
}
host_signal_strategy_.reset();
client_signal_strategy_.reset();
}
void InitiateConnection(int auth_round_trips,
FakeAuthenticator::Action auth_action,
bool expect_fail) {
EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _))
.WillOnce(DoAll(
WithArg<0>(Invoke(this, &JingleSessionTest::SetHostSession)),
SetArgumentPointee<1>(protocol::SessionManager::ACCEPT)));
{
InSequence dummy;
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::CONNECTED))
.Times(AtMost(1));
if (expect_fail) {
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::FAILED))
.Times(1);
} else {
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::AUTHENTICATED))
.Times(1);
// Expect that the connection will be closed eventually.
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::CLOSED))
.Times(AtMost(1));
}
}
{
InSequence dummy;
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::CONNECTED))
.Times(AtMost(1));
if (expect_fail) {
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::FAILED))
.Times(1);
} else {
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::AUTHENTICATED))
.Times(1);
// Expect that the connection will be closed eventually.
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::CLOSED))
.Times(AtMost(1));
}
}
scoped_ptr<Authenticator> authenticator(new FakeAuthenticator(
FakeAuthenticator::CLIENT, auth_round_trips, auth_action, true));
client_session_ = client_server_->Connect(
kHostJid, authenticator.Pass(),
CandidateSessionConfig::CreateDefault());
client_session_->SetEventHandler(&client_session_event_handler_);
message_loop_->RunAllPending();
}
void CreateChannel() {
client_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnClientChannelCreated, base::Unretained(this)));
host_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnHostChannelCreated, base::Unretained(this)));
int counter = 2;
EXPECT_CALL(client_channel_callback_, OnDone(_))
.WillOnce(QuitThreadOnCounter(&counter));
EXPECT_CALL(host_channel_callback_, OnDone(_))
.WillOnce(QuitThreadOnCounter(&counter));
message_loop_->Run();
EXPECT_TRUE(client_socket_.get());
EXPECT_TRUE(host_socket_.get());
}
scoped_ptr<JingleThreadMessageLoop> message_loop_;
scoped_ptr<FakeSignalStrategy> host_signal_strategy_;
scoped_ptr<FakeSignalStrategy> client_signal_strategy_;
scoped_ptr<JingleSessionManager> host_server_;
MockSessionManagerListener host_server_listener_;
scoped_ptr<JingleSessionManager> client_server_;
MockSessionManagerListener client_server_listener_;
scoped_ptr<Session> host_session_;
MockSessionEventHandler host_session_event_handler_;
scoped_ptr<Session> client_session_;
MockSessionEventHandler client_session_event_handler_;
MockStreamChannelCallback client_channel_callback_;
MockStreamChannelCallback host_channel_callback_;
scoped_ptr<net::StreamSocket> client_socket_;
scoped_ptr<net::StreamSocket> host_socket_;
};
// Verify that we can create and destroy session managers without a
// connection.
TEST_F(JingleSessionTest, CreateAndDestoy) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
}
// Verify that an incoming session can be rejected, and that the
// status of the connection is set to FAILED in this case.
TEST_F(JingleSessionTest, RejectConnection) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
// Reject incoming session.
EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _))
.WillOnce(SetArgumentPointee<1>(protocol::SessionManager::DECLINE));
{
InSequence dummy;
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::FAILED))
.Times(1);
}
scoped_ptr<Authenticator> authenticator(new FakeAuthenticator(
FakeAuthenticator::CLIENT, 1, FakeAuthenticator::ACCEPT, true));
client_session_ = client_server_->Connect(
kHostJid, authenticator.Pass(), CandidateSessionConfig::CreateDefault());
client_session_->SetEventHandler(&client_session_event_handler_);
message_loop_->RunAllPending();
}
// Verify that we can connect two endpoints with single-step authentication.
TEST_F(JingleSessionTest, Connect) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
InitiateConnection(1, FakeAuthenticator::ACCEPT, false);
// Verify that the client specified correct initiator value.
ASSERT_GT(host_signal_strategy_->received_messages().size(), 0U);
const buzz::XmlElement* initiate_xml =
host_signal_strategy_->received_messages().front();
const buzz::XmlElement* jingle_element =
initiate_xml->FirstNamed(buzz::QName(kJingleNamespace, "jingle"));
ASSERT_TRUE(jingle_element);
ASSERT_EQ(kClientJid,
jingle_element->Attr(buzz::QName("", "initiator")));
}
// Verify that we can connect two endpoints with multi-step authentication.
TEST_F(JingleSessionTest, ConnectWithMultistep) {
CreateSessionManagers(3, FakeAuthenticator::ACCEPT);
InitiateConnection(3, FakeAuthenticator::ACCEPT, false);
}
// Verify that connection is terminated when single-step auth fails.
TEST_F(JingleSessionTest, ConnectWithBadAuth) {
CreateSessionManagers(1, FakeAuthenticator::REJECT);
InitiateConnection(1, FakeAuthenticator::ACCEPT, true);
}
// Verify that connection is terminated when multi-step auth fails.
TEST_F(JingleSessionTest, ConnectWithBadMultistepAuth) {
CreateSessionManagers(3, FakeAuthenticator::REJECT);
InitiateConnection(3, FakeAuthenticator::ACCEPT, true);
}
// Verify that data can be sent over stream channel.
TEST_F(JingleSessionTest, TestStreamChannel) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
ASSERT_NO_FATAL_FAILURE(
InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
ASSERT_NO_FATAL_FAILURE(CreateChannel());
StreamConnectionTester tester(host_socket_.get(), client_socket_.get(),
kMessageSize, kMessages);
tester.Start();
message_loop_->Run();
tester.CheckResults();
}
// Verify that we can connect channels with multistep auth.
TEST_F(JingleSessionTest, TestMultistepAuthStreamChannel) {
CreateSessionManagers(3, FakeAuthenticator::ACCEPT);
ASSERT_NO_FATAL_FAILURE(
InitiateConnection(3, FakeAuthenticator::ACCEPT, false));
ASSERT_NO_FATAL_FAILURE(CreateChannel());
StreamConnectionTester tester(host_socket_.get(), client_socket_.get(),
kMessageSize, kMessages);
tester.Start();
message_loop_->Run();
tester.CheckResults();
}
// Verify that we shutdown properly when channel authentication fails.
TEST_F(JingleSessionTest, TestFailedChannelAuth) {
CreateSessionManagers(1, FakeAuthenticator::REJECT_CHANNEL);
ASSERT_NO_FATAL_FAILURE(
InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
client_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnClientChannelCreated, base::Unretained(this)));
host_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnHostChannelCreated, base::Unretained(this)));
// Terminate the message loop when we get rejection notification
// from the host.
EXPECT_CALL(host_channel_callback_, OnDone(NULL))
.WillOnce(QuitThread());
EXPECT_CALL(client_channel_callback_, OnDone(_))
.Times(AtMost(1));
message_loop_->Run();
EXPECT_TRUE(!host_socket_.get());
}
} // namespace protocol
} // namespace remoting
<commit_msg>[Chromoting] Fix unit test warnings introduced in r146455.<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 "remoting/protocol/jingle_session.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "base/test/test_timeouts.h"
#include "net/socket/socket.h"
#include "net/socket/stream_socket.h"
#include "remoting/base/constants.h"
#include "remoting/protocol/authenticator.h"
#include "remoting/protocol/channel_authenticator.h"
#include "remoting/protocol/connection_tester.h"
#include "remoting/protocol/fake_authenticator.h"
#include "remoting/protocol/jingle_session_manager.h"
#include "remoting/protocol/libjingle_transport_factory.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/fake_signal_strategy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::AtLeast;
using testing::AtMost;
using testing::DeleteArg;
using testing::DoAll;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::SaveArg;
using testing::SetArgumentPointee;
using testing::WithArg;
namespace remoting {
namespace protocol {
namespace {
const char kHostJid[] = "host1@gmail.com/123";
const char kClientJid[] = "host2@gmail.com/321";
// Send 100 messages 1024 bytes each. UDP messages are sent with 10ms delay
// between messages (about 1 second for 100 messages).
const int kMessageSize = 1024;
const int kMessages = 100;
const char kChannelName[] = "test_channel";
void QuitCurrentThread() {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
ACTION(QuitThread) {
QuitCurrentThread();
}
ACTION_P(QuitThreadOnCounter, counter) {
--(*counter);
EXPECT_GE(*counter, 0);
if (*counter == 0)
QuitCurrentThread();
}
class MockSessionManagerListener : public SessionManager::Listener {
public:
MOCK_METHOD0(OnSessionManagerReady, void());
MOCK_METHOD2(OnIncomingSession,
void(Session*,
SessionManager::IncomingSessionResponse*));
};
class MockSessionEventHandler : public Session::EventHandler {
public:
MOCK_METHOD1(OnSessionStateChange, void(Session::State));
MOCK_METHOD2(OnSessionRouteChange, void(const std::string& channel_name,
const TransportRoute& route));
};
class MockStreamChannelCallback {
public:
MOCK_METHOD1(OnDone, void(net::StreamSocket* socket));
};
} // namespace
class JingleSessionTest : public testing::Test {
public:
JingleSessionTest() {
talk_base::ThreadManager::Instance()->WrapCurrentThread();
message_loop_.reset(
new JingleThreadMessageLoop(talk_base::Thread::Current()));
}
// Helper method that handles OnIncomingSession().
void SetHostSession(Session* session) {
DCHECK(session);
host_session_.reset(session);
host_session_->SetEventHandler(&host_session_event_handler_);
session->set_config(SessionConfig::GetDefault());
}
void OnClientChannelCreated(scoped_ptr<net::StreamSocket> socket) {
client_channel_callback_.OnDone(socket.get());
client_socket_ = socket.Pass();
}
void OnHostChannelCreated(scoped_ptr<net::StreamSocket> socket) {
host_channel_callback_.OnDone(socket.get());
host_socket_ = socket.Pass();
}
protected:
virtual void SetUp() {
}
virtual void TearDown() {
CloseSessions();
CloseSessionManager();
message_loop_->RunAllPending();
}
void CloseSessions() {
host_socket_.reset();
host_session_.reset();
client_socket_.reset();
client_session_.reset();
}
void CreateSessionManagers(int auth_round_trips,
FakeAuthenticator::Action auth_action) {
host_signal_strategy_.reset(new FakeSignalStrategy(kHostJid));
client_signal_strategy_.reset(new FakeSignalStrategy(kClientJid));
FakeSignalStrategy::Connect(host_signal_strategy_.get(),
client_signal_strategy_.get());
EXPECT_CALL(host_server_listener_, OnSessionManagerReady())
.Times(1);
host_server_.reset(new JingleSessionManager(
scoped_ptr<TransportFactory>(new LibjingleTransportFactory()),
false));
host_server_->Init(host_signal_strategy_.get(), &host_server_listener_);
scoped_ptr<AuthenticatorFactory> factory(
new FakeHostAuthenticatorFactory(auth_round_trips, auth_action, true));
host_server_->set_authenticator_factory(factory.Pass());
EXPECT_CALL(client_server_listener_, OnSessionManagerReady())
.Times(1);
client_server_.reset(new JingleSessionManager(
scoped_ptr<TransportFactory>(new LibjingleTransportFactory()), false));
client_server_->Init(client_signal_strategy_.get(),
&client_server_listener_);
}
void CloseSessionManager() {
if (host_server_.get()) {
host_server_->Close();
host_server_.reset();
}
if (client_server_.get()) {
client_server_->Close();
client_server_.reset();
}
host_signal_strategy_.reset();
client_signal_strategy_.reset();
}
void InitiateConnection(int auth_round_trips,
FakeAuthenticator::Action auth_action,
bool expect_fail) {
EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _))
.WillOnce(DoAll(
WithArg<0>(Invoke(this, &JingleSessionTest::SetHostSession)),
SetArgumentPointee<1>(protocol::SessionManager::ACCEPT)));
{
InSequence dummy;
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::CONNECTED))
.Times(AtMost(1));
if (expect_fail) {
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::FAILED))
.Times(1);
} else {
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::AUTHENTICATED))
.Times(1);
// Expect that the connection will be closed eventually.
EXPECT_CALL(host_session_event_handler_,
OnSessionStateChange(Session::CLOSED))
.Times(AtMost(1));
}
}
{
InSequence dummy;
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::CONNECTED))
.Times(AtMost(1));
if (expect_fail) {
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::FAILED))
.Times(1);
} else {
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::AUTHENTICATED))
.Times(1);
// Expect that the connection will be closed eventually.
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::CLOSED))
.Times(AtMost(1));
}
}
scoped_ptr<Authenticator> authenticator(new FakeAuthenticator(
FakeAuthenticator::CLIENT, auth_round_trips, auth_action, true));
client_session_ = client_server_->Connect(
kHostJid, authenticator.Pass(),
CandidateSessionConfig::CreateDefault());
client_session_->SetEventHandler(&client_session_event_handler_);
message_loop_->RunAllPending();
}
void CreateChannel() {
client_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnClientChannelCreated, base::Unretained(this)));
host_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnHostChannelCreated, base::Unretained(this)));
int counter = 2;
ExpectRouteChange();
EXPECT_CALL(client_channel_callback_, OnDone(_))
.WillOnce(QuitThreadOnCounter(&counter));
EXPECT_CALL(host_channel_callback_, OnDone(_))
.WillOnce(QuitThreadOnCounter(&counter));
message_loop_->Run();
EXPECT_TRUE(client_socket_.get());
EXPECT_TRUE(host_socket_.get());
}
void ExpectRouteChange() {
EXPECT_CALL(host_session_event_handler_,
OnSessionRouteChange(kChannelName, _))
.Times(AtLeast(1));
EXPECT_CALL(client_session_event_handler_,
OnSessionRouteChange(kChannelName, _))
.Times(AtLeast(1));
}
scoped_ptr<JingleThreadMessageLoop> message_loop_;
scoped_ptr<FakeSignalStrategy> host_signal_strategy_;
scoped_ptr<FakeSignalStrategy> client_signal_strategy_;
scoped_ptr<JingleSessionManager> host_server_;
MockSessionManagerListener host_server_listener_;
scoped_ptr<JingleSessionManager> client_server_;
MockSessionManagerListener client_server_listener_;
scoped_ptr<Session> host_session_;
MockSessionEventHandler host_session_event_handler_;
scoped_ptr<Session> client_session_;
MockSessionEventHandler client_session_event_handler_;
MockStreamChannelCallback client_channel_callback_;
MockStreamChannelCallback host_channel_callback_;
scoped_ptr<net::StreamSocket> client_socket_;
scoped_ptr<net::StreamSocket> host_socket_;
};
// Verify that we can create and destroy session managers without a
// connection.
TEST_F(JingleSessionTest, CreateAndDestoy) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
}
// Verify that an incoming session can be rejected, and that the
// status of the connection is set to FAILED in this case.
TEST_F(JingleSessionTest, RejectConnection) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
// Reject incoming session.
EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _))
.WillOnce(SetArgumentPointee<1>(protocol::SessionManager::DECLINE));
{
InSequence dummy;
EXPECT_CALL(client_session_event_handler_,
OnSessionStateChange(Session::FAILED))
.Times(1);
}
scoped_ptr<Authenticator> authenticator(new FakeAuthenticator(
FakeAuthenticator::CLIENT, 1, FakeAuthenticator::ACCEPT, true));
client_session_ = client_server_->Connect(
kHostJid, authenticator.Pass(), CandidateSessionConfig::CreateDefault());
client_session_->SetEventHandler(&client_session_event_handler_);
message_loop_->RunAllPending();
}
// Verify that we can connect two endpoints with single-step authentication.
TEST_F(JingleSessionTest, Connect) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
InitiateConnection(1, FakeAuthenticator::ACCEPT, false);
// Verify that the client specified correct initiator value.
ASSERT_GT(host_signal_strategy_->received_messages().size(), 0U);
const buzz::XmlElement* initiate_xml =
host_signal_strategy_->received_messages().front();
const buzz::XmlElement* jingle_element =
initiate_xml->FirstNamed(buzz::QName(kJingleNamespace, "jingle"));
ASSERT_TRUE(jingle_element);
ASSERT_EQ(kClientJid,
jingle_element->Attr(buzz::QName("", "initiator")));
}
// Verify that we can connect two endpoints with multi-step authentication.
TEST_F(JingleSessionTest, ConnectWithMultistep) {
CreateSessionManagers(3, FakeAuthenticator::ACCEPT);
InitiateConnection(3, FakeAuthenticator::ACCEPT, false);
}
// Verify that connection is terminated when single-step auth fails.
TEST_F(JingleSessionTest, ConnectWithBadAuth) {
CreateSessionManagers(1, FakeAuthenticator::REJECT);
InitiateConnection(1, FakeAuthenticator::ACCEPT, true);
}
// Verify that connection is terminated when multi-step auth fails.
TEST_F(JingleSessionTest, ConnectWithBadMultistepAuth) {
CreateSessionManagers(3, FakeAuthenticator::REJECT);
InitiateConnection(3, FakeAuthenticator::ACCEPT, true);
}
// Verify that data can be sent over stream channel.
TEST_F(JingleSessionTest, TestStreamChannel) {
CreateSessionManagers(1, FakeAuthenticator::ACCEPT);
ASSERT_NO_FATAL_FAILURE(
InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
ASSERT_NO_FATAL_FAILURE(CreateChannel());
StreamConnectionTester tester(host_socket_.get(), client_socket_.get(),
kMessageSize, kMessages);
tester.Start();
message_loop_->Run();
tester.CheckResults();
}
// Verify that we can connect channels with multistep auth.
TEST_F(JingleSessionTest, TestMultistepAuthStreamChannel) {
CreateSessionManagers(3, FakeAuthenticator::ACCEPT);
ASSERT_NO_FATAL_FAILURE(
InitiateConnection(3, FakeAuthenticator::ACCEPT, false));
ASSERT_NO_FATAL_FAILURE(CreateChannel());
StreamConnectionTester tester(host_socket_.get(), client_socket_.get(),
kMessageSize, kMessages);
tester.Start();
message_loop_->Run();
tester.CheckResults();
}
// Verify that we shutdown properly when channel authentication fails.
TEST_F(JingleSessionTest, TestFailedChannelAuth) {
CreateSessionManagers(1, FakeAuthenticator::REJECT_CHANNEL);
ASSERT_NO_FATAL_FAILURE(
InitiateConnection(1, FakeAuthenticator::ACCEPT, false));
client_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnClientChannelCreated, base::Unretained(this)));
host_session_->CreateStreamChannel(kChannelName, base::Bind(
&JingleSessionTest::OnHostChannelCreated, base::Unretained(this)));
// Terminate the message loop when we get rejection notification
// from the host.
EXPECT_CALL(host_channel_callback_, OnDone(NULL))
.WillOnce(QuitThread());
EXPECT_CALL(client_channel_callback_, OnDone(_))
.Times(AtMost(1));
ExpectRouteChange();
message_loop_->Run();
EXPECT_TRUE(!host_socket_.get());
}
} // namespace protocol
} // namespace remoting
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tcommuni.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:39:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_automation.hxx"
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLS_TIME_HXX //autogen
#include <tools/time.hxx>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#include <vcl/timer.hxx>
#ifndef _BASIC_TTRESHLP_HXX
#include <basic/ttstrhlp.hxx>
#endif
#include "rcontrol.hxx"
#include "tcommuni.hxx"
#include <basic/testtool.hxx>
CommunicationManagerClientViaSocketTT::CommunicationManagerClientViaSocketTT()
: CommunicationManagerClientViaSocket( TRUE )
, aAppPath()
, aAppParams()
, pProcess( NULL )
{
}
BOOL CommunicationManagerClientViaSocketTT::StartCommunication()
{
bApplicationStarted = FALSE;
return CommunicationManagerClientViaSocket::StartCommunication( ByteString( GetHostConfig(), RTL_TEXTENCODING_UTF8 ), GetTTPortConfig() );
}
BOOL CommunicationManagerClientViaSocketTT::StartCommunication( String aApp, String aParams, Environment *pChildEnv )
{
aAppPath = aApp;
aAppParams = aParams;
aAppEnv = (*pChildEnv);
return StartCommunication();
}
BOOL CommunicationManagerClientViaSocketTT::RetryConnect()
{
if ( !bApplicationStarted )
{
// Die App ist wohl nicht da. Starten wir sie mal.
if ( aAppPath.Len() )
{
delete pProcess;
pProcess = new Process();
pProcess->SetImage( aAppPath, aAppParams, &aAppEnv );
BOOL bSucc = pProcess->Start();
bApplicationStarted = TRUE;
if ( bSucc )
{
aFirstRetryCall = Time() + Time( 0, 1 ); // Max eine Minute Zeit
for ( int i = 10 ; i-- ; )
GetpApp()->Reschedule();
}
return bSucc;
}
return FALSE;
}
else
{
if ( aFirstRetryCall > Time() )
{
Timer aWait;
aWait.SetTimeout( 500 ); // Max 500 mSec
aWait.Start();
while ( aWait.IsActive() )
GetpApp()->Yield();
return TRUE;
}
else
return FALSE;
}
}
BOOL CommunicationManagerClientViaSocketTT::KillApplication()
{
if ( pProcess )
return pProcess->Terminate();
return TRUE;
}
#define GETSET(aVar, KeyName, Dafault) \
aVar = aConf.ReadKey(KeyName,"No Entry"); \
if ( aVar.CompareTo("No Entry") == COMPARE_EQUAL ) \
{ \
aVar = ByteString(Dafault); \
aConf.WriteKey(KeyName, aVar); \
}
String GetHostConfig()
{
String aHostToTalk;
for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
{
if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-host=") == COMPARE_EQUAL
#ifndef UNX
|| Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/host=") == COMPARE_EQUAL
#endif
)
return Application::GetCommandLineParam( i ).Copy(6);
}
ByteString abHostToTalk;
Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
aConf.SetGroup("Communication");
GETSET( abHostToTalk, "Host", DEFAULT_HOST );
return UniString( abHostToTalk, RTL_TEXTENCODING_UTF8 );
}
ULONG GetTTPortConfig()
{
String aPortToTalk;
for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
{
if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-port=") == COMPARE_EQUAL
#ifndef UNX
|| Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/port=") == COMPARE_EQUAL
#endif
)
{
aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
return (ULONG)aPortToTalk.ToInt64();
}
}
ByteString abPortToTalk;
Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
aConf.SetGroup("Communication");
GETSET( abPortToTalk, "TTPort", ByteString::CreateFromInt32( TESTTOOL_DEFAULT_PORT ) );
return (ULONG)abPortToTalk.ToInt64();
}
ULONG GetUnoPortConfig()
{
String aPortToTalk;
for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
{
if ( Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("-unoport=") == COMPARE_EQUAL
#ifndef UNX
|| Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("/unoport=") == COMPARE_EQUAL
#endif
)
{
aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
return (ULONG)aPortToTalk.ToInt64();
}
}
ByteString abPortToTalk;
Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
aConf.SetGroup("Communication");
GETSET( abPortToTalk, "UnoPort", ByteString::CreateFromInt32( UNO_DEFAULT_PORT ) );
return (ULONG)abPortToTalk.ToInt64();
}
<commit_msg>INTEGRATION: CWS sb59 (1.8.54); FILE MERGED 2006/08/16 14:46:07 sb 1.8.54.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tcommuni.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-10-12 11:19:37 $
*
* 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_automation.hxx"
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLS_TIME_HXX //autogen
#include <tools/time.hxx>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#include <vcl/timer.hxx>
#ifndef _BASIC_TTRESHLP_HXX
#include <basic/ttstrhlp.hxx>
#endif
#include "rcontrol.hxx"
#include "tcommuni.hxx"
#include <basic/testtool.hxx>
CommunicationManagerClientViaSocketTT::CommunicationManagerClientViaSocketTT()
: CommunicationManagerClientViaSocket( TRUE )
, aAppPath()
, aAppParams()
, pProcess( NULL )
{
}
BOOL CommunicationManagerClientViaSocketTT::StartCommunication()
{
bApplicationStarted = FALSE;
return CommunicationManagerClientViaSocket::StartCommunication( ByteString( GetHostConfig(), RTL_TEXTENCODING_UTF8 ), GetTTPortConfig() );
}
BOOL CommunicationManagerClientViaSocketTT::StartCommunication( String aApp, String aParams, Environment *pChildEnv )
{
aAppPath = aApp;
aAppParams = aParams;
aAppEnv = (*pChildEnv);
return StartCommunication();
}
BOOL CommunicationManagerClientViaSocketTT::RetryConnect()
{
if ( !bApplicationStarted )
{
// Die App ist wohl nicht da. Starten wir sie mal.
if ( aAppPath.Len() )
{
delete pProcess;
pProcess = new Process();
pProcess->SetImage( aAppPath, aAppParams, &aAppEnv );
BOOL bSucc = pProcess->Start();
bApplicationStarted = TRUE;
if ( bSucc )
{
aFirstRetryCall = Time() + Time( 0, 1 ); // Max eine Minute Zeit
for ( int i = 10 ; i-- ; )
GetpApp()->Reschedule();
}
return bSucc;
}
return FALSE;
}
else
{
if ( aFirstRetryCall > Time() )
{
Timer aWait;
aWait.SetTimeout( 500 ); // Max 500 mSec
aWait.Start();
while ( aWait.IsActive() )
GetpApp()->Yield();
return TRUE;
}
else
return FALSE;
}
}
BOOL CommunicationManagerClientViaSocketTT::KillApplication()
{
if ( pProcess )
return pProcess->Terminate();
return TRUE;
}
#define GETSET(aVar, KeyName, Dafault) \
aVar = aConf.ReadKey(KeyName,"No Entry"); \
if ( aVar.CompareTo("No Entry") == COMPARE_EQUAL ) \
{ \
aVar = ByteString(Dafault); \
aConf.WriteKey(KeyName, aVar); \
}
String GetHostConfig()
{
String aHostToTalk;
for ( USHORT i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
{
if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-host=") == COMPARE_EQUAL
#ifndef UNX
|| Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/host=") == COMPARE_EQUAL
#endif
)
return Application::GetCommandLineParam( i ).Copy(6);
}
ByteString abHostToTalk;
Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
aConf.SetGroup("Communication");
GETSET( abHostToTalk, "Host", DEFAULT_HOST );
return UniString( abHostToTalk, RTL_TEXTENCODING_UTF8 );
}
ULONG GetTTPortConfig()
{
String aPortToTalk;
for ( USHORT i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
{
if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-port=") == COMPARE_EQUAL
#ifndef UNX
|| Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/port=") == COMPARE_EQUAL
#endif
)
{
aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
return (ULONG)aPortToTalk.ToInt64();
}
}
ByteString abPortToTalk;
Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
aConf.SetGroup("Communication");
GETSET( abPortToTalk, "TTPort", ByteString::CreateFromInt32( TESTTOOL_DEFAULT_PORT ) );
return (ULONG)abPortToTalk.ToInt64();
}
ULONG GetUnoPortConfig()
{
String aPortToTalk;
for ( USHORT i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
{
if ( Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("-unoport=") == COMPARE_EQUAL
#ifndef UNX
|| Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("/unoport=") == COMPARE_EQUAL
#endif
)
{
aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
return (ULONG)aPortToTalk.ToInt64();
}
}
ByteString abPortToTalk;
Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
aConf.SetGroup("Communication");
GETSET( abPortToTalk, "UnoPort", ByteString::CreateFromInt32( UNO_DEFAULT_PORT ) );
return (ULONG)abPortToTalk.ToInt64();
}
<|endoftext|>
|
<commit_before>/*
* DIPlib 3.0 viewer
* This file contains source for all classes need to use the DIPviewer.
*
* (c)2017, Wouter Caarls
*
* 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 "dipviewer.h"
#ifdef DIP__HAS_GLFW
#include "diplib/viewer/glfw.h"
using ViewerManager = dip::viewer::GLFWManager;
#else
#include "diplib/viewer/glut.h"
using ViewerManager = dip::viewer::GLUTManager;
#endif
#include "diplib/viewer/image.h"
#include "diplib/viewer/slice.h"
namespace dip { namespace viewer {
namespace {
ViewerManager* manager__ = nullptr;
size_t count__ = 0;
String getWindowTitle( String const& title ) {
if( !title.empty()) {
return title;
}
return String( "Window " ) + std::to_string( count__ );
}
inline void Create() {
if( !manager__ ) {
manager__ = new ViewerManager();
count__ = 1;
}
}
inline void Delete() {
delete manager__;
manager__ = nullptr;
}
} // namespace
void Show( Image const& image, String const& title ) {
Create();
DIP_STACK_TRACE_THIS( manager__->createWindow( SliceViewer::Create( image, getWindowTitle( title ))));
++count__;
}
void ShowSimple( Image const& image, String const& title ) {
Create();
DIP_STACK_TRACE_THIS( manager__->createWindow( ImageViewer::Create( image, getWindowTitle( title ))));
++count__;
}
void Spin() {
if( !manager__ ) {
return;
}
while( manager__->activeWindows()) {
Draw();
std::this_thread::sleep_for( std::chrono::microseconds( 100 ));
}
Delete();
}
void Draw() {
if( !manager__ ) {
return;
}
manager__->processEvents();
}
void CloseAll() {
if( !manager__ ) {
return;
}
manager__->destroyWindows();
Spin();
}
}} // namespace dip::viewer
<commit_msg>DIPviewer interface throws error if we're trying to show a 0D image.<commit_after>/*
* DIPlib 3.0 viewer
* This file contains source for all classes need to use the DIPviewer.
*
* (c)2017, Wouter Caarls
*
* 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 "dipviewer.h"
#ifdef DIP__HAS_GLFW
#include "diplib/viewer/glfw.h"
using ViewerManager = dip::viewer::GLFWManager;
#else
#include "diplib/viewer/glut.h"
using ViewerManager = dip::viewer::GLUTManager;
#endif
#include "diplib/viewer/image.h"
#include "diplib/viewer/slice.h"
namespace dip { namespace viewer {
namespace {
ViewerManager* manager__ = nullptr;
size_t count__ = 0;
String getWindowTitle( String const& title ) {
if( !title.empty()) {
return title;
}
return String( "Window " ) + std::to_string( count__ );
}
inline void Create() {
if( !manager__ ) {
manager__ = new ViewerManager();
count__ = 1;
}
}
inline void Delete() {
delete manager__;
manager__ = nullptr;
}
} // namespace
void Show( Image const& image, String const& title ) {
DIP_THROW_IF( image.Dimensionality() == 0, E::DIMENSIONALITY_NOT_SUPPORTED );
Create();
DIP_STACK_TRACE_THIS( manager__->createWindow( SliceViewer::Create( image, getWindowTitle( title ))));
++count__;
}
void ShowSimple( Image const& image, String const& title ) {
DIP_THROW_IF( image.Dimensionality() == 0, E::DIMENSIONALITY_NOT_SUPPORTED );
Create();
DIP_STACK_TRACE_THIS( manager__->createWindow( ImageViewer::Create( image, getWindowTitle( title ))));
++count__;
}
void Spin() {
if( !manager__ ) {
return;
}
while( manager__->activeWindows()) {
Draw();
std::this_thread::sleep_for( std::chrono::microseconds( 100 ));
}
Delete();
}
void Draw() {
if( !manager__ ) {
return;
}
manager__->processEvents();
}
void CloseAll() {
if( !manager__ ) {
return;
}
manager__->destroyWindows();
Spin();
}
}} // namespace dip::viewer
<|endoftext|>
|
<commit_before>#include "caffe2/operators/half_float_ops.h"
namespace caffe2 {
OPERATOR_SCHEMA(FloatToHalf).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(HalfToFloat).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(Float16ConstantFill)
.NumInputs(0)
.NumOutputs(1)
.TensorInferenceFunction(Float16FillerTensorInference)
.Arg("value", "The value for the elements of the output tensor.")
.Arg("shape", "The shape of the output tensor.")
.Output(
0,
"output",
"Output tensor of constant values specified by 'value'");
class GetFloatToHalfGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"HalfToFloat", "", vector<string>{GO(0)}, vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(FloatToHalf, GetFloatToHalfGradient);
class GetHalfToFloatGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"FloatToHalf", "", vector<string>{GO(0)}, vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(HalfToFloat, GetHalfToFloatGradient);
NO_GRADIENT(Float16ConstantFill);
} // namespace caffe2
<commit_msg>Add shape inference to fp16<->fp32 ops<commit_after>#include "caffe2/operators/half_float_ops.h"
namespace caffe2 {
OPERATOR_SCHEMA(FloatToHalf)
.NumInputs(1)
.NumOutputs(1)
.TensorInferenceFunction(
[](const OperatorDef& def, const vector<TensorShape>& in) {
vector<TensorShape> out;
const TensorShape& X = in[0];
out.push_back(X);
out[0].set_data_type(TensorProto_DataType_FLOAT16);
return out;
});
OPERATOR_SCHEMA(HalfToFloat)
.NumInputs(1)
.NumOutputs(1)
.TensorInferenceFunction(
[](const OperatorDef& def, const vector<TensorShape>& in) {
vector<TensorShape> out;
const TensorShape& X = in[0];
out.push_back(X);
out[0].set_data_type(TensorProto_DataType_FLOAT);
return out;
});
OPERATOR_SCHEMA(Float16ConstantFill)
.NumInputs(0)
.NumOutputs(1)
.TensorInferenceFunction(Float16FillerTensorInference)
.Arg("value", "The value for the elements of the output tensor.")
.Arg("shape", "The shape of the output tensor.")
.Output(
0,
"output",
"Output tensor of constant values specified by 'value'");
class GetFloatToHalfGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"HalfToFloat", "", vector<string>{GO(0)}, vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(FloatToHalf, GetFloatToHalfGradient);
class GetHalfToFloatGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"FloatToHalf", "", vector<string>{GO(0)}, vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(HalfToFloat, GetHalfToFloatGradient);
NO_GRADIENT(Float16ConstantFill);
} // namespace caffe2
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hwpreader.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _HWPREADER_HXX_
#define _HWPREADER_HXX_
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sal/alloca.h>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/document/XFilter.hpp>
#include <com/sun/star/document/XImporter.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/ucb/XContentIdentifierFactory.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
#include <com/sun/star/ucb/XContentIdentifier.hpp>
#include <com/sun/star/ucb/XContent.hpp>
#include <com/sun/star/ucb/OpenCommandArgument2.hpp>
#include <com/sun/star/ucb/OpenMode.hpp>
#include <com/sun/star/ucb/XCommandProcessor.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>
#include <cppuhelper/servicefactory.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::xml::sax;
#include <assert.h>
#include "hwpfile.h"
#include "hcode.h"
#include "hbox.h"
#include "htags.h"
#include "hstream.h"
#include "drawdef.h"
#include "attributes.hxx"
#define IMPLEMENTATION_NAME "com.sun.comp.hwpimport.HwpImportFilter"
#define SERVICE_NAME "com.sun.star.document.ImportFilter"
#define WRITER_IMPORTER_NAME "com.sun.star.comp.Writer.XMLImporter"
class MyDataSink : public ::cppu::WeakImplHelper2< XActiveDataControl, XActiveDataSink >
{
Reference < XInputStream > m_xInputStream;
public:
// XActiveDataControl.
virtual void SAL_CALL addListener ( const Reference<XStreamListener> &)
throw(RuntimeException) {}
virtual void SAL_CALL removeListener ( const Reference<XStreamListener> &)
throw(RuntimeException) {}
virtual void SAL_CALL start (void) throw(RuntimeException) {}
virtual void SAL_CALL terminate (void) throw(RuntimeException) {}
// XActiveDataSink.
virtual void SAL_CALL setInputStream ( const Reference<XInputStream> &rxInputStream)
throw(RuntimeException);
virtual Reference<XInputStream> SAL_CALL getInputStream (void)
throw(RuntimeException);
};
void SAL_CALL MyDataSink::setInputStream ( const Reference<XInputStream> &rxInputStream)
throw(RuntimeException )
{
m_xInputStream = rxInputStream;
}
Reference < XInputStream > SAL_CALL MyDataSink::getInputStream (void)
throw(RuntimeException)
{
return m_xInputStream;
}
struct HwpReaderPrivate;
/**
* This class implements the external Parser interface
*/
class HwpReader : public WeakImplHelper1<XFilter>
{
public:
HwpReader();
~HwpReader();
public:
/**
* parseStream does Parser-startup initializations
*/
virtual sal_Bool SAL_CALL filter(const Sequence< PropertyValue >& aDescriptor) throw (RuntimeException);
virtual void SAL_CALL cancel() throw(RuntimeException) {}
virtual void SAL_CALL setDocumentHandler(Reference< XDocumentHandler > xHandler)
{
rDocumentHandler = xHandler;
}
void setUCB( Reference< XInterface > xUCB ){
rUCB = xUCB;
}
private:
Reference< XDocumentHandler > rDocumentHandler;
Reference< XInterface > rUCB;
Reference< XAttributeList > rList;
AttributeListImpl *pList;
HWPFile hwpfile;
HwpReaderPrivate *d;
private:
/* -------- Document Parsing --------- */
void makeMeta();
void makeStyles();
void makeDrawMiscStyle(HWPDrawingObject *);
void makeAutoStyles();
void makeMasterStyles();
void makeBody();
void makeTextDecls();
/* -------- Paragraph Parsing --------- */
void parsePara(HWPPara *para, sal_Bool bParaStart = sal_False);
void make_text_p0(HWPPara *para, sal_Bool bParaStart = sal_False);
void make_text_p1(HWPPara *para, sal_Bool bParaStart = sal_False);
void make_text_p3(HWPPara *para, sal_Bool bParaStart = sal_False);
/* -------- rDocument->characters(x) --------- */
void makeChars(hchar *, int);
/* -------- Special Char Parsing --------- */
void makeFieldCode(FieldCode *hbox); //6
void makeBookmark(Bookmark *hbox); //6
void makeDateFormat(DateCode *hbox); //7
void makeDateCode(DateCode *hbox); //8
void makeTab(Tab *hbox); //9
void makeTable(TxtBox *hbox);
void makeTextBox(TxtBox *hbox);
void makeFormula(TxtBox *hbox);
void makeHyperText(TxtBox *hbox);
void makePicture(Picture *hbox);
void makePictureOLE(Picture *hbox);
void makePictureDRAW(HWPDrawingObject *drawobj, Picture *hbox);
void makeLine(Line *hbox);
void makeHidden(Hidden *hbox);
void makeHeaderFooter(HeaderFooter *hbox);
void makeFootnote(Footnote *hbox);
void makeAutoNum(AutoNum *hbox);
void makeNewNum(NewNum *hbox);
void makeShowPageNum();
void makePageNumCtrl(PageNumCtrl *hbox);
void makeMailMerge(MailMerge *hbox);
void makeCompose(Compose *hbox);
void makeHyphen(Hyphen *hbox);
void makeTocMark(TocMark *hbox);
void makeIndexMark(IndexMark *hbox);
void makeOutline(Outline *hbox);
void makeKeepSpace(KeepSpace *hbox);
void makeFixedSpace(FixedSpace *hbox);
/* --------- Styles Parsing ------------ */
void makePageStyle();
void makeColumns(ColumnDef *);
void makeTStyle(CharShape *);
void makePStyle(ParaShape *);
void makeFStyle(FBoxStyle *);
void makeCaptionStyle(FBoxStyle *);
void makeDrawStyle(HWPDrawingObject *,FBoxStyle *);
void makeTableStyle(Table *);
void parseCharShape(CharShape *);
void parseParaShape(ParaShape *);
char* getTStyleName(int, char *);
char* getPStyleName(int, char *);
};
class HwpImportFilter : public WeakImplHelper3< XFilter, XImporter, XServiceInfo >
{
public:
HwpImportFilter( const Reference< XMultiServiceFactory > xFact );
~HwpImportFilter();
public:
static Sequence< OUString > getSupportedServiceNames_Static( void ) throw();
static OUString getImplementationName_Static() throw();
public:
// XFilter
virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& aDescriptor )
throw( RuntimeException );
virtual void SAL_CALL cancel() throw(RuntimeException);
// XImporter
virtual void SAL_CALL setTargetDocument( const Reference< XComponent >& xDoc)
throw( IllegalArgumentException, RuntimeException );
// XServiceInfo
OUString SAL_CALL getImplementationName() throw (RuntimeException);
Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw (::com::sun::star::uno::RuntimeException);
public:
Reference< XFilter > rFilter;
Reference< XImporter > rImporter;
};
Reference< XInterface > HwpImportFilter_CreateInstance(
const Reference< XMultiServiceFactory >& rSMgr ) throw( Exception )
{
HwpImportFilter *p = new HwpImportFilter( rSMgr );
return Reference< XInterface > ( (OWeakObject* )p );
}
Sequence< OUString > HwpImportFilter::getSupportedServiceNames_Static( void ) throw ()
{
Sequence< OUString > aRet(1);
aRet.getArray()[0] = HwpImportFilter::getImplementationName_Static();
return aRet;
}
HwpImportFilter::HwpImportFilter( const Reference< XMultiServiceFactory > xFact )
{
OUString sService = OUString::createFromAscii( WRITER_IMPORTER_NAME );
try {
Reference< XDocumentHandler >
xHandler( xFact->createInstance( sService ), UNO_QUERY );
HwpReader *p = new HwpReader;
p->setDocumentHandler( xHandler );
Sequence< Any > aArgs( 2 );
aArgs[0] <<= OUString::createFromAscii( "Local" );
aArgs[1] <<= OUString::createFromAscii( "Office" );
Reference< XInterface > xUCB
( xFact->createInstanceWithArguments
(OUString::createFromAscii("com.sun.star.ucb.UniversalContentBroker"),
aArgs));
p->setUCB( xUCB );
Reference< XImporter > xImporter = Reference< XImporter >( xHandler, UNO_QUERY );
rImporter = xImporter;
Reference< XFilter > xFilter = Reference< XFilter >( p );
rFilter = xFilter;
}
catch( Exception & )
{
printf(" fail to instanciate %s\n", WRITER_IMPORTER_NAME );
exit( 1 );
}
}
HwpImportFilter::~HwpImportFilter()
{
}
sal_Bool HwpImportFilter::filter( const Sequence< PropertyValue >& aDescriptor )
throw( RuntimeException )
{
// delegate to IchitaroImpoter
rFilter->filter( aDescriptor );
return sal_True;
}
void HwpImportFilter::cancel() throw(::com::sun::star::uno::RuntimeException)
{
rFilter->cancel();
}
void HwpImportFilter::setTargetDocument( const Reference< XComponent >& xDoc )
throw( IllegalArgumentException, RuntimeException )
{
// delegate
rImporter->setTargetDocument( xDoc );
}
OUString HwpImportFilter::getImplementationName_Static() throw()
{
return OUString::createFromAscii( IMPLEMENTATION_NAME );
}
OUString HwpImportFilter::getImplementationName() throw(::com::sun::star::uno::RuntimeException)
{
return OUString::createFromAscii( IMPLEMENTATION_NAME );
}
sal_Bool HwpImportFilter::supportsService( const OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< OUString > aSNL = getSupportedServiceNames();
const OUString *pArray = aSNL.getConstArray();
for ( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
if ( pArray[i] == ServiceName )
return sal_True;
return sal_False;
}
Sequence< OUString> HwpImportFilter::getSupportedServiceNames( void ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< OUString > seq(1);
seq.getArray()[0] = OUString::createFromAscii( SERVICE_NAME );
return seq;
}
/////////////////////////////////////////////////////////////////////////////////////
// The below three C functions are nessesary for this shared library is treaded as
// UNO component library.
/////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo(
void * , void * pRegistryKey )
{
if (pRegistryKey)
{
try
{
Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey * >( pRegistryKey ) );
Reference< XRegistryKey > xNewKey = xKey->createKey(
OUString::createFromAscii( "/" IMPLEMENTATION_NAME "/UNO/SERVICES" ) );
xNewKey->createKey( OUString::createFromAscii( SERVICE_NAME ) );
return sal_True;
}
catch (InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
}
return sal_False;
}
void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * )
{
void * pRet = 0;
if (pServiceManager )
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > xSMgr = reinterpret_cast< XMultiServiceFactory * > ( pServiceManager );
OUString aImplementationName = OUString::createFromAscii( pImplName );
if (aImplementationName == OUString::createFromAscii( IMPLEMENTATION_NAME ) )
{
xRet = createSingleFactory( xSMgr, aImplementationName,
HwpImportFilter_CreateInstance,
HwpImportFilter::getSupportedServiceNames_Static() );
}
if (xRet.is())
{
xRet->acquire();
pRet = xRet.get();
}
}
return pRet;
}
}
#endif
<commit_msg>INTEGRATION: CWS sw30bf04 (1.6.2); FILE MERGED 2008/04/16 14:07:55 ama 1.6.2.1: Patch #i86356#: Remove unused methods<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: hwpreader.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _HWPREADER_HXX_
#define _HWPREADER_HXX_
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sal/alloca.h>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/document/XFilter.hpp>
#include <com/sun/star/document/XImporter.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/ucb/XContentIdentifierFactory.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
#include <com/sun/star/ucb/XContentIdentifier.hpp>
#include <com/sun/star/ucb/XContent.hpp>
#include <com/sun/star/ucb/OpenCommandArgument2.hpp>
#include <com/sun/star/ucb/OpenMode.hpp>
#include <com/sun/star/ucb/XCommandProcessor.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>
#include <cppuhelper/servicefactory.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::xml::sax;
#include <assert.h>
#include "hwpfile.h"
#include "hcode.h"
#include "hbox.h"
#include "htags.h"
#include "hstream.h"
#include "drawdef.h"
#include "attributes.hxx"
#define IMPLEMENTATION_NAME "com.sun.comp.hwpimport.HwpImportFilter"
#define SERVICE_NAME "com.sun.star.document.ImportFilter"
#define WRITER_IMPORTER_NAME "com.sun.star.comp.Writer.XMLImporter"
class MyDataSink : public ::cppu::WeakImplHelper2< XActiveDataControl, XActiveDataSink >
{
Reference < XInputStream > m_xInputStream;
public:
// XActiveDataControl.
virtual void SAL_CALL addListener ( const Reference<XStreamListener> &)
throw(RuntimeException) {}
virtual void SAL_CALL removeListener ( const Reference<XStreamListener> &)
throw(RuntimeException) {}
virtual void SAL_CALL start (void) throw(RuntimeException) {}
virtual void SAL_CALL terminate (void) throw(RuntimeException) {}
// XActiveDataSink.
virtual void SAL_CALL setInputStream ( const Reference<XInputStream> &rxInputStream)
throw(RuntimeException);
virtual Reference<XInputStream> SAL_CALL getInputStream (void)
throw(RuntimeException);
};
void SAL_CALL MyDataSink::setInputStream ( const Reference<XInputStream> &rxInputStream)
throw(RuntimeException )
{
m_xInputStream = rxInputStream;
}
Reference < XInputStream > SAL_CALL MyDataSink::getInputStream (void)
throw(RuntimeException)
{
return m_xInputStream;
}
struct HwpReaderPrivate;
/**
* This class implements the external Parser interface
*/
class HwpReader : public WeakImplHelper1<XFilter>
{
public:
HwpReader();
~HwpReader();
public:
/**
* parseStream does Parser-startup initializations
*/
virtual sal_Bool SAL_CALL filter(const Sequence< PropertyValue >& aDescriptor) throw (RuntimeException);
virtual void SAL_CALL cancel() throw(RuntimeException) {}
virtual void SAL_CALL setDocumentHandler(Reference< XDocumentHandler > xHandler)
{
rDocumentHandler = xHandler;
}
void setUCB( Reference< XInterface > xUCB ){
rUCB = xUCB;
}
private:
Reference< XDocumentHandler > rDocumentHandler;
Reference< XInterface > rUCB;
Reference< XAttributeList > rList;
AttributeListImpl *pList;
HWPFile hwpfile;
HwpReaderPrivate *d;
private:
/* -------- Document Parsing --------- */
void makeMeta();
void makeStyles();
void makeDrawMiscStyle(HWPDrawingObject *);
void makeAutoStyles();
void makeMasterStyles();
void makeBody();
void makeTextDecls();
/* -------- Paragraph Parsing --------- */
void parsePara(HWPPara *para, sal_Bool bParaStart = sal_False);
void make_text_p0(HWPPara *para, sal_Bool bParaStart = sal_False);
void make_text_p1(HWPPara *para, sal_Bool bParaStart = sal_False);
void make_text_p3(HWPPara *para, sal_Bool bParaStart = sal_False);
/* -------- rDocument->characters(x) --------- */
void makeChars(hchar *, int);
/* -------- Special Char Parsing --------- */
void makeFieldCode(FieldCode *hbox); //6
void makeBookmark(Bookmark *hbox); //6
void makeDateFormat(DateCode *hbox); //7
void makeDateCode(DateCode *hbox); //8
void makeTab(Tab *hbox); //9
void makeTable(TxtBox *hbox);
void makeTextBox(TxtBox *hbox);
void makeFormula(TxtBox *hbox);
void makeHyperText(TxtBox *hbox);
void makePicture(Picture *hbox);
void makePictureDRAW(HWPDrawingObject *drawobj, Picture *hbox);
void makeLine(Line *hbox);
void makeHidden(Hidden *hbox);
void makeFootnote(Footnote *hbox);
void makeAutoNum(AutoNum *hbox);
void makeShowPageNum();
void makeMailMerge(MailMerge *hbox);
void makeTocMark(TocMark *hbox);
void makeIndexMark(IndexMark *hbox);
void makeOutline(Outline *hbox);
/* --------- Styles Parsing ------------ */
void makePageStyle();
void makeColumns(ColumnDef *);
void makeTStyle(CharShape *);
void makePStyle(ParaShape *);
void makeFStyle(FBoxStyle *);
void makeCaptionStyle(FBoxStyle *);
void makeDrawStyle(HWPDrawingObject *,FBoxStyle *);
void makeTableStyle(Table *);
void parseCharShape(CharShape *);
void parseParaShape(ParaShape *);
char* getTStyleName(int, char *);
char* getPStyleName(int, char *);
};
class HwpImportFilter : public WeakImplHelper3< XFilter, XImporter, XServiceInfo >
{
public:
HwpImportFilter( const Reference< XMultiServiceFactory > xFact );
~HwpImportFilter();
public:
static Sequence< OUString > getSupportedServiceNames_Static( void ) throw();
static OUString getImplementationName_Static() throw();
public:
// XFilter
virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& aDescriptor )
throw( RuntimeException );
virtual void SAL_CALL cancel() throw(RuntimeException);
// XImporter
virtual void SAL_CALL setTargetDocument( const Reference< XComponent >& xDoc)
throw( IllegalArgumentException, RuntimeException );
// XServiceInfo
OUString SAL_CALL getImplementationName() throw (RuntimeException);
Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw (::com::sun::star::uno::RuntimeException);
public:
Reference< XFilter > rFilter;
Reference< XImporter > rImporter;
};
Reference< XInterface > HwpImportFilter_CreateInstance(
const Reference< XMultiServiceFactory >& rSMgr ) throw( Exception )
{
HwpImportFilter *p = new HwpImportFilter( rSMgr );
return Reference< XInterface > ( (OWeakObject* )p );
}
Sequence< OUString > HwpImportFilter::getSupportedServiceNames_Static( void ) throw ()
{
Sequence< OUString > aRet(1);
aRet.getArray()[0] = HwpImportFilter::getImplementationName_Static();
return aRet;
}
HwpImportFilter::HwpImportFilter( const Reference< XMultiServiceFactory > xFact )
{
OUString sService = OUString::createFromAscii( WRITER_IMPORTER_NAME );
try {
Reference< XDocumentHandler >
xHandler( xFact->createInstance( sService ), UNO_QUERY );
HwpReader *p = new HwpReader;
p->setDocumentHandler( xHandler );
Sequence< Any > aArgs( 2 );
aArgs[0] <<= OUString::createFromAscii( "Local" );
aArgs[1] <<= OUString::createFromAscii( "Office" );
Reference< XInterface > xUCB
( xFact->createInstanceWithArguments
(OUString::createFromAscii("com.sun.star.ucb.UniversalContentBroker"),
aArgs));
p->setUCB( xUCB );
Reference< XImporter > xImporter = Reference< XImporter >( xHandler, UNO_QUERY );
rImporter = xImporter;
Reference< XFilter > xFilter = Reference< XFilter >( p );
rFilter = xFilter;
}
catch( Exception & )
{
printf(" fail to instanciate %s\n", WRITER_IMPORTER_NAME );
exit( 1 );
}
}
HwpImportFilter::~HwpImportFilter()
{
}
sal_Bool HwpImportFilter::filter( const Sequence< PropertyValue >& aDescriptor )
throw( RuntimeException )
{
// delegate to IchitaroImpoter
rFilter->filter( aDescriptor );
return sal_True;
}
void HwpImportFilter::cancel() throw(::com::sun::star::uno::RuntimeException)
{
rFilter->cancel();
}
void HwpImportFilter::setTargetDocument( const Reference< XComponent >& xDoc )
throw( IllegalArgumentException, RuntimeException )
{
// delegate
rImporter->setTargetDocument( xDoc );
}
OUString HwpImportFilter::getImplementationName_Static() throw()
{
return OUString::createFromAscii( IMPLEMENTATION_NAME );
}
OUString HwpImportFilter::getImplementationName() throw(::com::sun::star::uno::RuntimeException)
{
return OUString::createFromAscii( IMPLEMENTATION_NAME );
}
sal_Bool HwpImportFilter::supportsService( const OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< OUString > aSNL = getSupportedServiceNames();
const OUString *pArray = aSNL.getConstArray();
for ( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
if ( pArray[i] == ServiceName )
return sal_True;
return sal_False;
}
Sequence< OUString> HwpImportFilter::getSupportedServiceNames( void ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< OUString > seq(1);
seq.getArray()[0] = OUString::createFromAscii( SERVICE_NAME );
return seq;
}
/////////////////////////////////////////////////////////////////////////////////////
// The below three C functions are nessesary for this shared library is treaded as
// UNO component library.
/////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo(
void * , void * pRegistryKey )
{
if (pRegistryKey)
{
try
{
Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey * >( pRegistryKey ) );
Reference< XRegistryKey > xNewKey = xKey->createKey(
OUString::createFromAscii( "/" IMPLEMENTATION_NAME "/UNO/SERVICES" ) );
xNewKey->createKey( OUString::createFromAscii( SERVICE_NAME ) );
return sal_True;
}
catch (InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
}
return sal_False;
}
void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * )
{
void * pRet = 0;
if (pServiceManager )
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > xSMgr = reinterpret_cast< XMultiServiceFactory * > ( pServiceManager );
OUString aImplementationName = OUString::createFromAscii( pImplName );
if (aImplementationName == OUString::createFromAscii( IMPLEMENTATION_NAME ) )
{
xRet = createSingleFactory( xSMgr, aImplementationName,
HwpImportFilter_CreateInstance,
HwpImportFilter::getSupportedServiceNames_Static() );
}
if (xRet.is())
{
xRet->acquire();
pRet = xRet.get();
}
}
return pRet;
}
}
#endif
<|endoftext|>
|
<commit_before>// $Id$
// Author: Akira Okumura 2007/09/24
/******************************************************************************
* Copyright (C) 2006-, Akira Okumura *
* All rights reserved. *
*****************************************************************************/
///////////////////////////////////////////////////////////////////////////////
//
// ALens
//
// Lens class
//
///////////////////////////////////////////////////////////////////////////////
#include "ALens.h"
ClassImp(ALens)
ALens::ALens()
{
// Default constructor
fAbsorptionLength = 0;
fIndex = 0;
fConstantIndex = 1;
SetLineColor(7);
}
//_____________________________________________________________________________
ALens::ALens(const char* name, const TGeoShape* shape,
const TGeoMedium* med) : AOpticalComponent(name, shape, med)
{
fIndex = 0;
fConstantIndex = 1;
fConstantAbsorptionLength = -1;
SetLineColor(7);
}
//_____________________________________________________________________________
ALens::~ALens()
{
}
//_____________________________________________________________________________
Double_t ALens::GetAbsorptionLength(Double_t lambda) const
{
if(!fAbsorptionLength){
return fConstantAbsorptionLength;
} // if
Double_t abs = fAbsorptionLength->Eval(lambda);
return abs >= 0 ? abs : 0;
}
//_____________________________________________________________________________
Double_t ALens::GetRefractiveIndex(Double_t lambda) const
{
Double_t ret = fConstantIndex;
if(fIndex){
ret = fIndex->GetIndex(lambda);
} // if
return ret;
}
<commit_msg>Fixed uninitialized pointers<commit_after>// $Id$
// Author: Akira Okumura 2007/09/24
/******************************************************************************
* Copyright (C) 2006-, Akira Okumura *
* All rights reserved. *
*****************************************************************************/
///////////////////////////////////////////////////////////////////////////////
//
// ALens
//
// Lens class
//
///////////////////////////////////////////////////////////////////////////////
#include "ALens.h"
ClassImp(ALens)
ALens::ALens()
{
// Default constructor
fAbsorptionLength = NULL;
fIndex = NULL;
fConstantIndex = 1;
fConstantAbsorptionLength = -1;
SetLineColor(7);
}
//_____________________________________________________________________________
ALens::ALens(const char* name, const TGeoShape* shape,
const TGeoMedium* med) : AOpticalComponent(name, shape, med)
{
fAbsorptionLength = NULL;
fIndex = NULL;
fConstantIndex = 1;
fConstantAbsorptionLength = -1;
SetLineColor(7);
}
//_____________________________________________________________________________
ALens::~ALens()
{
}
//_____________________________________________________________________________
Double_t ALens::GetAbsorptionLength(Double_t lambda) const
{
if(!fAbsorptionLength){
return fConstantAbsorptionLength;
} // if
Double_t abs = fAbsorptionLength->Eval(lambda);
return abs >= 0 ? abs : 0;
}
//_____________________________________________________________________________
Double_t ALens::GetRefractiveIndex(Double_t lambda) const
{
Double_t ret = fConstantIndex;
if(fIndex){
ret = fIndex->GetIndex(lambda);
} // if
return ret;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: GridWrapper.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-05-22 17:18:14 $
*
* 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_chart2.hxx"
#include "GridWrapper.hxx"
#include "macros.hxx"
#include "AxisHelper.hxx"
#include "Scaling.hxx"
#include "Chart2ModelContact.hxx"
#include "ContainerHelper.hxx"
#include "AxisIndexDefines.hxx"
#ifndef INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX
#include <comphelper/InlineContainer.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#include "LineProperties.hxx"
// #include "NamedLineProperties.hxx"
#include "UserDefinedProperties.hxx"
// #include "WrappedNamedProperty.hxx"
#include "WrappedDefaultProperty.hxx"
#include <algorithm>
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::beans::Property;
using ::osl::MutexGuard;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
namespace
{
static const OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart.Grid" ));
const Sequence< Property > & lcl_GetPropertySequence()
{
static Sequence< Property > aPropSeq;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
::chart::LineProperties::AddPropertiesToVector( aProperties );
// ::chart::NamedLineProperties::AddPropertiesToVector( aProperties );
::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
}
return aPropSeq;
}
} // anonymous namespace
// --------------------------------------------------------------------------------
namespace chart
{
namespace wrapper
{
GridWrapper::GridWrapper(
tGridType eType, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact ) :
m_spChart2ModelContact( spChart2ModelContact ),
m_aEventListenerContainer( m_aMutex ),
m_eType( eType )
{
}
GridWrapper::~GridWrapper()
{}
// static
void GridWrapper::getDimensionAndSubGridBool( tGridType eType, sal_Int32& rnDimensionIndex, bool& rbSubGrid )
{
rnDimensionIndex = 1;
rbSubGrid = false;
switch( eType )
{
case X_MAIN_GRID:
rnDimensionIndex = 0; rbSubGrid = false; break;
case Y_MAIN_GRID:
rnDimensionIndex = 1; rbSubGrid = false; break;
case Z_MAIN_GRID:
rnDimensionIndex = 2; rbSubGrid = false; break;
case X_SUB_GRID:
rnDimensionIndex = 0; rbSubGrid = true; break;
case Y_SUB_GRID:
rnDimensionIndex = 1; rbSubGrid = true; break;
case Z_SUB_GRID:
rnDimensionIndex = 2; rbSubGrid = true; break;
}
}
// ____ XComponent ____
void SAL_CALL GridWrapper::dispose()
throw (uno::RuntimeException)
{
Reference< uno::XInterface > xSource( static_cast< ::cppu::OWeakObject* >( this ) );
m_aEventListenerContainer.disposeAndClear( lang::EventObject( xSource ) );
clearWrappedPropertySet();
}
void SAL_CALL GridWrapper::addEventListener(
const Reference< lang::XEventListener >& xListener )
throw (uno::RuntimeException)
{
m_aEventListenerContainer.addInterface( xListener );
}
void SAL_CALL GridWrapper::removeEventListener(
const Reference< lang::XEventListener >& aListener )
throw (uno::RuntimeException)
{
m_aEventListenerContainer.removeInterface( aListener );
}
// ================================================================================
// WrappedPropertySet
Reference< beans::XPropertySet > GridWrapper::getInnerPropertySet()
{
Reference< beans::XPropertySet > xRet;
try
{
Reference< chart2::XDiagram > xDiagram( m_spChart2ModelContact->getChart2Diagram() );
uno::Reference< XCoordinateSystem > xCooSys( AxisHelper::getCoordinateSystemByIndex( xDiagram, 0 /*nCooSysIndex*/ ) );
sal_Int32 nDimensionIndex = 1;
bool bSubGrid = false;
getDimensionAndSubGridBool( m_eType, nDimensionIndex, bSubGrid );
sal_Int32 nSubGridIndex = bSubGrid ? 0 : -1;
xRet.set( AxisHelper::getGridProperties( xCooSys , nDimensionIndex, MAIN_AXIS_INDEX, nSubGridIndex ) );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return xRet;
}
const Sequence< beans::Property >& GridWrapper::getPropertySequence()
{
return lcl_GetPropertySequence();
}
const std::vector< WrappedProperty* > GridWrapper::createWrappedProperties()
{
::std::vector< ::chart::WrappedProperty* > aWrappedProperties;
// WrappedNamedProperty::addWrappedLineProperties( aWrappedProperties, m_spChart2ModelContact );
aWrappedProperties.push_back( new WrappedDefaultProperty( C2U("LineColor"), C2U("LineColor"), uno::makeAny( sal_Int32( 0x000000) ) ) ); // black
return aWrappedProperties;
}
// ================================================================================
Sequence< OUString > GridWrapper::getSupportedServiceNames_Static()
{
Sequence< OUString > aServices( 4 );
aServices[ 0 ] = C2U( "com.sun.star.chart.ChartGrid" );
aServices[ 1 ] = C2U( "com.sun.star.xml.UserDefinedAttributeSupplier" );
aServices[ 2 ] = C2U( "com.sun.star.drawing.LineProperties" );
aServices[ 3 ] = C2U( "com.sun.star.beans.PropertySet" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( GridWrapper, lcl_aServiceName );
} // namespace wrapper
} // namespace chart
<commit_msg>INTEGRATION: CWS changefileheader (1.2.126); FILE MERGED 2008/04/01 15:03:57 thb 1.2.126.3: #i85898# Stripping all external header guards 2008/04/01 10:50:16 thb 1.2.126.2: #i85898# Stripping all external header guards 2008/03/28 16:43:14 rt 1.2.126.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: GridWrapper.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "GridWrapper.hxx"
#include "macros.hxx"
#include "AxisHelper.hxx"
#include "Scaling.hxx"
#include "Chart2ModelContact.hxx"
#include "ContainerHelper.hxx"
#include "AxisIndexDefines.hxx"
#include <comphelper/InlineContainer.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include "LineProperties.hxx"
// #include "NamedLineProperties.hxx"
#include "UserDefinedProperties.hxx"
// #include "WrappedNamedProperty.hxx"
#include "WrappedDefaultProperty.hxx"
#include <algorithm>
#include <rtl/ustrbuf.hxx>
#include <rtl/math.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::beans::Property;
using ::osl::MutexGuard;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
namespace
{
static const OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart.Grid" ));
const Sequence< Property > & lcl_GetPropertySequence()
{
static Sequence< Property > aPropSeq;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
::chart::LineProperties::AddPropertiesToVector( aProperties );
// ::chart::NamedLineProperties::AddPropertiesToVector( aProperties );
::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
}
return aPropSeq;
}
} // anonymous namespace
// --------------------------------------------------------------------------------
namespace chart
{
namespace wrapper
{
GridWrapper::GridWrapper(
tGridType eType, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact ) :
m_spChart2ModelContact( spChart2ModelContact ),
m_aEventListenerContainer( m_aMutex ),
m_eType( eType )
{
}
GridWrapper::~GridWrapper()
{}
// static
void GridWrapper::getDimensionAndSubGridBool( tGridType eType, sal_Int32& rnDimensionIndex, bool& rbSubGrid )
{
rnDimensionIndex = 1;
rbSubGrid = false;
switch( eType )
{
case X_MAIN_GRID:
rnDimensionIndex = 0; rbSubGrid = false; break;
case Y_MAIN_GRID:
rnDimensionIndex = 1; rbSubGrid = false; break;
case Z_MAIN_GRID:
rnDimensionIndex = 2; rbSubGrid = false; break;
case X_SUB_GRID:
rnDimensionIndex = 0; rbSubGrid = true; break;
case Y_SUB_GRID:
rnDimensionIndex = 1; rbSubGrid = true; break;
case Z_SUB_GRID:
rnDimensionIndex = 2; rbSubGrid = true; break;
}
}
// ____ XComponent ____
void SAL_CALL GridWrapper::dispose()
throw (uno::RuntimeException)
{
Reference< uno::XInterface > xSource( static_cast< ::cppu::OWeakObject* >( this ) );
m_aEventListenerContainer.disposeAndClear( lang::EventObject( xSource ) );
clearWrappedPropertySet();
}
void SAL_CALL GridWrapper::addEventListener(
const Reference< lang::XEventListener >& xListener )
throw (uno::RuntimeException)
{
m_aEventListenerContainer.addInterface( xListener );
}
void SAL_CALL GridWrapper::removeEventListener(
const Reference< lang::XEventListener >& aListener )
throw (uno::RuntimeException)
{
m_aEventListenerContainer.removeInterface( aListener );
}
// ================================================================================
// WrappedPropertySet
Reference< beans::XPropertySet > GridWrapper::getInnerPropertySet()
{
Reference< beans::XPropertySet > xRet;
try
{
Reference< chart2::XDiagram > xDiagram( m_spChart2ModelContact->getChart2Diagram() );
uno::Reference< XCoordinateSystem > xCooSys( AxisHelper::getCoordinateSystemByIndex( xDiagram, 0 /*nCooSysIndex*/ ) );
sal_Int32 nDimensionIndex = 1;
bool bSubGrid = false;
getDimensionAndSubGridBool( m_eType, nDimensionIndex, bSubGrid );
sal_Int32 nSubGridIndex = bSubGrid ? 0 : -1;
xRet.set( AxisHelper::getGridProperties( xCooSys , nDimensionIndex, MAIN_AXIS_INDEX, nSubGridIndex ) );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return xRet;
}
const Sequence< beans::Property >& GridWrapper::getPropertySequence()
{
return lcl_GetPropertySequence();
}
const std::vector< WrappedProperty* > GridWrapper::createWrappedProperties()
{
::std::vector< ::chart::WrappedProperty* > aWrappedProperties;
// WrappedNamedProperty::addWrappedLineProperties( aWrappedProperties, m_spChart2ModelContact );
aWrappedProperties.push_back( new WrappedDefaultProperty( C2U("LineColor"), C2U("LineColor"), uno::makeAny( sal_Int32( 0x000000) ) ) ); // black
return aWrappedProperties;
}
// ================================================================================
Sequence< OUString > GridWrapper::getSupportedServiceNames_Static()
{
Sequence< OUString > aServices( 4 );
aServices[ 0 ] = C2U( "com.sun.star.chart.ChartGrid" );
aServices[ 1 ] = C2U( "com.sun.star.xml.UserDefinedAttributeSupplier" );
aServices[ 2 ] = C2U( "com.sun.star.drawing.LineProperties" );
aServices[ 3 ] = C2U( "com.sun.star.beans.PropertySet" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( GridWrapper, lcl_aServiceName );
} // namespace wrapper
} // namespace chart
<|endoftext|>
|
<commit_before>#include "../scheduled_task.hpp"
#include "../thread.hpp"
#include "../../testing/testing.hpp"
#include "../../std/bind.hpp"
namespace
{
void add_int(int & val, int a)
{
val += a;
}
void mul_int(int & val, int b)
{
val *= b;
}
}
UNIT_TEST(ScheduledTask_Smoke)
{
int val = 0;
ScheduledTask t(bind(&add_int, ref(val), 10), 1000);
CHECK(val == 0, ());
threads::Sleep(1100);
CHECK(val == 10, ());
}
UNIT_TEST(ScheduledTask_CancelInfinite)
{
int val = 2;
ScheduledTask t0(bind(&add_int, ref(val), 10), -1);
t0.Cancel();
}
UNIT_TEST(ScheduledTask_Cancel)
{
int val = 2;
ScheduledTask t0(bind(&add_int, ref(val), 10), 500);
ScheduledTask t1(bind(&mul_int, ref(val), 2), 1000);
CHECK(val == 2, ());
t0.Cancel();
threads::Sleep(1100);
CHECK(val == 4, ());
}
UNIT_TEST(ScheduledTask_NoWaitInCancel)
{
int val = 2;
ScheduledTask t0(bind(&add_int, ref(val), 10), 1000);
ScheduledTask t1(bind(&mul_int, ref(val), 3), 500);
t0.Cancel();
val += 3;
threads::Sleep(600);
CHECK(val == 15, (val));
}
<commit_msg>Fix test according to code style.<commit_after>#include "../scheduled_task.hpp"
#include "../thread.hpp"
#include "../../testing/testing.hpp"
#include "../../std/bind.hpp"
namespace
{
void add_int(int & val, int a)
{
val += a;
}
void mul_int(int & val, int b)
{
val *= b;
}
}
UNIT_TEST(ScheduledTask_Smoke)
{
int val = 0;
ScheduledTask t(bind(&add_int, ref(val), 10), 1000);
TEST_EQUAL(val, 0, ());
threads::Sleep(1100);
TEST_EQUAL(val, 10, ());
}
UNIT_TEST(ScheduledTask_CancelInfinite)
{
int val = 2;
ScheduledTask t0(bind(&add_int, ref(val), 10), -1);
t0.Cancel();
}
UNIT_TEST(ScheduledTask_Cancel)
{
int val = 2;
ScheduledTask t0(bind(&add_int, ref(val), 10), 500);
ScheduledTask t1(bind(&mul_int, ref(val), 2), 1000);
TEST_EQUAL(val, 2, ());
t0.Cancel();
threads::Sleep(1100);
TEST_EQUAL(val, 4, ());
}
UNIT_TEST(ScheduledTask_NoWaitInCancel)
{
int val = 2;
ScheduledTask t0(bind(&add_int, ref(val), 10), 1000);
ScheduledTask t1(bind(&mul_int, ref(val), 3), 500);
t0.Cancel();
val += 3;
threads::Sleep(600);
TEST_EQUAL(val, 15, ());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/shown_sections_handler.h"
#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/json_pref_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"
class ShownSectionsHandlerTest : public testing::Test {
};
TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) {
PrefService pref(new JsonPrefStore(FilePath()));
// Set an *old* value
pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
pref.SetInteger(prefs::kNTPShownSections, THUMB);
ShownSectionsHandler::MigrateUserPrefs(&pref, 0, 1);
int shown_sections = pref.GetInteger(prefs::kNTPShownSections);
EXPECT_TRUE(shown_sections & THUMB);
EXPECT_FALSE(shown_sections & LIST);
EXPECT_FALSE(shown_sections & RECENT);
EXPECT_TRUE(shown_sections & TIPS);
EXPECT_TRUE(shown_sections & SYNC);
}
TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs1To2) {
PrefService pref((FilePath()));
// Set an *old* value
pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
pref.SetInteger(prefs::kNTPShownSections, LIST);
ShownSectionsHandler::MigrateUserPrefs(&pref, 1, 2);
int shown_sections = pref.GetInteger(prefs::kNTPShownSections);
EXPECT_TRUE(shown_sections & THUMB);
EXPECT_FALSE(shown_sections & LIST);
}
<commit_msg>Fix compile error in ShownSectionsHandlerTest.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/shown_sections_handler.h"
#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/json_pref_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"
class ShownSectionsHandlerTest : public testing::Test {
};
TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) {
PrefService pref(new JsonPrefStore(FilePath()));
// Set an *old* value
pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
pref.SetInteger(prefs::kNTPShownSections, THUMB);
ShownSectionsHandler::MigrateUserPrefs(&pref, 0, 1);
int shown_sections = pref.GetInteger(prefs::kNTPShownSections);
EXPECT_TRUE(shown_sections & THUMB);
EXPECT_FALSE(shown_sections & LIST);
EXPECT_FALSE(shown_sections & RECENT);
EXPECT_TRUE(shown_sections & TIPS);
EXPECT_TRUE(shown_sections & SYNC);
}
TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs1To2) {
PrefService pref(new JsonPrefStore(FilePath()));
// Set an *old* value
pref.RegisterIntegerPref(prefs::kNTPShownSections, 0);
pref.SetInteger(prefs::kNTPShownSections, LIST);
ShownSectionsHandler::MigrateUserPrefs(&pref, 1, 2);
int shown_sections = pref.GetInteger(prefs::kNTPShownSections);
EXPECT_TRUE(shown_sections & THUMB);
EXPECT_FALSE(shown_sections & LIST);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) {
FilePath websocket_root_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));
// TODO(toyoshim): Remove following logging after a bug investigation.
// http://crbug.com/107836 .
LOG(INFO) << "Assume LayoutTests in " << websocket_root_dir.MaybeAsASCII();
ui_test_utils::TestWebSocketServer server;
ASSERT_TRUE(server.Start(websocket_root_dir));
ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
<commit_msg>Disable ExtensionApiTest.WebSocket on Windows.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
// http://crbug.com/111165
#if defined(OS_WIN)
#define MAYBE_WebSocket FAILS_WebSocket
#else
#define MAYBE_WebSocket WebSocket
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) {
FilePath websocket_root_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));
// TODO(toyoshim): Remove following logging after a bug investigation.
// http://crbug.com/107836 .
LOG(INFO) << "Assume LayoutTests in " << websocket_root_dir.MaybeAsASCII();
ui_test_utils::TestWebSocketServer server;
ASSERT_TRUE(server.Start(websocket_root_dir));
ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
<|endoftext|>
|
<commit_before>
#include <NDBT.hpp>
#include <NdbApi.hpp>
#include <NdbRestarter.hpp>
#include <HugoOperations.hpp>
#include <UtilTransactions.hpp>
#include <signaldata/DumpStateOrd.hpp>
struct CASE
{
bool start_row;
bool end_row;
bool curr_row;
const char * op1;
const char * op2;
int val;
};
static CASE g_ops[] =
{
{ false, true, false, "INSERT", 0, 0 },
{ false, true, false, "INSERT", "UPDATE", 0 },
{ false, false, false, "INSERT", "DELETE", 0 },
{ true, true, false, "UPDATE", 0, 0 },
{ true, true, false, "UPDATE", "UPDATE", 0 },
{ true, false, false, "UPDATE", "DELETE", 0 },
{ true, false, false, "DELETE", 0, 0 },
{ true, true, false, "DELETE", "INSERT", 0 }
};
const size_t OP_COUNT = (sizeof(g_ops)/sizeof(g_ops[0]));
static Ndb* g_ndb = 0;
static CASE* g_cases;
static HugoOperations* g_hugo_ops;
static int g_rows = 1000;
static int g_setup_tables = 1;
static const char * g_tablename = "T1";
static const NdbDictionary::Table* g_table = 0;
static NdbRestarter g_restarter;
static int init_ndb(int argc, char** argv);
static int parse_args(int argc, char** argv);
static int connect_ndb();
static int drop_all_tables();
static int load_table();
static int pause_lcp();
static int do_op(int row);
static int continue_lcp(int error);
static int commit();
static int restart();
static int validate();
#define require(x) { bool b = x; if(!b){g_err << __LINE__ << endl; abort();}}
int
main(int argc, char ** argv){
require(!init_ndb(argc, argv));
require(!parse_args(argc, argv));
require(!connect_ndb());
if(g_setup_tables){
require(!drop_all_tables());
if(NDBT_Tables::createTable(g_ndb, g_tablename) != 0){
exit(-1);
}
}
g_table = g_ndb->getDictionary()->getTable(g_tablename);
if(g_table == 0){
g_err << "Failed to retreive table: " << g_tablename << endl;
exit(-1);
}
require(g_hugo_ops = new HugoOperations(* g_table));
require(!g_hugo_ops->startTransaction(g_ndb));
g_cases= new CASE[g_rows];
require(!load_table());
g_info << "Performing all ops wo/ inteference of LCP" << endl;
g_info << "Testing pre LCP operations, ZLCP_OP_WRITE_RT_BREAK" << endl;
g_info << " where ZLCP_OP_WRITE_RT_BREAK is finished before SAVE_PAGES"
<< endl;
require(!pause_lcp());
size_t j;
for(j = 0; j<g_rows; j++){
require(!do_op(j));
}
require(!continue_lcp(5900));
require(!commit());
require(!restart());
require(!validate());
g_info << "Testing pre LCP operations, ZLCP_OP_WRITE_RT_BREAK" << endl;
g_info << " where ZLCP_OP_WRITE_RT_BREAK is finished after SAVE_PAGES"
<< endl;
require(!load_table());
require(!pause_lcp());
for(j = 0; j<g_rows; j++){
require(!do_op(j));
}
require(!continue_lcp(5901));
require(!commit());
require(!restart());
require(!validate());
g_info << "Testing pre LCP operations, undo-ed at commit" << endl;
require(!load_table());
require(!pause_lcp());
for(j = 0; j<g_rows; j++){
require(!do_op(j));
}
require(!continue_lcp(5902));
require(!commit());
require(!continue_lcp(5903));
require(!restart());
require(!validate());
}
static int init_ndb(int argc, char** argv)
{
return 0;
}
static int parse_args(int argc, char** argv)
{
return 0;
}
static int connect_ndb()
{
g_ndb = new Ndb("TEST_DB");
g_ndb->init();
if(g_ndb->waitUntilReady(30) == 0){
int args[] = { DumpStateOrd::DihMaxTimeBetweenLCP };
return g_restarter.dumpStateAllNodes(args, 1);
}
return -1;
}
static int disconnect_ndb()
{
delete g_ndb;
g_ndb = 0;
g_table = 0;
return 0;
}
static int drop_all_tables()
{
NdbDictionary::Dictionary * dict = g_ndb->getDictionary();
require(dict);
BaseString db = g_ndb->getDatabaseName();
BaseString schema = g_ndb->getSchemaName();
NdbDictionary::Dictionary::List list;
if (dict->listObjects(list, NdbDictionary::Object::TypeUndefined) == -1){
g_err << "Failed to list tables: " << endl
<< dict->getNdbError() << endl;
return -1;
}
for (unsigned i = 0; i < list.count; i++) {
NdbDictionary::Dictionary::List::Element& elt = list.elements[i];
switch (elt.type) {
case NdbDictionary::Object::SystemTable:
case NdbDictionary::Object::UserTable:
g_ndb->setDatabaseName(elt.database);
g_ndb->setSchemaName(elt.schema);
if(dict->dropTable(elt.name) != 0){
g_err << "Failed to drop table: "
<< elt.database << "/" << elt.schema << "/" << elt.name <<endl;
g_err << dict->getNdbError() << endl;
return -1;
}
break;
case NdbDictionary::Object::UniqueHashIndex:
case NdbDictionary::Object::OrderedIndex:
case NdbDictionary::Object::HashIndexTrigger:
case NdbDictionary::Object::IndexTrigger:
case NdbDictionary::Object::SubscriptionTrigger:
case NdbDictionary::Object::ReadOnlyConstraint:
default:
break;
}
}
g_ndb->setDatabaseName(db.c_str());
g_ndb->setSchemaName(schema.c_str());
return 0;
}
static int load_table()
{
UtilTransactions clear(* g_table);
require(!clear.clearTable(g_ndb));
HugoOperations ops(* g_table);
require(!ops.startTransaction(g_ndb));
for(size_t i = 0; i<g_rows; i++){
g_cases[i] = g_ops[ i % OP_COUNT];
if(g_cases[i].start_row){
g_cases[i].curr_row = true;
g_cases[i].val = rand();
require(!ops.pkInsertRecord(g_ndb, i, 1, g_cases[i].val));
}
if((i+1) % 100 == 0){
require(!ops.execute_Commit(g_ndb));
require(!ops.getTransaction()->restart());
}
}
if((g_rows+1) % 100 != 0)
require(!ops.execute_Commit(g_ndb));
return 0;
}
static int pause_lcp()
{
return 0;
}
static int do_op(int row)
{
HugoOperations & ops = * g_hugo_ops;
if(strcmp(g_cases[row].op1, "INSERT") == 0){
require(!g_cases[row].curr_row);
g_cases[row].curr_row = true;
g_cases[row].val = rand();
require(!ops.pkInsertRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op1, "UPDATE") == 0){
require(g_cases[row].curr_row);
g_cases[row].val = rand();
require(!ops.pkUpdateRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op1, "DELETE") == 0){
require(g_cases[row].curr_row);
g_cases[row].curr_row = false;
require(!ops.pkDeleteRecord(g_ndb, row, 1));
}
require(!ops.execute_NoCommit(g_ndb));
if(g_cases[row].op2 == 0){
} else if(strcmp(g_cases[row].op2, "INSERT") == 0){
require(!g_cases[row].curr_row);
g_cases[row].curr_row = true;
g_cases[row].val = rand();
require(!ops.pkInsertRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op2, "UPDATE") == 0){
require(g_cases[row].curr_row);
g_cases[row].val = rand();
require(!ops.pkUpdateRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op2, "DELETE") == 0){
require(g_cases[row].curr_row);
g_cases[row].curr_row = false;
require(!ops.pkDeleteRecord(g_ndb, row, 1));
}
if(g_cases[row].op2 != 0)
require(!ops.execute_NoCommit(g_ndb));
return 0;
}
static int continue_lcp(int error)
{
error = 0;
if(g_restarter.insertErrorInAllNodes(error) == 0){
int args[] = { DumpStateOrd::DihStartLcpImmediately };
return g_restarter.dumpStateAllNodes(args, 1);
}
return -1;
}
static int commit()
{
HugoOperations & ops = * g_hugo_ops;
int res = ops.execute_Commit(g_ndb);
if(res == 0){
return ops.getTransaction()->restart();
}
return res;
}
static int restart()
{
g_info << "Restarting cluster" << endl;
disconnect_ndb();
delete g_hugo_ops;
require(!g_restarter.restartAll());
require(!g_restarter.waitClusterStarted(30));
require(!connect_ndb());
g_table = g_ndb->getDictionary()->getTable(g_tablename);
require(g_table);
require(g_hugo_ops = new HugoOperations(* g_table));
require(!g_hugo_ops->startTransaction(g_ndb));
return 0;
}
static int validate()
{
HugoOperations ops(* g_table);
for(size_t i = 0; i<g_rows; i++){
require(g_cases[i].curr_row == g_cases[i].end_row);
require(!ops.startTransaction(g_ndb));
ops.pkReadRecord(g_ndb, i, 1);
int res = ops.execute_Commit(g_ndb);
if(g_cases[i].curr_row){
require(res == 0 && ops.verifyUpdatesValue(g_cases[i].val) == 0);
} else {
require(res == 626);
}
ops.closeTransaction(g_ndb);
}
return 0;
}
<commit_msg>add ndb_init<commit_after>
#include <NDBT.hpp>
#include <NdbApi.hpp>
#include <NdbRestarter.hpp>
#include <HugoOperations.hpp>
#include <UtilTransactions.hpp>
#include <signaldata/DumpStateOrd.hpp>
struct CASE
{
bool start_row;
bool end_row;
bool curr_row;
const char * op1;
const char * op2;
int val;
};
static CASE g_ops[] =
{
{ false, true, false, "INSERT", 0, 0 },
{ false, true, false, "INSERT", "UPDATE", 0 },
{ false, false, false, "INSERT", "DELETE", 0 },
{ true, true, false, "UPDATE", 0, 0 },
{ true, true, false, "UPDATE", "UPDATE", 0 },
{ true, false, false, "UPDATE", "DELETE", 0 },
{ true, false, false, "DELETE", 0, 0 },
{ true, true, false, "DELETE", "INSERT", 0 }
};
const size_t OP_COUNT = (sizeof(g_ops)/sizeof(g_ops[0]));
static Ndb* g_ndb = 0;
static CASE* g_cases;
static HugoOperations* g_hugo_ops;
static int g_rows = 1000;
static int g_setup_tables = 1;
static const char * g_tablename = "T1";
static const NdbDictionary::Table* g_table = 0;
static NdbRestarter g_restarter;
static int init_ndb(int argc, char** argv);
static int parse_args(int argc, char** argv);
static int connect_ndb();
static int drop_all_tables();
static int load_table();
static int pause_lcp();
static int do_op(int row);
static int continue_lcp(int error);
static int commit();
static int restart();
static int validate();
#define require(x) { bool b = x; if(!b){g_err << __LINE__ << endl; abort();}}
int
main(int argc, char ** argv){
require(!init_ndb(argc, argv));
require(!parse_args(argc, argv));
require(!connect_ndb());
if(g_setup_tables){
require(!drop_all_tables());
if(NDBT_Tables::createTable(g_ndb, g_tablename) != 0){
exit(-1);
}
}
g_table = g_ndb->getDictionary()->getTable(g_tablename);
if(g_table == 0){
g_err << "Failed to retreive table: " << g_tablename << endl;
exit(-1);
}
require(g_hugo_ops = new HugoOperations(* g_table));
require(!g_hugo_ops->startTransaction(g_ndb));
g_cases= new CASE[g_rows];
require(!load_table());
g_info << "Performing all ops wo/ inteference of LCP" << endl;
g_info << "Testing pre LCP operations, ZLCP_OP_WRITE_RT_BREAK" << endl;
g_info << " where ZLCP_OP_WRITE_RT_BREAK is finished before SAVE_PAGES"
<< endl;
require(!pause_lcp());
size_t j;
for(j = 0; j<g_rows; j++){
require(!do_op(j));
}
require(!continue_lcp(5900));
require(!commit());
require(!restart());
require(!validate());
g_info << "Testing pre LCP operations, ZLCP_OP_WRITE_RT_BREAK" << endl;
g_info << " where ZLCP_OP_WRITE_RT_BREAK is finished after SAVE_PAGES"
<< endl;
require(!load_table());
require(!pause_lcp());
for(j = 0; j<g_rows; j++){
require(!do_op(j));
}
require(!continue_lcp(5901));
require(!commit());
require(!restart());
require(!validate());
g_info << "Testing pre LCP operations, undo-ed at commit" << endl;
require(!load_table());
require(!pause_lcp());
for(j = 0; j<g_rows; j++){
require(!do_op(j));
}
require(!continue_lcp(5902));
require(!commit());
require(!continue_lcp(5903));
require(!restart());
require(!validate());
}
static int init_ndb(int argc, char** argv)
{
ndb_init();
return 0;
}
static int parse_args(int argc, char** argv)
{
return 0;
}
static int connect_ndb()
{
g_ndb = new Ndb("TEST_DB");
g_ndb->init();
if(g_ndb->waitUntilReady(30) == 0){
int args[] = { DumpStateOrd::DihMaxTimeBetweenLCP };
return g_restarter.dumpStateAllNodes(args, 1);
}
return -1;
}
static int disconnect_ndb()
{
delete g_ndb;
g_ndb = 0;
g_table = 0;
return 0;
}
static int drop_all_tables()
{
NdbDictionary::Dictionary * dict = g_ndb->getDictionary();
require(dict);
BaseString db = g_ndb->getDatabaseName();
BaseString schema = g_ndb->getSchemaName();
NdbDictionary::Dictionary::List list;
if (dict->listObjects(list, NdbDictionary::Object::TypeUndefined) == -1){
g_err << "Failed to list tables: " << endl
<< dict->getNdbError() << endl;
return -1;
}
for (unsigned i = 0; i < list.count; i++) {
NdbDictionary::Dictionary::List::Element& elt = list.elements[i];
switch (elt.type) {
case NdbDictionary::Object::SystemTable:
case NdbDictionary::Object::UserTable:
g_ndb->setDatabaseName(elt.database);
g_ndb->setSchemaName(elt.schema);
if(dict->dropTable(elt.name) != 0){
g_err << "Failed to drop table: "
<< elt.database << "/" << elt.schema << "/" << elt.name <<endl;
g_err << dict->getNdbError() << endl;
return -1;
}
break;
case NdbDictionary::Object::UniqueHashIndex:
case NdbDictionary::Object::OrderedIndex:
case NdbDictionary::Object::HashIndexTrigger:
case NdbDictionary::Object::IndexTrigger:
case NdbDictionary::Object::SubscriptionTrigger:
case NdbDictionary::Object::ReadOnlyConstraint:
default:
break;
}
}
g_ndb->setDatabaseName(db.c_str());
g_ndb->setSchemaName(schema.c_str());
return 0;
}
static int load_table()
{
UtilTransactions clear(* g_table);
require(!clear.clearTable(g_ndb));
HugoOperations ops(* g_table);
require(!ops.startTransaction(g_ndb));
for(size_t i = 0; i<g_rows; i++){
g_cases[i] = g_ops[ i % OP_COUNT];
if(g_cases[i].start_row){
g_cases[i].curr_row = true;
g_cases[i].val = rand();
require(!ops.pkInsertRecord(g_ndb, i, 1, g_cases[i].val));
}
if((i+1) % 100 == 0){
require(!ops.execute_Commit(g_ndb));
require(!ops.getTransaction()->restart());
}
}
if((g_rows+1) % 100 != 0)
require(!ops.execute_Commit(g_ndb));
return 0;
}
static int pause_lcp()
{
return 0;
}
static int do_op(int row)
{
HugoOperations & ops = * g_hugo_ops;
if(strcmp(g_cases[row].op1, "INSERT") == 0){
require(!g_cases[row].curr_row);
g_cases[row].curr_row = true;
g_cases[row].val = rand();
require(!ops.pkInsertRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op1, "UPDATE") == 0){
require(g_cases[row].curr_row);
g_cases[row].val = rand();
require(!ops.pkUpdateRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op1, "DELETE") == 0){
require(g_cases[row].curr_row);
g_cases[row].curr_row = false;
require(!ops.pkDeleteRecord(g_ndb, row, 1));
}
require(!ops.execute_NoCommit(g_ndb));
if(g_cases[row].op2 == 0){
} else if(strcmp(g_cases[row].op2, "INSERT") == 0){
require(!g_cases[row].curr_row);
g_cases[row].curr_row = true;
g_cases[row].val = rand();
require(!ops.pkInsertRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op2, "UPDATE") == 0){
require(g_cases[row].curr_row);
g_cases[row].val = rand();
require(!ops.pkUpdateRecord(g_ndb, row, 1, g_cases[row].val));
} else if(strcmp(g_cases[row].op2, "DELETE") == 0){
require(g_cases[row].curr_row);
g_cases[row].curr_row = false;
require(!ops.pkDeleteRecord(g_ndb, row, 1));
}
if(g_cases[row].op2 != 0)
require(!ops.execute_NoCommit(g_ndb));
return 0;
}
static int continue_lcp(int error)
{
error = 0;
if(g_restarter.insertErrorInAllNodes(error) == 0){
int args[] = { DumpStateOrd::DihStartLcpImmediately };
return g_restarter.dumpStateAllNodes(args, 1);
}
return -1;
}
static int commit()
{
HugoOperations & ops = * g_hugo_ops;
int res = ops.execute_Commit(g_ndb);
if(res == 0){
return ops.getTransaction()->restart();
}
return res;
}
static int restart()
{
g_info << "Restarting cluster" << endl;
disconnect_ndb();
delete g_hugo_ops;
require(!g_restarter.restartAll());
require(!g_restarter.waitClusterStarted(30));
require(!connect_ndb());
g_table = g_ndb->getDictionary()->getTable(g_tablename);
require(g_table);
require(g_hugo_ops = new HugoOperations(* g_table));
require(!g_hugo_ops->startTransaction(g_ndb));
return 0;
}
static int validate()
{
HugoOperations ops(* g_table);
for(size_t i = 0; i<g_rows; i++){
require(g_cases[i].curr_row == g_cases[i].end_row);
require(!ops.startTransaction(g_ndb));
ops.pkReadRecord(g_ndb, i, 1);
int res = ops.execute_Commit(g_ndb);
if(g_cases[i].curr_row){
require(res == 0 && ops.verifyUpdatesValue(g_cases[i].val) == 0);
} else {
require(res == 626);
}
ops.closeTransaction(g_ndb);
}
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/ged:$Id: TStyleDialog.cxx,v 1.0 2005/09/08
// Author: Denis Favre-Miville 08/09/05
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStyleDialog //
// //
// This small class is useful to ask the user for a name and a title, //
// in order to rename a style, create a new style or import a //
// style from a canvas. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStyleDialog.h"
#include "TStyleManager.h"
#include <TCanvas.h>
#include <TGButton.h>
#include <TGFrame.h>
#include <TGLabel.h>
#include <TGLayout.h>
#include <TGTextEntry.h>
#include <TROOT.h>
#include <TStyle.h>
#include <TVirtualPad.h>
#include <TVirtualMutex.h>
#include <stdlib.h>
ClassImp(TStyleDialog)
enum EStyleDialogWid {
kName,
kTitle,
kButOK,
kButCancel
};
//______________________________________________________________________________
TStyleDialog::TStyleDialog(TStyleManager *sm, TStyle *cur, Int_t mode,
TVirtualPad *currentPad)
: TGTransientFrame(0, sm)
{
// Constructor. Create the dialog window and draw it centered over the
// main window 'mf'. A pointer to the style to copy or rename is given
// by 'cur' and the parameter 'mode' specify the mode:
// 1 = copy | 2 = rename | 3 = import from canvas.
fStyleManager = sm;
// Create the main frame.
SetCleanup(kNoCleanup);
fCurStyle = cur;
fMode = mode;
fCurPad = currentPad;
switch (fMode) {
case 1: SetWindowName("Create a New Style"); break;
case 2: SetWindowName("Rename the Selected Style"); break;
case 3: SetWindowName("Import a New Style from Canvas");
}
// Create the trash lists to have an effective deletion of every object.
fTrashListLayout = new TList();
fTrashListFrame = new TList();
// Create the layouts and add them to the layout trash list.
TGLayoutHints *layoutNameLabel = new TGLayoutHints(kLHintsNormal, 0, 70, 3);
fTrashListLayout->Add(layoutNameLabel);
TGLayoutHints *layoutTitleLabel = new TGLayoutHints(kLHintsNormal, 0, 39, 3);
fTrashListLayout->Add(layoutTitleLabel);
TGLayoutHints *layoutWarningLabel = new TGLayoutHints(kLHintsExpandX);
fTrashListLayout->Add(layoutWarningLabel);
TGLayoutHints *layoutOKButton = new TGLayoutHints(kLHintsExpandX, 0, 5);
fTrashListLayout->Add(layoutOKButton);
TGLayoutHints *layoutCancelButton = new TGLayoutHints(kLHintsExpandX, 5);
fTrashListLayout->Add(layoutCancelButton);
TGLayoutHints *layoutH1 = new TGLayoutHints(kLHintsExpandX, 10, 10, 10, 5);
fTrashListLayout->Add(layoutH1);
TGLayoutHints *layoutH2 = new TGLayoutHints(kLHintsExpandX, 10, 10, 5, 5);
fTrashListLayout->Add(layoutH2);
TGLayoutHints *layoutH4 = new TGLayoutHints(kLHintsExpandX, 10, 10, 5, 10);
fTrashListLayout->Add(layoutH4);
// Create and place the widgets in the main window.
// Every frame created here must be added to the frame trash list.
TGHorizontalFrame *h1 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h1);
fNameLabel = new TGLabel(h1, "Name:");
h1->AddFrame(fNameLabel, layoutNameLabel);
if (fMode == 1) {
TString newName;
newName.Form("%s_1", fCurStyle->GetName());
fName = new TGTextEntry(h1, newName.Data(), kName);
} else if (fMode == 2) {
// The names of the 5 basics styles can not be modified.
fName = new TGTextEntry(h1, fCurStyle->GetName(), kName);
if ((!strcmp(fName->GetText(), "Default"))
|| (!strcmp(fName->GetText(), "Plain" ))
|| (!strcmp(fName->GetText(), "Bold" ))
|| (!strcmp(fName->GetText(), "Video" ))
|| (!strcmp(fName->GetText(), "Pub" ))) fName->SetEnabled(kFALSE);
} else
fName = new TGTextEntry(h1, "Imported_Style", kName);
fName->Associate(this);
fName->Resize(200, 22);
h1->AddFrame(fName);
AddFrame(h1, layoutH1);
TGHorizontalFrame *h2 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h2);
fTitleLabel = new TGLabel(h2, "Description:");
h2->AddFrame(fTitleLabel, layoutTitleLabel);
switch (fMode) {
case 1:
case 2:
fTitle = new TGTextEntry(h2, fCurStyle->GetTitle(), kTitle);
break;
case 3: {
TString newTitle("Imported from canvas ");
newTitle += fCurPad->GetCanvas()->GetName();
fTitle = new TGTextEntry(h2, newTitle.Data(), kTitle);
}
}
fTitle->Associate(this);
fTitle->Resize(200, 22);
h2->AddFrame(fTitle);
fTitle->Associate(h2);
AddFrame(h2, layoutH2);
TGHorizontalFrame *h3 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h3);
fWarnLabel = new TGLabel(h3);
Pixel_t red;
gClient->GetColorByName("#FF0000", red);
fWarnLabel->SetTextColor(red, kFALSE);
fWarnLabel->Resize(200, 22);
h3->AddFrame(fWarnLabel, layoutWarningLabel);
AddFrame(h3, layoutH2);
TGHorizontalFrame *h4 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h4);
fOK = new TGTextButton(h4, "&OK", kButOK);
fOK->Associate(this);
h4->AddFrame(fOK, layoutOKButton);
fOK->Associate(h4);
fCancel = new TGTextButton(h4, "&Cancel", kButCancel);
fCancel->Associate(this);
h4->AddFrame(fCancel, layoutCancelButton);
fCancel->Associate(h4);
AddFrame(h4, layoutH4);
// Refresh the warning message.
DoUpdate();
Resize();
CenterOnParent();
MapSubwindows();
Int_t w = GetDefaultWidth();
Int_t h = GetDefaultHeight();
SetWMSizeHints(w, h, w, h, 0, 0);
MapWindow();
switch (fMode) {
case 1:
fOK->SetToolTipText("Create this new style");
fCancel->SetToolTipText("Cancel the creation ");
break;
case 2:
fOK->SetToolTipText("Rename the selected style");
fCancel->SetToolTipText("Cancel the rename ");
break;
case 3:
fOK->SetToolTipText("Import this new style from the canvas");
fCancel->SetToolTipText("Cancel the import");
break;
}
Connect("CloseWindow()", "TStyleDialog", this, "DoCloseWindow()");
fName->Connect("TextChanged(const char *)", "TStyleDialog", this, "DoUpdate()");
fOK->Connect("Clicked()", "TStyleDialog", this, "DoOK()");
fCancel->Connect("Clicked()", "TStyleDialog", this, "DoCancel()");
gClient->WaitFor(this);
}
//______________________________________________________________________________
TStyleDialog::~TStyleDialog()
{
// Destructor.
Disconnect("DoCloseWindow()");
fName->Disconnect("TextChanged(const char *)");
fOK->Disconnect("Clicked()");
fCancel->Disconnect("Clicked()");
delete fName;
delete fNameLabel;
delete fTitle;
delete fTitleLabel;
delete fWarnLabel;
delete fOK;
delete fCancel;
TObject *obj1;
TObject *obj2;
obj1 = fTrashListFrame->First();
while (obj1) {
obj2 = fTrashListFrame->After(obj1);
fTrashListFrame->Remove(obj1);
delete obj1;
obj1 = obj2;
}
delete fTrashListFrame;
obj1 = fTrashListLayout->First();
while (obj1) {
obj2 = fTrashListLayout->After(obj1);
fTrashListLayout->Remove(obj1);
delete obj1;
obj1 = obj2;
}
delete fTrashListLayout;
}
//______________________________________________________________________________
void TStyleDialog::DoCancel()
{
// Slot called when the Cancel button is clicked. Close the window
// without saving submitted changes.
fStyleManager->SetLastChoice(kFALSE);
SendCloseMessage();
}
//______________________________________________________________________________
void TStyleDialog::DoCloseWindow()
{
// Slot called when the window is closed via the window manager.
// Close the window without saving submitted changes.
delete this;
}
//______________________________________________________________________________
void TStyleDialog::DoOK()
{
// Slot called when the OK button is clicked. Rename or create the style
// before closing the window.
if (fMode == 2) {
// Update the name and the title of the style.
fCurStyle->SetName(fName->GetText());
fCurStyle->SetTitle(fTitle->GetText());
} else {
// Create a new style (copy of fCurStyle), with the given name and title.
TStyle *tmpStyle = new TStyle(*fCurStyle);
tmpStyle->SetName(fName->GetText());
tmpStyle->SetTitle(fTitle->GetText());
{
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfStyles()->Add(tmpStyle);
}
if (fMode == 3) {
// Import the properties of the canvas.
TStyle *tmp = gStyle;
gStyle = tmpStyle;
gStyle->SetIsReading(kFALSE);
fCurPad->GetCanvas()->UseCurrentStyle();
gStyle->SetIsReading(kTRUE);
gStyle = tmp;
}
}
fStyleManager->SetLastChoice(kTRUE);
SendCloseMessage();
}
//______________________________________________________________________________
void TStyleDialog::DoUpdate()
{
// Slot called every time the name is changed. Provide some protection
// to avoid letting the user use an empty name or an already used one.
// A warning message can be shown and the OK button disabled.
if (!strlen(fName->GetText())) {
fWarnLabel->SetText("That name is empty");
fOK->SetEnabled(kFALSE);
return;
}
if (strstr(fName->GetText(), " ") != 0) {
fWarnLabel->SetText("That name contains some spaces");
fOK->SetEnabled(kFALSE);
return;
}
switch (fMode) {
case 1:
case 3:
if (gROOT->GetStyle(fName->GetText())) {
fWarnLabel->SetText("That name is already used by another style.");
fOK->SetEnabled(kFALSE);
return;
}
break;
case 2:
TStyle *tmp = gROOT->GetStyle(fName->GetText());
if (tmp && (tmp != fCurStyle)) {
fWarnLabel->SetText("That name is already used by another style.");
fOK->SetEnabled(kFALSE);
return;
}
}
fWarnLabel->SetText("");
fOK->SetEnabled(kTRUE);
}
<commit_msg>Fix coverity reports #33682 & #33683 (dereference null return)<commit_after>// @(#)root/ged:$Id: TStyleDialog.cxx,v 1.0 2005/09/08
// Author: Denis Favre-Miville 08/09/05
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStyleDialog //
// //
// This small class is useful to ask the user for a name and a title, //
// in order to rename a style, create a new style or import a //
// style from a canvas. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStyleDialog.h"
#include "TStyleManager.h"
#include <TCanvas.h>
#include <TGButton.h>
#include <TGFrame.h>
#include <TGLabel.h>
#include <TGLayout.h>
#include <TGTextEntry.h>
#include <TROOT.h>
#include <TStyle.h>
#include <TVirtualPad.h>
#include <TVirtualMutex.h>
#include <stdlib.h>
ClassImp(TStyleDialog)
enum EStyleDialogWid {
kName,
kTitle,
kButOK,
kButCancel
};
//______________________________________________________________________________
TStyleDialog::TStyleDialog(TStyleManager *sm, TStyle *cur, Int_t mode,
TVirtualPad *currentPad)
: TGTransientFrame(0, sm)
{
// Constructor. Create the dialog window and draw it centered over the
// main window 'mf'. A pointer to the style to copy or rename is given
// by 'cur' and the parameter 'mode' specify the mode:
// 1 = copy | 2 = rename | 3 = import from canvas.
fStyleManager = sm;
// Create the main frame.
SetCleanup(kNoCleanup);
fCurStyle = cur;
fMode = mode;
fCurPad = currentPad;
switch (fMode) {
case 1: SetWindowName("Create a New Style"); break;
case 2: SetWindowName("Rename the Selected Style"); break;
case 3: SetWindowName("Import a New Style from Canvas");
}
// Create the trash lists to have an effective deletion of every object.
fTrashListLayout = new TList();
fTrashListFrame = new TList();
// Create the layouts and add them to the layout trash list.
TGLayoutHints *layoutNameLabel = new TGLayoutHints(kLHintsNormal, 0, 70, 3);
fTrashListLayout->Add(layoutNameLabel);
TGLayoutHints *layoutTitleLabel = new TGLayoutHints(kLHintsNormal, 0, 39, 3);
fTrashListLayout->Add(layoutTitleLabel);
TGLayoutHints *layoutWarningLabel = new TGLayoutHints(kLHintsExpandX);
fTrashListLayout->Add(layoutWarningLabel);
TGLayoutHints *layoutOKButton = new TGLayoutHints(kLHintsExpandX, 0, 5);
fTrashListLayout->Add(layoutOKButton);
TGLayoutHints *layoutCancelButton = new TGLayoutHints(kLHintsExpandX, 5);
fTrashListLayout->Add(layoutCancelButton);
TGLayoutHints *layoutH1 = new TGLayoutHints(kLHintsExpandX, 10, 10, 10, 5);
fTrashListLayout->Add(layoutH1);
TGLayoutHints *layoutH2 = new TGLayoutHints(kLHintsExpandX, 10, 10, 5, 5);
fTrashListLayout->Add(layoutH2);
TGLayoutHints *layoutH4 = new TGLayoutHints(kLHintsExpandX, 10, 10, 5, 10);
fTrashListLayout->Add(layoutH4);
// Create and place the widgets in the main window.
// Every frame created here must be added to the frame trash list.
TGHorizontalFrame *h1 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h1);
fNameLabel = new TGLabel(h1, "Name:");
h1->AddFrame(fNameLabel, layoutNameLabel);
if (fMode == 1) {
TString newName;
newName.Form("%s_1", fCurStyle->GetName());
fName = new TGTextEntry(h1, newName.Data(), kName);
} else if (fMode == 2) {
// The names of the 5 basics styles can not be modified.
fName = new TGTextEntry(h1, fCurStyle->GetName(), kName);
if ((!strcmp(fName->GetText(), "Default"))
|| (!strcmp(fName->GetText(), "Plain" ))
|| (!strcmp(fName->GetText(), "Bold" ))
|| (!strcmp(fName->GetText(), "Video" ))
|| (!strcmp(fName->GetText(), "Pub" ))) fName->SetEnabled(kFALSE);
} else
fName = new TGTextEntry(h1, "Imported_Style", kName);
fName->Associate(this);
fName->Resize(200, 22);
h1->AddFrame(fName);
AddFrame(h1, layoutH1);
TGHorizontalFrame *h2 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h2);
fTitleLabel = new TGLabel(h2, "Description:");
h2->AddFrame(fTitleLabel, layoutTitleLabel);
switch (fMode) {
case 1:
case 2:
fTitle = new TGTextEntry(h2, fCurStyle->GetTitle(), kTitle);
break;
case 3: {
TString newTitle("Imported from canvas ");
if (fCurPad->GetCanvas())
newTitle += fCurPad->GetCanvas()->GetName();
fTitle = new TGTextEntry(h2, newTitle.Data(), kTitle);
}
}
fTitle->Associate(this);
fTitle->Resize(200, 22);
h2->AddFrame(fTitle);
fTitle->Associate(h2);
AddFrame(h2, layoutH2);
TGHorizontalFrame *h3 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h3);
fWarnLabel = new TGLabel(h3);
Pixel_t red;
gClient->GetColorByName("#FF0000", red);
fWarnLabel->SetTextColor(red, kFALSE);
fWarnLabel->Resize(200, 22);
h3->AddFrame(fWarnLabel, layoutWarningLabel);
AddFrame(h3, layoutH2);
TGHorizontalFrame *h4 = new TGHorizontalFrame(this);
fTrashListFrame->Add(h4);
fOK = new TGTextButton(h4, "&OK", kButOK);
fOK->Associate(this);
h4->AddFrame(fOK, layoutOKButton);
fOK->Associate(h4);
fCancel = new TGTextButton(h4, "&Cancel", kButCancel);
fCancel->Associate(this);
h4->AddFrame(fCancel, layoutCancelButton);
fCancel->Associate(h4);
AddFrame(h4, layoutH4);
// Refresh the warning message.
DoUpdate();
Resize();
CenterOnParent();
MapSubwindows();
Int_t w = GetDefaultWidth();
Int_t h = GetDefaultHeight();
SetWMSizeHints(w, h, w, h, 0, 0);
MapWindow();
switch (fMode) {
case 1:
fOK->SetToolTipText("Create this new style");
fCancel->SetToolTipText("Cancel the creation ");
break;
case 2:
fOK->SetToolTipText("Rename the selected style");
fCancel->SetToolTipText("Cancel the rename ");
break;
case 3:
fOK->SetToolTipText("Import this new style from the canvas");
fCancel->SetToolTipText("Cancel the import");
break;
}
Connect("CloseWindow()", "TStyleDialog", this, "DoCloseWindow()");
fName->Connect("TextChanged(const char *)", "TStyleDialog", this, "DoUpdate()");
fOK->Connect("Clicked()", "TStyleDialog", this, "DoOK()");
fCancel->Connect("Clicked()", "TStyleDialog", this, "DoCancel()");
gClient->WaitFor(this);
}
//______________________________________________________________________________
TStyleDialog::~TStyleDialog()
{
// Destructor.
Disconnect("DoCloseWindow()");
fName->Disconnect("TextChanged(const char *)");
fOK->Disconnect("Clicked()");
fCancel->Disconnect("Clicked()");
delete fName;
delete fNameLabel;
delete fTitle;
delete fTitleLabel;
delete fWarnLabel;
delete fOK;
delete fCancel;
TObject *obj1;
TObject *obj2;
obj1 = fTrashListFrame->First();
while (obj1) {
obj2 = fTrashListFrame->After(obj1);
fTrashListFrame->Remove(obj1);
delete obj1;
obj1 = obj2;
}
delete fTrashListFrame;
obj1 = fTrashListLayout->First();
while (obj1) {
obj2 = fTrashListLayout->After(obj1);
fTrashListLayout->Remove(obj1);
delete obj1;
obj1 = obj2;
}
delete fTrashListLayout;
}
//______________________________________________________________________________
void TStyleDialog::DoCancel()
{
// Slot called when the Cancel button is clicked. Close the window
// without saving submitted changes.
fStyleManager->SetLastChoice(kFALSE);
SendCloseMessage();
}
//______________________________________________________________________________
void TStyleDialog::DoCloseWindow()
{
// Slot called when the window is closed via the window manager.
// Close the window without saving submitted changes.
delete this;
}
//______________________________________________________________________________
void TStyleDialog::DoOK()
{
// Slot called when the OK button is clicked. Rename or create the style
// before closing the window.
if (fMode == 2) {
// Update the name and the title of the style.
fCurStyle->SetName(fName->GetText());
fCurStyle->SetTitle(fTitle->GetText());
} else {
// Create a new style (copy of fCurStyle), with the given name and title.
TStyle *tmpStyle = new TStyle(*fCurStyle);
tmpStyle->SetName(fName->GetText());
tmpStyle->SetTitle(fTitle->GetText());
{
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfStyles()->Add(tmpStyle);
}
if (fMode == 3) {
// Import the properties of the canvas.
TStyle *tmp = gStyle;
gStyle = tmpStyle;
gStyle->SetIsReading(kFALSE);
if (fCurPad->GetCanvas())
fCurPad->GetCanvas()->UseCurrentStyle();
gStyle->SetIsReading(kTRUE);
gStyle = tmp;
}
}
fStyleManager->SetLastChoice(kTRUE);
SendCloseMessage();
}
//______________________________________________________________________________
void TStyleDialog::DoUpdate()
{
// Slot called every time the name is changed. Provide some protection
// to avoid letting the user use an empty name or an already used one.
// A warning message can be shown and the OK button disabled.
if (!strlen(fName->GetText())) {
fWarnLabel->SetText("That name is empty");
fOK->SetEnabled(kFALSE);
return;
}
if (strstr(fName->GetText(), " ") != 0) {
fWarnLabel->SetText("That name contains some spaces");
fOK->SetEnabled(kFALSE);
return;
}
switch (fMode) {
case 1:
case 3:
if (gROOT->GetStyle(fName->GetText())) {
fWarnLabel->SetText("That name is already used by another style.");
fOK->SetEnabled(kFALSE);
return;
}
break;
case 2:
TStyle *tmp = gROOT->GetStyle(fName->GetText());
if (tmp && (tmp != fCurStyle)) {
fWarnLabel->SetText("That name is already used by another style.");
fOK->SetEnabled(kFALSE);
return;
}
}
fWarnLabel->SetText("");
fOK->SetEnabled(kTRUE);
}
<|endoftext|>
|
<commit_before>/* The simple ByteArray class, used to implement String. */
#include <stdint.h>
#include "vm.hpp"
#include "objectmemory.hpp"
#include "primitives.hpp"
#include "builtin/bytearray.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/string.hpp"
#include "builtin/tuple.hpp"
#include "object_utils.hpp"
#include "ontology.hpp"
namespace rubinius {
void ByteArray::init(STATE) {
GO(bytearray).set(ontology::new_class_under(state,
"ByteArray", G(rubinius)));
G(bytearray)->set_object_type(state, ByteArrayType);
}
ByteArray* ByteArray::create(STATE, native_int bytes) {
assert(bytes >= 0 && bytes < INT32_MAX);
size_t body = bytes;
ByteArray* ba = state->vm()->new_object_bytes<ByteArray>(G(bytearray), body);
if(unlikely(!ba)) {
Exception::memory_error(state);
}
ba->full_size_ = body;
memset(ba->bytes, 0, bytes);
return ba;
}
ByteArray* ByteArray::create_pinned(STATE, native_int bytes) {
assert(bytes >= 0 && bytes < INT32_MAX);
size_t body = bytes;
ByteArray* ba = state->memory()->new_object_bytes_mature<ByteArray>(state, G(bytearray), body);
if(unlikely(!ba)) {
Exception::memory_error(state);
}
if(!ba->pin()) {
rubinius::bug("unable to allocate pinned ByteArray");
}
ba->full_size_ = body;
memset(ba->bytes, 0, bytes);
return ba;
}
ByteArray* ByteArray::allocate(STATE, Fixnum* bytes) {
native_int size = bytes->to_native();
if(size < 0) {
Exception::argument_error(state, "negative byte array size");
} else if (size > INT32_MAX) {
Exception::argument_error(state, "too large byte array size");
}
return ByteArray::create(state, size);
}
Fixnum* ByteArray::size(STATE) {
return Fixnum::from(size());
}
char* ByteArray::to_chars(STATE, Fixnum* size) {
native_int sz = size->to_native();
native_int ba_sz = this->size(state)->to_native();
if(sz < 0) {
Exception::object_bounds_exceeded_error(state, "size less than zero");
} else if(sz > ba_sz) {
Exception::object_bounds_exceeded_error(state, "size beyond actual size");
}
char* str = (char*)(this->bytes);
char* out = ALLOC_N(char, sz + 1);
memcpy(out, str, sz);
out[sz] = 0;
return out;
}
Fixnum* ByteArray::get_byte(STATE, Fixnum* index) {
native_int idx = index->to_native();
if(idx < 0 || idx >= size()) {
Exception::object_bounds_exceeded_error(state, "index out of bounds");
}
return Fixnum::from(this->bytes[idx]);
}
Fixnum* ByteArray::set_byte(STATE, Fixnum* index, Fixnum* value) {
native_int idx = index->to_native();
if(idx < 0 || idx >= size()) {
Exception::object_bounds_exceeded_error(state, "index out of bounds");
}
this->bytes[idx] = value->to_native();
return Fixnum::from(this->bytes[idx]);
}
Fixnum* ByteArray::move_bytes(STATE, Fixnum* start, Fixnum* count, Fixnum* dest) {
native_int src = start->to_native();
native_int cnt = count->to_native();
native_int dst = dest->to_native();
if(src < 0) {
Exception::object_bounds_exceeded_error(state, "start less than zero");
} else if(dst < 0) {
Exception::object_bounds_exceeded_error(state, "dest less than zero");
} else if(cnt < 0) {
Exception::object_bounds_exceeded_error(state, "count less than zero");
} else if((dst + cnt) > size()) {
Exception::object_bounds_exceeded_error(state, "move is beyond end of bytearray");
} else if((src + cnt) > size()) {
Exception::object_bounds_exceeded_error(state, "move is more than available bytes");
}
memmove(this->bytes + dst, this->bytes + src, cnt);
return count;
}
ByteArray* ByteArray::fetch_bytes(STATE, Fixnum* start, Fixnum* count) {
native_int src = start->to_native();
native_int cnt = count->to_native();
if(src < 0) {
Exception::object_bounds_exceeded_error(state, "start less than zero");
} else if(cnt < 0) {
Exception::object_bounds_exceeded_error(state, "count less than zero");
} else if((src + cnt) > size()) {
Exception::object_bounds_exceeded_error(state, "fetch is more than available bytes");
}
ByteArray* ba = ByteArray::create(state, cnt + 1);
memcpy(ba->bytes, this->bytes + src, cnt);
ba->bytes[cnt] = 0;
return ba;
}
ByteArray* ByteArray::prepend(STATE, String* str) {
ByteArray* ba = ByteArray::create(state, size() + str->byte_size());
memcpy(ba->bytes, str->data()->bytes, str->byte_size());
memcpy(ba->bytes + str->byte_size(), bytes, size());
return ba;
}
ByteArray* ByteArray::reverse(STATE, Fixnum* o_start, Fixnum* o_total) {
native_int start = o_start->to_native();
native_int total = o_total->to_native();
if(total <= 0 || start < 0 || start >= size()) return this;
uint8_t* pos1 = this->bytes + start;
uint8_t* pos2 = this->bytes + total - 1;
register uint8_t tmp;
while(pos1 < pos2) {
tmp = *pos1;
*pos1++ = *pos2;
*pos2-- = tmp;
}
return this;
}
Fixnum* ByteArray::compare_bytes(STATE, ByteArray* other, Fixnum* a, Fixnum* b) {
native_int slim = a->to_native();
native_int olim = b->to_native();
if(slim < 0) {
Exception::object_bounds_exceeded_error(state,
"bytes of self to compare is less than zero");
} else if(olim < 0) {
Exception::object_bounds_exceeded_error(state,
"bytes of other to compare is less than zero");
}
// clamp limits to actual sizes
native_int m = size() < slim ? size() : slim;
native_int n = other->size() < olim ? other->size() : olim;
// only compare the shortest string
native_int len = m < n ? m : n;
native_int cmp = memcmp(this->bytes, other->bytes, len);
// even if substrings are equal, check actual requested limits
// of comparison e.g. "xyz", "xyzZ"
if(cmp == 0) {
if(m < n) {
return Fixnum::from(-1);
} else if(m > n) {
return Fixnum::from(1);
} else {
return Fixnum::from(0);
}
} else {
return cmp < 0 ? Fixnum::from(-1) : Fixnum::from(1);
}
}
Object* ByteArray::locate(STATE, String* pattern, Fixnum* start, Fixnum* max_o) {
const uint8_t* pat = pattern->byte_address();
native_int len = pattern->byte_size();
native_int max = max_o->to_native();
if(len == 0) return start;
if(max == 0) return cNil;
if(max > size()) max = size();
max -= (len - 1);
for(native_int i = start->to_native(); i < max; i++) {
if(this->bytes[i] == pat[0]) {
native_int j;
// match the rest of the pattern string
for(j = 1; j < len; j++) {
if(this->bytes[i+j] != pat[j]) break;
}
// if the full pattern matched, return the index
// of the end of the pattern in 'this'.
if(j == len) return Fixnum::from(i + len);
}
}
return cNil;
}
// Ripped from 1.8.7 and cleaned up
static const long utf8_limits[] = {
0x0, /* 1 */
0x80, /* 2 */
0x800, /* 3 */
0x10000, /* 4 */
0x200000, /* 5 */
0x4000000, /* 6 */
0x80000000, /* 7 */
};
static long utf8_to_uv(char* p, long* lenp) {
int c = *p++ & 0xff;
long uv = c;
long n;
if (!(uv & 0x80)) {
*lenp = 1;
return uv;
}
if (!(uv & 0x40)) {
*lenp = 1;
return -1;
}
if (!(uv & 0x20)) { n = 2; uv &= 0x1f; }
else if (!(uv & 0x10)) { n = 3; uv &= 0x0f; }
else if (!(uv & 0x08)) { n = 4; uv &= 0x07; }
else if (!(uv & 0x04)) { n = 5; uv &= 0x03; }
else if (!(uv & 0x02)) { n = 6; uv &= 0x01; }
else {
*lenp = 1;
return -1;
}
if (n > *lenp) return -1;
*lenp = n--;
if (n != 0) {
while (n--) {
c = *p++ & 0xff;
if ((c & 0xc0) != 0x80) {
*lenp -= n + 1;
return -1;
}
else {
c &= 0x3f;
uv = uv << 6 | c;
}
}
}
n = *lenp - 1;
if (uv < utf8_limits[n]) return -1;
return uv;
}
Object* ByteArray::get_utf8_char(STATE, Fixnum* offset) {
native_int o = offset->to_native();
if(o >= (native_int)size()) return Primitives::failure();
char* start = (char*)bytes + o;
long len = size() - o;
long res = utf8_to_uv(start, &len);
if(res == -1) return Primitives::failure();
return Tuple::from(state, 2, Integer::from(state, res), Fixnum::from(len));
}
size_t ByteArray::Info::object_size(const ObjectHeader* obj) {
const ByteArray *ba = reinterpret_cast<const ByteArray*>(obj);
assert(ba);
return ba->full_size_;
}
void ByteArray::Info::mark(Object* t, ObjectMark& mark) {
// @todo implement
}
}
<commit_msg>Use rubinius::bug over assert<commit_after>/* The simple ByteArray class, used to implement String. */
#include <stdint.h>
#include "vm.hpp"
#include "objectmemory.hpp"
#include "primitives.hpp"
#include "builtin/bytearray.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/string.hpp"
#include "builtin/tuple.hpp"
#include "object_utils.hpp"
#include "ontology.hpp"
namespace rubinius {
void ByteArray::init(STATE) {
GO(bytearray).set(ontology::new_class_under(state,
"ByteArray", G(rubinius)));
G(bytearray)->set_object_type(state, ByteArrayType);
}
ByteArray* ByteArray::create(STATE, native_int bytes) {
if(bytes < 0 || bytes >= INT32_MAX) {
rubinius::bug("Invalid byte array size");
}
size_t body = bytes;
ByteArray* ba = state->vm()->new_object_bytes<ByteArray>(G(bytearray), body);
if(unlikely(!ba)) {
Exception::memory_error(state);
}
ba->full_size_ = body;
memset(ba->bytes, 0, bytes);
return ba;
}
ByteArray* ByteArray::create_pinned(STATE, native_int bytes) {
if(bytes < 0 || bytes >= INT32_MAX) {
rubinius::bug("Invalid byte array size");
}
size_t body = bytes;
ByteArray* ba = state->memory()->new_object_bytes_mature<ByteArray>(state, G(bytearray), body);
if(unlikely(!ba)) {
Exception::memory_error(state);
}
if(!ba->pin()) {
rubinius::bug("unable to allocate pinned ByteArray");
}
ba->full_size_ = body;
memset(ba->bytes, 0, bytes);
return ba;
}
ByteArray* ByteArray::allocate(STATE, Fixnum* bytes) {
native_int size = bytes->to_native();
if(size < 0) {
Exception::argument_error(state, "negative byte array size");
} else if (size > INT32_MAX) {
Exception::argument_error(state, "too large byte array size");
}
return ByteArray::create(state, size);
}
Fixnum* ByteArray::size(STATE) {
return Fixnum::from(size());
}
char* ByteArray::to_chars(STATE, Fixnum* size) {
native_int sz = size->to_native();
native_int ba_sz = this->size(state)->to_native();
if(sz < 0) {
Exception::object_bounds_exceeded_error(state, "size less than zero");
} else if(sz > ba_sz) {
Exception::object_bounds_exceeded_error(state, "size beyond actual size");
}
char* str = (char*)(this->bytes);
char* out = ALLOC_N(char, sz + 1);
memcpy(out, str, sz);
out[sz] = 0;
return out;
}
Fixnum* ByteArray::get_byte(STATE, Fixnum* index) {
native_int idx = index->to_native();
if(idx < 0 || idx >= size()) {
Exception::object_bounds_exceeded_error(state, "index out of bounds");
}
return Fixnum::from(this->bytes[idx]);
}
Fixnum* ByteArray::set_byte(STATE, Fixnum* index, Fixnum* value) {
native_int idx = index->to_native();
if(idx < 0 || idx >= size()) {
Exception::object_bounds_exceeded_error(state, "index out of bounds");
}
this->bytes[idx] = value->to_native();
return Fixnum::from(this->bytes[idx]);
}
Fixnum* ByteArray::move_bytes(STATE, Fixnum* start, Fixnum* count, Fixnum* dest) {
native_int src = start->to_native();
native_int cnt = count->to_native();
native_int dst = dest->to_native();
if(src < 0) {
Exception::object_bounds_exceeded_error(state, "start less than zero");
} else if(dst < 0) {
Exception::object_bounds_exceeded_error(state, "dest less than zero");
} else if(cnt < 0) {
Exception::object_bounds_exceeded_error(state, "count less than zero");
} else if((dst + cnt) > size()) {
Exception::object_bounds_exceeded_error(state, "move is beyond end of bytearray");
} else if((src + cnt) > size()) {
Exception::object_bounds_exceeded_error(state, "move is more than available bytes");
}
memmove(this->bytes + dst, this->bytes + src, cnt);
return count;
}
ByteArray* ByteArray::fetch_bytes(STATE, Fixnum* start, Fixnum* count) {
native_int src = start->to_native();
native_int cnt = count->to_native();
if(src < 0) {
Exception::object_bounds_exceeded_error(state, "start less than zero");
} else if(cnt < 0) {
Exception::object_bounds_exceeded_error(state, "count less than zero");
} else if((src + cnt) > size()) {
Exception::object_bounds_exceeded_error(state, "fetch is more than available bytes");
}
ByteArray* ba = ByteArray::create(state, cnt + 1);
memcpy(ba->bytes, this->bytes + src, cnt);
ba->bytes[cnt] = 0;
return ba;
}
ByteArray* ByteArray::prepend(STATE, String* str) {
ByteArray* ba = ByteArray::create(state, size() + str->byte_size());
memcpy(ba->bytes, str->data()->bytes, str->byte_size());
memcpy(ba->bytes + str->byte_size(), bytes, size());
return ba;
}
ByteArray* ByteArray::reverse(STATE, Fixnum* o_start, Fixnum* o_total) {
native_int start = o_start->to_native();
native_int total = o_total->to_native();
if(total <= 0 || start < 0 || start >= size()) return this;
uint8_t* pos1 = this->bytes + start;
uint8_t* pos2 = this->bytes + total - 1;
register uint8_t tmp;
while(pos1 < pos2) {
tmp = *pos1;
*pos1++ = *pos2;
*pos2-- = tmp;
}
return this;
}
Fixnum* ByteArray::compare_bytes(STATE, ByteArray* other, Fixnum* a, Fixnum* b) {
native_int slim = a->to_native();
native_int olim = b->to_native();
if(slim < 0) {
Exception::object_bounds_exceeded_error(state,
"bytes of self to compare is less than zero");
} else if(olim < 0) {
Exception::object_bounds_exceeded_error(state,
"bytes of other to compare is less than zero");
}
// clamp limits to actual sizes
native_int m = size() < slim ? size() : slim;
native_int n = other->size() < olim ? other->size() : olim;
// only compare the shortest string
native_int len = m < n ? m : n;
native_int cmp = memcmp(this->bytes, other->bytes, len);
// even if substrings are equal, check actual requested limits
// of comparison e.g. "xyz", "xyzZ"
if(cmp == 0) {
if(m < n) {
return Fixnum::from(-1);
} else if(m > n) {
return Fixnum::from(1);
} else {
return Fixnum::from(0);
}
} else {
return cmp < 0 ? Fixnum::from(-1) : Fixnum::from(1);
}
}
Object* ByteArray::locate(STATE, String* pattern, Fixnum* start, Fixnum* max_o) {
const uint8_t* pat = pattern->byte_address();
native_int len = pattern->byte_size();
native_int max = max_o->to_native();
if(len == 0) return start;
if(max == 0) return cNil;
if(max > size()) max = size();
max -= (len - 1);
for(native_int i = start->to_native(); i < max; i++) {
if(this->bytes[i] == pat[0]) {
native_int j;
// match the rest of the pattern string
for(j = 1; j < len; j++) {
if(this->bytes[i+j] != pat[j]) break;
}
// if the full pattern matched, return the index
// of the end of the pattern in 'this'.
if(j == len) return Fixnum::from(i + len);
}
}
return cNil;
}
// Ripped from 1.8.7 and cleaned up
static const long utf8_limits[] = {
0x0, /* 1 */
0x80, /* 2 */
0x800, /* 3 */
0x10000, /* 4 */
0x200000, /* 5 */
0x4000000, /* 6 */
0x80000000, /* 7 */
};
static long utf8_to_uv(char* p, long* lenp) {
int c = *p++ & 0xff;
long uv = c;
long n;
if (!(uv & 0x80)) {
*lenp = 1;
return uv;
}
if (!(uv & 0x40)) {
*lenp = 1;
return -1;
}
if (!(uv & 0x20)) { n = 2; uv &= 0x1f; }
else if (!(uv & 0x10)) { n = 3; uv &= 0x0f; }
else if (!(uv & 0x08)) { n = 4; uv &= 0x07; }
else if (!(uv & 0x04)) { n = 5; uv &= 0x03; }
else if (!(uv & 0x02)) { n = 6; uv &= 0x01; }
else {
*lenp = 1;
return -1;
}
if (n > *lenp) return -1;
*lenp = n--;
if (n != 0) {
while (n--) {
c = *p++ & 0xff;
if ((c & 0xc0) != 0x80) {
*lenp -= n + 1;
return -1;
}
else {
c &= 0x3f;
uv = uv << 6 | c;
}
}
}
n = *lenp - 1;
if (uv < utf8_limits[n]) return -1;
return uv;
}
Object* ByteArray::get_utf8_char(STATE, Fixnum* offset) {
native_int o = offset->to_native();
if(o >= (native_int)size()) return Primitives::failure();
char* start = (char*)bytes + o;
long len = size() - o;
long res = utf8_to_uv(start, &len);
if(res == -1) return Primitives::failure();
return Tuple::from(state, 2, Integer::from(state, res), Fixnum::from(len));
}
size_t ByteArray::Info::object_size(const ObjectHeader* obj) {
const ByteArray *ba = reinterpret_cast<const ByteArray*>(obj);
assert(ba);
return ba->full_size_;
}
void ByteArray::Info::mark(Object* t, ObjectMark& mark) {
// @todo implement
}
}
<|endoftext|>
|
<commit_before>#include "Course.h"
#include <string>
using namespace std;
Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){
startTime = _startTime;
endTime = _endTime;
days = _days;
courseName = _courseName;
courseLoc = _courseLoc;
courseId = _courseId;
}
int const Course::getEndTime(){
return endTime;
}
int const Course::getStartTime(){
return startTime;
}
string const Course::getDays(){
return "";
}<commit_msg>Course.it7 - pass: get days<commit_after>#include "Course.h"
#include <string>
using namespace std;
Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){
startTime = _startTime;
endTime = _endTime;
days = _days;
courseName = _courseName;
courseLoc = _courseLoc;
courseId = _courseId;
}
int const Course::getEndTime(){
return endTime;
}
int const Course::getStartTime(){
return startTime;
}
string const Course::getDays(){
return days;
}<|endoftext|>
|
<commit_before>//
// Iteration_test.cpp
//
// Created by David Wicks on 9/13/15.
// Copyright (c) 2015 David Wicks. All rights reserved.
//
#include "catch.hpp"
#include "pockets/CollectionViews.h"
#include <vector>
#include <unordered_set>
#include <iostream>
using namespace std;
TEST_CASE("Iteration_test")
{
auto collection = vector<int>{ 1, 2, 3, 4, 5, 6 };
auto unordered_collection = set<string>{ "hi", "hello", "tony" };
SECTION("reverse_view allows us to walk a collection backwards.")
{
auto forward = vector<int>();
auto reversed = vector<int>();
for (auto &i: collection)
{
forward.push_back(i);
}
for (auto &i: pk::reverse_view(collection))
{
reversed.push_back(i);
}
REQUIRE(forward == collection);
REQUIRE(reversed == (vector<int>{ 6, 5, 4, 3, 2, 1 }));
}
SECTION("partial_view allows us to look at a subset of a collection.")
{
auto first = vector<int>();
auto last = vector<int>();
auto copy = vector<int>();
for (auto &i: pk::partial_view(collection, 0, collection.size() / 2))
{
first.push_back(i);
}
for (auto &i: pk::partial_view(collection, 0, collection.size()))
{
copy.push_back(i);
}
for (auto &i: pk::partial_view(collection, 3, collection.size()))
{
last.push_back(i);
}
REQUIRE(copy == collection);
REQUIRE(first == (vector<int>{ 1, 2, 3 }));
REQUIRE(last == (vector<int>{ 4, 5, 6 }));
}
SECTION("Ascending and descending numeric ranges can be used as generators.")
{
for (auto i: pk::range(0.0f, 10.0f, 1.0f))
{
cout << i << endl;
}
for (auto i: pk::range(20.0f, 0.0f, -1.0f))
{
cout << i << endl;
}
}
SECTION("enumerate allows us to walk a collection with corresponding counting numbers.")
{
for (auto p: pk::enumerate(collection))
{
REQUIRE(p.value == collection.at(p.index));
}
// For non-sequential containers, the indices can still be used with std::next.
for (auto p: pk::enumerate(unordered_collection))
{
REQUIRE(p.value == *std::next(unordered_collection.begin(), p.index));
}
}
// Untested (and hence currently unsupported):
// combining different views onto the same collection.
}
<commit_msg>Less printing in iteration test.<commit_after>//
// Iteration_test.cpp
//
// Created by David Wicks on 9/13/15.
// Copyright (c) 2015 David Wicks. All rights reserved.
//
#include "catch.hpp"
#include "pockets/CollectionViews.h"
#include <vector>
#include <unordered_set>
#include <iostream>
using namespace std;
TEST_CASE("Iteration_test")
{
auto collection = vector<int>{ 1, 2, 3, 4, 5, 6 };
auto unordered_collection = set<string>{ "hi", "hello", "tony" };
SECTION("reverse_view allows us to walk a collection backwards.")
{
auto forward = vector<int>();
auto reversed = vector<int>();
for (auto &i: collection)
{
forward.push_back(i);
}
for (auto &i: pk::reverse_view(collection))
{
reversed.push_back(i);
}
REQUIRE(forward == collection);
REQUIRE(reversed == (vector<int>{ 6, 5, 4, 3, 2, 1 }));
}
SECTION("partial_view allows us to look at a subset of a collection.")
{
auto first = vector<int>();
auto last = vector<int>();
auto copy = vector<int>();
for (auto &i: pk::partial_view(collection, 0, collection.size() / 2))
{
first.push_back(i);
}
for (auto &i: pk::partial_view(collection, 0, collection.size()))
{
copy.push_back(i);
}
for (auto &i: pk::partial_view(collection, 3, collection.size()))
{
last.push_back(i);
}
REQUIRE(copy == collection);
REQUIRE(first == (vector<int>{ 1, 2, 3 }));
REQUIRE(last == (vector<int>{ 4, 5, 6 }));
}
SECTION("Ascending and descending numeric ranges can be used as generators.")
{
for (auto i: pk::range(0.0f, 10.0f, 3.0f))
{
cout << i << endl;
}
for (auto i: pk::range(5.0f, 0.0f, -1.0f))
{
cout << i << endl;
}
}
SECTION("enumerate allows us to walk a collection with corresponding counting numbers.")
{
for (auto p: pk::enumerate(collection))
{
REQUIRE(p.value == collection.at(p.index));
}
// For non-sequential containers, the indices can still be used with std::next.
for (auto p: pk::enumerate(unordered_collection))
{
REQUIRE(p.value == *std::next(unordered_collection.begin(), p.index));
}
}
// Untested (and hence currently unsupported):
// combining different views onto the same collection.
}
<|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 "chrome/browser/api/prefs/pref_member.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/passwords_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/common/pref_names.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "sync/protocol/sync_protocol_error.h"
using bookmarks_helper::AddFolder;
using bookmarks_helper::SetTitle;
class SyncErrorTest : public SyncTest {
public:
SyncErrorTest() : SyncTest(SINGLE_CLIENT) {}
virtual ~SyncErrorTest() {}
private:
DISALLOW_COPY_AND_ASSIGN(SyncErrorTest);
};
IN_PROC_BROWSER_TEST_F(SyncErrorTest, BirthdayErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change."));
TriggerBirthdayError();
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(GetClient(0)->AwaitSyncDisabled("Birthday error."));
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest, TransientErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change."));
TriggerTransientError();
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(
GetClient(0)->AwaitExponentialBackoffVerification());
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest, ActionableErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
syncer::SyncProtocolError protocol_error;
protocol_error.error_type = syncer::TRANSIENT_ERROR;
protocol_error.action = syncer::UPGRADE_CLIENT;
protocol_error.error_description = "Not My Fault";
protocol_error.url = "www.google.com";
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_ALWAYS);
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(
GetClient(0)->AwaitActionableError());
ProfileSyncService::Status status = GetClient(0)->GetStatus();
ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type);
ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action);
ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url);
ASSERT_EQ(status.sync_protocol_error.error_description,
protocol_error.error_description);
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest, ErrorWhileSettingUp) {
ASSERT_TRUE(SetupClients());
syncer::SyncProtocolError protocol_error;
protocol_error.error_type = syncer::TRANSIENT_ERROR;
protocol_error.error_description = "Not My Fault";
protocol_error.url = "www.google.com";
if (clients()[0]->AutoStartEnabled()) {
// In auto start enabled platforms like chrome os we should be
// able to set up even if the first sync while setting up fails.
// Trigger error on every 2 out of 3 requests.
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_TWO_THIRDS);
// Now setup sync and it should succeed.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
} else {
// In Non auto start enabled environments if the setup sync fails then
// the setup would fail. So setup sync normally.
ASSERT_TRUE(SetupSync()) << "Setup sync failed";
ASSERT_TRUE(clients()[0]->DisableSyncForDatatype(syncer::AUTOFILL));
// Trigger error on every 2 out of 3 requests.
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_TWO_THIRDS);
// Now enable a datatype, whose first 2 syncs would fail, but we should
// recover and setup succesfully on the third attempt.
ASSERT_TRUE(clients()[0]->EnableSyncForDatatype(syncer::AUTOFILL));
}
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest,
BirthdayErrorUsingActionableErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
syncer::SyncProtocolError protocol_error;
protocol_error.error_type = syncer::NOT_MY_BIRTHDAY;
protocol_error.action = syncer::DISABLE_SYNC_ON_CLIENT;
protocol_error.error_description = "Not My Fault";
protocol_error.url = "www.google.com";
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_ALWAYS);
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(
GetClient(0)->AwaitSyncDisabled("Birthday Error."));
ProfileSyncService::Status status = GetClient(0)->GetStatus();
ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type);
ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action);
ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url);
ASSERT_EQ(status.sync_protocol_error.error_description,
protocol_error.error_description);
}
// Trigger an auth error and make sure the sync client detects it when
// trying to commit.
IN_PROC_BROWSER_TEST_F(SyncErrorTest, AuthErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
TriggerAuthError();
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(GetClient(0)->AwaitExponentialBackoffVerification());
ASSERT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS,
GetClient(0)->service()->GetAuthError().state());
}
// Trigger an XMPP auth error, and make sure sync treats it like any
// other auth error.
IN_PROC_BROWSER_TEST_F(SyncErrorTest, XmppAuthErrorTest) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
TriggerXmppAuthError();
ASSERT_FALSE(GetClient(0)->SetupSync());
ASSERT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS,
GetClient(0)->service()->GetAuthError().state());
}
// TODO(lipalani): Fix the typed_url dtc so this test case can pass.
IN_PROC_BROWSER_TEST_F(SyncErrorTest, DISABLED_DisableDatatypeWhileRunning) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
syncer::ModelTypeSet synced_datatypes =
GetClient(0)->service()->GetPreferredDataTypes();
ASSERT_TRUE(synced_datatypes.Has(syncer::TYPED_URLS));
GetProfile(0)->GetPrefs()->SetBoolean(
prefs::kSavingBrowserHistoryDisabled, true);
synced_datatypes = GetClient(0)->service()->GetPreferredDataTypes();
ASSERT_FALSE(synced_datatypes.Has(syncer::TYPED_URLS));
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
// TODO(lipalani)" Verify initial sync ended for typed url is false.
}
<commit_msg>Un-flake Mac 10.6 Sync by labelling SyncErrorTest.XmppAuthErrorTest 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 "chrome/browser/api/prefs/pref_member.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/passwords_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/common/pref_names.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "sync/protocol/sync_protocol_error.h"
using bookmarks_helper::AddFolder;
using bookmarks_helper::SetTitle;
class SyncErrorTest : public SyncTest {
public:
SyncErrorTest() : SyncTest(SINGLE_CLIENT) {}
virtual ~SyncErrorTest() {}
private:
DISALLOW_COPY_AND_ASSIGN(SyncErrorTest);
};
IN_PROC_BROWSER_TEST_F(SyncErrorTest, BirthdayErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change."));
TriggerBirthdayError();
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(GetClient(0)->AwaitSyncDisabled("Birthday error."));
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest, TransientErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change."));
TriggerTransientError();
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(
GetClient(0)->AwaitExponentialBackoffVerification());
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest, ActionableErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
syncer::SyncProtocolError protocol_error;
protocol_error.error_type = syncer::TRANSIENT_ERROR;
protocol_error.action = syncer::UPGRADE_CLIENT;
protocol_error.error_description = "Not My Fault";
protocol_error.url = "www.google.com";
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_ALWAYS);
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(
GetClient(0)->AwaitActionableError());
ProfileSyncService::Status status = GetClient(0)->GetStatus();
ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type);
ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action);
ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url);
ASSERT_EQ(status.sync_protocol_error.error_description,
protocol_error.error_description);
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest, ErrorWhileSettingUp) {
ASSERT_TRUE(SetupClients());
syncer::SyncProtocolError protocol_error;
protocol_error.error_type = syncer::TRANSIENT_ERROR;
protocol_error.error_description = "Not My Fault";
protocol_error.url = "www.google.com";
if (clients()[0]->AutoStartEnabled()) {
// In auto start enabled platforms like chrome os we should be
// able to set up even if the first sync while setting up fails.
// Trigger error on every 2 out of 3 requests.
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_TWO_THIRDS);
// Now setup sync and it should succeed.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
} else {
// In Non auto start enabled environments if the setup sync fails then
// the setup would fail. So setup sync normally.
ASSERT_TRUE(SetupSync()) << "Setup sync failed";
ASSERT_TRUE(clients()[0]->DisableSyncForDatatype(syncer::AUTOFILL));
// Trigger error on every 2 out of 3 requests.
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_TWO_THIRDS);
// Now enable a datatype, whose first 2 syncs would fail, but we should
// recover and setup succesfully on the third attempt.
ASSERT_TRUE(clients()[0]->EnableSyncForDatatype(syncer::AUTOFILL));
}
}
IN_PROC_BROWSER_TEST_F(SyncErrorTest,
BirthdayErrorUsingActionableErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
syncer::SyncProtocolError protocol_error;
protocol_error.error_type = syncer::NOT_MY_BIRTHDAY;
protocol_error.action = syncer::DISABLE_SYNC_ON_CLIENT;
protocol_error.error_description = "Not My Fault";
protocol_error.url = "www.google.com";
TriggerSyncError(protocol_error, SyncTest::ERROR_FREQUENCY_ALWAYS);
// Now make one more change so we will do another sync.
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(
GetClient(0)->AwaitSyncDisabled("Birthday Error."));
ProfileSyncService::Status status = GetClient(0)->GetStatus();
ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type);
ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action);
ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url);
ASSERT_EQ(status.sync_protocol_error.error_description,
protocol_error.error_description);
}
// Trigger an auth error and make sure the sync client detects it when
// trying to commit.
IN_PROC_BROWSER_TEST_F(SyncErrorTest, AuthErrorTest) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
TriggerAuthError();
const BookmarkNode* node2 = AddFolder(0, 0, L"title2");
SetTitle(0, node2, L"new_title2");
ASSERT_TRUE(GetClient(0)->AwaitExponentialBackoffVerification());
ASSERT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS,
GetClient(0)->service()->GetAuthError().state());
}
// Trigger an XMPP auth error, and make sure sync treats it like any
// other auth error.
// This has been flaking a lot recently on Mac. http://crbug.com/165328
#if defined(OS_MACOSX)
#define MAYBE_XmppAuthErrorTest FLAKY_XmppAuthErrorTest
#else
#define MAYBE_XmppAuthErrorTest XmppAuthErrorTest
#endif
IN_PROC_BROWSER_TEST_F(SyncErrorTest, MAYBE_XmppAuthErrorTest) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
TriggerXmppAuthError();
ASSERT_FALSE(GetClient(0)->SetupSync());
ASSERT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS,
GetClient(0)->service()->GetAuthError().state());
}
// TODO(lipalani): Fix the typed_url dtc so this test case can pass.
IN_PROC_BROWSER_TEST_F(SyncErrorTest, DISABLED_DisableDatatypeWhileRunning) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
syncer::ModelTypeSet synced_datatypes =
GetClient(0)->service()->GetPreferredDataTypes();
ASSERT_TRUE(synced_datatypes.Has(syncer::TYPED_URLS));
GetProfile(0)->GetPrefs()->SetBoolean(
prefs::kSavingBrowserHistoryDisabled, true);
synced_datatypes = GetClient(0)->service()->GetPreferredDataTypes();
ASSERT_FALSE(synced_datatypes.Has(syncer::TYPED_URLS));
const BookmarkNode* node1 = AddFolder(0, 0, L"title1");
SetTitle(0, node1, L"new_title1");
ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync."));
// TODO(lipalani)" Verify initial sync ended for typed url is false.
}
<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <test_common.h>
#include <vistk/pipeline/utils.h>
#include <stdexcept>
#include <iostream>
#include <string>
#include <cstdlib>
int
main(int argc, char* argv[])
{
if (argc != 2)
{
TEST_ERROR("Expected one argument");
return EXIT_FAILURE;
}
std::string const test_name = argv[1];
if (test_name == "return_code")
{
return EXIT_FAILURE;
}
else if (test_name == "error_string")
{
TEST_ERROR("an error");
}
else if (test_name == "error_string_mid")
{
std::cerr << "Test";
TEST_ERROR("an error");
}
else if (test_name == "error_string_stdout")
{
std::cout << "Error: an error" << std::endl;
}
else if (test_name == "error_string_second_line")
{
std::cerr << "Not an error" << std::endl;
TEST_ERROR("an error");
}
else if (test_name == "expected_exception")
{
EXPECT_EXCEPTION(std::logic_error,
throw std::logic_error("reason"),
"when throwing an exception");
}
else if (test_name == "unexpected_exception")
{
EXPECT_EXCEPTION(std::runtime_error,
throw std::logic_error("reason"),
"when throwing an unexpected exception");
}
else if (test_name == "environment")
{
vistk::envvar_name_t const envvar = "TEST_ENVVAR";
vistk::envvar_value_t envvalue = vistk::get_envvar(envvar);
if (!envvalue)
{
TEST_ERROR("failed to get environment from CTest");
}
else
{
char const* const expected = "test_value";
if (strcmp(envvalue, expected))
{
TEST_ERROR("Did not get expected value: "
"Expected: " << expected << " "
"Received: " << envvalue);
}
}
vistk::free_envvar(envvalue);
envvalue = NULL;
}
else
{
TEST_ERROR("Unknown test: " << test_name);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Include cstring for strcmp<commit_after>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <test_common.h>
#include <vistk/pipeline/utils.h>
#include <stdexcept>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
int
main(int argc, char* argv[])
{
if (argc != 2)
{
TEST_ERROR("Expected one argument");
return EXIT_FAILURE;
}
std::string const test_name = argv[1];
if (test_name == "return_code")
{
return EXIT_FAILURE;
}
else if (test_name == "error_string")
{
TEST_ERROR("an error");
}
else if (test_name == "error_string_mid")
{
std::cerr << "Test";
TEST_ERROR("an error");
}
else if (test_name == "error_string_stdout")
{
std::cout << "Error: an error" << std::endl;
}
else if (test_name == "error_string_second_line")
{
std::cerr << "Not an error" << std::endl;
TEST_ERROR("an error");
}
else if (test_name == "expected_exception")
{
EXPECT_EXCEPTION(std::logic_error,
throw std::logic_error("reason"),
"when throwing an exception");
}
else if (test_name == "unexpected_exception")
{
EXPECT_EXCEPTION(std::runtime_error,
throw std::logic_error("reason"),
"when throwing an unexpected exception");
}
else if (test_name == "environment")
{
vistk::envvar_name_t const envvar = "TEST_ENVVAR";
vistk::envvar_value_t envvalue = vistk::get_envvar(envvar);
if (!envvalue)
{
TEST_ERROR("failed to get environment from CTest");
}
else
{
char const* const expected = "test_value";
if (strcmp(envvalue, expected))
{
TEST_ERROR("Did not get expected value: "
"Expected: " << expected << " "
"Received: " << envvalue);
}
}
vistk::free_envvar(envvalue);
envvalue = NULL;
}
else
{
TEST_ERROR("Unknown test: " << test_name);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>//===-- lldb-log.cpp --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/lldb-private-log.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamFile.h"
#include <string.h>
using namespace lldb;
using namespace lldb_private;
// We want to avoid global constructors where code needs to be run so here we
// control access to our static g_log_sp by hiding it in a singleton function
// that will construct the static g_lob_sp the first time this function is
// called.
static bool g_log_enabled = false;
static Log * g_log = NULL;
static Log *
GetLog ()
{
if (!g_log_enabled)
return NULL;
return g_log;
}
uint32_t
lldb_private::GetLogMask ()
{
Log *log(GetLog ());
if (log)
return log->GetMask().Get();
return 0;
}
bool
lldb_private::IsLogVerbose ()
{
uint32_t mask = GetLogMask();
return (mask & LIBLLDB_LOG_VERBOSE);
}
Log *
lldb_private::GetLogIfAllCategoriesSet (uint32_t mask)
{
Log *log(GetLog ());
if (log && mask)
{
uint32_t log_mask = log->GetMask().Get();
if ((log_mask & mask) != mask)
return NULL;
}
return log;
}
void
lldb_private::LogIfAllCategoriesSet (uint32_t mask, const char *format, ...)
{
Log *log(GetLogIfAllCategoriesSet (mask));
if (log)
{
va_list args;
va_start (args, format);
log->VAPrintf (format, args);
va_end (args);
}
}
void
lldb_private::LogIfAnyCategoriesSet (uint32_t mask, const char *format, ...)
{
Log *log(GetLogIfAnyCategoriesSet (mask));
if (log)
{
va_list args;
va_start (args, format);
log->VAPrintf (format, args);
va_end (args);
}
}
Log *
lldb_private::GetLogIfAnyCategoriesSet (uint32_t mask)
{
Log *log(GetLog ());
if (log && mask && (mask & log->GetMask().Get()))
return log;
return NULL;
}
void
lldb_private::DisableLog (const char **categories, Stream *feedback_strm)
{
Log *log(GetLog ());
if (log)
{
uint32_t flag_bits = 0;
if (categories[0] != NULL)
{
flag_bits = log->GetMask().Get();
for (size_t i = 0; categories[i] != NULL; ++i)
{
const char *arg = categories[i];
if (0 == ::strcasecmp(arg, "all")) flag_bits &= ~LIBLLDB_LOG_ALL;
else if (0 == ::strcasecmp(arg, "api")) flag_bits &= ~LIBLLDB_LOG_API;
else if (0 == ::strncasecmp(arg, "break", 5)) flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS;
else if (0 == ::strcasecmp(arg, "commands")) flag_bits &= ~LIBLLDB_LOG_COMMANDS;
else if (0 == ::strcasecmp(arg, "default")) flag_bits &= ~LIBLLDB_LOG_DEFAULT;
else if (0 == ::strcasecmp(arg, "dyld")) flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER;
else if (0 == ::strncasecmp(arg, "event", 5)) flag_bits &= ~LIBLLDB_LOG_EVENTS;
else if (0 == ::strncasecmp(arg, "expr", 4)) flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS;
else if (0 == ::strncasecmp(arg, "object", 6)) flag_bits &= ~LIBLLDB_LOG_OBJECT;
else if (0 == ::strcasecmp(arg, "process")) flag_bits &= ~LIBLLDB_LOG_PROCESS;
else if (0 == ::strcasecmp(arg, "platform")) flag_bits &= ~LIBLLDB_LOG_PLATFORM;
else if (0 == ::strcasecmp(arg, "script")) flag_bits &= ~LIBLLDB_LOG_SCRIPT;
else if (0 == ::strcasecmp(arg, "state")) flag_bits &= ~LIBLLDB_LOG_STATE;
else if (0 == ::strcasecmp(arg, "step")) flag_bits &= ~LIBLLDB_LOG_STEP;
else if (0 == ::strcasecmp(arg, "thread")) flag_bits &= ~LIBLLDB_LOG_THREAD;
else if (0 == ::strcasecmp(arg, "target")) flag_bits &= ~LIBLLDB_LOG_TARGET;
else if (0 == ::strcasecmp(arg, "verbose")) flag_bits &= ~LIBLLDB_LOG_VERBOSE;
else if (0 == ::strncasecmp(arg, "watch", 5)) flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS;
else if (0 == ::strncasecmp(arg, "temp", 4)) flag_bits &= ~LIBLLDB_LOG_TEMPORARY;
else if (0 == ::strncasecmp(arg, "comm", 4)) flag_bits &= ~LIBLLDB_LOG_COMMUNICATION;
else if (0 == ::strncasecmp(arg, "conn", 4)) flag_bits &= ~LIBLLDB_LOG_CONNECTION;
else if (0 == ::strncasecmp(arg, "host", 4)) flag_bits &= ~LIBLLDB_LOG_HOST;
else if (0 == ::strncasecmp(arg, "unwind", 6)) flag_bits &= ~LIBLLDB_LOG_UNWIND;
else if (0 == ::strncasecmp(arg, "types", 5)) flag_bits &= ~LIBLLDB_LOG_TYPES;
else if (0 == ::strncasecmp(arg, "symbol", 6)) flag_bits &= ~LIBLLDB_LOG_SYMBOLS;
else if (0 == ::strcasecmp(arg, "system-runtime")) flag_bits &= ~LIBLLDB_LOG_SYSTEM_RUNTIME;
else if (0 == ::strncasecmp(arg, "module", 6)) flag_bits &= ~LIBLLDB_LOG_MODULES;
else if (0 == ::strncasecmp(arg, "mmap", 4)) flag_bits &= ~LIBLLDB_LOG_MMAP;
else if (0 == ::strcasecmp(arg, "os")) flag_bits &= ~LIBLLDB_LOG_OS;
else if (0 == ::strcasecmp(arg, "jit")) flag_bits &= ~LIBLLDB_LOG_JIT_LOADER;
else
{
feedback_strm->Printf ("error: unrecognized log category '%s'\n", arg);
ListLogCategories (feedback_strm);
return;
}
}
}
log->GetMask().Reset (flag_bits);
if (flag_bits == 0)
{
log->SetStream(lldb::StreamSP());
g_log_enabled = false;
}
}
return;
}
Log *
lldb_private::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, const char **categories, Stream *feedback_strm)
{
// Try see if there already is a log - that way we can reuse its settings.
// We could reuse the log in toto, but we don't know that the stream is the same.
uint32_t flag_bits;
if (g_log)
flag_bits = g_log->GetMask().Get();
else
flag_bits = 0;
// Now make a new log with this stream if one was provided
if (log_stream_sp)
{
if (g_log)
g_log->SetStream(log_stream_sp);
else
g_log = new Log(log_stream_sp);
}
if (g_log)
{
for (size_t i=0; categories[i] != NULL; ++i)
{
const char *arg = categories[i];
if (0 == ::strcasecmp(arg, "all")) flag_bits |= LIBLLDB_LOG_ALL;
else if (0 == ::strcasecmp(arg, "api")) flag_bits |= LIBLLDB_LOG_API;
else if (0 == ::strncasecmp(arg, "break", 5)) flag_bits |= LIBLLDB_LOG_BREAKPOINTS;
else if (0 == ::strcasecmp(arg, "commands")) flag_bits |= LIBLLDB_LOG_COMMANDS;
else if (0 == ::strncasecmp(arg, "commu", 5)) flag_bits |= LIBLLDB_LOG_COMMUNICATION;
else if (0 == ::strncasecmp(arg, "conn", 4)) flag_bits |= LIBLLDB_LOG_CONNECTION;
else if (0 == ::strcasecmp(arg, "default")) flag_bits |= LIBLLDB_LOG_DEFAULT;
else if (0 == ::strcasecmp(arg, "dyld")) flag_bits |= LIBLLDB_LOG_DYNAMIC_LOADER;
else if (0 == ::strncasecmp(arg, "event", 5)) flag_bits |= LIBLLDB_LOG_EVENTS;
else if (0 == ::strncasecmp(arg, "expr", 4)) flag_bits |= LIBLLDB_LOG_EXPRESSIONS;
else if (0 == ::strncasecmp(arg, "host", 4)) flag_bits |= LIBLLDB_LOG_HOST;
else if (0 == ::strncasecmp(arg, "mmap", 4)) flag_bits |= LIBLLDB_LOG_MMAP;
else if (0 == ::strncasecmp(arg, "module", 6)) flag_bits |= LIBLLDB_LOG_MODULES;
else if (0 == ::strncasecmp(arg, "object", 6)) flag_bits |= LIBLLDB_LOG_OBJECT;
else if (0 == ::strcasecmp(arg, "os")) flag_bits |= LIBLLDB_LOG_OS;
else if (0 == ::strcasecmp(arg, "platform")) flag_bits |= LIBLLDB_LOG_PLATFORM;
else if (0 == ::strcasecmp(arg, "process")) flag_bits |= LIBLLDB_LOG_PROCESS;
else if (0 == ::strcasecmp(arg, "script")) flag_bits |= LIBLLDB_LOG_SCRIPT;
else if (0 == ::strcasecmp(arg, "state")) flag_bits |= LIBLLDB_LOG_STATE;
else if (0 == ::strcasecmp(arg, "step")) flag_bits |= LIBLLDB_LOG_STEP;
else if (0 == ::strncasecmp(arg, "symbol", 6)) flag_bits |= LIBLLDB_LOG_SYMBOLS;
else if (0 == ::strcasecmp(arg, "system-runtime")) flag_bits |= LIBLLDB_LOG_SYSTEM_RUNTIME;
else if (0 == ::strcasecmp(arg, "target")) flag_bits |= LIBLLDB_LOG_TARGET;
else if (0 == ::strncasecmp(arg, "temp", 4)) flag_bits |= LIBLLDB_LOG_TEMPORARY;
else if (0 == ::strcasecmp(arg, "thread")) flag_bits |= LIBLLDB_LOG_THREAD;
else if (0 == ::strncasecmp(arg, "types", 5)) flag_bits |= LIBLLDB_LOG_TYPES;
else if (0 == ::strncasecmp(arg, "unwind", 6)) flag_bits |= LIBLLDB_LOG_UNWIND;
else if (0 == ::strcasecmp(arg, "verbose")) flag_bits |= LIBLLDB_LOG_VERBOSE;
else if (0 == ::strncasecmp(arg, "watch", 5)) flag_bits |= LIBLLDB_LOG_WATCHPOINTS;
else if (0 == ::strcasecmp(arg, "jit")) flag_bits |= LIBLLDB_LOG_JIT_LOADER;
else
{
feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
ListLogCategories (feedback_strm);
return g_log;
}
}
g_log->GetMask().Reset(flag_bits);
g_log->GetOptions().Reset(log_options);
}
g_log_enabled = true;
return g_log;
}
void
lldb_private::ListLogCategories (Stream *strm)
{
strm->Printf("Logging categories for 'lldb':\n"
" all - turn on all available logging categories\n"
" api - enable logging of API calls and return values\n"
" break - log breakpoints\n"
" commands - log command argument parsing\n"
" communication - log communication activities\n"
" connection - log connection details\n"
" default - enable the default set of logging categories for liblldb\n"
" dyld - log shared library related activities\n"
" events - log broadcaster, listener and event queue activities\n"
" expr - log expressions\n"
" host - log host activities\n"
" mmap - log mmap related activities\n"
" module - log module activities such as when modules are created, detroyed, replaced, and more\n"
" object - log object construction/destruction for important objects\n"
" os - log OperatingSystem plugin related activities\n"
" platform - log platform events and activities\n"
" process - log process events and activities\n"
" script - log events about the script interpreter\n"
" state - log private and public process state changes\n"
" step - log step related activities\n"
" symbol - log symbol related issues and warnings\n"
" system-runtime - log system runtime events\n"
" target - log target events and activities\n"
" thread - log thread events and activities\n"
" types - log type system related activities\n"
" unwind - log stack unwind activities\n"
" verbose - enable verbose logging\n"
" watch - log watchpoint related activities\n"
" jit - log JIT events in the target\n");
}
<commit_msg>Put "jit" in alpha order in log category list<commit_after>//===-- lldb-log.cpp --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/lldb-private-log.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamFile.h"
#include <string.h>
using namespace lldb;
using namespace lldb_private;
// We want to avoid global constructors where code needs to be run so here we
// control access to our static g_log_sp by hiding it in a singleton function
// that will construct the static g_lob_sp the first time this function is
// called.
static bool g_log_enabled = false;
static Log * g_log = NULL;
static Log *
GetLog ()
{
if (!g_log_enabled)
return NULL;
return g_log;
}
uint32_t
lldb_private::GetLogMask ()
{
Log *log(GetLog ());
if (log)
return log->GetMask().Get();
return 0;
}
bool
lldb_private::IsLogVerbose ()
{
uint32_t mask = GetLogMask();
return (mask & LIBLLDB_LOG_VERBOSE);
}
Log *
lldb_private::GetLogIfAllCategoriesSet (uint32_t mask)
{
Log *log(GetLog ());
if (log && mask)
{
uint32_t log_mask = log->GetMask().Get();
if ((log_mask & mask) != mask)
return NULL;
}
return log;
}
void
lldb_private::LogIfAllCategoriesSet (uint32_t mask, const char *format, ...)
{
Log *log(GetLogIfAllCategoriesSet (mask));
if (log)
{
va_list args;
va_start (args, format);
log->VAPrintf (format, args);
va_end (args);
}
}
void
lldb_private::LogIfAnyCategoriesSet (uint32_t mask, const char *format, ...)
{
Log *log(GetLogIfAnyCategoriesSet (mask));
if (log)
{
va_list args;
va_start (args, format);
log->VAPrintf (format, args);
va_end (args);
}
}
Log *
lldb_private::GetLogIfAnyCategoriesSet (uint32_t mask)
{
Log *log(GetLog ());
if (log && mask && (mask & log->GetMask().Get()))
return log;
return NULL;
}
void
lldb_private::DisableLog (const char **categories, Stream *feedback_strm)
{
Log *log(GetLog ());
if (log)
{
uint32_t flag_bits = 0;
if (categories[0] != NULL)
{
flag_bits = log->GetMask().Get();
for (size_t i = 0; categories[i] != NULL; ++i)
{
const char *arg = categories[i];
if (0 == ::strcasecmp(arg, "all")) flag_bits &= ~LIBLLDB_LOG_ALL;
else if (0 == ::strcasecmp(arg, "api")) flag_bits &= ~LIBLLDB_LOG_API;
else if (0 == ::strncasecmp(arg, "break", 5)) flag_bits &= ~LIBLLDB_LOG_BREAKPOINTS;
else if (0 == ::strcasecmp(arg, "commands")) flag_bits &= ~LIBLLDB_LOG_COMMANDS;
else if (0 == ::strcasecmp(arg, "default")) flag_bits &= ~LIBLLDB_LOG_DEFAULT;
else if (0 == ::strcasecmp(arg, "dyld")) flag_bits &= ~LIBLLDB_LOG_DYNAMIC_LOADER;
else if (0 == ::strncasecmp(arg, "event", 5)) flag_bits &= ~LIBLLDB_LOG_EVENTS;
else if (0 == ::strncasecmp(arg, "expr", 4)) flag_bits &= ~LIBLLDB_LOG_EXPRESSIONS;
else if (0 == ::strncasecmp(arg, "object", 6)) flag_bits &= ~LIBLLDB_LOG_OBJECT;
else if (0 == ::strcasecmp(arg, "process")) flag_bits &= ~LIBLLDB_LOG_PROCESS;
else if (0 == ::strcasecmp(arg, "platform")) flag_bits &= ~LIBLLDB_LOG_PLATFORM;
else if (0 == ::strcasecmp(arg, "script")) flag_bits &= ~LIBLLDB_LOG_SCRIPT;
else if (0 == ::strcasecmp(arg, "state")) flag_bits &= ~LIBLLDB_LOG_STATE;
else if (0 == ::strcasecmp(arg, "step")) flag_bits &= ~LIBLLDB_LOG_STEP;
else if (0 == ::strcasecmp(arg, "thread")) flag_bits &= ~LIBLLDB_LOG_THREAD;
else if (0 == ::strcasecmp(arg, "target")) flag_bits &= ~LIBLLDB_LOG_TARGET;
else if (0 == ::strcasecmp(arg, "verbose")) flag_bits &= ~LIBLLDB_LOG_VERBOSE;
else if (0 == ::strncasecmp(arg, "watch", 5)) flag_bits &= ~LIBLLDB_LOG_WATCHPOINTS;
else if (0 == ::strncasecmp(arg, "temp", 4)) flag_bits &= ~LIBLLDB_LOG_TEMPORARY;
else if (0 == ::strncasecmp(arg, "comm", 4)) flag_bits &= ~LIBLLDB_LOG_COMMUNICATION;
else if (0 == ::strncasecmp(arg, "conn", 4)) flag_bits &= ~LIBLLDB_LOG_CONNECTION;
else if (0 == ::strncasecmp(arg, "host", 4)) flag_bits &= ~LIBLLDB_LOG_HOST;
else if (0 == ::strncasecmp(arg, "unwind", 6)) flag_bits &= ~LIBLLDB_LOG_UNWIND;
else if (0 == ::strncasecmp(arg, "types", 5)) flag_bits &= ~LIBLLDB_LOG_TYPES;
else if (0 == ::strncasecmp(arg, "symbol", 6)) flag_bits &= ~LIBLLDB_LOG_SYMBOLS;
else if (0 == ::strcasecmp(arg, "system-runtime")) flag_bits &= ~LIBLLDB_LOG_SYSTEM_RUNTIME;
else if (0 == ::strncasecmp(arg, "module", 6)) flag_bits &= ~LIBLLDB_LOG_MODULES;
else if (0 == ::strncasecmp(arg, "mmap", 4)) flag_bits &= ~LIBLLDB_LOG_MMAP;
else if (0 == ::strcasecmp(arg, "os")) flag_bits &= ~LIBLLDB_LOG_OS;
else if (0 == ::strcasecmp(arg, "jit")) flag_bits &= ~LIBLLDB_LOG_JIT_LOADER;
else
{
feedback_strm->Printf ("error: unrecognized log category '%s'\n", arg);
ListLogCategories (feedback_strm);
return;
}
}
}
log->GetMask().Reset (flag_bits);
if (flag_bits == 0)
{
log->SetStream(lldb::StreamSP());
g_log_enabled = false;
}
}
return;
}
Log *
lldb_private::EnableLog (StreamSP &log_stream_sp, uint32_t log_options, const char **categories, Stream *feedback_strm)
{
// Try see if there already is a log - that way we can reuse its settings.
// We could reuse the log in toto, but we don't know that the stream is the same.
uint32_t flag_bits;
if (g_log)
flag_bits = g_log->GetMask().Get();
else
flag_bits = 0;
// Now make a new log with this stream if one was provided
if (log_stream_sp)
{
if (g_log)
g_log->SetStream(log_stream_sp);
else
g_log = new Log(log_stream_sp);
}
if (g_log)
{
for (size_t i=0; categories[i] != NULL; ++i)
{
const char *arg = categories[i];
if (0 == ::strcasecmp(arg, "all")) flag_bits |= LIBLLDB_LOG_ALL;
else if (0 == ::strcasecmp(arg, "api")) flag_bits |= LIBLLDB_LOG_API;
else if (0 == ::strncasecmp(arg, "break", 5)) flag_bits |= LIBLLDB_LOG_BREAKPOINTS;
else if (0 == ::strcasecmp(arg, "commands")) flag_bits |= LIBLLDB_LOG_COMMANDS;
else if (0 == ::strncasecmp(arg, "commu", 5)) flag_bits |= LIBLLDB_LOG_COMMUNICATION;
else if (0 == ::strncasecmp(arg, "conn", 4)) flag_bits |= LIBLLDB_LOG_CONNECTION;
else if (0 == ::strcasecmp(arg, "default")) flag_bits |= LIBLLDB_LOG_DEFAULT;
else if (0 == ::strcasecmp(arg, "dyld")) flag_bits |= LIBLLDB_LOG_DYNAMIC_LOADER;
else if (0 == ::strncasecmp(arg, "event", 5)) flag_bits |= LIBLLDB_LOG_EVENTS;
else if (0 == ::strncasecmp(arg, "expr", 4)) flag_bits |= LIBLLDB_LOG_EXPRESSIONS;
else if (0 == ::strncasecmp(arg, "host", 4)) flag_bits |= LIBLLDB_LOG_HOST;
else if (0 == ::strncasecmp(arg, "mmap", 4)) flag_bits |= LIBLLDB_LOG_MMAP;
else if (0 == ::strncasecmp(arg, "module", 6)) flag_bits |= LIBLLDB_LOG_MODULES;
else if (0 == ::strncasecmp(arg, "object", 6)) flag_bits |= LIBLLDB_LOG_OBJECT;
else if (0 == ::strcasecmp(arg, "os")) flag_bits |= LIBLLDB_LOG_OS;
else if (0 == ::strcasecmp(arg, "platform")) flag_bits |= LIBLLDB_LOG_PLATFORM;
else if (0 == ::strcasecmp(arg, "process")) flag_bits |= LIBLLDB_LOG_PROCESS;
else if (0 == ::strcasecmp(arg, "script")) flag_bits |= LIBLLDB_LOG_SCRIPT;
else if (0 == ::strcasecmp(arg, "state")) flag_bits |= LIBLLDB_LOG_STATE;
else if (0 == ::strcasecmp(arg, "step")) flag_bits |= LIBLLDB_LOG_STEP;
else if (0 == ::strncasecmp(arg, "symbol", 6)) flag_bits |= LIBLLDB_LOG_SYMBOLS;
else if (0 == ::strcasecmp(arg, "system-runtime")) flag_bits |= LIBLLDB_LOG_SYSTEM_RUNTIME;
else if (0 == ::strcasecmp(arg, "target")) flag_bits |= LIBLLDB_LOG_TARGET;
else if (0 == ::strncasecmp(arg, "temp", 4)) flag_bits |= LIBLLDB_LOG_TEMPORARY;
else if (0 == ::strcasecmp(arg, "thread")) flag_bits |= LIBLLDB_LOG_THREAD;
else if (0 == ::strncasecmp(arg, "types", 5)) flag_bits |= LIBLLDB_LOG_TYPES;
else if (0 == ::strncasecmp(arg, "unwind", 6)) flag_bits |= LIBLLDB_LOG_UNWIND;
else if (0 == ::strcasecmp(arg, "verbose")) flag_bits |= LIBLLDB_LOG_VERBOSE;
else if (0 == ::strncasecmp(arg, "watch", 5)) flag_bits |= LIBLLDB_LOG_WATCHPOINTS;
else if (0 == ::strcasecmp(arg, "jit")) flag_bits |= LIBLLDB_LOG_JIT_LOADER;
else
{
feedback_strm->Printf("error: unrecognized log category '%s'\n", arg);
ListLogCategories (feedback_strm);
return g_log;
}
}
g_log->GetMask().Reset(flag_bits);
g_log->GetOptions().Reset(log_options);
}
g_log_enabled = true;
return g_log;
}
void
lldb_private::ListLogCategories (Stream *strm)
{
strm->Printf("Logging categories for 'lldb':\n"
" all - turn on all available logging categories\n"
" api - enable logging of API calls and return values\n"
" break - log breakpoints\n"
" commands - log command argument parsing\n"
" communication - log communication activities\n"
" connection - log connection details\n"
" default - enable the default set of logging categories for liblldb\n"
" dyld - log shared library related activities\n"
" events - log broadcaster, listener and event queue activities\n"
" expr - log expressions\n"
" host - log host activities\n"
" jit - log JIT events in the target\n"
" mmap - log mmap related activities\n"
" module - log module activities such as when modules are created, detroyed, replaced, and more\n"
" object - log object construction/destruction for important objects\n"
" os - log OperatingSystem plugin related activities\n"
" platform - log platform events and activities\n"
" process - log process events and activities\n"
" script - log events about the script interpreter\n"
" state - log private and public process state changes\n"
" step - log step related activities\n"
" symbol - log symbol related issues and warnings\n"
" system-runtime - log system runtime events\n"
" target - log target events and activities\n"
" thread - log thread events and activities\n"
" types - log type system related activities\n"
" unwind - log stack unwind activities\n"
" verbose - enable verbose logging\n"
" watch - log watchpoint related activities\n");
}
<|endoftext|>
|
<commit_before><commit_msg>Implement dot and cross product<commit_after><|endoftext|>
|
<commit_before><commit_msg>Forgot aliasupdate patch<commit_after><|endoftext|>
|
<commit_before>// Copyright (C) 2011, Luis Pedro Coelho <luis@luispedro.org>
// License: MIT
#include <iostream>
#include <memory>
#include <cmath>
#include <cassert>
extern "C" {
#include <Python.h>
#include <numpy/ndarrayobject.h>
}
namespace {
template <typename T>
int perceptron(PyArrayObject* data_arr, const int* labels, PyArrayObject* weights_arr, double eta) {
const T* data = reinterpret_cast<T*>(PyArray_DATA(data_arr));
T* weights = reinterpret_cast<T*>(PyArray_DATA(weights_arr));
const int N0 = PyArray_DIM(data_arr, 0);
const int N1 = PyArray_DIM(data_arr, 1);
int nr_errors = 0;
for (int i = 0; i != N0; ++i, data += N1, ++labels) {
T val = weights[0];
for (int j = 0; j != N1; ++j) {
val += weights[j+1] * data[j];
}
int ell = (val > 0);
if (ell != *labels) {
int pm = (*labels ? +1 : -1);
++nr_errors;
T error = pm * eta * std::abs(pm-val);
weights[0] += error;
for (int j = 0; j != N1; ++j) {
weights[j+1] += error*data[j];
}
}
}
return nr_errors;
}
PyObject* py_perceptron(PyObject* self, PyObject* args) {
const char* errmsg = "Arguments were not what was expected for perceptron.\n"
"This is an internal function: Do not call directly unless you know exactly what you're doing.\n";
PyArrayObject* data;
PyArrayObject* labels;
PyArrayObject* weights;
double eta;
if (!PyArg_ParseTuple(args, "OOOd", &data, &labels, &weights, &eta)) {
PyErr_SetString(PyExc_RuntimeError,errmsg);
return 0;
}
if (!PyArray_Check(data) || !PyArray_ISCONTIGUOUS(data) ||
!PyArray_Check(weights) || !PyArray_ISCONTIGUOUS(weights) ||
!PyArray_Check(labels) || !PyArray_ISCONTIGUOUS(labels) || !PyArray_EquivTypenums(PyArray_TYPE(labels), NPY_INT) ||
PyArray_TYPE(data) != PyArray_TYPE(weights)||
PyArray_NDIM(data) != 2 || PyArray_NDIM(weights) != 1 || PyArray_DIM(data,1) + 1 != PyArray_DIM(weights,0)) {
PyErr_SetString(PyExc_RuntimeError,errmsg);
return 0;
}
int nr_errors;
if (PyArray_TYPE(data) == NPY_FLOAT) {
nr_errors = perceptron<float>(data, reinterpret_cast<const int*>(PyArray_DATA(labels)), weights, eta);
} else if (PyArray_TYPE(data) == NPY_DOUBLE) {
nr_errors = perceptron<double>(data, reinterpret_cast<const int*>(PyArray_DATA(labels)), weights, eta);
} else {
PyErr_SetString(PyExc_RuntimeError, errmsg);
return 0;
}
return PyLong_FromLong(nr_errors);
}
PyMethodDef methods[] = {
{"perceptron", py_perceptron, METH_VARARGS , "Do NOT call directly.\n" },
{NULL, NULL,0,NULL},
};
const char * module_doc =
"Internal Module.\n"
"\n"
"Do NOT use directly!\n";
} // namespace
extern "C"
void init_perceptron()
{
import_array();
(void)Py_InitModule3("_perceptron", methods, module_doc);
}
<commit_msg>BUG Fix perceptron for 64 bits<commit_after>// Copyright (C) 2011, Luis Pedro Coelho <luis@luispedro.org>
// License: MIT
#include <iostream>
#include <memory>
#include <cmath>
#include <cassert>
extern "C" {
#include <Python.h>
#include <numpy/ndarrayobject.h>
}
namespace {
template <typename T>
int perceptron(PyArrayObject* data_arr, const long* labels, PyArrayObject* weights_arr, double eta) {
const T* data = reinterpret_cast<T*>(PyArray_DATA(data_arr));
T* weights = reinterpret_cast<T*>(PyArray_DATA(weights_arr));
const int N0 = PyArray_DIM(data_arr, 0);
const int N1 = PyArray_DIM(data_arr, 1);
int nr_errors = 0;
for (int i = 0; i != N0; ++i, data += N1, ++labels) {
T val = weights[0];
for (int j = 0; j != N1; ++j) {
val += weights[j+1] * data[j];
}
int ell = (val > 0);
if (ell != *labels) {
int pm = (*labels ? +1 : -1);
++nr_errors;
T error = pm * eta * std::abs(pm-val);
weights[0] += error;
for (int j = 0; j != N1; ++j) {
weights[j+1] += error*data[j];
}
}
}
return nr_errors;
}
PyObject* py_perceptron(PyObject* self, PyObject* args) {
const char* errmsg = "Arguments were not what was expected for perceptron.\n"
"This is an internal function: Do not call directly unless you know exactly what you're doing.\n";
PyArrayObject* data;
PyArrayObject* labels;
PyArrayObject* weights;
double eta;
if (!PyArg_ParseTuple(args, "OOOd", &data, &labels, &weights, &eta)) {
PyErr_SetString(PyExc_RuntimeError,errmsg);
return 0;
}
if (!PyArray_Check(data) || !PyArray_ISCONTIGUOUS(data) ||
!PyArray_Check(weights) || !PyArray_ISCONTIGUOUS(weights) ||
!PyArray_Check(labels) || !PyArray_ISCONTIGUOUS(labels) || !PyArray_EquivTypenums(PyArray_TYPE(labels), NPY_LONG) ||
PyArray_TYPE(data) != PyArray_TYPE(weights)||
PyArray_NDIM(data) != 2 || PyArray_NDIM(weights) != 1 || PyArray_DIM(data,1) + 1 != PyArray_DIM(weights,0)) {
PyErr_SetString(PyExc_RuntimeError,errmsg);
return 0;
}
int nr_errors;
if (PyArray_TYPE(data) == NPY_FLOAT) {
nr_errors = perceptron<float>(data, reinterpret_cast<const long*>(PyArray_DATA(labels)), weights, eta);
} else if (PyArray_TYPE(data) == NPY_DOUBLE) {
nr_errors = perceptron<double>(data, reinterpret_cast<const long*>(PyArray_DATA(labels)), weights, eta);
} else {
PyErr_SetString(PyExc_RuntimeError, errmsg);
return 0;
}
return PyLong_FromLong(nr_errors);
}
PyMethodDef methods[] = {
{"perceptron", py_perceptron, METH_VARARGS , "Do NOT call directly.\n" },
{NULL, NULL,0,NULL},
};
const char * module_doc =
"Internal Module.\n"
"\n"
"Do NOT use directly!\n";
} // namespace
extern "C"
void init_perceptron()
{
import_array();
(void)Py_InitModule3("_perceptron", methods, module_doc);
}
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include "../physics/vec2.h"
namespace test_vec2 {
SCENARIO( "assignment" ) {
GIVEN("empty vector") {
vec2 v;
REQUIRE(v.x() == 0);
REQUIRE(v.y() == 0);
WHEN("assign x") {
v.x(8);
THEN("only x changed") {
REQUIRE(v.x() > 0);
REQUIRE(v.x() == Approx(8));
REQUIRE(v.y() == Approx(0));
}
}
WHEN("assign y") {
v.y(-2.1);
THEN("only y changed") {
REQUIRE(v.y() < 0);
REQUIRE(v.y() == Approx(-2.1));
REQUIRE(v.x() == Approx(0));
}
}
WHEN("assign to another vector") {
const vec2 v2{5,6};
v = v2;
THEN("both coordinates changed") {
REQUIRE(v.x() == Approx(v2.x()));
REQUIRE(v.y() == Approx(v2.y()));
}
}
}
GIVEN("vector copy constructed from another ") {
const vec2 v2(7, 8);
vec2 v(v2);
SECTION("both coordinates are equal to another ones") {
REQUIRE(v.x() == Approx(v2.x()));
REQUIRE(v.y() == Approx(v2.y()));
}
}
}
SCENARIO("length") {
GIVEN("default constructed vector") {
vec2 v{};
SECTION("length is 0")
REQUIRE(v.length() == 0);
}
GIVEN("some vector") {
vec2 v1{1,0}, v2{0,1}, v3{3,4};
SECTION("length is present") {
REQUIRE(v1.length() == Approx(1));
REQUIRE(v2.length() == Approx(1));
REQUIRE(v3.length() == Approx(5));
}
}
}
SCENARIO("from two points") {
GIVEN("2 zero vectors") {
vec2 a{}, b{};
SECTION("result is zero") {
auto r = vec2::from_two_points(a,b);
REQUIRE(r.x() == Approx(0));
REQUIRE(r.y() == Approx(0));
}
}
GIVEN("2 same vectors") {
vec2 a{10,12}, b{a};
SECTION("result is zero") {
auto r = vec2::from_two_points(a,b);
REQUIRE(r.x() == Approx(0));
REQUIRE(r.y() == Approx(0));
}
}
GIVEN("zero and some vectors") {
vec2 a{0,0}, b{3,5};
SECTION("result is second") {
auto r = vec2::from_two_points(a,b);
REQUIRE(r.x() == Approx(b.x()));
REQUIRE(r.y() == Approx(b.y()));
}
SECTION("backwards is -second") {
auto r = vec2::from_two_points(b,a);
REQUIRE(r.x() == Approx(-b.x()));
REQUIRE(r.y() == Approx(-b.y()));
}
}
}
}
<commit_msg>test: operators for vec2 comparsion and print<commit_after>#include <catch.hpp>
#include "../physics/vec2.h"
bool operator==(const vec2& lhs, const vec2 &rhs) {
return lhs.x() == Approx(rhs.x())
&& lhs.y() == Approx(rhs.y());
}
std::ostream& operator<<(std::ostream& s, const vec2 &v) {
return s << "vec2{" << v.x() << " , " << v.y() << "}";
}
namespace test_vec2 {
SCENARIO( "assignment" ) {
GIVEN("empty vector") {
vec2 v;
REQUIRE(v.x() == 0);
REQUIRE(v.y() == 0);
WHEN("assign x") {
v.x(8);
THEN("only x changed") {
REQUIRE(v.x() > 0);
REQUIRE(v.x() == Approx(8));
REQUIRE(v.y() == Approx(0));
}
}
WHEN("assign y") {
v.y(-2.1);
THEN("only y changed") {
REQUIRE(v.y() < 0);
REQUIRE(v.y() == Approx(-2.1));
REQUIRE(v.x() == Approx(0));
}
}
WHEN("assign to another vector") {
const vec2 v2{5,6};
v = v2;
THEN("both coordinates changed") {
REQUIRE(v.x() == Approx(v2.x()));
REQUIRE(v.y() == Approx(v2.y()));
}
}
}
GIVEN("vector copy constructed from another ") {
const vec2 v2(7, 8);
vec2 v(v2);
SECTION("both coordinates are equal to another ones") {
REQUIRE(v.x() == Approx(v2.x()));
REQUIRE(v.y() == Approx(v2.y()));
}
}
}
SCENARIO("length") {
GIVEN("default constructed vector") {
vec2 v{};
SECTION("length is 0")
REQUIRE(v.length() == 0);
}
GIVEN("some vector") {
vec2 v1{1,0}, v2{0,1}, v3{3,4};
SECTION("length is present") {
REQUIRE(v1.length() == Approx(1));
REQUIRE(v2.length() == Approx(1));
REQUIRE(v3.length() == Approx(5));
}
}
}
SCENARIO("from two points") {
GIVEN("2 zero vectors") {
vec2 a{}, b{};
SECTION("result is zero") {
auto r = vec2::from_two_points(a,b);
REQUIRE(r.x() == Approx(0));
REQUIRE(r.y() == Approx(0));
}
}
GIVEN("2 same vectors") {
vec2 a{10,12}, b{a};
SECTION("result is zero") {
auto r = vec2::from_two_points(a,b);
REQUIRE(r.x() == Approx(0));
REQUIRE(r.y() == Approx(0));
}
}
GIVEN("zero and some vectors") {
vec2 a{0,0}, b{3,5};
SECTION("result is second") {
auto r = vec2::from_two_points(a,b);
REQUIRE(r.x() == Approx(b.x()));
REQUIRE(r.y() == Approx(b.y()));
}
SECTION("backwards is -second") {
auto r = vec2::from_two_points(b,a);
REQUIRE(r.x() == Approx(-b.x()));
REQUIRE(r.y() == Approx(-b.y()));
}
}
}
}
<|endoftext|>
|
<commit_before>#include <common/log.h>
#include <common/pty.h>
#include <common/string.h>
#include <common/file.h>
#include <common/list.h>
#include <gui/gui.h>
#include <gdb/gdb.h>
#include <gdb/frame.h>
#include <gdb/parser.tab.h>
#include <user_cmd/cmd.hash.h>
#include <user_cmd/subcmd.hash.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <math.h>
#include <unistd.h>
/* class definition */
/**
* \brief standard constructor
*/
gdbif::gdbif(){
main_tid = 0;
read_tid = 0;
gdb = 0;
token = 1;
is_running = false;
event_lst = 0;
stop_hdlr = 0;
pthread_mutex_init(&resp_mtx, 0);
pthread_mutex_init(&event_mtx, 0);
pthread_cond_init(&resp_avail, 0);
pthread_cond_init(&event_avail, 0);
}
/**
* \brief standard desctructor
*/
gdbif::~gdbif(){
// close gdb terminal
delete this->gdb;
this->gdb = 0;
if(read_tid != 0){
pthread_cancel(read_tid);
pthread_join(read_tid, 0);
}
if(event_tid != 0){
pthread_cancel(event_tid);
pthread_join(event_tid, 0);
}
pthread_cond_destroy(&resp_avail);
pthread_cond_destroy(&event_avail);
pthread_mutex_destroy(&resp_mtx);
pthread_mutex_destroy(&event_mtx);
}
/**
* \brief exec gdb and initialise its controlling terminal
*
* \return 0 on success
* -1 on error (check errno)
*/
int gdbif::init(pthread_t main_tid){
this->main_tid = main_tid;
// initialise pseudo terminal
this->gdb = new pty();
// fork child process
gdb_pid = gdb->fork();
if(gdb_pid == 0){
/* child */
log::cleanup();
return execl(GDB_CMD, GDB_CMD, GDB_ARGS, (char*)0);
}
else if(gdb_pid > 0){
/* parent */
if(pthread_create(&read_tid, 0, readline_thread, this) != 0)
return -1;
thread_name[read_tid] = "gdb-readline";
if(pthread_create(&event_tid, 0, event_thread, this) != 0)
return -1;
thread_name[event_tid] = "gdb-event";
return 0;
}
else{
/* error */
return -1;
}
}
void gdbif::on_stop(int (*hdlr)(gdbif*)){
stop_hdlr_t* e;
e = new stop_hdlr_t;
e->hdlr = hdlr;
list_add_tail(&stop_hdlr, e);
}
/**
* \brief create gdb machine interface (MI) command
*
* \param cmd target command
* \param fmt printf-like format string, describing the following parameters
* supported identifiers:
* '%d' integer
* '%s' string
* '%ss %d' array of strings, length is defined by the
* following integer
* '--' separator between options and parameters
* . everything else except blanks is printed literaly
*
* \param ... parameters according to param_fmt
*
* \return >0 token used for the command
* -1 error
*/
int gdbif::mi_issue_cmd(char* cmd, gdb_result_class_t ok_mask, int(*process)(gdb_result_t*, void**), void** r, const char* fmt, ...){
static char* volatile s = 0;
static unsigned int volatile s_len = 0;
unsigned int i, j, argc;
char** argv;
va_list lst;
va_start(lst, fmt);
gdb->write(itoa(token, (char**)&s, (unsigned int*)&s_len));
gdb->write((char*)"-");
gdb->write(cmd);
if(*fmt != 0)
gdb->write((char*)" ");
for(i=0; i<strlen(fmt); i++){
switch(fmt[i]){
case '%':
switch(fmt[i + 1]){
case 'd':
gdb->write(itoa(va_arg(lst, int), (char**)&s, (unsigned int*)&s_len));
i++;
break;
case 's':
if(strncmp(fmt + i + 2, "s %d", 4) == 0){
argv = va_arg(lst, char**);
argc = va_arg(lst, int);
for(j=0; j<argc; j++)
gdb->write(argv[j]);
i += 4;
}
else
gdb->write(va_arg(lst, char*));
i++;
break;
default:
ERROR("invalid format sequence %%%c\n", fmt[i + 1]);
va_end(lst);
return -1;
};
break;
default:
gdb->write((void*)(fmt + i), 1);
break;
};
}
/* wait for gdb response */
pthread_mutex_lock(&resp_mtx);
memset((void*)&resp, 0x0, sizeof(response_t));
gdb->write((char*)"\n"); // ensure that response cannot arrive
// before it is expected
pthread_cond_wait(&resp_avail, &resp_mtx);
token++;
if((resp.rclass & ok_mask)){
if(resp.result && r && process){
if(process(resp.result, r) != 0){
ERROR("unable to process result for \"%s\"\n", cmd);
resp.rclass = RC_ERROR;
}
}
}
else
USER("gdb-error %s: \"%s\"\n", cmd, resp.result->value->value);
gdb_result_free(resp.result);
pthread_mutex_unlock(&resp_mtx);
va_end(lst);
if(resp.rclass & ok_mask)
return 0;
return -1;
}
int gdbif::mi_proc_result(gdb_result_class_t rclass, unsigned int token, gdb_result_t* result){
pthread_mutex_lock(&resp_mtx);
if(this->token != token)
ERROR("result token (%d) doesn't match issued token (%d)\n", token, this->token);
resp.result = result;
resp.rclass = rclass;
pthread_cond_signal(&resp_avail);
pthread_mutex_unlock(&resp_mtx);
return 0;
}
int gdbif::mi_proc_async(gdb_result_class_t rclass, unsigned int token, gdb_result_t* result){
int r;
response_t* e;
pthread_mutex_lock(&event_mtx);
switch(rclass){
case RC_STOPPED:
case RC_RUNNING:
e = new response_t;
e->rclass = rclass;
e->result = result;
list_add_tail(&event_lst, e);
pthread_cond_signal(&event_avail);
break;
default:
GDB("unhandled gdb-event %d\n", rclass);
gdb_result_free(result);
};
pthread_mutex_unlock(&event_mtx);
return 0;
}
int gdbif::mi_proc_stream(gdb_stream_class_t sclass, char* stream){
USER("%s", strdeescape(stream)); // use "%s" to avoid issues with '%' within stream
return 0;
}
/**
* \brief read from gdb terminal
*
* \param buf target buffer
* \param nbytes max bytes to read
*
* \return number of read bytes on success
* -1 on error
*/
int gdbif::read(void* buf, unsigned int nbytes){
return gdb->read(buf, nbytes);
}
/**
* \brief write to gdb terminal
*
* \param buf source buffer
* \param nbytes number of bytes to write
*
* \return number of written bytes on success
* -1 on error
*/
int gdbif::write(void* buf, unsigned int nbytes){
return gdb->write(buf, nbytes);
}
int gdbif::sigsend(int sig){
sigval v;
return sigqueue(gdb_pid, sig, v);
}
bool gdbif::running(){
return is_running;
}
bool gdbif::running(bool state){
return (is_running = state);
}
void* gdbif::readline_thread(void* arg){
char c, *line;
unsigned int i, len;
gdbif* gdb;
sigval v;
i = 0;
gdb = (gdbif*)arg;
len = 255;
line = (char*)malloc(len * sizeof(char));
if(line == 0)
goto err_0;
#ifdef GUI_CURSES
if(ui->win_create("gdb-log", true, 0) < 0)
goto err_1;
#endif // GUI_CURSES
while(1){
if(gdb->read(&c, 1) == 1){
// ignore CR to avoid issues when printing the string
if(c == '\r')
continue;
line[i++] = c;
if(i >= len){
len *= 2;
line = (char*)realloc(line, len);
if(line == 0)
goto err_2;
}
// check for end of gdb line, a simple newline as separator
// doesn't work, since the parse would try to parse the line,
// detecting a syntax error
if(strncmp(line + i - 6, "(gdb)\n", 6) == 0 ||
strncmp(line + i - 7, "(gdb) \n", 7) == 0
){
line[i] = 0;
GDB("parse gdb string \"%.10s\"\n", line);
ui->win_print(ui->win_getid("gdb-log"), "%s", line); // use "%s" to avoid issues with '%' within line
i = gdbparse(line, gdb);
GDB("parser return value: %d\n", i);
ui->win_print(ui->win_getid("gdb-log"), "parser return value: %d\n", i);
i = 0;
}
}
else{
DEBUG("gdb read shutdown\n");
break;
}
}
ui->win_destroy(ui->win_getid("gdb-log"));
free(line);
err_2:
#ifdef GUI_CURSES
ui->win_destroy(ui->win_getid("gdb-log"));
err_1:
free(line);
#endif // GUI_CURSES
err_0:
pthread_sigqueue(gdb->main_tid, SIGTERM, v);
pthread_exit(0);
}
void* gdbif::event_thread(void* arg){
int r;
gdbif* gdb;
response_t* e;
gdb = (gdbif*)arg;
while(1){
pthread_mutex_lock(&gdb->event_mtx);
if(list_empty(gdb->event_lst))
pthread_cond_wait(&gdb->event_avail, &gdb->event_mtx);
e = list_first(gdb->event_lst);
list_rm(&gdb->event_lst, e);
pthread_mutex_unlock(&gdb->event_mtx);
switch(e->rclass){
case RC_STOPPED:
GDB("handle event STOPPED\n");
r = gdb->evt_stopped(e->result);
break;
case RC_RUNNING:
GDB("handle event RUNNING\n");
r = gdb->evt_running(e->result);
break;
default:
r = -1;
};
if(r != 0)
ERROR("error handling gdb-event %d\n", e->rclass);
gdb_result_free(e->result);
delete e;
}
}
int gdbif::evt_running(gdb_result_t* result){
running(true);
return 0;
}
int gdbif::evt_stopped(gdb_result_t* result){
char* reason;
gdb_result_t* r;
gdb_frame_t* frame;
stop_hdlr_t* e;
reason = 0;
frame = 0;
running(false);
/* parse result */
list_for_each(result, r){
switch(r->var_id){
case IDV_REASON:
reason = (char*)r->value->value;
break;
case IDV_FRAME:
conv_frame((gdb_result_t*)r->value->value, &frame);
break;
default:
break;
};
}
if(reason == 0)
goto err;
/* check reason */
if(reason != 0 && frame != 0){
if(FILE_EXISTS(frame->fullname)){
ui->win_anno_add(ui->win_create(frame->fullname), frame->line, "ip", "White", "Black");
ui->win_cursor_set(ui->win_create(frame->fullname), frame->line);
}
else
USER("file \"%s\" does not exist\n", frame->fullname);
}
else if(strcmp(reason, "exited-normally") == 0){
USER("program exited\n");
}
/* execute callbacks */
list_for_each(stop_hdlr, e){
if(e->hdlr(this) != 0)
USER("error executing on-stop handler\n");
}
delete frame;
return 0;
err:
delete frame;
return -1;
}
<commit_msg>[gdb: destructor]<commit_after>#include <common/log.h>
#include <common/pty.h>
#include <common/string.h>
#include <common/file.h>
#include <common/list.h>
#include <gui/gui.h>
#include <gdb/gdb.h>
#include <gdb/frame.h>
#include <gdb/parser.tab.h>
#include <user_cmd/cmd.hash.h>
#include <user_cmd/subcmd.hash.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <math.h>
#include <unistd.h>
/* class definition */
/**
* \brief standard constructor
*/
gdbif::gdbif(){
main_tid = 0;
read_tid = 0;
gdb = 0;
token = 1;
is_running = false;
event_lst = 0;
stop_hdlr = 0;
pthread_mutex_init(&resp_mtx, 0);
pthread_mutex_init(&event_mtx, 0);
pthread_cond_init(&resp_avail, 0);
pthread_cond_init(&event_avail, 0);
}
/**
* \brief standard desctructor
*/
gdbif::~gdbif(){
// close gdb terminal
delete this->gdb;
if(read_tid != 0)
pthread_join(read_tid, 0);
if(event_tid != 0){
pthread_cancel(event_tid);
pthread_join(event_tid, 0);
}
pthread_cond_destroy(&resp_avail);
pthread_cond_destroy(&event_avail);
pthread_mutex_destroy(&resp_mtx);
pthread_mutex_destroy(&event_mtx);
}
/**
* \brief exec gdb and initialise its controlling terminal
*
* \return 0 on success
* -1 on error (check errno)
*/
int gdbif::init(pthread_t main_tid){
this->main_tid = main_tid;
// initialise pseudo terminal
this->gdb = new pty();
// fork child process
gdb_pid = gdb->fork();
if(gdb_pid == 0){
/* child */
log::cleanup();
return execl(GDB_CMD, GDB_CMD, GDB_ARGS, (char*)0);
}
else if(gdb_pid > 0){
/* parent */
if(pthread_create(&read_tid, 0, readline_thread, this) != 0)
return -1;
thread_name[read_tid] = "gdb-readline";
if(pthread_create(&event_tid, 0, event_thread, this) != 0)
return -1;
thread_name[event_tid] = "gdb-event";
return 0;
}
else{
/* error */
return -1;
}
}
void gdbif::on_stop(int (*hdlr)(gdbif*)){
stop_hdlr_t* e;
e = new stop_hdlr_t;
e->hdlr = hdlr;
list_add_tail(&stop_hdlr, e);
}
/**
* \brief create gdb machine interface (MI) command
*
* \param cmd target command
* \param fmt printf-like format string, describing the following parameters
* supported identifiers:
* '%d' integer
* '%s' string
* '%ss %d' array of strings, length is defined by the
* following integer
* '--' separator between options and parameters
* . everything else except blanks is printed literaly
*
* \param ... parameters according to param_fmt
*
* \return >0 token used for the command
* -1 error
*/
int gdbif::mi_issue_cmd(char* cmd, gdb_result_class_t ok_mask, int(*process)(gdb_result_t*, void**), void** r, const char* fmt, ...){
static char* volatile s = 0;
static unsigned int volatile s_len = 0;
unsigned int i, j, argc;
char** argv;
va_list lst;
va_start(lst, fmt);
gdb->write(itoa(token, (char**)&s, (unsigned int*)&s_len));
gdb->write((char*)"-");
gdb->write(cmd);
if(*fmt != 0)
gdb->write((char*)" ");
for(i=0; i<strlen(fmt); i++){
switch(fmt[i]){
case '%':
switch(fmt[i + 1]){
case 'd':
gdb->write(itoa(va_arg(lst, int), (char**)&s, (unsigned int*)&s_len));
i++;
break;
case 's':
if(strncmp(fmt + i + 2, "s %d", 4) == 0){
argv = va_arg(lst, char**);
argc = va_arg(lst, int);
for(j=0; j<argc; j++)
gdb->write(argv[j]);
i += 4;
}
else
gdb->write(va_arg(lst, char*));
i++;
break;
default:
ERROR("invalid format sequence %%%c\n", fmt[i + 1]);
va_end(lst);
return -1;
};
break;
default:
gdb->write((void*)(fmt + i), 1);
break;
};
}
/* wait for gdb response */
pthread_mutex_lock(&resp_mtx);
memset((void*)&resp, 0x0, sizeof(response_t));
gdb->write((char*)"\n"); // ensure that response cannot arrive
// before it is expected
pthread_cond_wait(&resp_avail, &resp_mtx);
token++;
if((resp.rclass & ok_mask)){
if(resp.result && r && process){
if(process(resp.result, r) != 0){
ERROR("unable to process result for \"%s\"\n", cmd);
resp.rclass = RC_ERROR;
}
}
}
else
USER("gdb-error %s: \"%s\"\n", cmd, resp.result->value->value);
gdb_result_free(resp.result);
pthread_mutex_unlock(&resp_mtx);
va_end(lst);
if(resp.rclass & ok_mask)
return 0;
return -1;
}
int gdbif::mi_proc_result(gdb_result_class_t rclass, unsigned int token, gdb_result_t* result){
pthread_mutex_lock(&resp_mtx);
if(this->token != token)
ERROR("result token (%d) doesn't match issued token (%d)\n", token, this->token);
resp.result = result;
resp.rclass = rclass;
pthread_cond_signal(&resp_avail);
pthread_mutex_unlock(&resp_mtx);
return 0;
}
int gdbif::mi_proc_async(gdb_result_class_t rclass, unsigned int token, gdb_result_t* result){
int r;
response_t* e;
pthread_mutex_lock(&event_mtx);
switch(rclass){
case RC_STOPPED:
case RC_RUNNING:
e = new response_t;
e->rclass = rclass;
e->result = result;
list_add_tail(&event_lst, e);
pthread_cond_signal(&event_avail);
break;
default:
GDB("unhandled gdb-event %d\n", rclass);
gdb_result_free(result);
};
pthread_mutex_unlock(&event_mtx);
return 0;
}
int gdbif::mi_proc_stream(gdb_stream_class_t sclass, char* stream){
USER("%s", strdeescape(stream)); // use "%s" to avoid issues with '%' within stream
return 0;
}
/**
* \brief read from gdb terminal
*
* \param buf target buffer
* \param nbytes max bytes to read
*
* \return number of read bytes on success
* -1 on error
*/
int gdbif::read(void* buf, unsigned int nbytes){
return gdb->read(buf, nbytes);
}
/**
* \brief write to gdb terminal
*
* \param buf source buffer
* \param nbytes number of bytes to write
*
* \return number of written bytes on success
* -1 on error
*/
int gdbif::write(void* buf, unsigned int nbytes){
return gdb->write(buf, nbytes);
}
int gdbif::sigsend(int sig){
sigval v;
return sigqueue(gdb_pid, sig, v);
}
bool gdbif::running(){
return is_running;
}
bool gdbif::running(bool state){
return (is_running = state);
}
void* gdbif::readline_thread(void* arg){
char c, *line;
unsigned int i, len;
gdbif* gdb;
sigval v;
i = 0;
gdb = (gdbif*)arg;
len = 255;
line = (char*)malloc(len * sizeof(char));
if(line == 0)
goto err_0;
#ifdef GUI_CURSES
if(ui->win_create("gdb-log", true, 0) < 0)
goto err_1;
#endif // GUI_CURSES
while(1){
if(gdb->read(&c, 1) == 1){
// ignore CR to avoid issues when printing the string
if(c == '\r')
continue;
line[i++] = c;
if(i >= len){
len *= 2;
line = (char*)realloc(line, len);
if(line == 0)
goto err_2;
}
// check for end of gdb line, a simple newline as separator
// doesn't work, since the parse would try to parse the line,
// detecting a syntax error
if(strncmp(line + i - 6, "(gdb)\n", 6) == 0 ||
strncmp(line + i - 7, "(gdb) \n", 7) == 0
){
line[i] = 0;
GDB("parse gdb string \"%.10s\"\n", line);
ui->win_print(ui->win_getid("gdb-log"), "%s", line); // use "%s" to avoid issues with '%' within line
i = gdbparse(line, gdb);
GDB("parser return value: %d\n", i);
ui->win_print(ui->win_getid("gdb-log"), "parser return value: %d\n", i);
i = 0;
}
}
else{
DEBUG("gdb read shutdown\n");
break;
}
}
err_2:
ui->win_destroy(ui->win_getid("gdb-log"));
err_1:
free(line);
err_0:
pthread_sigqueue(gdb->main_tid, SIGTERM, v);
pthread_exit(0);
}
void* gdbif::event_thread(void* arg){
int r;
gdbif* gdb;
response_t* e;
gdb = (gdbif*)arg;
while(1){
pthread_mutex_lock(&gdb->event_mtx);
if(list_empty(gdb->event_lst))
pthread_cond_wait(&gdb->event_avail, &gdb->event_mtx);
e = list_first(gdb->event_lst);
list_rm(&gdb->event_lst, e);
pthread_mutex_unlock(&gdb->event_mtx);
switch(e->rclass){
case RC_STOPPED:
GDB("handle event STOPPED\n");
r = gdb->evt_stopped(e->result);
break;
case RC_RUNNING:
GDB("handle event RUNNING\n");
r = gdb->evt_running(e->result);
break;
default:
r = -1;
};
if(r != 0)
ERROR("error handling gdb-event %d\n", e->rclass);
gdb_result_free(e->result);
delete e;
}
}
int gdbif::evt_running(gdb_result_t* result){
running(true);
return 0;
}
int gdbif::evt_stopped(gdb_result_t* result){
char* reason;
gdb_result_t* r;
gdb_frame_t* frame;
stop_hdlr_t* e;
reason = 0;
frame = 0;
running(false);
/* parse result */
list_for_each(result, r){
switch(r->var_id){
case IDV_REASON:
reason = (char*)r->value->value;
break;
case IDV_FRAME:
conv_frame((gdb_result_t*)r->value->value, &frame);
break;
default:
break;
};
}
if(reason == 0)
goto err;
/* check reason */
if(reason != 0 && frame != 0){
if(FILE_EXISTS(frame->fullname)){
ui->win_anno_add(ui->win_create(frame->fullname), frame->line, "ip", "White", "Black");
ui->win_cursor_set(ui->win_create(frame->fullname), frame->line);
}
else
USER("file \"%s\" does not exist\n", frame->fullname);
}
else if(strcmp(reason, "exited-normally") == 0){
USER("program exited\n");
}
/* execute callbacks */
list_for_each(stop_hdlr, e){
if(e->hdlr(this) != 0)
USER("error executing on-stop handler\n");
}
delete frame;
return 0;
err:
delete frame;
return -1;
}
<|endoftext|>
|
<commit_before>#include "PointLocation.h"
#include <math/random.h>
#include <set>
using namespace std;
PointLocationBase::PointLocationBase(vector<Vector>& _points)
:points(_points)
{}
NaivePointLocation::NaivePointLocation(vector<Vector>& points,CSpace* _space)
:PointLocationBase(points),space(_space)
{}
bool NaivePointLocation::NN(const Vector& p,int& nn,Real& distance)
{
nn = -1;
distance = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < distance) {
nn = (int)i;
distance = d;
}
}
return true;
}
bool NaivePointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d > 0 && d < dmax) {
pair<Real,int> idx(d,i);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
bool NaivePointLocation::Close(const Vector& p,Real r,std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(0);
distances.resize(0);
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < r) {
nn.push_back((int)i);
distances.push_back(d);
}
}
return true;
}
bool NaivePointLocation::FilteredNN(const Vector& p,bool (*filter)(int),int& nn,Real& distance)
{
nn = -1;
distance = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < distance && filter((int)i)) {
nn = (int)i;
distance = d;
}
}
return true;
}
bool NaivePointLocation::FilteredKNN(const Vector& p,int k,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d > 0 && d < dmax && filter((int)i)) {
pair<Real,int> idx(d,i);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
bool NaivePointLocation::FilteredClose(const Vector& p,Real r,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(0);
distances.resize(0);
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < r && filter((int)i)) {
nn.push_back((int)i);
distances.push_back(d);
}
}
return true;
}
RandomPointLocation::RandomPointLocation(vector<Vector>& points)
:PointLocationBase(points)
{}
bool RandomPointLocation::NN(const Vector& p,int& nn,Real& distance)
{
nn = RandInt(points.size());
distance = 0;
return true;
}
bool RandomPointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(k);
distances.resize(k);
for(int i=0;i<k;i++) {
nn[i] = RandInt(points.size());
distances[i] = 0;
}
return true;
}
bool RandomPointLocation::FilteredNN(const Vector& p,bool (*filter)(int),int& nn,Real& distance)
{
distance = 0;
while(true) {
nn = RandInt(points.size());
if(filter(nn)) return true;
}
return false;
}
bool RandomPointLocation::FilteredKNN(const Vector& p,int k,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(k);
distances.resize(k);
for(int i=0;i<k;i++) {
while(true) {
nn[i] = RandInt(points.size());
if(filter(nn[i])) break;
}
distances[i] = 0;
}
return true;
}
RandomBestPointLocation::RandomBestPointLocation(vector<Vector>& points,CSpace* _space,int _k)
:PointLocationBase(points),space(_space),k(_k)
{}
bool RandomBestPointLocation::NN(const Vector& p,int& nn,Real& distance)
{
distance = Inf;
nn = -1;
for(int i=0;i<k;i++) {
int n = RandInt(points.size());
Real d = space->Distance(points[n],p);
if(d < distance) {
nn = n;
distance = d;
}
}
return true;
}
bool RandomBestPointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
int count = k*this->k;
for(int i=0;i<count;i++) {
int n = RandInt(points.size());
Real d=space->Distance(points[n],p);
if(d > 0 && d < dmax) {
pair<Real,int> idx(d,n);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
bool RandomBestPointLocation::FilteredNN(const Vector& p,bool (*filter)(int),int& nn,Real& distance)
{
distance = Inf;
nn = -1;
for(int i=0;i<k;i++) {
int n = RandInt(points.size());
Real d = space->Distance(points[n],p);
if(d < distance && filter(i)) {
nn = n;
distance = d;
}
}
return true;
}
bool RandomBestPointLocation::FilteredKNN(const Vector& p,int k,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
int count = k*this->k;
for(int i=0;i<count;i++) {
int n = RandInt(points.size());
Real d=space->Distance(points[n],p);
if(d > 0 && d < dmax && filter(n)) {
pair<Real,int> idx(d,n);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
KDTreePointLocation::KDTreePointLocation(vector<Vector>& points)
:PointLocationBase(points),norm(2.0)
{}
KDTreePointLocation::KDTreePointLocation(vector<Vector>& points,Real _norm,const Vector& _weights)
:PointLocationBase(points),norm(_norm),weights(_weights)
{}
void KDTreePointLocation::OnAppend()
{
int id=(int)points.size()-1;
tree.Insert(points.back(),id);
/*
if(points.size() % 100 == 0)
printf("K-D Tree size %d, depth %d\n",tree.TreeSize(),tree.MaxDepth());
*/
}
bool KDTreePointLocation::OnClear()
{
tree.Clear();
return true;
}
bool KDTreePointLocation::NN(const Vector& p,int& nn,Real& distance)
{
nn = tree.ClosestPoint(p,distance);
return true;
}
bool KDTreePointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(k);
distances.resize(k);
tree.KClosestPoints(p,k,norm,weights,&distances[0],&nn[0]);
//may have fewer than k points
for(size_t i=0;i<nn.size();i++)
if(nn[i] < 0) {
nn.resize(i);
distances.resize(i);
break;
}
vector<pair<Real,int> > items(nn.size());
for(size_t i=0;i<nn.size();i++)
items[i] = pair<Real,int>(distances[i],nn[i]);
sort(items.begin(),items.end());
for(size_t i=0;i<nn.size();i++) {
nn[i] = items[i].second;
distances[i] = items[i].first;
}
return true;
}
bool KDTreePointLocation::Close(const Vector& p,Real r,std::vector<int>& nn,std::vector<Real>& distances)
{
tree.ClosePoints(p,r,norm,weights,distances,nn);
return true;
}
<commit_msg>Added include for Windows STL<commit_after>#include "PointLocation.h"
#include <math/random.h>
#include <set>
#include <algorithm>
using namespace std;
PointLocationBase::PointLocationBase(vector<Vector>& _points)
:points(_points)
{}
NaivePointLocation::NaivePointLocation(vector<Vector>& points,CSpace* _space)
:PointLocationBase(points),space(_space)
{}
bool NaivePointLocation::NN(const Vector& p,int& nn,Real& distance)
{
nn = -1;
distance = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < distance) {
nn = (int)i;
distance = d;
}
}
return true;
}
bool NaivePointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d > 0 && d < dmax) {
pair<Real,int> idx(d,i);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
bool NaivePointLocation::Close(const Vector& p,Real r,std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(0);
distances.resize(0);
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < r) {
nn.push_back((int)i);
distances.push_back(d);
}
}
return true;
}
bool NaivePointLocation::FilteredNN(const Vector& p,bool (*filter)(int),int& nn,Real& distance)
{
nn = -1;
distance = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < distance && filter((int)i)) {
nn = (int)i;
distance = d;
}
}
return true;
}
bool NaivePointLocation::FilteredKNN(const Vector& p,int k,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d > 0 && d < dmax && filter((int)i)) {
pair<Real,int> idx(d,i);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
bool NaivePointLocation::FilteredClose(const Vector& p,Real r,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(0);
distances.resize(0);
for(size_t i=0;i<points.size();i++) {
Real d=space->Distance(points[i],p);
if(d < r && filter((int)i)) {
nn.push_back((int)i);
distances.push_back(d);
}
}
return true;
}
RandomPointLocation::RandomPointLocation(vector<Vector>& points)
:PointLocationBase(points)
{}
bool RandomPointLocation::NN(const Vector& p,int& nn,Real& distance)
{
nn = RandInt(points.size());
distance = 0;
return true;
}
bool RandomPointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(k);
distances.resize(k);
for(int i=0;i<k;i++) {
nn[i] = RandInt(points.size());
distances[i] = 0;
}
return true;
}
bool RandomPointLocation::FilteredNN(const Vector& p,bool (*filter)(int),int& nn,Real& distance)
{
distance = 0;
while(true) {
nn = RandInt(points.size());
if(filter(nn)) return true;
}
return false;
}
bool RandomPointLocation::FilteredKNN(const Vector& p,int k,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(k);
distances.resize(k);
for(int i=0;i<k;i++) {
while(true) {
nn[i] = RandInt(points.size());
if(filter(nn[i])) break;
}
distances[i] = 0;
}
return true;
}
RandomBestPointLocation::RandomBestPointLocation(vector<Vector>& points,CSpace* _space,int _k)
:PointLocationBase(points),space(_space),k(_k)
{}
bool RandomBestPointLocation::NN(const Vector& p,int& nn,Real& distance)
{
distance = Inf;
nn = -1;
for(int i=0;i<k;i++) {
int n = RandInt(points.size());
Real d = space->Distance(points[n],p);
if(d < distance) {
nn = n;
distance = d;
}
}
return true;
}
bool RandomBestPointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
int count = k*this->k;
for(int i=0;i<count;i++) {
int n = RandInt(points.size());
Real d=space->Distance(points[n],p);
if(d > 0 && d < dmax) {
pair<Real,int> idx(d,n);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
bool RandomBestPointLocation::FilteredNN(const Vector& p,bool (*filter)(int),int& nn,Real& distance)
{
distance = Inf;
nn = -1;
for(int i=0;i<k;i++) {
int n = RandInt(points.size());
Real d = space->Distance(points[n],p);
if(d < distance && filter(i)) {
nn = n;
distance = d;
}
}
return true;
}
bool RandomBestPointLocation::FilteredKNN(const Vector& p,int k,bool (*filter)(int),std::vector<int>& nn,std::vector<Real>& distances)
{
set<pair<Real,int> > knn;
Real dmax = Inf;
int count = k*this->k;
for(int i=0;i<count;i++) {
int n = RandInt(points.size());
Real d=space->Distance(points[n],p);
if(d > 0 && d < dmax && filter(n)) {
pair<Real,int> idx(d,n);
knn.insert(idx);
if((int)knn.size() > k)
knn.erase(--knn.end());
dmax = (--knn.end())->first;
}
}
nn.resize(0);
distances.resize(0);
for(set<pair<Real,int> >::const_iterator j=knn.begin();j!=knn.end();j++) {
nn.push_back(j->second);
distances.push_back(j->first);
}
return true;
}
KDTreePointLocation::KDTreePointLocation(vector<Vector>& points)
:PointLocationBase(points),norm(2.0)
{}
KDTreePointLocation::KDTreePointLocation(vector<Vector>& points,Real _norm,const Vector& _weights)
:PointLocationBase(points),norm(_norm),weights(_weights)
{}
void KDTreePointLocation::OnAppend()
{
int id=(int)points.size()-1;
tree.Insert(points.back(),id);
/*
if(points.size() % 100 == 0)
printf("K-D Tree size %d, depth %d\n",tree.TreeSize(),tree.MaxDepth());
*/
}
bool KDTreePointLocation::OnClear()
{
tree.Clear();
return true;
}
bool KDTreePointLocation::NN(const Vector& p,int& nn,Real& distance)
{
nn = tree.ClosestPoint(p,distance);
return true;
}
bool KDTreePointLocation::KNN(const Vector& p,int k,std::vector<int>& nn,std::vector<Real>& distances)
{
nn.resize(k);
distances.resize(k);
tree.KClosestPoints(p,k,norm,weights,&distances[0],&nn[0]);
//may have fewer than k points
for(size_t i=0;i<nn.size();i++)
if(nn[i] < 0) {
nn.resize(i);
distances.resize(i);
break;
}
vector<pair<Real,int> > items(nn.size());
for(size_t i=0;i<nn.size();i++)
items[i] = pair<Real,int>(distances[i],nn[i]);
sort(items.begin(),items.end());
for(size_t i=0;i<nn.size();i++) {
nn[i] = items[i].second;
distances[i] = items[i].first;
}
return true;
}
bool KDTreePointLocation::Close(const Vector& p,Real r,std::vector<int>& nn,std::vector<Real>& distances)
{
tree.ClosePoints(p,r,norm,weights,distances,nn);
return true;
}
<|endoftext|>
|
<commit_before>#include "pinger"
#include <paku/builder/icmp>
#include <paku/layer>
namespace wd {
const uint32_t GRANULARITY = 100;
struct stats {
uint32_t sent;
uint32_t recv;
uint32_t min;
uint32_t max;
double avg;
};
static
void
_stats(msgpack::packer<std::ostream>& packer, struct stats* stats)
{
packer.pack(command::event::pinger::STATS);
packer.pack_int(stats->sent);
packer.pack_int(stats->recv);
if (stats->sent != stats->recv) {
packer.pack_float(((stats->sent - (stats->recv + 1)) * 100.0) / stats->sent);
}
else {
packer.pack_float(0);
}
packer.pack_int(stats->min);
packer.pack_int(stats->max);
packer.pack_int((stats->avg / stats->recv) * 1'000'000);
}
static
void
_analyze(int id, struct stats* stats, size_t length, const uint8_t* buffer)
{
auto ip = paku::layer<paku::packet::ip>(buffer, length);
auto icmp = ip.icmp();
icmp.parent()->icmp();
switch (icmp->type()) {
case paku::packet::icmp::ECHO_REPLY: {
auto echo = icmp->details<paku::packet::icmp::echo>();
if (echo.identifier() != id) {
return;
}
struct timeval now;
gettimeofday(&now, nullptr);
const struct timeval* then
= reinterpret_cast<const struct timeval*>(echo.data());
uint32_t sec = (now.tv_sec - then->tv_sec) * 1'000'000;
int32_t usec = (now.tv_usec - then->tv_usec);
if (usec < 0) {
sec -= 1'000'000;
usec += 1'000'000;
}
uint32_t trip = sec + usec;
stats->min = std::min(stats->min, trip);
stats->max = std::max(stats->max, trip);
stats->avg += trip / 1'000'000.0l;
stats->recv += 1;
wd::response(command::PINGER, id, [&](auto& packer) {
_stats(packer, stats);
});
wd::response(command::PINGER, id, [&](auto& packer) {
packer.pack(command::event::pinger::PACKET);
packer.pack(ip->source());
packer.pack(echo.sequence());
packer.pack(ip->ttl());
packer.pack(trip);
});
break;
}
case paku::packet::icmp::DESTINATION_UNREACHABLE:
case paku::packet::icmp::SOURCE_QUENCH:
case paku::packet::icmp::TIME_EXCEEDED: {
auto previous = icmp->details<paku::packet::icmp::previous>();
if (previous.header().protocol() != paku::packet::ip::ICMP) {
return;
}
paku::packet::icmp prev(reinterpret_cast<const paku::packet::icmp::raw*>(previous.data()));
if (prev.type() != paku::packet::icmp::ECHO_REQUEST) {
return;
}
auto echo = prev.details<paku::packet::icmp::echo>();
if (echo.identifier() != id) {
return;
}
wd::response(command::PINGER, id, [&](auto& packer) {
packer.pack(command::event::pinger::ERROR);
packer.pack(ip->source());
packer.pack(echo.sequence());
packer.pack(ip->ttl());
switch (icmp->type()) {
case paku::packet::icmp::DESTINATION_UNREACHABLE: {
if (auto string = paku::to_string(icmp->code<paku::packet::icmp::code::destination_unreachable>())) {
packer.pack(*string);
}
else {
packer.pack(*paku::to_string(icmp->type()));
}
break;
}
default:
packer.pack("unknown");
}
});
break;
}
}
}
static
void
_loop(wd::creator<>* creation, int id, int request, std::string target, uint32_t interval, std::shared_ptr<queue<pinger::command>> queue)
{
struct hostent* host = ::gethostbyname(target.c_str());
if (host == NULL) {
creation->err(id, request, command::pinger::error::UNKNOWN_HOST);
return;
}
int sock = ::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sock < 0) {
creation->err(id, request, command::pinger::error::SOCKET);
return;
}
if (socket::timeout(sock, std::chrono::milliseconds(GRANULARITY)) < 0) {
creation->err(id, request, command::pinger::error::SOCKET);
return;
}
struct sockaddr_in to;
std::memcpy(&to.sin_addr, host->h_addr, sizeof(to.sin_addr));
creation->ok(id, request);
uint8_t buffer[60 + 76 + sizeof(struct timeval)] = { 0 };
struct sockaddr_in from;
socklen_t from_s;
bool paused = true;
uint32_t slept = 0;
pinger::command command;
struct stats stats = {
.sent = 0,
.recv = 0,
.min = std::numeric_limits<uint32_t>::max(),
.max = std::numeric_limits<uint32_t>::min(),
.avg = 0,
};
while (true) {
if (paused) {
queue->wait_dequeue(command);
}
else {
if (!queue->try_dequeue(command)) {
command.type = -1;
}
}
switch (command.type) {
case command::pinger::START: {
if (!paused) {
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::pinger::error::ALREADY_STARTED);
});
continue;
}
paused = false;
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::SUCCESS);
});
break;
}
case command::pinger::STOP: {
if (paused) {
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::pinger::error::NOT_STARTED);
});
continue;
}
paused = true;
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::SUCCESS);
});
break;
}
case command::pinger::DESTROY: {
close(sock);
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::SUCCESS);
});
return;
}
default: {
ssize_t length = 0;
uint32_t sleep = GRANULARITY;
if (slept + GRANULARITY > interval) {
sleep = interval - slept;
}
length = recvfrom(sock, buffer, sizeof(buffer),
0, reinterpret_cast<struct sockaddr*>(&from), &from_s);
if (length >= 0) {
_analyze(id, &stats, length, buffer);
wd::socket::nonblocking(sock);
while (true) {
length = recvfrom(sock, buffer, sizeof(buffer),
0, reinterpret_cast<struct sockaddr*>(&from), &from_s);
if (length < 0) {
break;
}
_analyze(id, &stats, length, buffer);
}
wd::socket::blocking(sock);
}
slept += GRANULARITY;
if (slept >= interval) {
slept = 0;
struct timeval now;
gettimeofday(&now, nullptr);
paku::builder::icmp builder;
auto buffer = builder.echo().request()
.identifier(id)
.sequence(stats.sent)
.data(reinterpret_cast<uint8_t*>(&now), sizeof(now))
.build();
length = sendto(sock, buffer->whole(), buffer->total(),
0, reinterpret_cast<sockaddr*>(&to), sizeof(to));
if (length == buffer->total()) {
stats.sent += 1;
wd::response(command::PINGER, id, [&](auto& packer) {
_stats(packer, &stats);
});
}
}
}
}
}
}
pinger::pinger(wd::creator<>* creator, int id, int request, std::string target, uint32_t interval)
: _id(id),
_target(target),
_interval(interval),
_queue(std::make_shared<queue<pinger::command>>(1))
{
_thread = std::thread(_loop, creator, _id, request, _target, _interval, _queue);
_thread.detach();
}
pinger::~pinger()
{
_queue->enqueue(pinger::command {
.request = 0,
.type = wd::command::pinger::DESTROY,
});
}
void
pinger::start(int request)
{
_queue->enqueue(command {
.request = request,
.type = wd::command::pinger::START
});
}
void
pinger::stop(int request)
{
_queue->enqueue(command {
.request = request,
.type = wd::command::pinger::STOP
});
}
void
pinger::destroy(int request)
{
_queue->enqueue(command {
.request = request,
.type = wd::command::pinger::DESTROY
});
}
}
<commit_msg>pinger: type cast not needed now<commit_after>#include "pinger"
#include <paku/builder/icmp>
#include <paku/layer>
namespace wd {
const uint32_t GRANULARITY = 100;
struct stats {
uint32_t sent;
uint32_t recv;
uint32_t min;
uint32_t max;
double avg;
};
static
void
_stats(msgpack::packer<std::ostream>& packer, struct stats* stats)
{
packer.pack(command::event::pinger::STATS);
packer.pack_int(stats->sent);
packer.pack_int(stats->recv);
if (stats->sent != stats->recv) {
packer.pack_float(((stats->sent - (stats->recv + 1)) * 100.0) / stats->sent);
}
else {
packer.pack_float(0);
}
packer.pack_int(stats->min);
packer.pack_int(stats->max);
packer.pack_int((stats->avg / stats->recv) * 1'000'000);
}
static
void
_analyze(int id, struct stats* stats, size_t length, const uint8_t* buffer)
{
auto ip = paku::layer<paku::packet::ip>(buffer, length);
auto icmp = ip.icmp();
icmp.parent()->icmp();
switch (icmp->type()) {
case paku::packet::icmp::ECHO_REPLY: {
auto echo = icmp->details<paku::packet::icmp::echo>();
if (echo.identifier() != id) {
return;
}
struct timeval now;
gettimeofday(&now, nullptr);
const struct timeval* then
= reinterpret_cast<const struct timeval*>(echo.data());
uint32_t sec = (now.tv_sec - then->tv_sec) * 1'000'000;
int32_t usec = (now.tv_usec - then->tv_usec);
if (usec < 0) {
sec -= 1'000'000;
usec += 1'000'000;
}
uint32_t trip = sec + usec;
stats->min = std::min(stats->min, trip);
stats->max = std::max(stats->max, trip);
stats->avg += trip / 1'000'000.0l;
stats->recv += 1;
wd::response(command::PINGER, id, [&](auto& packer) {
_stats(packer, stats);
});
wd::response(command::PINGER, id, [&](auto& packer) {
packer.pack(command::event::pinger::PACKET);
packer.pack(ip->source());
packer.pack(echo.sequence());
packer.pack(ip->ttl());
packer.pack(trip);
});
break;
}
case paku::packet::icmp::DESTINATION_UNREACHABLE:
case paku::packet::icmp::SOURCE_QUENCH:
case paku::packet::icmp::TIME_EXCEEDED: {
auto previous = icmp->details<paku::packet::icmp::previous>();
if (previous.header().protocol() != paku::packet::ip::ICMP) {
return;
}
paku::packet::icmp prev(previous.data());
if (prev.type() != paku::packet::icmp::ECHO_REQUEST) {
return;
}
auto echo = prev.details<paku::packet::icmp::echo>();
if (echo.identifier() != id) {
return;
}
wd::response(command::PINGER, id, [&](auto& packer) {
packer.pack(command::event::pinger::ERROR);
packer.pack(ip->source());
packer.pack(echo.sequence());
packer.pack(ip->ttl());
switch (icmp->type()) {
case paku::packet::icmp::DESTINATION_UNREACHABLE: {
if (auto string = paku::to_string(icmp->code<paku::packet::icmp::code::destination_unreachable>())) {
packer.pack(*string);
}
else {
packer.pack(*paku::to_string(icmp->type()));
}
break;
}
default:
packer.pack("unknown");
}
});
break;
}
}
}
static
void
_loop(wd::creator<>* creation, int id, int request, std::string target, uint32_t interval, std::shared_ptr<queue<pinger::command>> queue)
{
struct hostent* host = ::gethostbyname(target.c_str());
if (host == NULL) {
creation->err(id, request, command::pinger::error::UNKNOWN_HOST);
return;
}
int sock = ::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sock < 0) {
creation->err(id, request, command::pinger::error::SOCKET);
return;
}
if (socket::timeout(sock, std::chrono::milliseconds(GRANULARITY)) < 0) {
creation->err(id, request, command::pinger::error::SOCKET);
return;
}
struct sockaddr_in to;
std::memcpy(&to.sin_addr, host->h_addr, sizeof(to.sin_addr));
creation->ok(id, request);
uint8_t buffer[60 + 76 + sizeof(struct timeval)] = { 0 };
struct sockaddr_in from;
socklen_t from_s;
bool paused = true;
uint32_t slept = 0;
pinger::command command;
struct stats stats = {
.sent = 0,
.recv = 0,
.min = std::numeric_limits<uint32_t>::max(),
.max = std::numeric_limits<uint32_t>::min(),
.avg = 0,
};
while (true) {
if (paused) {
queue->wait_dequeue(command);
}
else {
if (!queue->try_dequeue(command)) {
command.type = -1;
}
}
switch (command.type) {
case command::pinger::START: {
if (!paused) {
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::pinger::error::ALREADY_STARTED);
});
continue;
}
paused = false;
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::SUCCESS);
});
break;
}
case command::pinger::STOP: {
if (paused) {
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::pinger::error::NOT_STARTED);
});
continue;
}
paused = true;
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::SUCCESS);
});
break;
}
case command::pinger::DESTROY: {
close(sock);
wd::response(command::CONTROL, command.request, [](auto& packer) {
packer.pack_uint8(command::SUCCESS);
});
return;
}
default: {
ssize_t length = 0;
uint32_t sleep = GRANULARITY;
if (slept + GRANULARITY > interval) {
sleep = interval - slept;
}
length = recvfrom(sock, buffer, sizeof(buffer),
0, reinterpret_cast<struct sockaddr*>(&from), &from_s);
if (length >= 0) {
_analyze(id, &stats, length, buffer);
wd::socket::nonblocking(sock);
while (true) {
length = recvfrom(sock, buffer, sizeof(buffer),
0, reinterpret_cast<struct sockaddr*>(&from), &from_s);
if (length < 0) {
break;
}
_analyze(id, &stats, length, buffer);
}
wd::socket::blocking(sock);
}
slept += GRANULARITY;
if (slept >= interval) {
slept = 0;
struct timeval now;
gettimeofday(&now, nullptr);
paku::builder::icmp builder;
auto buffer = builder.echo().request()
.identifier(id)
.sequence(stats.sent)
.data(&now, sizeof(now))
.build();
length = sendto(sock, buffer->whole(), buffer->total(),
0, reinterpret_cast<sockaddr*>(&to), sizeof(to));
if (length == buffer->total()) {
stats.sent += 1;
wd::response(command::PINGER, id, [&](auto& packer) {
_stats(packer, &stats);
});
}
}
}
}
}
}
pinger::pinger(wd::creator<>* creator, int id, int request, std::string target, uint32_t interval)
: _id(id),
_target(target),
_interval(interval),
_queue(std::make_shared<queue<pinger::command>>(1))
{
_thread = std::thread(_loop, creator, _id, request, _target, _interval, _queue);
_thread.detach();
}
pinger::~pinger()
{
_queue->enqueue(pinger::command {
.request = 0,
.type = wd::command::pinger::DESTROY,
});
}
void
pinger::start(int request)
{
_queue->enqueue(command {
.request = request,
.type = wd::command::pinger::START
});
}
void
pinger::stop(int request)
{
_queue->enqueue(command {
.request = request,
.type = wd::command::pinger::STOP
});
}
void
pinger::destroy(int request)
{
_queue->enqueue(command {
.request = request,
.type = wd::command::pinger::DESTROY
});
}
}
<|endoftext|>
|
<commit_before>#include "filter.h"
namespace qqsfpm {
Filter::Filter(QObject *parent) : QObject(parent)
{
connect(this, &Filter::filterChanged, this, &Filter::onFilterChanged);
}
bool Filter::enabled() const
{
return m_enabled;
}
void Filter::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
emit enabledChanged();
emit filterChanged();
}
bool Filter::inverted() const
{
return m_inverted;
}
void Filter::setInverted(bool inverted)
{
if (m_inverted == inverted)
return;
m_inverted = inverted;
emit invertedChanged();
emit filterChanged();
}
bool Filter::filterAcceptsRow(const QModelIndex &sourceIndex) const
{
return !m_enabled || filterRow(sourceIndex) ^ m_inverted;
}
QQmlSortFilterProxyModel* Filter::proxyModel() const
{
return m_proxyModel;
}
void Filter::proxyModelCompleted()
{
}
void Filter::onFilterChanged()
{
if (m_enabled)
invalidate();
}
const QString& RoleFilter::roleName() const
{
return m_roleName;
}
void RoleFilter::setRoleName(const QString& roleName)
{
if (m_roleName == roleName)
return;
m_roleName = roleName;
emit roleNameChanged();
emit filterChanged();
}
QVariant RoleFilter::sourceData(const QModelIndex &sourceIndex) const
{
return proxyModel()->sourceData(sourceIndex, m_roleName);
}
const QVariant &ValueFilter::value() const
{
return m_value;
}
void ValueFilter::setValue(const QVariant& value)
{
if (m_value == value)
return;
m_value = value;
emit valueChanged();
emit filterChanged();
}
bool ValueFilter::filterRow(const QModelIndex& sourceIndex) const
{
return !m_value.isValid() || m_value == sourceData(sourceIndex);
}
}
<commit_msg>Register Filters type to QML<commit_after>#include "filter.h"
#include <QtQml>
namespace qqsfpm {
Filter::Filter(QObject *parent) : QObject(parent)
{
connect(this, &Filter::filterChanged, this, &Filter::onFilterChanged);
}
bool Filter::enabled() const
{
return m_enabled;
}
void Filter::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
emit enabledChanged();
emit filterChanged();
}
bool Filter::inverted() const
{
return m_inverted;
}
void Filter::setInverted(bool inverted)
{
if (m_inverted == inverted)
return;
m_inverted = inverted;
emit invertedChanged();
emit filterChanged();
}
bool Filter::filterAcceptsRow(const QModelIndex &sourceIndex) const
{
return !m_enabled || filterRow(sourceIndex) ^ m_inverted;
}
QQmlSortFilterProxyModel* Filter::proxyModel() const
{
return m_proxyModel;
}
void Filter::proxyModelCompleted()
{
}
void Filter::onFilterChanged()
{
if (m_enabled)
invalidate();
}
const QString& RoleFilter::roleName() const
{
return m_roleName;
}
void RoleFilter::setRoleName(const QString& roleName)
{
if (m_roleName == roleName)
return;
m_roleName = roleName;
emit roleNameChanged();
emit filterChanged();
}
QVariant RoleFilter::sourceData(const QModelIndex &sourceIndex) const
{
return proxyModel()->sourceData(sourceIndex, m_roleName);
}
const QVariant &ValueFilter::value() const
{
return m_value;
}
void ValueFilter::setValue(const QVariant& value)
{
if (m_value == value)
return;
m_value = value;
emit valueChanged();
emit filterChanged();
}
bool ValueFilter::filterRow(const QModelIndex& sourceIndex) const
{
return !m_value.isValid() || m_value == sourceData(sourceIndex);
}
void registerFilterTypes() {
qmlRegisterUncreatableType<Filter>("SortFilterProxyModel", 0, 2, "Filter", "Filter is an abstract class");
qmlRegisterType<ValueFilter>("SortFilterProxyModel", 0, 2, "ValueFilter");
}
Q_COREAPP_STARTUP_FUNCTION(registerFilterTypes)
}
<|endoftext|>
|
<commit_before>#include "Graphics.h"
#include "sfwindow.h"
#include <SFML/Graphics.hpp>
#include "utility/misc.h"
#include "imgui.h"
#include "imgui-events-SFML.h"
#include "imgui-rendering-SFML.h"
using namespace WalrusRPG; /*::Graphics*/
using WalrusRPG::Utils::Rect;
sf::RenderWindow window;
sf::View view;
sf::RenderTexture buffer;
void Graphics::init()
{
// window.create(sf::VideoMode::getDesktopMode(), "WalrusRPG",
// sf::Style::Fullscreen);
window.create(sf::VideoMode(640, 480), "WalrusRPG");
window.setFramerateLimit(60);
view = sf::View(window.getDefaultView());
buffer.create(320, 240);
ImGui::SFML::SetRenderTarget(window);
ImGui::SFML::InitImGuiRendering();
ImGui::SFML::SetWindow(window);
ImGui::SFML::InitImGuiEvents();
}
void Graphics::deinit()
{
ImGui::SFML::Shutdown();
window.close();
}
void Graphics::frame_begin()
{
window.clear(sf::Color::Black);
ImGui::SFML::UpdateImGui();
ImGui::SFML::UpdateImGuiRendering();
sf::Event e;
while (window.pollEvent(e))
{
ImGui::SFML::ProcessEvent(e);
if (e.type == sf::Event::Closed)
{
window.close();
}
}
}
void Graphics::frame_end()
{
sf::Sprite sprite(buffer.getTexture());
sf::Vector2u winsize = window.getSize();
sf::Event event;
float winscale_x = winsize.x / 320.f;
float winscale_y = winsize.y / 240.f;
float scale = winscale_x < winscale_y ? winscale_x : winscale_y;
while (window.pollEvent(event))
{
}
window.setView(view = sf::View(sf::FloatRect(0, 0, winsize.x, winsize.y)));
buffer.display();
window.clear();
sprite.setScale(scale, scale);
sprite.setPosition((winsize.x - 320.f * scale) / 2, (winsize.y - 240.f * scale) / 2);
window.draw(sprite);
ImGui::Render();
window.display();
}
void Graphics::put_sprite(const Texture &sheet, int x, int y, const Rect &window)
{
sf::Sprite sprite;
sprite.setTexture(sheet.data);
sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
sprite.setPosition(x, y);
buffer.draw(sprite);
}
void Graphics::put_sprite_tint(const Texture &sheet, int x, int y, const Rect &window,
const Pixel &color)
{
sf::Sprite sprite;
sprite.setTexture(sheet.data);
sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
sprite.setPosition(x, y);
sprite.setColor(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
buffer.draw(sprite);
}
void Graphics::put_sprite_clipping(const Texture &sheet, int x, int y,
const Rect &sprite_window, const Rect &clipping_window)
{
const signed &ss_x = sprite_window.x, ss_y = sprite_window.y;
const signed &ss_w = sprite_window.width, &ss_h = sprite_window.height;
const signed &cx = clipping_window.x, &cy = clipping_window.y;
const signed &cw = clipping_window.width, &ch = clipping_window.height;
const signed lx = x - cx, ly = y - cy;
if (lx < -ss_w || lx > cw)
return;
if (ly < -ss_h || ly > ch)
return;
signed fx = x, fy = y;
signed fssx = ss_x, fssy = ss_y, fssw = ss_w, fssh = ss_h;
if (lx < 0)
{
fssw = ss_w + lx;
fssx = -lx;
fx = cx;
}
if (lx > cw - ss_w)
{
fssw -= lx - (cw - ss_w);
}
if (ly > ch - ss_h)
{
fssh -= ly - (ch - ss_h);
}
if (ly < 0)
{
fssh = ss_h + ly;
fssy = -ly;
fy = cy;
}
sf::Sprite sprite;
sprite.setTexture(sheet.data);
sprite.setTextureRect(sf::IntRect(fssx, fssy, fssw, fssh));
sprite.setPosition(fx, fy);
buffer.draw(sprite);
}
void Graphics::fill(const Pixel &color)
{
buffer.clear(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
}
void Graphics::put_pixel(uint16_t x, uint16_t y, const Pixel &color)
{
sf::RectangleShape pixel;
pixel.setSize(sf::Vector2f(1, 1));
pixel.setFillColor(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
pixel.setPosition(x, y);
buffer.draw(pixel);
}
void Graphics::put_horizontal_line(uint16_t x, uint16_t x2, uint16_t y,
const Pixel &color)
{
put_rectangle({x, y, x2 - x + 1u, 1}, color);
}
void Graphics::put_vertical_line(uint16_t x, uint16_t y, uint16_t y2, const Pixel &color)
{
put_rectangle({x, y, 1, y2 - y + 1u}, color);
}
void Graphics::put_line(uint16_t x, uint16_t y, uint16_t x2, uint16_t y2,
const Pixel &color)
{
sf::Color lineColor(color.r << 3, color.g << 2, color.b << 3, 255);
sf::Vertex line[] = {sf::Vertex(sf::Vector2f(x, y), lineColor),
sf::Vertex(sf::Vector2f(x2 + 1, y2 + 1), lineColor)};
buffer.draw(line, 2, sf::Lines);
}
void Graphics::put_rectangle(const Rect &rect, const Pixel &color)
{
sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(rect.width, rect.height));
rectangle.setFillColor(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
rectangle.setPosition(rect.x, rect.y);
buffer.draw(rectangle);
}
<commit_msg>Removed the window close handler to avoid having a program which runs headlessly.<commit_after>#include "Graphics.h"
#include "sfwindow.h"
#include <SFML/Graphics.hpp>
#include "utility/misc.h"
#include "imgui.h"
#include "imgui-events-SFML.h"
#include "imgui-rendering-SFML.h"
using namespace WalrusRPG; /*::Graphics*/
using WalrusRPG::Utils::Rect;
sf::RenderWindow window;
sf::View view;
sf::RenderTexture buffer;
void Graphics::init()
{
// window.create(sf::VideoMode::getDesktopMode(), "WalrusRPG",
// sf::Style::Fullscreen);
window.create(sf::VideoMode(640, 480), "WalrusRPG");
window.setFramerateLimit(60);
view = sf::View(window.getDefaultView());
buffer.create(320, 240);
ImGui::SFML::SetRenderTarget(window);
ImGui::SFML::InitImGuiRendering();
ImGui::SFML::SetWindow(window);
ImGui::SFML::InitImGuiEvents();
}
void Graphics::deinit()
{
ImGui::SFML::Shutdown();
window.close();
}
void Graphics::frame_begin()
{
window.clear(sf::Color::Black);
ImGui::SFML::UpdateImGui();
ImGui::SFML::UpdateImGuiRendering();
sf::Event e;
while (window.pollEvent(e))
{
ImGui::SFML::ProcessEvent(e);
}
}
void Graphics::frame_end()
{
sf::Sprite sprite(buffer.getTexture());
sf::Vector2u winsize = window.getSize();
sf::Event event;
float winscale_x = winsize.x / 320.f;
float winscale_y = winsize.y / 240.f;
float scale = winscale_x < winscale_y ? winscale_x : winscale_y;
while (window.pollEvent(event))
{
}
window.setView(view = sf::View(sf::FloatRect(0, 0, winsize.x, winsize.y)));
buffer.display();
window.clear();
sprite.setScale(scale, scale);
sprite.setPosition((winsize.x - 320.f * scale) / 2, (winsize.y - 240.f * scale) / 2);
window.draw(sprite);
ImGui::Render();
window.display();
}
void Graphics::put_sprite(const Texture &sheet, int x, int y, const Rect &window)
{
sf::Sprite sprite;
sprite.setTexture(sheet.data);
sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
sprite.setPosition(x, y);
buffer.draw(sprite);
}
void Graphics::put_sprite_tint(const Texture &sheet, int x, int y, const Rect &window,
const Pixel &color)
{
sf::Sprite sprite;
sprite.setTexture(sheet.data);
sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
sprite.setPosition(x, y);
sprite.setColor(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
buffer.draw(sprite);
}
void Graphics::put_sprite_clipping(const Texture &sheet, int x, int y,
const Rect &sprite_window, const Rect &clipping_window)
{
const signed &ss_x = sprite_window.x, ss_y = sprite_window.y;
const signed &ss_w = sprite_window.width, &ss_h = sprite_window.height;
const signed &cx = clipping_window.x, &cy = clipping_window.y;
const signed &cw = clipping_window.width, &ch = clipping_window.height;
const signed lx = x - cx, ly = y - cy;
if (lx < -ss_w || lx > cw)
return;
if (ly < -ss_h || ly > ch)
return;
signed fx = x, fy = y;
signed fssx = ss_x, fssy = ss_y, fssw = ss_w, fssh = ss_h;
if (lx < 0)
{
fssw = ss_w + lx;
fssx = -lx;
fx = cx;
}
if (lx > cw - ss_w)
{
fssw -= lx - (cw - ss_w);
}
if (ly > ch - ss_h)
{
fssh -= ly - (ch - ss_h);
}
if (ly < 0)
{
fssh = ss_h + ly;
fssy = -ly;
fy = cy;
}
sf::Sprite sprite;
sprite.setTexture(sheet.data);
sprite.setTextureRect(sf::IntRect(fssx, fssy, fssw, fssh));
sprite.setPosition(fx, fy);
buffer.draw(sprite);
}
void Graphics::fill(const Pixel &color)
{
buffer.clear(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
}
void Graphics::put_pixel(uint16_t x, uint16_t y, const Pixel &color)
{
sf::RectangleShape pixel;
pixel.setSize(sf::Vector2f(1, 1));
pixel.setFillColor(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
pixel.setPosition(x, y);
buffer.draw(pixel);
}
void Graphics::put_horizontal_line(uint16_t x, uint16_t x2, uint16_t y,
const Pixel &color)
{
put_rectangle({x, y, x2 - x + 1u, 1}, color);
}
void Graphics::put_vertical_line(uint16_t x, uint16_t y, uint16_t y2, const Pixel &color)
{
put_rectangle({x, y, 1, y2 - y + 1u}, color);
}
void Graphics::put_line(uint16_t x, uint16_t y, uint16_t x2, uint16_t y2,
const Pixel &color)
{
sf::Color lineColor(color.r << 3, color.g << 2, color.b << 3, 255);
sf::Vertex line[] = {sf::Vertex(sf::Vector2f(x, y), lineColor),
sf::Vertex(sf::Vector2f(x2 + 1, y2 + 1), lineColor)};
buffer.draw(line, 2, sf::Lines);
}
void Graphics::put_rectangle(const Rect &rect, const Pixel &color)
{
sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(rect.width, rect.height));
rectangle.setFillColor(sf::Color(color.r << 3, color.g << 2, color.b << 3, 255));
rectangle.setPosition(rect.x, rect.y);
buffer.draw(rectangle);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* video.cpp : wxWindows plugin for vlc
*****************************************************************************
* Copyright (C) 2000-2004, 2003 VideoLAN
* $Id: interface.cpp 6961 2004-03-05 17:34:23Z sam $
*
* Authors: Gildas Bazin <gbazin@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#include <vlc/vlc.h>
#include <vlc/vout.h>
#include <vlc/intf.h>
#include "stream_control.h"
#include "wxwindows.h"
static void *GetWindow( intf_thread_t *p_intf, int *pi_x_hint, int *pi_y_hint,
unsigned int *pi_width_hint,
unsigned int *pi_height_hint );
static void ReleaseWindow( intf_thread_t *p_intf, void *p_window );
/* IDs for the controls and the menu commands */
enum
{
UpdateSize_Event = wxID_HIGHEST + 1,
UpdateHide_Event
};
class VideoWindow: public wxWindow
{
public:
/* Constructor */
VideoWindow( intf_thread_t *_p_intf, wxWindow *p_parent );
virtual ~VideoWindow();
void *GetWindow( int *, int *, unsigned int *, unsigned int * );
void ReleaseWindow( void * );
private:
intf_thread_t *p_intf;
wxWindow *p_parent;
vlc_mutex_t lock;
vlc_bool_t b_in_use;
wxWindow *p_child_window;
void UpdateSize( wxSizeEvent & );
void UpdateHide( wxSizeEvent & );
DECLARE_EVENT_TABLE();
};
BEGIN_EVENT_TABLE(VideoWindow, wxWindow)
EVT_CUSTOM( wxEVT_SIZE, UpdateSize_Event, VideoWindow::UpdateSize )
EVT_CUSTOM( wxEVT_SIZE, UpdateHide_Event, VideoWindow::UpdateHide )
END_EVENT_TABLE()
/*****************************************************************************
* Public methods.
*****************************************************************************/
wxWindow *VideoWindow( intf_thread_t *p_intf, wxWindow *p_parent )
{
return new VideoWindow::VideoWindow( p_intf, p_parent );
}
/*****************************************************************************
* Constructor.
*****************************************************************************/
VideoWindow::VideoWindow( intf_thread_t *_p_intf, wxWindow *_p_parent ):
wxWindow( _p_parent, -1 )
{
/* Initializations */
p_intf = _p_intf;
p_parent = _p_parent;
vlc_mutex_init( p_intf, &lock );
b_in_use = VLC_FALSE;
p_intf->pf_request_window = ::GetWindow;
p_intf->pf_release_window = ::ReleaseWindow;
p_intf->p_sys->p_video_window = this;
p_child_window = new wxWindow( this, -1, wxDefaultPosition, wxSize(0,0) );
p_child_window->Show();
Show();
p_intf->p_sys->p_video_sizer = new wxBoxSizer( wxHORIZONTAL );
p_intf->p_sys->p_video_sizer->Add( this, 1, wxEXPAND );
ReleaseWindow( NULL );
}
VideoWindow::~VideoWindow()
{
vlc_mutex_destroy( &lock );
}
/*****************************************************************************
* Private methods.
*****************************************************************************/
static void *GetWindow( intf_thread_t *p_intf, int *pi_x_hint, int *pi_y_hint,
unsigned int *pi_width_hint,
unsigned int *pi_height_hint )
{
return p_intf->p_sys->p_video_window->GetWindow( pi_x_hint, pi_y_hint,
pi_width_hint,
pi_height_hint );
}
/* Part of the hack to get the X11 window handle from the GtkWidget */
#ifdef __WXGTK__
extern "C" {
#ifdef __WXGTK20__
int gdk_x11_drawable_get_xid( void * );
#endif
void *gtk_widget_get_parent_window( void * );
}
#endif
void *VideoWindow::GetWindow( int *pi_x_hint, int *pi_y_hint,
unsigned int *pi_width_hint,
unsigned int *pi_height_hint )
{
#if defined(__WXGTK__) || defined(WIN32)
vlc_mutex_lock( &lock );
if( b_in_use )
{
msg_Dbg( p_intf, "Video window already in use" );
return NULL;
}
b_in_use = VLC_TRUE;
wxSizeEvent event( wxSize(*pi_width_hint, *pi_height_hint),
UpdateSize_Event );
AddPendingEvent( event );
vlc_mutex_unlock( &lock );
#ifdef __WXGTK__
GtkWidget *p_widget = p_child_window->GetHandle();
#ifdef __WXGTK20__
return (void *)gdk_x11_drawable_get_xid(
gtk_widget_get_parent_window( p_widget ) );
#elif defined(__WXGTK__)
return (void *)( (char *)gtk_widget_get_parent_window( p_widget )
+ 2 * sizeof(void *) );
#endif
#elif defined(WIN32)
return (void*)GetHandle();
#endif
#else // defined(__WXGTK__) || defined(WIN32)
return NULL;
#endif
}
static void ReleaseWindow( intf_thread_t *p_intf, void *p_window )
{
return p_intf->p_sys->p_video_window->ReleaseWindow( p_window );
}
void VideoWindow::ReleaseWindow( void *p_window )
{
vlc_mutex_lock( &lock );
b_in_use = VLC_FALSE;
#if defined(__WXGTK__) || defined(WIN32)
wxSizeEvent event( wxSize(0, 0), UpdateHide_Event );
AddPendingEvent( event );
#endif
vlc_mutex_unlock( &lock );
}
void VideoWindow::UpdateSize( wxSizeEvent &event )
{
if( !IsShown() )
{
p_intf->p_sys->p_video_sizer->Show( this, TRUE );
p_intf->p_sys->p_video_sizer->Layout();
SetFocus();
}
p_intf->p_sys->p_video_sizer->SetMinSize( event.GetSize() );
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_parent->AddPendingEvent( intf_event );
}
void VideoWindow::UpdateHide( wxSizeEvent &event )
{
if( IsShown() )
{
p_intf->p_sys->p_video_sizer->Show( this, FALSE );
p_intf->p_sys->p_video_sizer->Layout();
}
p_intf->p_sys->p_video_sizer->SetMinSize( event.GetSize() );
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_parent->AddPendingEvent( intf_event );
}
<commit_msg>* modules/gui/wxwindows/video.cpp: fix for wxGtk built with GTK1.<commit_after>/*****************************************************************************
* video.cpp : wxWindows plugin for vlc
*****************************************************************************
* Copyright (C) 2000-2004, 2003 VideoLAN
* $Id: interface.cpp 6961 2004-03-05 17:34:23Z sam $
*
* Authors: Gildas Bazin <gbazin@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#include <vlc/vlc.h>
#include <vlc/vout.h>
#include <vlc/intf.h>
#include "stream_control.h"
#include "wxwindows.h"
static void *GetWindow( intf_thread_t *p_intf, int *pi_x_hint, int *pi_y_hint,
unsigned int *pi_width_hint,
unsigned int *pi_height_hint );
static void ReleaseWindow( intf_thread_t *p_intf, void *p_window );
/* IDs for the controls and the menu commands */
enum
{
UpdateSize_Event = wxID_HIGHEST + 1,
UpdateHide_Event
};
class VideoWindow: public wxWindow
{
public:
/* Constructor */
VideoWindow( intf_thread_t *_p_intf, wxWindow *p_parent );
virtual ~VideoWindow();
void *GetWindow( int *, int *, unsigned int *, unsigned int * );
void ReleaseWindow( void * );
private:
intf_thread_t *p_intf;
wxWindow *p_parent;
vlc_mutex_t lock;
vlc_bool_t b_in_use;
wxWindow *p_child_window;
void UpdateSize( wxSizeEvent & );
void UpdateHide( wxSizeEvent & );
DECLARE_EVENT_TABLE();
};
BEGIN_EVENT_TABLE(VideoWindow, wxWindow)
EVT_CUSTOM( wxEVT_SIZE, UpdateSize_Event, VideoWindow::UpdateSize )
EVT_CUSTOM( wxEVT_SIZE, UpdateHide_Event, VideoWindow::UpdateHide )
END_EVENT_TABLE()
/*****************************************************************************
* Public methods.
*****************************************************************************/
wxWindow *VideoWindow( intf_thread_t *p_intf, wxWindow *p_parent )
{
return new VideoWindow::VideoWindow( p_intf, p_parent );
}
/*****************************************************************************
* Constructor.
*****************************************************************************/
VideoWindow::VideoWindow( intf_thread_t *_p_intf, wxWindow *_p_parent ):
wxWindow( _p_parent, -1 )
{
/* Initializations */
p_intf = _p_intf;
p_parent = _p_parent;
vlc_mutex_init( p_intf, &lock );
b_in_use = VLC_FALSE;
p_intf->pf_request_window = ::GetWindow;
p_intf->pf_release_window = ::ReleaseWindow;
p_intf->p_sys->p_video_window = this;
p_child_window = new wxWindow( this, -1, wxDefaultPosition, wxSize(0,0) );
p_child_window->Show();
Show();
p_intf->p_sys->p_video_sizer = new wxBoxSizer( wxHORIZONTAL );
p_intf->p_sys->p_video_sizer->Add( this, 1, wxEXPAND );
ReleaseWindow( NULL );
}
VideoWindow::~VideoWindow()
{
vlc_mutex_destroy( &lock );
}
/*****************************************************************************
* Private methods.
*****************************************************************************/
static void *GetWindow( intf_thread_t *p_intf, int *pi_x_hint, int *pi_y_hint,
unsigned int *pi_width_hint,
unsigned int *pi_height_hint )
{
return p_intf->p_sys->p_video_window->GetWindow( pi_x_hint, pi_y_hint,
pi_width_hint,
pi_height_hint );
}
/* Part of the hack to get the X11 window handle from the GtkWidget */
#ifdef __WXGTK__
extern "C" {
#ifdef __WXGTK20__
int gdk_x11_drawable_get_xid( void * );
#endif
void *gtk_widget_get_parent_window( void * );
}
#endif
void *VideoWindow::GetWindow( int *pi_x_hint, int *pi_y_hint,
unsigned int *pi_width_hint,
unsigned int *pi_height_hint )
{
#if defined(__WXGTK__) || defined(WIN32)
vlc_mutex_lock( &lock );
if( b_in_use )
{
msg_Dbg( p_intf, "Video window already in use" );
return NULL;
}
b_in_use = VLC_TRUE;
wxSizeEvent event( wxSize(*pi_width_hint, *pi_height_hint),
UpdateSize_Event );
AddPendingEvent( event );
vlc_mutex_unlock( &lock );
#ifdef __WXGTK__
GtkWidget *p_widget = p_child_window->GetHandle();
#ifdef __WXGTK20__
return (void *)gdk_x11_drawable_get_xid(
gtk_widget_get_parent_window( p_widget ) );
#elif defined(__WXGTK__)
return (void *)*(int *)( (char *)gtk_widget_get_parent_window( p_widget )
+ 2 * sizeof(void *) );
#endif
#elif defined(WIN32)
return (void*)GetHandle();
#endif
#else // defined(__WXGTK__) || defined(WIN32)
return NULL;
#endif
}
static void ReleaseWindow( intf_thread_t *p_intf, void *p_window )
{
return p_intf->p_sys->p_video_window->ReleaseWindow( p_window );
}
void VideoWindow::ReleaseWindow( void *p_window )
{
vlc_mutex_lock( &lock );
b_in_use = VLC_FALSE;
#if defined(__WXGTK__) || defined(WIN32)
wxSizeEvent event( wxSize(0, 0), UpdateHide_Event );
AddPendingEvent( event );
#endif
vlc_mutex_unlock( &lock );
}
void VideoWindow::UpdateSize( wxSizeEvent &event )
{
if( !IsShown() )
{
p_intf->p_sys->p_video_sizer->Show( this, TRUE );
p_intf->p_sys->p_video_sizer->Layout();
SetFocus();
}
p_intf->p_sys->p_video_sizer->SetMinSize( event.GetSize() );
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_parent->AddPendingEvent( intf_event );
}
void VideoWindow::UpdateHide( wxSizeEvent &event )
{
if( IsShown() )
{
p_intf->p_sys->p_video_sizer->Show( this, FALSE );
p_intf->p_sys->p_video_sizer->Layout();
}
p_intf->p_sys->p_video_sizer->SetMinSize( event.GetSize() );
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_parent->AddPendingEvent( intf_event );
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH
#define DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH
#include <dune/common/fmatrix.hh>
#include <dune/common/fvector.hh>
#if HAVE_DUNE_PDELAB
#include <dune/pdelab/gridfunctionspace/localfunctionspace.hh>
#endif
#include <dune/stuff/common/type_utils.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace BaseFunctionSet {
#if HAVE_DUNE_PDELAB
// forwards, to be used in the traits and to allow for specialization
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PdelabWrapper
{
static_assert(Dune::AlwaysFalse<PdelabSpaceImp>::value, "Untested for arbitrary dimension!");
};
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PiolaTransformedPdelabWrapper
{
static_assert(Dune::AlwaysFalse<PdelabSpaceImp>::value, "Untested for these dimensions!");
};
namespace internal {
// forward, to allow for specialization
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols>
class PdelabWrapperTraits;
//! Specialization for dimRange = 1, dimRangeRows = 1
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp>
class PdelabWrapperTraits<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
{
public:
typedef PdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> derived_type;
private:
typedef PDELab::LocalFunctionSpace<PdelabSpaceImp, PDELab::TrialSpaceTag> PdelabLFSType;
typedef FiniteElementInterfaceSwitch<typename PdelabSpaceImp::Traits::FiniteElementType> FESwitchType;
public:
typedef typename FESwitchType::Basis BackendType;
typedef EntityImp EntityType;
private:
friend class PdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>;
};
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim>
class PiolaTransformedPdelabWrapperTraits
{
static_assert(domainDim == rangeDim, "Untested!");
public:
typedef PiolaTransformedPdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim>
derived_type;
private:
typedef PDELab::LocalFunctionSpace<PdelabSpaceImp, PDELab::TrialSpaceTag> PdelabLFSType;
typedef FiniteElementInterfaceSwitch<typename PdelabSpaceImp::Traits::FiniteElementType> FESwitchType;
public:
typedef typename FESwitchType::Basis BackendType;
typedef EntityImp EntityType;
private:
friend class PiolaTransformedPdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp,
rangeDim, 1>;
};
} // namespace internal
//! Specialization for dimRange = 1, dimRangeRows = 1
template <class PdelabSpaceType, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp>
class PdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
: public BaseFunctionSetInterface<internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp,
domainDim, RangeFieldImp, 1, 1>,
DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
{
typedef PdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> ThisType;
typedef BaseFunctionSetInterface<internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, 1, 1>,
DomainFieldImp, domainDim, RangeFieldImp, 1, 1> BaseType;
public:
typedef internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
private:
typedef typename Traits::PdelabLFSType PdelabLFSType;
typedef typename Traits::FESwitchType FESwitchType;
public:
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)
: BaseType(ent)
, tmp_domain_(0)
{
PdelabLFSType* lfs_ptr = new PdelabLFSType(space);
lfs_ptr->bind(this->entity());
lfs_ = std::unique_ptr<PdelabLFSType>(lfs_ptr);
backend_ = std::unique_ptr<BackendType>(new BackendType(FESwitchType::basis(lfs_->finiteElement())));
} // PdelabWrapper(...)
PdelabWrapper(ThisType&& source) = default;
PdelabWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const override final
{
return backend_->size();
}
virtual size_t order() const override final
{
return backend_->order();
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const override final
{
assert(ret.size() >= backend_->size());
backend_->evaluateFunction(xx, ret);
}
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const override final
{
assert(ret.size() >= backend_->size());
backend_->evaluateJacobian(xx, ret);
const auto jacobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx);
for (size_t ii = 0; ii < ret.size(); ++ii) {
jacobian_inverse_transposed.mv(ret[ii][0], tmp_domain_);
ret[ii][0] = tmp_domain_;
}
} // ... jacobian(...)
using BaseType::jacobian;
private:
mutable DomainType tmp_domain_;
std::unique_ptr<const PdelabLFSType> lfs_;
std::unique_ptr<const BackendType> backend_;
}; // class PdelabWrapper
template <class PdelabSpaceType, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim>
class PiolaTransformedPdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
: public BaseFunctionSetInterface<internal::PiolaTransformedPdelabWrapperTraits<PdelabSpaceType, EntityImp,
DomainFieldImp, domainDim,
RangeFieldImp, rangeDim>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
typedef PiolaTransformedPdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
1> ThisType;
typedef BaseFunctionSetInterface<internal::PiolaTransformedPdelabWrapperTraits<PdelabSpaceType, EntityImp,
DomainFieldImp, domainDim,
RangeFieldImp, rangeDim>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;
public:
typedef internal::PiolaTransformedPdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim> Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
private:
typedef typename Traits::PdelabLFSType PdelabLFSType;
typedef typename Traits::FESwitchType FESwitchType;
public:
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
using typename BaseType::RangeType;
using typename BaseType::JacobianRangeType;
PiolaTransformedPdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)
: BaseType(ent)
, tmp_domain_(DomainFieldType(0))
, tmp_jacobian_transposed_(DomainFieldType(0))
, tmp_jacobian_inverse_transposed_(DomainFieldType(0))
{
PdelabLFSType* lfs_ptr = new PdelabLFSType(space);
lfs_ptr->bind(this->entity());
lfs_ = std::unique_ptr<PdelabLFSType>(lfs_ptr);
backend_ = std::unique_ptr<BackendType>(new BackendType(FESwitchType::basis(lfs_->finiteElement())));
tmp_ranges_ = std::vector<RangeType>(backend_->size(), RangeType(0));
tmp_jacobian_ranges_ = std::vector<JacobianRangeType>(backend_->size(), JacobianRangeType(0));
} // PdelabWrapper(...)
PiolaTransformedPdelabWrapper(ThisType&& source) = default;
PiolaTransformedPdelabWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const override final
{
return backend_->size();
}
virtual size_t order() const override final
{
return backend_->order();
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const override final
{
assert(lfs_);
assert(backend_);
assert(tmp_ranges_.size() >= backend_->size());
assert(ret.size() >= backend_->size());
backend_->evaluateFunction(xx, tmp_ranges_);
const auto geometry = this->entity().geometry();
tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);
const DomainFieldType integration_element = geometry.integrationElement(xx);
for (size_t ii = 0; ii < backend_->size(); ++ii) {
tmp_jacobian_transposed_.mtv(tmp_ranges_[ii], ret[ii]);
ret[ii] /= integration_element;
}
} // ... evaluate(...)
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const override final
{
assert(lfs_);
assert(backend_);
assert(ret.size() >= backend_->size());
backend_->evaluateJacobian(xx, tmp_jacobian_ranges_);
const auto geometry = this->entity().geometry();
tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);
tmp_jacobian_inverse_transposed_ = geometry.jacobianInverseTransposed(xx);
const DomainFieldType integration_element = geometry.integrationElement(xx);
for (size_t ii = 0; ii < backend_->size(); ++ii) {
for (size_t jj = 0; jj < dimDomain; ++jj) {
tmp_jacobian_inverse_transposed_.mv(tmp_jacobian_ranges_[ii][jj], ret[ii][jj]);
tmp_jacobian_transposed_.mv(ret[ii][jj], tmp_jacobian_ranges_[ii][jj]);
tmp_jacobian_ranges_[ii][jj] /= integration_element;
ret[ii][jj] = tmp_jacobian_ranges_[ii][jj];
}
}
} // ... jacobian(...)
using BaseType::jacobian;
private:
mutable DomainType tmp_domain_;
mutable typename EntityType::Geometry::JacobianTransposed tmp_jacobian_transposed_;
mutable typename EntityType::Geometry::JacobianInverseTransposed tmp_jacobian_inverse_transposed_;
std::unique_ptr<const PdelabLFSType> lfs_;
std::unique_ptr<const BackendType> backend_;
mutable std::vector<RangeType> tmp_ranges_;
mutable std::vector<JacobianRangeType> tmp_jacobian_ranges_;
}; // class PiolaTransformedPdelabWrapper
#else // HAVE_DUNE_PDELAB
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PdelabWrapper
{
static_assert(AlwaysFalse<PdelabSpaceImp>::value, "You are missing dune-pdelab!");
};
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PiolaTransformedPdelabWrapper
{
static_assert(AlwaysFalse<PdelabSpaceImp>::value, "You are missing dune-pdelab!");
};
#endif // HAVE_DUNE_PDELAB
} // namespace BaseFunctionSet
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH
<commit_msg>[basefunctionset.pdelab] add specialization for dimRange > 1<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH
#define DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH
#include <dune/common/fmatrix.hh>
#include <dune/common/fvector.hh>
#if HAVE_DUNE_PDELAB
#include <dune/pdelab/gridfunctionspace/localfunctionspace.hh>
#endif
#include <dune/stuff/common/type_utils.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace BaseFunctionSet {
#if HAVE_DUNE_PDELAB
// forwards, to be used in the traits and to allow for specialization
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PdelabWrapper
{
static_assert(Dune::AlwaysFalse<PdelabSpaceImp>::value, "Untested for arbitrary dimension!");
};
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PiolaTransformedPdelabWrapper
{
static_assert(Dune::AlwaysFalse<PdelabSpaceImp>::value, "Untested for these dimensions!");
};
namespace internal {
// forward, to allow for specialization
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols>
class PdelabWrapperTraits;
//! Specialization for rangeDimCols = 1
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim>
class PdelabWrapperTraits<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
public:
typedef PdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> derived_type;
private:
typedef PDELab::LocalFunctionSpace<PdelabSpaceImp, PDELab::TrialSpaceTag> PdelabLFSType;
typedef FiniteElementInterfaceSwitch<typename PdelabSpaceImp::Traits::FiniteElementType> FESwitchType;
public:
typedef typename FESwitchType::Basis BackendType;
typedef EntityImp EntityType;
private:
friend class PdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>;
};
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim>
class PiolaTransformedPdelabWrapperTraits
{
static_assert(domainDim == rangeDim, "Untested!");
public:
typedef PiolaTransformedPdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim>
derived_type;
private:
typedef PDELab::LocalFunctionSpace<PdelabSpaceImp, PDELab::TrialSpaceTag> PdelabLFSType;
typedef FiniteElementInterfaceSwitch<typename PdelabSpaceImp::Traits::FiniteElementType> FESwitchType;
public:
typedef typename FESwitchType::Basis BackendType;
typedef EntityImp EntityType;
private:
friend class PiolaTransformedPdelabWrapper<PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp,
rangeDim, 1>;
};
} // namespace internal
//! Specialization for dimRange = 1, dimRangeRows = 1
template <class PdelabSpaceType, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp>
class PdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
: public BaseFunctionSetInterface<internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp,
domainDim, RangeFieldImp, 1, 1>,
DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
{
typedef PdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1> ThisType;
typedef BaseFunctionSetInterface<internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, 1, 1>,
DomainFieldImp, domainDim, RangeFieldImp, 1, 1> BaseType;
public:
typedef internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1>
Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
private:
typedef typename Traits::PdelabLFSType PdelabLFSType;
typedef typename Traits::FESwitchType FESwitchType;
public:
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)
: BaseType(ent)
, tmp_domain_(0)
{
PdelabLFSType* lfs_ptr = new PdelabLFSType(space);
lfs_ptr->bind(this->entity());
lfs_ = std::unique_ptr<PdelabLFSType>(lfs_ptr);
backend_ = std::unique_ptr<BackendType>(new BackendType(FESwitchType::basis(lfs_->finiteElement())));
} // PdelabWrapper(...)
PdelabWrapper(ThisType&& source) = default;
PdelabWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const override final
{
return backend_->size();
}
virtual size_t order() const override final
{
return backend_->order();
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const override final
{
assert(ret.size() >= backend_->size());
backend_->evaluateFunction(xx, ret);
}
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const override final
{
assert(ret.size() >= backend_->size());
backend_->evaluateJacobian(xx, ret);
const auto jacobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx);
for (size_t ii = 0; ii < ret.size(); ++ii) {
jacobian_inverse_transposed.mv(ret[ii][0], tmp_domain_);
ret[ii][0] = tmp_domain_;
}
} // ... jacobian(...)
using BaseType::jacobian;
private:
mutable DomainType tmp_domain_;
std::unique_ptr<const PdelabLFSType> lfs_;
std::unique_ptr<const BackendType> backend_;
}; // class PdelabWrapper
template <class PdelabSpaceType, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim>
class PdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
: public BaseFunctionSetInterface<internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp,
domainDim, RangeFieldImp, rangeDim, 1>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
typedef PdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
typedef BaseFunctionSetInterface<internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim, 1>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;
public:
typedef internal::PdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
1> Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
private:
typedef typename Traits::PdelabLFSType PdelabLFSType;
typedef typename Traits::FESwitchType FESwitchType;
public:
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
static const size_t dimDomain = domainDim;
static const size_t dimRange = rangeDim;
PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)
: BaseType(ent)
, tmp_domain_(0)
{
PdelabLFSType* lfs_ptr = new PdelabLFSType(space);
lfs_ptr->bind(this->entity());
lfs_ = std::unique_ptr<PdelabLFSType>(lfs_ptr);
backend_ = std::unique_ptr<BackendType>(new BackendType(FESwitchType::basis(lfs_->finiteElement())));
} // PdelabWrapper(...)
PdelabWrapper(ThisType&& source) = default;
PdelabWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const override final
{
return backend_->size() * dimRange;
}
virtual size_t order() const override final
{
return backend_->order();
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const override final
{
assert(ret.size() >= size());
const size_t size_of_factor_basefunctionset = backend_->size();
std::vector<Dune::FieldVector<RangeFieldImp, 1>> factor_ret(size_of_factor_basefunctionset);
backend_->evaluateFunction(xx, factor_ret);
// if factor_ret is [1 2] and we have two factors, we want to return [[1 0] [2 0] [0 1] [0 2]]
for (size_t ii = 0; ii < size(); ++ii) {
size_t factor_index = 0;
size_t jj = ii;
while (jj >= size_of_factor_basefunctionset) {
jj -= size_of_factor_basefunctionset;
++factor_index;
}
ret[ii] *= 0;
ret[ii][factor_index] = factor_ret[jj][0];
}
}
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const override final
{
assert(ret.size() >= backend_->size());
const size_t size_of_factor_basefunctionset = backend_->size();
std::vector<FieldMatrix<RangeFieldImp, 1, dimDomain>> factor_ret(size_of_factor_basefunctionset);
backend_->evaluateJacobian(xx, factor_ret);
const auto jacobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx);
for (size_t ii = 0; ii < ret.size(); ++ii) {
jacobian_inverse_transposed.mv(factor_ret[ii][0], tmp_domain_);
factor_ret[ii][0] = tmp_domain_;
}
for (size_t ii = 0; ii < dimRange; ++ii)
for (size_t jj = 0; jj < size_of_factor_basefunctionset; ++jj)
ret[jj][ii] = factor_ret[jj][0];
} // ... jacobian(...)
using BaseType::jacobian;
private:
mutable DomainType tmp_domain_;
std::unique_ptr<const PdelabLFSType> lfs_;
std::unique_ptr<const BackendType> backend_;
}; // class PdelabWrapper
template <class PdelabSpaceType, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim>
class PiolaTransformedPdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
: public BaseFunctionSetInterface<internal::PiolaTransformedPdelabWrapperTraits<PdelabSpaceType, EntityImp,
DomainFieldImp, domainDim,
RangeFieldImp, rangeDim>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>
{
typedef PiolaTransformedPdelabWrapper<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim,
1> ThisType;
typedef BaseFunctionSetInterface<internal::PiolaTransformedPdelabWrapperTraits<PdelabSpaceType, EntityImp,
DomainFieldImp, domainDim,
RangeFieldImp, rangeDim>,
DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;
public:
typedef internal::PiolaTransformedPdelabWrapperTraits<PdelabSpaceType, EntityImp, DomainFieldImp, domainDim,
RangeFieldImp, rangeDim> Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
private:
typedef typename Traits::PdelabLFSType PdelabLFSType;
typedef typename Traits::FESwitchType FESwitchType;
public:
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
using typename BaseType::RangeType;
using typename BaseType::JacobianRangeType;
PiolaTransformedPdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)
: BaseType(ent)
, tmp_domain_(DomainFieldType(0))
, tmp_jacobian_transposed_(DomainFieldType(0))
, tmp_jacobian_inverse_transposed_(DomainFieldType(0))
{
PdelabLFSType* lfs_ptr = new PdelabLFSType(space);
lfs_ptr->bind(this->entity());
lfs_ = std::unique_ptr<PdelabLFSType>(lfs_ptr);
backend_ = std::unique_ptr<BackendType>(new BackendType(FESwitchType::basis(lfs_->finiteElement())));
tmp_ranges_ = std::vector<RangeType>(backend_->size(), RangeType(0));
tmp_jacobian_ranges_ = std::vector<JacobianRangeType>(backend_->size(), JacobianRangeType(0));
} // PdelabWrapper(...)
PiolaTransformedPdelabWrapper(ThisType&& source) = default;
PiolaTransformedPdelabWrapper(const ThisType& /*other*/) = delete;
ThisType& operator=(const ThisType& /*other*/) = delete;
const BackendType& backend() const
{
return *backend_;
}
virtual size_t size() const override final
{
return backend_->size();
}
virtual size_t order() const override final
{
return backend_->order();
}
virtual void evaluate(const DomainType& xx, std::vector<RangeType>& ret) const override final
{
assert(lfs_);
assert(backend_);
assert(tmp_ranges_.size() >= backend_->size());
assert(ret.size() >= backend_->size());
backend_->evaluateFunction(xx, tmp_ranges_);
const auto geometry = this->entity().geometry();
tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);
const DomainFieldType integration_element = geometry.integrationElement(xx);
for (size_t ii = 0; ii < backend_->size(); ++ii) {
tmp_jacobian_transposed_.mtv(tmp_ranges_[ii], ret[ii]);
ret[ii] /= integration_element;
}
} // ... evaluate(...)
using BaseType::evaluate;
virtual void jacobian(const DomainType& xx, std::vector<JacobianRangeType>& ret) const override final
{
assert(lfs_);
assert(backend_);
assert(ret.size() >= backend_->size());
backend_->evaluateJacobian(xx, tmp_jacobian_ranges_);
const auto geometry = this->entity().geometry();
tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);
tmp_jacobian_inverse_transposed_ = geometry.jacobianInverseTransposed(xx);
const DomainFieldType integration_element = geometry.integrationElement(xx);
for (size_t ii = 0; ii < backend_->size(); ++ii) {
for (size_t jj = 0; jj < dimDomain; ++jj) {
tmp_jacobian_inverse_transposed_.mv(tmp_jacobian_ranges_[ii][jj], ret[ii][jj]);
tmp_jacobian_transposed_.mv(ret[ii][jj], tmp_jacobian_ranges_[ii][jj]);
tmp_jacobian_ranges_[ii][jj] /= integration_element;
ret[ii][jj] = tmp_jacobian_ranges_[ii][jj];
}
}
} // ... jacobian(...)
using BaseType::jacobian;
private:
mutable DomainType tmp_domain_;
mutable typename EntityType::Geometry::JacobianTransposed tmp_jacobian_transposed_;
mutable typename EntityType::Geometry::JacobianInverseTransposed tmp_jacobian_inverse_transposed_;
std::unique_ptr<const PdelabLFSType> lfs_;
std::unique_ptr<const BackendType> backend_;
mutable std::vector<RangeType> tmp_ranges_;
mutable std::vector<JacobianRangeType> tmp_jacobian_ranges_;
}; // class PiolaTransformedPdelabWrapper
#else // HAVE_DUNE_PDELAB
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PdelabWrapper
{
static_assert(AlwaysFalse<PdelabSpaceImp>::value, "You are missing dune-pdelab!");
};
template <class PdelabSpaceImp, class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp,
size_t rangeDim, size_t rangeDimCols = 1>
class PiolaTransformedPdelabWrapper
{
static_assert(AlwaysFalse<PdelabSpaceImp>::value, "You are missing dune-pdelab!");
};
#endif // HAVE_DUNE_PDELAB
} // namespace BaseFunctionSet
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH
<|endoftext|>
|
<commit_before>#include "log4qt/dailyfileappender.h"
#include "log4qt/loggingevent.h"
#include "log4qt/simplelayout.h"
#include <QDate>
#include <QSharedPointer>
#include <QTemporaryDir>
#include <QtTest/QtTest>
using Log4Qt::DailyFileAppender;
namespace
{
class DateRetrieverMock final : public Log4Qt::IDateRetriever
{
public:
QDate currentDate() const override
{
return mCurrentDate;
}
void setCurrentDate(const QDate currentDate)
{
mCurrentDate = currentDate;
}
private:
QDate mCurrentDate = QDate(2019, 1, 15);
};
}
class DailyFileAppenderTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void init();
void cleanup();
void testFileCreation_data();
void testFileCreation();
void testAppend();
void testRollOver();
void testObsoleteLogFileDeletion();
private:
QTemporaryDir *mLogDirectory;
QSharedPointer<DateRetrieverMock> mDateRetriever;
DailyFileAppender *mAppender;
};
void DailyFileAppenderTest::init()
{
mLogDirectory = new QTemporaryDir;
mDateRetriever.reset(new DateRetrieverMock);
mAppender = new DailyFileAppender;
mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
mAppender->setDateRetriever(mDateRetriever);
}
void DailyFileAppenderTest::cleanup()
{
delete mAppender;
delete mLogDirectory; // destructor will remove temporary directory
}
void DailyFileAppenderTest::testFileCreation_data()
{
QTest::addColumn<QString>("appName");
QTest::addColumn<QString>("datePattern");
QTest::addColumn<QString>("fileName");
QTest::newRow("default") << "app" << "_yyyy_MM_dd" << "app_2019_07_09.log";
QTest::newRow("Austria") << "app" << "_dd.MM.yyyy" << "app_09.07.2019.log";
QTest::newRow("service") << "srv" << "_yyyy_MM_dd" << "srv_2019_07_09.log";
}
void DailyFileAppenderTest::testFileCreation()
{
mDateRetriever->setCurrentDate(QDate(2019, 7, 9));
QFETCH(QString, appName);
QFETCH(QString, datePattern);
QFETCH(QString, fileName);
mAppender->setDatePattern(datePattern);
mAppender->setFile(mLogDirectory->filePath(appName + ".log"));
mAppender->activateOptions();
const QFileInfo fileInfo(mAppender->file());
QVERIFY(fileInfo.exists());
QCOMPARE(fileInfo.fileName(), fileName);
}
void DailyFileAppenderTest::testAppend()
{
mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));
mAppender->activateOptions();
const auto fileName = mAppender->file();
QVERIFY(QFileInfo::exists(fileName));
const QFile logFile(fileName);
// nothing written yet
QCOMPARE(logFile.size(), 0);
mAppender->append(Log4Qt::LoggingEvent());
QVERIFY(logFile.size() > 0);
}
void DailyFileAppenderTest::testRollOver()
{
mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));
mAppender->activateOptions();
mAppender->append(Log4Qt::LoggingEvent());
const auto fileNameDay1 = mAppender->file();
QVERIFY(QFileInfo::exists(fileNameDay1));
// one day has passed ...
mDateRetriever->setCurrentDate(mDateRetriever->currentDate().addDays(1));
// ... and when we try to append ...
mAppender->append(Log4Qt::LoggingEvent());
// ... we get a new log file
const auto fileNameDay2 = mAppender->file();
QVERIFY(QFileInfo::exists(fileNameDay2));
QVERIFY(fileNameDay1 != fileNameDay2);
}
namespace
{
void createFile(const QString& fileName)
{
QFile file(fileName);
file.open(QFile::WriteOnly);
file.close();
QVERIFY2(file.exists(), qPrintable(fileName));
}
}
void DailyFileAppenderTest::testObsoleteLogFileDeletion()
{
const auto deleteOnActivateFileName = mLogDirectory->filePath("app_2019_01_05.log");
createFile(deleteOnActivateFileName);
const auto deleteAfterOneDayFileName = mLogDirectory->filePath("app_2019_01_06.log");
createFile(deleteAfterOneDayFileName);
const auto alwaysKeptFileName = mLogDirectory->filePath("app_2019_01_07.log");
createFile(alwaysKeptFileName);
mDateRetriever->setCurrentDate(QDate(2019, 01, 10));
mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));
mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
mAppender->setKeepDays(4);
// after configuration ...
mAppender->activateOptions();
// ... we delete obsolete files
QVERIFY(!QFileInfo::exists(deleteOnActivateFileName));
QVERIFY(QFileInfo::exists(deleteAfterOneDayFileName));
QVERIFY(QFileInfo::exists(alwaysKeptFileName));
// appending later today ...
mAppender->append(Log4Qt::LoggingEvent());
// ... does not delete anything
QVERIFY(QFileInfo::exists(deleteAfterOneDayFileName));
QVERIFY(QFileInfo::exists(alwaysKeptFileName));
// one day has passed ...
mDateRetriever->setCurrentDate(mDateRetriever->currentDate().addDays(1));
// ... and we append additional messages ...
mAppender->append(Log4Qt::LoggingEvent());
// ... one file becomes obsolete and is deleted automatically
// Since deletion takes place in a separate thread, we would need to sleep here. To avoid that,
// we rely on the appender to wait for completion in its destructor
delete mAppender;
mAppender = nullptr;
QVERIFY(!QFileInfo::exists(deleteAfterOneDayFileName));
QVERIFY(QFileInfo::exists(alwaysKeptFileName));
}
QTEST_GUILESS_MAIN(DailyFileAppenderTest)
#include "dailyfileappendertest.moc"
<commit_msg>Made unit test source compatible with qt version < 5.9<commit_after>#include "log4qt/dailyfileappender.h"
#include "log4qt/loggingevent.h"
#include "log4qt/simplelayout.h"
#include <QDate>
#include <QSharedPointer>
#include <QTemporaryDir>
#include <QtTest/QtTest>
using Log4Qt::DailyFileAppender;
namespace
{
class DateRetrieverMock final : public Log4Qt::IDateRetriever
{
public:
QDate currentDate() const override
{
return mCurrentDate;
}
void setCurrentDate(const QDate currentDate)
{
mCurrentDate = currentDate;
}
private:
QDate mCurrentDate = QDate(2019, 1, 15);
};
}
class DailyFileAppenderTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void init();
void cleanup();
void testFileCreation_data();
void testFileCreation();
void testAppend();
void testRollOver();
void testObsoleteLogFileDeletion();
private:
QTemporaryDir *mLogDirectory;
QSharedPointer<DateRetrieverMock> mDateRetriever;
DailyFileAppender *mAppender;
};
void DailyFileAppenderTest::init()
{
mLogDirectory = new QTemporaryDir;
mDateRetriever.reset(new DateRetrieverMock);
mAppender = new DailyFileAppender;
mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
mAppender->setDateRetriever(mDateRetriever);
}
void DailyFileAppenderTest::cleanup()
{
delete mAppender;
delete mLogDirectory; // destructor will remove temporary directory
}
void DailyFileAppenderTest::testFileCreation_data()
{
QTest::addColumn<QString>("appName");
QTest::addColumn<QString>("datePattern");
QTest::addColumn<QString>("fileName");
QTest::newRow("default") << "app" << "_yyyy_MM_dd" << "app_2019_07_09.log";
QTest::newRow("Austria") << "app" << "_dd.MM.yyyy" << "app_09.07.2019.log";
QTest::newRow("service") << "srv" << "_yyyy_MM_dd" << "srv_2019_07_09.log";
}
void DailyFileAppenderTest::testFileCreation()
{
mDateRetriever->setCurrentDate(QDate(2019, 7, 9));
QFETCH(QString, appName);
QFETCH(QString, datePattern);
QFETCH(QString, fileName);
mAppender->setDatePattern(datePattern);
mAppender->setFile(mLogDirectory->path() + '/' + appName + ".log");
mAppender->activateOptions();
const QFileInfo fileInfo(mAppender->file());
QVERIFY(fileInfo.exists());
QCOMPARE(fileInfo.fileName(), fileName);
}
void DailyFileAppenderTest::testAppend()
{
mAppender->setFile(mLogDirectory->path() + '/' + QStringLiteral("app.log"));
mAppender->activateOptions();
const auto fileName = mAppender->file();
QVERIFY(QFileInfo::exists(fileName));
const QFile logFile(fileName);
// nothing written yet
QCOMPARE(logFile.size(), 0);
mAppender->append(Log4Qt::LoggingEvent());
QVERIFY(logFile.size() > 0);
}
void DailyFileAppenderTest::testRollOver()
{
mAppender->setFile(mLogDirectory->path() + '/' + QStringLiteral("app.log"));
mAppender->activateOptions();
mAppender->append(Log4Qt::LoggingEvent());
const auto fileNameDay1 = mAppender->file();
QVERIFY(QFileInfo::exists(fileNameDay1));
// one day has passed ...
mDateRetriever->setCurrentDate(mDateRetriever->currentDate().addDays(1));
// ... and when we try to append ...
mAppender->append(Log4Qt::LoggingEvent());
// ... we get a new log file
const auto fileNameDay2 = mAppender->file();
QVERIFY(QFileInfo::exists(fileNameDay2));
QVERIFY(fileNameDay1 != fileNameDay2);
}
namespace
{
void createFile(const QString& fileName)
{
QFile file(fileName);
file.open(QFile::WriteOnly);
file.close();
QVERIFY2(file.exists(), qPrintable(fileName));
}
}
void DailyFileAppenderTest::testObsoleteLogFileDeletion()
{
const auto deleteOnActivateFileName = mLogDirectory->path() + '/' + QStringLiteral("app_2019_01_05.log");
createFile(deleteOnActivateFileName);
const auto deleteAfterOneDayFileName = mLogDirectory->path() + '/' + QStringLiteral("app_2019_01_06.log");
createFile(deleteAfterOneDayFileName);
const auto alwaysKeptFileName = mLogDirectory->path() + '/' + QStringLiteral("app_2019_01_07.log");
createFile(alwaysKeptFileName);
mDateRetriever->setCurrentDate(QDate(2019, 01, 10));
mAppender->setFile(mLogDirectory->path() + '/' + QStringLiteral("app.log"));
mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
mAppender->setKeepDays(4);
// after configuration ...
mAppender->activateOptions();
// ... we delete obsolete files
QVERIFY(!QFileInfo::exists(deleteOnActivateFileName));
QVERIFY(QFileInfo::exists(deleteAfterOneDayFileName));
QVERIFY(QFileInfo::exists(alwaysKeptFileName));
// appending later today ...
mAppender->append(Log4Qt::LoggingEvent());
// ... does not delete anything
QVERIFY(QFileInfo::exists(deleteAfterOneDayFileName));
QVERIFY(QFileInfo::exists(alwaysKeptFileName));
// one day has passed ...
mDateRetriever->setCurrentDate(mDateRetriever->currentDate().addDays(1));
// ... and we append additional messages ...
mAppender->append(Log4Qt::LoggingEvent());
// ... one file becomes obsolete and is deleted automatically
// Since deletion takes place in a separate thread, we would need to sleep here. To avoid that,
// we rely on the appender to wait for completion in its destructor
delete mAppender;
mAppender = nullptr;
QVERIFY(!QFileInfo::exists(deleteAfterOneDayFileName));
QVERIFY(QFileInfo::exists(alwaysKeptFileName));
}
QTEST_GUILESS_MAIN(DailyFileAppenderTest)
#include "dailyfileappendertest.moc"
<|endoftext|>
|
<commit_before>#include "ctrcommon/common.hpp"
#include <sys/unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <3ds.h>
static bool amInitialized = false;
static bool nsInitialized = false;
bool am_prepare() {
if(!amInitialized && amInit() == 0) {
amInitialized = true;
}
return amInitialized;
}
bool ns_prepare() {
if(!nsInitialized && nsInit() == 0) {
nsInitialized = true;
}
return nsInitialized;
}
void apps_cleanup() {
if(amInitialized) {
amExit();
amInitialized = false;
}
if(nsInitialized) {
nsExit();
nsInitialized = false;
}
}
u8 app_mediatype_to_byte(MediaType mediaType) {
return mediaType == NAND ? mediatype_NAND : mediatype_SDMC;
}
AppPlatform app_platform_from_id(u16 id) {
switch(id) {
case 1:
return WII;
case 3:
return DSI;
case 4:
return THREEDS;
case 5:
return WIIU;
default:
return UNKNOWN_PLATFORM;
}
}
AppCategory app_category_from_id(u16 id) {
if((id & 0x2) == 0x2) {
return DLC;
} else if((id & 0x6) == 0x6) {
return PATCH;
} else if((id & 0x10) == 0x10) {
return SYSTEM;
} else if((id & 0x8000) == 0x8000) {
return TWL;
}
return APP;
}
const std::string app_get_platform_name(AppPlatform platform) {
switch(platform) {
case WII:
return "Wii";
case DSI:
return "DSi";
case THREEDS:
return "3DS";
case WIIU:
return "Wii U";
default:
return "Unknown";
}
}
const std::string app_get_category_name(AppCategory category) {
switch(category) {
case APP:
return "App";
case DLC:
return "DLC";
case PATCH:
return "Patch";
case SYSTEM:
return "System";
case TWL:
return "TWL";
default:
return "Unknown";
}
}
std::vector<App> app_list(MediaType mediaType) {
std::vector<App> titles;
if(!am_prepare()) {
return titles;
}
u32 titleCount;
if(AM_GetTitleCount(app_mediatype_to_byte(mediaType), &titleCount) != 0) {
return titles;
}
u64 titleIds[titleCount];
if(AM_GetTitleList(app_mediatype_to_byte(mediaType), titleCount, titleIds) != 0) {
return titles;
}
for(u32 i = 0; i < titleCount; i++) {
u64 titleId = titleIds[i];
App app;
app.titleId = titleId;
app.uniqueId = ((u32 *) &titleId)[0];
AM_GetTitleProductCode(app_mediatype_to_byte(mediaType), titleId, app.productCode);
if(strcmp(app.productCode, "") == 0) {
strcpy(app.productCode, "<N/A>");
}
app.mediaType = mediaType;
app.platform = app_platform_from_id(((u16 *) &titleId)[3]);
app.category = app_category_from_id(((u16 *) &titleId)[2]);
titles.push_back(app);
}
return titles;
}
int app_install_file(MediaType mediaType, const std::string path, std::function<bool(int progress)> onProgress) {
FILE *fd = fopen(path.c_str(), "r");
if(!fd) {
return -1;
}
fseek(fd, 0, SEEK_END);
u64 size = (u64) ftell(fd);
fseek(fd, 0, SEEK_SET);
int ret = app_install(mediaType, fd, size, onProgress);
fclose(fd);
return ret;
}
int app_install(MediaType mediaType, FILE* fd, u64 size, std::function<bool(int progress)> onProgress) {
if(!am_prepare()) {
return -1;
}
if(onProgress != NULL) {
onProgress(0);
}
Handle ciaHandle;
int startRet = AM_StartCiaInstall(app_mediatype_to_byte(mediaType), &ciaHandle);
if(startRet != 0) {
return startRet;
}
u32 bufSize = 1024 * 16; // 16KB
void *buf = malloc(bufSize);
bool cancelled = false;
u64 pos = 0;
while(platform_is_running()) {
if(onProgress != NULL && !onProgress(size != 0 ? (int) ((pos / (float) size) * 100) : 0)) {
AM_CancelCIAInstall(&ciaHandle);
cancelled = true;
break;
}
u64 bytesRead = fread(buf, 1, bufSize, fd);
if(bytesRead == 0) {
break;
}
FSFILE_Write(ciaHandle, NULL, pos, buf, (u32) bytesRead, FS_WRITE_NOFLUSH);
pos += bytesRead;
}
free(buf);
if(cancelled) {
return -2;
}
if(size != 0 && pos != size) {
AM_CancelCIAInstall(&ciaHandle);
return -1;
}
if(onProgress != NULL) {
onProgress(100);
}
Result res = AM_FinishCiaInstall(app_mediatype_to_byte(mediaType), &ciaHandle);
if(res != 0 && (u32) res != 0xC8A044DC) { // Happens when already installed, but seems to have succeeded anyway...
return res;
}
return 0;
}
int app_delete(App app) {
if(!am_prepare()) {
return -1;
}
return AM_DeleteAppTitle(app_mediatype_to_byte(app.mediaType), app.titleId);
}
int app_launch(App app) {
if(!ns_prepare()) {
return -1;
}
return NS_RebootToTitle(app.mediaType, app.titleId);
}<commit_msg>Differentiate app_install return codes.<commit_after>#include "ctrcommon/common.hpp"
#include <sys/errno.h>
#include <sys/unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <3ds.h>
static bool amInitialized = false;
static bool nsInitialized = false;
bool am_prepare() {
if(!amInitialized && amInit() == 0) {
amInitialized = true;
}
return amInitialized;
}
bool ns_prepare() {
if(!nsInitialized && nsInit() == 0) {
nsInitialized = true;
}
return nsInitialized;
}
void apps_cleanup() {
if(amInitialized) {
amExit();
amInitialized = false;
}
if(nsInitialized) {
nsExit();
nsInitialized = false;
}
}
u8 app_mediatype_to_byte(MediaType mediaType) {
return mediaType == NAND ? mediatype_NAND : mediatype_SDMC;
}
AppPlatform app_platform_from_id(u16 id) {
switch(id) {
case 1:
return WII;
case 3:
return DSI;
case 4:
return THREEDS;
case 5:
return WIIU;
default:
return UNKNOWN_PLATFORM;
}
}
AppCategory app_category_from_id(u16 id) {
if((id & 0x2) == 0x2) {
return DLC;
} else if((id & 0x6) == 0x6) {
return PATCH;
} else if((id & 0x10) == 0x10) {
return SYSTEM;
} else if((id & 0x8000) == 0x8000) {
return TWL;
}
return APP;
}
const std::string app_get_platform_name(AppPlatform platform) {
switch(platform) {
case WII:
return "Wii";
case DSI:
return "DSi";
case THREEDS:
return "3DS";
case WIIU:
return "Wii U";
default:
return "Unknown";
}
}
const std::string app_get_category_name(AppCategory category) {
switch(category) {
case APP:
return "App";
case DLC:
return "DLC";
case PATCH:
return "Patch";
case SYSTEM:
return "System";
case TWL:
return "TWL";
default:
return "Unknown";
}
}
std::vector<App> app_list(MediaType mediaType) {
std::vector<App> titles;
if(!am_prepare()) {
return titles;
}
u32 titleCount;
if(AM_GetTitleCount(app_mediatype_to_byte(mediaType), &titleCount) != 0) {
return titles;
}
u64 titleIds[titleCount];
if(AM_GetTitleList(app_mediatype_to_byte(mediaType), titleCount, titleIds) != 0) {
return titles;
}
for(u32 i = 0; i < titleCount; i++) {
u64 titleId = titleIds[i];
App app;
app.titleId = titleId;
app.uniqueId = ((u32 *) &titleId)[0];
AM_GetTitleProductCode(app_mediatype_to_byte(mediaType), titleId, app.productCode);
if(strcmp(app.productCode, "") == 0) {
strcpy(app.productCode, "<N/A>");
}
app.mediaType = mediaType;
app.platform = app_platform_from_id(((u16 *) &titleId)[3]);
app.category = app_category_from_id(((u16 *) &titleId)[2]);
titles.push_back(app);
}
return titles;
}
int app_install_file(MediaType mediaType, const std::string path, std::function<bool(int progress)> onProgress) {
FILE *fd = fopen(path.c_str(), "r");
if(!fd) {
return -4;
}
fseek(fd, 0, SEEK_END);
u64 size = (u64) ftell(fd);
fseek(fd, 0, SEEK_SET);
int ret = app_install(mediaType, fd, size, onProgress);
fclose(fd);
return ret;
}
int app_install(MediaType mediaType, FILE* fd, u64 size, std::function<bool(int progress)> onProgress) {
if(!am_prepare()) {
return -1;
}
if(onProgress != NULL) {
onProgress(0);
}
Handle ciaHandle;
int startRet = AM_StartCiaInstall(app_mediatype_to_byte(mediaType), &ciaHandle);
if(startRet != 0) {
return startRet;
}
u32 bufSize = 1024 * 16; // 16KB
void *buf = malloc(bufSize);
bool cancelled = false;
bool eof = false;
u64 pos = 0;
while(platform_is_running()) {
if(onProgress != NULL && !onProgress(size != 0 ? (int) ((pos / (float) size) * 100) : 0)) {
AM_CancelCIAInstall(&ciaHandle);
cancelled = true;
break;
}
u64 bytesRead = fread(buf, 1, bufSize, fd);
if(bytesRead == 0) {
eof = true;
break;
}
FSFILE_Write(ciaHandle, NULL, pos, buf, (u32) bytesRead, FS_WRITE_NOFLUSH);
pos += bytesRead;
}
free(buf);
if(cancelled) {
return -2;
}
if(size != 0 && pos != size) {
AM_CancelCIAInstall(&ciaHandle);
if(eof && errno != 0) {
return errno;
}
return -3;
}
if(onProgress != NULL) {
onProgress(100);
}
Result res = AM_FinishCiaInstall(app_mediatype_to_byte(mediaType), &ciaHandle);
if(res != 0 && (u32) res != 0xC8A044DC) { // Happens when already installed, but seems to have succeeded anyway...
return res;
}
return 0;
}
int app_delete(App app) {
if(!am_prepare()) {
return -1;
}
return AM_DeleteAppTitle(app_mediatype_to_byte(app.mediaType), app.titleId);
}
int app_launch(App app) {
if(!ns_prepare()) {
return -1;
}
return NS_RebootToTitle(app.mediaType, app.titleId);
}<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/upgrade_detector.h"
#include "base/file_version_info.h"
#include "base/scoped_ptr.h"
#include "base/time.h"
#include "base/version.h"
#include "chrome/app/chrome_version_info.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/installer/util/browser_distribution.h"
#if defined(OS_WIN)
#include "chrome/installer/util/install_util.h"
#endif
// TODO(finnur): For the stable channel we want to check daily and notify
// the user if more than 2 weeks have passed since the upgrade happened
// (without a reboot). For the dev channel however, I want quicker feedback
// on how the feature works so I'm checking every hour and notifying the
// user immediately.
// How often to check for an upgrade.
static int kCheckForUpgradeEveryMs = 60 * 60 * 1000; // 1 hour.
// How long to wait before notifying the user about the upgrade.
static int kNotifyUserAfterMs = 0;
UpgradeDetector::UpgradeDetector()
: upgrade_detected_(false),
notify_upgrade_(false) {
#if !defined(OS_WIN)
return;
#endif
detect_upgrade_timer_.Start(
base::TimeDelta::FromMilliseconds(kCheckForUpgradeEveryMs),
this, &UpgradeDetector::CheckForUpgrade);
}
UpgradeDetector::~UpgradeDetector() {
}
void UpgradeDetector::CheckForUpgrade() {
#if defined(OS_WIN)
using installer::Version;
// Get the version of the currently *installed* instance of Chrome,
// which might be newer than the *running* instance if we have been
// upgraded in the background.
Version* installed_version = InstallUtil::GetChromeVersion(false);
if (!installed_version) {
// User level Chrome is not installed, check system level.
installed_version = InstallUtil::GetChromeVersion(true);
}
// Get the version of the currently *running* instance of Chrome.
scoped_ptr<FileVersionInfo> version(chrome_app::GetChromeVersionInfo());
if (version.get() == NULL) {
NOTREACHED() << L"Failed to get current file version";
return;
}
scoped_ptr<Version> running_version(Version::GetVersionFromString(
version->file_version()));
if (installed_version->IsHigherThan(running_version.get())) {
// Stop the recurring timer (that is checking for changes).
detect_upgrade_timer_.Stop();
upgrade_detected_ = true;
NotificationService::current()->Notify(
NotificationType::UPGRADE_DETECTED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
// Start the OneShot timer for notifying the user after a certain period.
upgrade_notification_timer_.Start(
base::TimeDelta::FromMilliseconds(kNotifyUserAfterMs),
this, &UpgradeDetector::NotifyOnUpgrade);
}
#else
DCHECK(kNotifyUserAfterMs > 0); // Avoid error: var defined but not used.
NOTIMPLEMENTED();
#endif
}
void UpgradeDetector::NotifyOnUpgrade() {
notify_upgrade_ = true;
NotificationService::current()->Notify(
NotificationType::UPGRADE_RECOMMENDED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
}
<commit_msg>Make sure the upgrade notification only happens on the official build, not on Chromium.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/upgrade_detector.h"
#include "base/file_version_info.h"
#include "base/scoped_ptr.h"
#include "base/time.h"
#include "base/version.h"
#include "chrome/app/chrome_version_info.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/installer/util/browser_distribution.h"
#if defined(OS_WIN)
#include "chrome/installer/util/install_util.h"
#endif
// TODO(finnur): For the stable channel we want to check daily and notify
// the user if more than 2 weeks have passed since the upgrade happened
// (without a reboot). For the dev channel however, I want quicker feedback
// on how the feature works so I'm checking every hour and notifying the
// user immediately.
// How often to check for an upgrade.
static int kCheckForUpgradeEveryMs = 60 * 60 * 1000; // 1 hour.
// How long to wait before notifying the user about the upgrade.
static int kNotifyUserAfterMs = 0;
UpgradeDetector::UpgradeDetector()
: upgrade_detected_(false),
notify_upgrade_(false) {
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
detect_upgrade_timer_.Start(
base::TimeDelta::FromMilliseconds(kCheckForUpgradeEveryMs),
this, &UpgradeDetector::CheckForUpgrade);
#endif
}
UpgradeDetector::~UpgradeDetector() {
}
void UpgradeDetector::CheckForUpgrade() {
#if defined(OS_WIN)
using installer::Version;
// Get the version of the currently *installed* instance of Chrome,
// which might be newer than the *running* instance if we have been
// upgraded in the background.
Version* installed_version = InstallUtil::GetChromeVersion(false);
if (!installed_version) {
// User level Chrome is not installed, check system level.
installed_version = InstallUtil::GetChromeVersion(true);
}
// Get the version of the currently *running* instance of Chrome.
scoped_ptr<FileVersionInfo> version(chrome_app::GetChromeVersionInfo());
if (version.get() == NULL) {
NOTREACHED() << L"Failed to get current file version";
return;
}
scoped_ptr<Version> running_version(Version::GetVersionFromString(
version->file_version()));
if (installed_version->IsHigherThan(running_version.get())) {
// Stop the recurring timer (that is checking for changes).
detect_upgrade_timer_.Stop();
upgrade_detected_ = true;
NotificationService::current()->Notify(
NotificationType::UPGRADE_DETECTED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
// Start the OneShot timer for notifying the user after a certain period.
upgrade_notification_timer_.Start(
base::TimeDelta::FromMilliseconds(kNotifyUserAfterMs),
this, &UpgradeDetector::NotifyOnUpgrade);
}
#else
DCHECK(kNotifyUserAfterMs > 0); // Avoid error: var defined but not used.
NOTIMPLEMENTED();
#endif
}
void UpgradeDetector::NotifyOnUpgrade() {
notify_upgrade_ = true;
NotificationService::current()->Notify(
NotificationType::UPGRADE_RECOMMENDED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_plugin_lib.h"
#include "base/command_line.h"
#include "base/hash_tables.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/perftimer.h"
#include "base/thread.h"
#if defined(OS_WIN)
#include "base/registry.h"
#endif
#include "base/string_util.h"
#include "chrome/common/chrome_counters.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/chrome_paths.h"
#include "webkit/glue/plugins/plugin_list.h"
using base::TimeDelta;
// TODO(port): revisit when plugins happier
#if defined(OS_WIN)
const TCHAR ChromePluginLib::kRegistryChromePlugins[] =
_T("Software\\Google\\Chrome\\Plugins");
static const TCHAR kRegistryLoadOnStartup[] = _T("LoadOnStartup");
static const TCHAR kRegistryPath[] = _T("Path");
#endif
typedef base::hash_map<FilePath, scoped_refptr<ChromePluginLib> >
PluginMap;
// A map of all the instantiated plugins.
static PluginMap* g_loaded_libs;
// The thread plugins are loaded and used in, lazily initialized upon
// the first creation call.
static PlatformThreadId g_plugin_thread_id = 0;
static MessageLoop* g_plugin_thread_loop = NULL;
static bool IsSingleProcessMode() {
// We don't support ChromePlugins in single-process mode.
return CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);
}
// static
bool ChromePluginLib::IsInitialized() {
return (g_loaded_libs != NULL);
}
// static
ChromePluginLib* ChromePluginLib::Create(const FilePath& filename,
const CPBrowserFuncs* bfuncs) {
// Keep a map of loaded plugins to ensure we only load each library once.
if (!g_loaded_libs) {
g_loaded_libs = new PluginMap();
g_plugin_thread_id = PlatformThread::CurrentId();
g_plugin_thread_loop = MessageLoop::current();
}
DCHECK(IsPluginThread());
PluginMap::const_iterator iter = g_loaded_libs->find(filename);
if (iter != g_loaded_libs->end())
return iter->second;
scoped_refptr<ChromePluginLib> plugin(new ChromePluginLib(filename));
if (!plugin->CP_Initialize(bfuncs))
return NULL;
(*g_loaded_libs)[filename] = plugin;
return plugin;
}
// static
ChromePluginLib* ChromePluginLib::Find(const FilePath& filename) {
if (g_loaded_libs) {
PluginMap::const_iterator iter = g_loaded_libs->find(filename);
if (iter != g_loaded_libs->end())
return iter->second;
}
return NULL;
}
// static
void ChromePluginLib::Destroy(const FilePath& filename) {
DCHECK(g_loaded_libs);
PluginMap::iterator iter = g_loaded_libs->find(filename);
if (iter != g_loaded_libs->end()) {
iter->second->Unload();
g_loaded_libs->erase(iter);
}
}
// static
bool ChromePluginLib::IsPluginThread() {
return PlatformThread::CurrentId() == g_plugin_thread_id;
}
// static
MessageLoop* ChromePluginLib::GetPluginThreadLoop() {
return g_plugin_thread_loop;
}
// static
void ChromePluginLib::RegisterPluginsWithNPAPI() {
// We don't support ChromePlugins in single-process mode.
if (IsSingleProcessMode())
return;
FilePath path;
// Register Gears, if available.
if (PathService::Get(chrome::FILE_GEARS_PLUGIN, &path))
NPAPI::PluginList::Singleton()->AddExtraPluginPath(path);
// Register the internal Flash, if available.
if (PathService::Get(chrome::FILE_FLASH_PLUGIN, &path))
NPAPI::PluginList::Singleton()->AddExtraPluginPath(path);
}
static void LogPluginLoadTime(const TimeDelta &time) {
UMA_HISTOGRAM_TIMES("Gears.LoadTime", time);
}
// static
void ChromePluginLib::LoadChromePlugins(const CPBrowserFuncs* bfuncs) {
static bool loaded = false;
if (loaded)
return;
loaded = true;
// We don't support ChromePlugins in single-process mode.
if (IsSingleProcessMode())
return;
FilePath path;
if (!PathService::Get(chrome::FILE_GEARS_PLUGIN, &path))
return;
PerfTimer timer;
ChromePluginLib::Create(path, bfuncs);
LogPluginLoadTime(timer.Elapsed());
// TODO(mpcomplete): disabled loading of plugins from the registry until we
// phase out registry keys from the gears installer.
#if 0
for (RegistryKeyIterator iter(HKEY_CURRENT_USER, kRegistryChromePlugins);
iter.Valid(); ++iter) {
// Use the registry to gather plugin across the file system.
std::wstring reg_path = kRegistryChromePlugins;
reg_path.append(L"\\");
reg_path.append(iter.Name());
RegKey key(HKEY_CURRENT_USER, reg_path.c_str());
DWORD is_persistent;
if (key.ReadValueDW(kRegistryLoadOnStartup, &is_persistent) &&
is_persistent) {
std::wstring path;
if (key.ReadValue(kRegistryPath, &path)) {
ChromePluginLib::Create(path, bfuncs);
}
}
}
#endif
}
// static
void ChromePluginLib::UnloadAllPlugins() {
if (g_loaded_libs) {
PluginMap::iterator it;
for (PluginMap::iterator it = g_loaded_libs->begin();
it != g_loaded_libs->end(); ++it) {
it->second->Unload();
}
delete g_loaded_libs;
g_loaded_libs = NULL;
}
}
const CPPluginFuncs& ChromePluginLib::functions() const {
DCHECK(initialized_);
DCHECK(IsPluginThread());
return plugin_funcs_;
}
ChromePluginLib::ChromePluginLib(const FilePath& filename)
: filename_(filename),
#if defined(OS_WIN)
module_(0),
#endif
initialized_(false),
CP_VersionNegotiate_(NULL),
CP_Initialize_(NULL) {
memset((void*)&plugin_funcs_, 0, sizeof(plugin_funcs_));
}
ChromePluginLib::~ChromePluginLib() {
}
bool ChromePluginLib::CP_Initialize(const CPBrowserFuncs* bfuncs) {
LOG(INFO) << "ChromePluginLib::CP_Initialize(" << filename_.value() <<
"): initialized=" << initialized_;
if (initialized_)
return true;
if (!Load())
return false;
if (CP_VersionNegotiate_) {
uint16 selected_version = 0;
CPError rv = CP_VersionNegotiate_(CP_VERSION, CP_VERSION,
&selected_version);
if ( (rv != CPERR_SUCCESS) || (selected_version != CP_VERSION))
return false;
}
plugin_funcs_.size = sizeof(plugin_funcs_);
CPError rv = CP_Initialize_(cpid(), bfuncs, &plugin_funcs_);
initialized_ = (rv == CPERR_SUCCESS) &&
(CP_GET_MAJOR_VERSION(plugin_funcs_.version) == CP_MAJOR_VERSION) &&
(CP_GET_MINOR_VERSION(plugin_funcs_.version) <= CP_MINOR_VERSION);
LOG(INFO) << "ChromePluginLib::CP_Initialize(" << filename_.value() <<
"): initialized=" << initialized_ <<
"): result=" << rv;
return initialized_;
}
void ChromePluginLib::CP_Shutdown() {
DCHECK(initialized_);
functions().shutdown();
initialized_ = false;
memset((void*)&plugin_funcs_, 0, sizeof(plugin_funcs_));
}
int ChromePluginLib::CP_Test(void* param) {
DCHECK(initialized_);
if (!CP_Test_)
return -1;
return CP_Test_(param);
}
bool ChromePluginLib::Load() {
#if !defined(OS_WIN)
// Mac and Linux won't implement Gears.
return false;
#else
DCHECK(module_ == 0);
module_ = LoadLibrary(filename_.value().c_str());
if (module_ == 0)
return false;
// required initialization function
CP_Initialize_ = reinterpret_cast<CP_InitializeFunc>
(GetProcAddress(module_, "CP_Initialize"));
if (!CP_Initialize_) {
FreeLibrary(module_);
module_ = 0;
return false;
}
// optional version negotiation function
CP_VersionNegotiate_ = reinterpret_cast<CP_VersionNegotiateFunc>
(GetProcAddress(module_, "CP_VersionNegotiate"));
// optional test function
CP_Test_ = reinterpret_cast<CP_TestFunc>
(GetProcAddress(module_, "CP_Test"));
return true;
#endif
}
void ChromePluginLib::Unload() {
NotificationService::current()->Notify(
NotificationType::CHROME_PLUGIN_UNLOADED,
Source<ChromePluginLib>(this),
NotificationService::NoDetails());
if (initialized_)
CP_Shutdown();
#if defined(OS_WIN)
if (module_) {
FreeLibrary(module_);
module_ = 0;
}
#endif
}
<commit_msg>Revert 42646 - Register internal plugins.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_plugin_lib.h"
#include "base/command_line.h"
#include "base/hash_tables.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/perftimer.h"
#include "base/thread.h"
#if defined(OS_WIN)
#include "base/registry.h"
#endif
#include "base/string_util.h"
#include "chrome/common/chrome_counters.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/chrome_paths.h"
#include "webkit/glue/plugins/plugin_list.h"
using base::TimeDelta;
// TODO(port): revisit when plugins happier
#if defined(OS_WIN)
const TCHAR ChromePluginLib::kRegistryChromePlugins[] =
_T("Software\\Google\\Chrome\\Plugins");
static const TCHAR kRegistryLoadOnStartup[] = _T("LoadOnStartup");
static const TCHAR kRegistryPath[] = _T("Path");
#endif
typedef base::hash_map<FilePath, scoped_refptr<ChromePluginLib> >
PluginMap;
// A map of all the instantiated plugins.
static PluginMap* g_loaded_libs;
// The thread plugins are loaded and used in, lazily initialized upon
// the first creation call.
static PlatformThreadId g_plugin_thread_id = 0;
static MessageLoop* g_plugin_thread_loop = NULL;
static bool IsSingleProcessMode() {
// We don't support ChromePlugins in single-process mode.
return CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);
}
// static
bool ChromePluginLib::IsInitialized() {
return (g_loaded_libs != NULL);
}
// static
ChromePluginLib* ChromePluginLib::Create(const FilePath& filename,
const CPBrowserFuncs* bfuncs) {
// Keep a map of loaded plugins to ensure we only load each library once.
if (!g_loaded_libs) {
g_loaded_libs = new PluginMap();
g_plugin_thread_id = PlatformThread::CurrentId();
g_plugin_thread_loop = MessageLoop::current();
}
DCHECK(IsPluginThread());
PluginMap::const_iterator iter = g_loaded_libs->find(filename);
if (iter != g_loaded_libs->end())
return iter->second;
scoped_refptr<ChromePluginLib> plugin(new ChromePluginLib(filename));
if (!plugin->CP_Initialize(bfuncs))
return NULL;
(*g_loaded_libs)[filename] = plugin;
return plugin;
}
// static
ChromePluginLib* ChromePluginLib::Find(const FilePath& filename) {
if (g_loaded_libs) {
PluginMap::const_iterator iter = g_loaded_libs->find(filename);
if (iter != g_loaded_libs->end())
return iter->second;
}
return NULL;
}
// static
void ChromePluginLib::Destroy(const FilePath& filename) {
DCHECK(g_loaded_libs);
PluginMap::iterator iter = g_loaded_libs->find(filename);
if (iter != g_loaded_libs->end()) {
iter->second->Unload();
g_loaded_libs->erase(iter);
}
}
// static
bool ChromePluginLib::IsPluginThread() {
return PlatformThread::CurrentId() == g_plugin_thread_id;
}
// static
MessageLoop* ChromePluginLib::GetPluginThreadLoop() {
return g_plugin_thread_loop;
}
// static
void ChromePluginLib::RegisterPluginsWithNPAPI() {
// We don't support ChromePlugins in single-process mode.
if (IsSingleProcessMode())
return;
FilePath path;
if (!PathService::Get(chrome::FILE_GEARS_PLUGIN, &path))
return;
NPAPI::PluginList::Singleton()->AddExtraPluginPath(path);
}
static void LogPluginLoadTime(const TimeDelta &time) {
UMA_HISTOGRAM_TIMES("Gears.LoadTime", time);
}
// static
void ChromePluginLib::LoadChromePlugins(const CPBrowserFuncs* bfuncs) {
static bool loaded = false;
if (loaded)
return;
loaded = true;
// We don't support ChromePlugins in single-process mode.
if (IsSingleProcessMode())
return;
FilePath path;
if (!PathService::Get(chrome::FILE_GEARS_PLUGIN, &path))
return;
PerfTimer timer;
ChromePluginLib::Create(path, bfuncs);
LogPluginLoadTime(timer.Elapsed());
// TODO(mpcomplete): disabled loading of plugins from the registry until we
// phase out registry keys from the gears installer.
#if 0
for (RegistryKeyIterator iter(HKEY_CURRENT_USER, kRegistryChromePlugins);
iter.Valid(); ++iter) {
// Use the registry to gather plugin across the file system.
std::wstring reg_path = kRegistryChromePlugins;
reg_path.append(L"\\");
reg_path.append(iter.Name());
RegKey key(HKEY_CURRENT_USER, reg_path.c_str());
DWORD is_persistent;
if (key.ReadValueDW(kRegistryLoadOnStartup, &is_persistent) &&
is_persistent) {
std::wstring path;
if (key.ReadValue(kRegistryPath, &path)) {
ChromePluginLib::Create(path, bfuncs);
}
}
}
#endif
}
// static
void ChromePluginLib::UnloadAllPlugins() {
if (g_loaded_libs) {
PluginMap::iterator it;
for (PluginMap::iterator it = g_loaded_libs->begin();
it != g_loaded_libs->end(); ++it) {
it->second->Unload();
}
delete g_loaded_libs;
g_loaded_libs = NULL;
}
}
const CPPluginFuncs& ChromePluginLib::functions() const {
DCHECK(initialized_);
DCHECK(IsPluginThread());
return plugin_funcs_;
}
ChromePluginLib::ChromePluginLib(const FilePath& filename)
: filename_(filename),
#if defined(OS_WIN)
module_(0),
#endif
initialized_(false),
CP_VersionNegotiate_(NULL),
CP_Initialize_(NULL) {
memset((void*)&plugin_funcs_, 0, sizeof(plugin_funcs_));
}
ChromePluginLib::~ChromePluginLib() {
}
bool ChromePluginLib::CP_Initialize(const CPBrowserFuncs* bfuncs) {
LOG(INFO) << "ChromePluginLib::CP_Initialize(" << filename_.value() <<
"): initialized=" << initialized_;
if (initialized_)
return true;
if (!Load())
return false;
if (CP_VersionNegotiate_) {
uint16 selected_version = 0;
CPError rv = CP_VersionNegotiate_(CP_VERSION, CP_VERSION,
&selected_version);
if ( (rv != CPERR_SUCCESS) || (selected_version != CP_VERSION))
return false;
}
plugin_funcs_.size = sizeof(plugin_funcs_);
CPError rv = CP_Initialize_(cpid(), bfuncs, &plugin_funcs_);
initialized_ = (rv == CPERR_SUCCESS) &&
(CP_GET_MAJOR_VERSION(plugin_funcs_.version) == CP_MAJOR_VERSION) &&
(CP_GET_MINOR_VERSION(plugin_funcs_.version) <= CP_MINOR_VERSION);
LOG(INFO) << "ChromePluginLib::CP_Initialize(" << filename_.value() <<
"): initialized=" << initialized_ <<
"): result=" << rv;
return initialized_;
}
void ChromePluginLib::CP_Shutdown() {
DCHECK(initialized_);
functions().shutdown();
initialized_ = false;
memset((void*)&plugin_funcs_, 0, sizeof(plugin_funcs_));
}
int ChromePluginLib::CP_Test(void* param) {
DCHECK(initialized_);
if (!CP_Test_)
return -1;
return CP_Test_(param);
}
bool ChromePluginLib::Load() {
#if !defined(OS_WIN)
// Mac and Linux won't implement Gears.
return false;
#else
DCHECK(module_ == 0);
module_ = LoadLibrary(filename_.value().c_str());
if (module_ == 0)
return false;
// required initialization function
CP_Initialize_ = reinterpret_cast<CP_InitializeFunc>
(GetProcAddress(module_, "CP_Initialize"));
if (!CP_Initialize_) {
FreeLibrary(module_);
module_ = 0;
return false;
}
// optional version negotiation function
CP_VersionNegotiate_ = reinterpret_cast<CP_VersionNegotiateFunc>
(GetProcAddress(module_, "CP_VersionNegotiate"));
// optional test function
CP_Test_ = reinterpret_cast<CP_TestFunc>
(GetProcAddress(module_, "CP_Test"));
return true;
#endif
}
void ChromePluginLib::Unload() {
NotificationService::current()->Notify(
NotificationType::CHROME_PLUGIN_UNLOADED,
Source<ChromePluginLib>(this),
NotificationService::NoDetails());
if (initialized_)
CP_Shutdown();
#if defined(OS_WIN)
if (module_) {
FreeLibrary(module_);
module_ = 0;
}
#endif
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/thread.h"
#include "chrome/common/ipc_channel_proxy.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/ipc_message_utils.h"
namespace IPC {
//-----------------------------------------------------------------------------
ChannelProxy::Context::Context(Channel::Listener* listener,
MessageFilter* filter,
MessageLoop* ipc_message_loop)
: listener_message_loop_(MessageLoop::current()),
listener_(listener),
ipc_message_loop_(ipc_message_loop),
channel_(NULL),
peer_pid_(0),
channel_connected_called_(false) {
if (filter)
filters_.push_back(filter);
}
void ChannelProxy::Context::CreateChannel(const std::string& id,
const Channel::Mode& mode) {
DCHECK(channel_ == NULL);
channel_id_ = id;
channel_ = new Channel(id, mode, this);
}
bool ChannelProxy::Context::TryFilters(const Message& message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::current();
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i]->OnMessageReceived(message)) {
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
return true;
}
}
return false;
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnMessageReceived(const Message& message) {
// First give a chance to the filters to process this message.
if (!TryFilters(message))
OnMessageReceivedNoFilter(message);
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnMessageReceivedNoFilter(const Message& message) {
// NOTE: This code relies on the listener's message loop not going away while
// this thread is active. That should be a reasonable assumption, but it
// feels risky. We may want to invent some more indirect way of referring to
// a MessageLoop if this becomes a problem.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchMessage, message));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelConnected(int32 peer_pid) {
peer_pid_ = peer_pid;
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelConnected(peer_pid);
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchConnected));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelError() {
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelError();
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchError));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelOpened() {
DCHECK(channel_ != NULL);
// Assume a reference to ourselves on behalf of this thread. This reference
// will be released when we are closed.
AddRef();
if (!channel_->Connect()) {
OnChannelError();
return;
}
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnFilterAdded(channel_);
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelClosed() {
// It's okay for IPC::ChannelProxy::Close to be called more than once, which
// would result in this branch being taken.
if (!channel_)
return;
for (size_t i = 0; i < filters_.size(); ++i) {
filters_[i]->OnChannelClosing();
filters_[i]->OnFilterRemoved();
}
// We don't need the filters anymore.
filters_.clear();
delete channel_;
channel_ = NULL;
// Balance with the reference taken during startup. This may result in
// self-destruction.
Release();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnSendMessage(Message* message) {
if (!channel_->Send(message))
OnChannelError();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnAddFilter(MessageFilter* filter) {
filters_.push_back(filter);
// If the channel has already been created, then we need to send this message
// so that the filter gets access to the Channel.
if (channel_)
filter->OnFilterAdded(channel_);
// Balances the AddRef in ChannelProxy::AddFilter.
filter->Release();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnRemoveFilter(MessageFilter* filter) {
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i].get() == filter) {
filter->OnFilterRemoved();
filters_.erase(filters_.begin() + i);
return;
}
}
NOTREACHED() << "filter to be removed not found";
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchMessage(const Message& message) {
if (!listener_)
return;
OnDispatchConnected();
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::current();
if (message.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(message);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
listener_->OnMessageReceived(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchConnected() {
if (channel_connected_called_)
return;
channel_connected_called_ = true;
if (listener_)
listener_->OnChannelConnected(peer_pid_);
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchError() {
if (listener_)
listener_->OnChannelError();
}
//-----------------------------------------------------------------------------
ChannelProxy::ChannelProxy(const std::string& channel_id, Channel::Mode mode,
Channel::Listener* listener, MessageFilter* filter,
MessageLoop* ipc_thread)
: context_(new Context(listener, filter, ipc_thread)) {
Init(channel_id, mode, ipc_thread, true);
}
ChannelProxy::ChannelProxy(const std::string& channel_id, Channel::Mode mode,
MessageLoop* ipc_thread, Context* context,
bool create_pipe_now)
: context_(context) {
Init(channel_id, mode, ipc_thread, create_pipe_now);
}
void ChannelProxy::Init(const std::string& channel_id, Channel::Mode mode,
MessageLoop* ipc_thread_loop, bool create_pipe_now) {
if (create_pipe_now) {
// Create the channel immediately. This effectively sets up the
// low-level pipe so that the client can connect. Without creating
// the pipe immediately, it is possible for a listener to attempt
// to connect and get an error since the pipe doesn't exist yet.
context_->CreateChannel(channel_id, mode);
} else {
#if defined(OS_POSIX)
// TODO(playmobil): On POSIX, IPC::Channel uses a socketpair(), one side of
// which needs to be mapped into the child process' address space.
// To know the value of the client side FD we need to have already
// created a socketpair which currently occurs in IPC::Channel's
// constructor.
// If we lazilly construct the IPC::Channel then the caller has no way
// of knowing the FD #.
//
// We can solve this either by having the Channel's creation launch the
// subprocess itself or by creating the socketpair() externally.
NOTIMPLEMENTED();
#endif // defined(OS_POSIX)
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::CreateChannel, channel_id, mode));
}
// complete initialization on the background thread
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelOpened));
}
void ChannelProxy::Close() {
// Clear the backpointer to the listener so that any pending calls to
// Context::OnDispatchMessage or OnDispatchError will be ignored. It is
// possible that the channel could be closed while it is receiving messages!
context_->Clear();
if (context_->ipc_message_loop()) {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelClosed));
}
}
bool ChannelProxy::Send(Message* message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::current()->OnSendMessage(message, context_->channel_id());
#endif
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnSendMessage, message));
return true;
}
void ChannelProxy::AddFilter(MessageFilter* filter) {
// We want to addref the filter to prevent it from
// being destroyed before the OnAddFilter call is invoked.
filter->AddRef();
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnAddFilter, filter));
}
void ChannelProxy::RemoveFilter(MessageFilter* filter) {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnRemoveFilter, filter));
}
#if defined(OS_POSIX)
// See the TODO regarding lazy initialization of the channel in
// ChannelProxy::Init().
// We assume that IPC::Channel::GetClientFileDescriptorMapping() is thread-safe.
int ChannelProxy::GetClientFileDescriptor() const {
Channel *channel = context_.get()->channel_;
DCHECK(channel); // Channel must have been created first.
return channel->GetClientFileDescriptor();
}
#endif
//-----------------------------------------------------------------------------
} // namespace IPC
<commit_msg>posix: drop a NOTIMPLEMENTED that is now implemented<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/thread.h"
#include "chrome/common/ipc_channel_proxy.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/ipc_message_utils.h"
namespace IPC {
//-----------------------------------------------------------------------------
ChannelProxy::Context::Context(Channel::Listener* listener,
MessageFilter* filter,
MessageLoop* ipc_message_loop)
: listener_message_loop_(MessageLoop::current()),
listener_(listener),
ipc_message_loop_(ipc_message_loop),
channel_(NULL),
peer_pid_(0),
channel_connected_called_(false) {
if (filter)
filters_.push_back(filter);
}
void ChannelProxy::Context::CreateChannel(const std::string& id,
const Channel::Mode& mode) {
DCHECK(channel_ == NULL);
channel_id_ = id;
channel_ = new Channel(id, mode, this);
}
bool ChannelProxy::Context::TryFilters(const Message& message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::current();
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i]->OnMessageReceived(message)) {
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
return true;
}
}
return false;
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnMessageReceived(const Message& message) {
// First give a chance to the filters to process this message.
if (!TryFilters(message))
OnMessageReceivedNoFilter(message);
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnMessageReceivedNoFilter(const Message& message) {
// NOTE: This code relies on the listener's message loop not going away while
// this thread is active. That should be a reasonable assumption, but it
// feels risky. We may want to invent some more indirect way of referring to
// a MessageLoop if this becomes a problem.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchMessage, message));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelConnected(int32 peer_pid) {
peer_pid_ = peer_pid;
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelConnected(peer_pid);
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchConnected));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelError() {
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelError();
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchError));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelOpened() {
DCHECK(channel_ != NULL);
// Assume a reference to ourselves on behalf of this thread. This reference
// will be released when we are closed.
AddRef();
if (!channel_->Connect()) {
OnChannelError();
return;
}
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnFilterAdded(channel_);
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelClosed() {
// It's okay for IPC::ChannelProxy::Close to be called more than once, which
// would result in this branch being taken.
if (!channel_)
return;
for (size_t i = 0; i < filters_.size(); ++i) {
filters_[i]->OnChannelClosing();
filters_[i]->OnFilterRemoved();
}
// We don't need the filters anymore.
filters_.clear();
delete channel_;
channel_ = NULL;
// Balance with the reference taken during startup. This may result in
// self-destruction.
Release();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnSendMessage(Message* message) {
if (!channel_->Send(message))
OnChannelError();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnAddFilter(MessageFilter* filter) {
filters_.push_back(filter);
// If the channel has already been created, then we need to send this message
// so that the filter gets access to the Channel.
if (channel_)
filter->OnFilterAdded(channel_);
// Balances the AddRef in ChannelProxy::AddFilter.
filter->Release();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnRemoveFilter(MessageFilter* filter) {
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i].get() == filter) {
filter->OnFilterRemoved();
filters_.erase(filters_.begin() + i);
return;
}
}
NOTREACHED() << "filter to be removed not found";
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchMessage(const Message& message) {
if (!listener_)
return;
OnDispatchConnected();
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::current();
if (message.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(message);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
listener_->OnMessageReceived(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchConnected() {
if (channel_connected_called_)
return;
channel_connected_called_ = true;
if (listener_)
listener_->OnChannelConnected(peer_pid_);
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchError() {
if (listener_)
listener_->OnChannelError();
}
//-----------------------------------------------------------------------------
ChannelProxy::ChannelProxy(const std::string& channel_id, Channel::Mode mode,
Channel::Listener* listener, MessageFilter* filter,
MessageLoop* ipc_thread)
: context_(new Context(listener, filter, ipc_thread)) {
Init(channel_id, mode, ipc_thread, true);
}
ChannelProxy::ChannelProxy(const std::string& channel_id, Channel::Mode mode,
MessageLoop* ipc_thread, Context* context,
bool create_pipe_now)
: context_(context) {
Init(channel_id, mode, ipc_thread, create_pipe_now);
}
void ChannelProxy::Init(const std::string& channel_id, Channel::Mode mode,
MessageLoop* ipc_thread_loop, bool create_pipe_now) {
if (create_pipe_now) {
// Create the channel immediately. This effectively sets up the
// low-level pipe so that the client can connect. Without creating
// the pipe immediately, it is possible for a listener to attempt
// to connect and get an error since the pipe doesn't exist yet.
context_->CreateChannel(channel_id, mode);
} else {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::CreateChannel, channel_id, mode));
}
// complete initialization on the background thread
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelOpened));
}
void ChannelProxy::Close() {
// Clear the backpointer to the listener so that any pending calls to
// Context::OnDispatchMessage or OnDispatchError will be ignored. It is
// possible that the channel could be closed while it is receiving messages!
context_->Clear();
if (context_->ipc_message_loop()) {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelClosed));
}
}
bool ChannelProxy::Send(Message* message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::current()->OnSendMessage(message, context_->channel_id());
#endif
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnSendMessage, message));
return true;
}
void ChannelProxy::AddFilter(MessageFilter* filter) {
// We want to addref the filter to prevent it from
// being destroyed before the OnAddFilter call is invoked.
filter->AddRef();
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnAddFilter, filter));
}
void ChannelProxy::RemoveFilter(MessageFilter* filter) {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnRemoveFilter, filter));
}
#if defined(OS_POSIX)
// See the TODO regarding lazy initialization of the channel in
// ChannelProxy::Init().
// We assume that IPC::Channel::GetClientFileDescriptorMapping() is thread-safe.
int ChannelProxy::GetClientFileDescriptor() const {
Channel *channel = context_.get()->channel_;
DCHECK(channel); // Channel must have been created first.
return channel->GetClientFileDescriptor();
}
#endif
//-----------------------------------------------------------------------------
} // namespace IPC
<|endoftext|>
|
<commit_before>/*
docker-script: run script files inside Docker containers
Copyright (c) 2017, Adam Rehn
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 "NvidiaDockerImages.h"
#include "Utility.h"
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using std::ifstream;
using std::vector;
using std::clog;
using std::endl;
int main (int argc, char* argv[])
{
//Check that a script file was specified
if (argc > 1)
{
try
{
//Parse CLI arguments, keeping docker-script options separate from script options
bool interactive = true;
bool verboseOutput = false;
bool enableDebugging = false;
string trailingArgs = "";
for (int i = 2; i < argc; ++i)
{
string currArg = string(argv[i]);
if (currArg == "---verbose") {
verboseOutput = true;
}
else if (currArg == "---debug") {
enableDebugging = true;
}
else if (currArg == "---non-interactive") {
interactive = false;
}
else {
trailingArgs += "\"" + currArg + "\" ";
}
}
//Attempt to open the script file
string scriptPath = argv[1];
ifstream script(scriptPath.c_str());
if (script.is_open() == false) {
throw std::runtime_error("failed to open script file \"" + scriptPath + "\"");
}
//Attempt to read the second shebang line in the script file
string shebang = "";
std::getline(script, shebang);
std::getline(script, shebang);
if (script.fail()) {
throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\"");
}
//Verify that the shebang line is well-formed
size_t spacePos = shebang.find(" ");
if (shebang.substr(0,2) != "#!" || spacePos == string::npos) {
throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\"");
}
//Parse the shebang line
string dockerImage = shebang.substr(2, spacePos - 2);
string interpreter = shebang.substr(spacePos + 1);
//Determine the full path to the script file
scriptPath = Utility::realPath(scriptPath);
//Extract the directory and filename components of the script's path, as well as our current working directory
string scriptFile = Utility::baseName(scriptPath);
string scriptDir = Utility::dirName(scriptPath);
string workingDir = Utility::cwd();
//Extract the docker image name, without trailing tag name
string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":"));
//If the specified docker image (or the specific image and tag combination) requires
//nvidia-docker, we invoke nvidia-docker instead of regular docker
string docker = "docker";
auto nvDockerImages = NvidiaDockerImages::getList();
if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) {
docker = "nvidia-docker";
}
//If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker`
if (string(argv[0]) == "nvidia-docker-script") {
docker = "nvidia-docker";
}
//Build the `docker run` command
string command = docker + " run " +
string("\"-v") + scriptDir + ":/scriptdir\" " +
string("\"-v") + workingDir + ":/workingdir\" " +
string((enableDebugging == true) ? "--privileged=true " : "") +
string("--workdir=/workingdir ") +
string("-e \"HOST_CWD=") + workingDir + "\" " +
string((interactive == true) ? "-ti " : "") +
string("--rm --entrypoint=\"\" ") +
string("\"") + dockerImage + "\" " +
string("\"") + interpreter + "\" " +
string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs;
//If verbose output was requested, display diagnostic information
if (verboseOutput == true)
{
clog << "Docker image: " << dockerImage << endl;
clog << "Interpreter: " << interpreter << endl;
clog << "Script path: " << scriptPath << endl;
clog << "Script basename: " << scriptFile << endl;
clog << "Script dirname: " << scriptDir << endl;
clog << "Working directory: " << workingDir << endl;
clog << "Trailing arguments: " << trailingArgs << endl;
clog << endl << "Docker command:" << endl << command << endl << endl;
}
//Invoke docker
return system(command.c_str());
}
catch (std::runtime_error& e)
{
clog << "Error: " << e.what() << endl << endl;
return 1;
}
}
else
{
clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl;
clog << "The first line of the script file should be a normal Unix shebang line." << endl;
clog << "The second line of the script file should be:" << endl;
clog << "#!<IMAGE> <INTERPRETER>" << endl << endl;
}
return 0;
}
<commit_msg>Add flag to force use of nvidia-docker<commit_after>/*
docker-script: run script files inside Docker containers
Copyright (c) 2017, Adam Rehn
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 "NvidiaDockerImages.h"
#include "Utility.h"
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using std::ifstream;
using std::vector;
using std::clog;
using std::endl;
//The different versions of docker we support
#define VANILLA_DOCKER "docker"
#define NVIDIA_DOCKER "nvidia-docker"
int main (int argc, char* argv[])
{
//Check that a script file was specified
if (argc > 1)
{
try
{
//Parse CLI arguments, keeping docker-script options separate from script options
string docker = VANILLA_DOCKER;
bool interactive = true;
bool verboseOutput = false;
bool enableDebugging = false;
string trailingArgs = "";
for (int i = 2; i < argc; ++i)
{
string currArg = string(argv[i]);
if (currArg == "---verbose") {
verboseOutput = true;
}
else if (currArg == "---debug") {
enableDebugging = true;
}
else if (currArg == "---non-interactive") {
interactive = false;
}
else if (currArg == "---nvidia-docker") {
docker = NVIDIA_DOCKER;
}
else {
trailingArgs += "\"" + currArg + "\" ";
}
}
//Attempt to open the script file
string scriptPath = argv[1];
ifstream script(scriptPath.c_str());
if (script.is_open() == false) {
throw std::runtime_error("failed to open script file \"" + scriptPath + "\"");
}
//Attempt to read the second shebang line in the script file
string shebang = "";
std::getline(script, shebang);
std::getline(script, shebang);
if (script.fail()) {
throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\"");
}
//Verify that the shebang line is well-formed
size_t spacePos = shebang.find(" ");
if (shebang.substr(0,2) != "#!" || spacePos == string::npos) {
throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\"");
}
//Parse the shebang line
string dockerImage = shebang.substr(2, spacePos - 2);
string interpreter = shebang.substr(spacePos + 1);
//Determine the full path to the script file
scriptPath = Utility::realPath(scriptPath);
//Extract the directory and filename components of the script's path, as well as our current working directory
string scriptFile = Utility::baseName(scriptPath);
string scriptDir = Utility::dirName(scriptPath);
string workingDir = Utility::cwd();
//Extract the docker image name, without trailing tag name
string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":"));
//If the specified docker image (or the specific image and tag combination) requires
//nvidia-docker, we invoke nvidia-docker instead of regular docker
auto nvDockerImages = NvidiaDockerImages::getList();
if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) {
docker = NVIDIA_DOCKER;
}
//If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker`
if (string(argv[0]) == "nvidia-docker-script") {
docker = NVIDIA_DOCKER;
}
//Build the `docker run` command
string command = docker + " run " +
string("\"-v") + scriptDir + ":/scriptdir\" " +
string("\"-v") + workingDir + ":/workingdir\" " +
string((enableDebugging == true) ? "--privileged=true " : "") +
string("--workdir=/workingdir ") +
string("-e \"HOST_CWD=") + workingDir + "\" " +
string((interactive == true) ? "-ti " : "") +
string("--rm --entrypoint=\"\" ") +
string("\"") + dockerImage + "\" " +
string("\"") + interpreter + "\" " +
string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs;
//If verbose output was requested, display diagnostic information
if (verboseOutput == true)
{
clog << "Docker image: " << dockerImage << endl;
clog << "Interpreter: " << interpreter << endl;
clog << "Script path: " << scriptPath << endl;
clog << "Script basename: " << scriptFile << endl;
clog << "Script dirname: " << scriptDir << endl;
clog << "Working directory: " << workingDir << endl;
clog << "Trailing arguments: " << trailingArgs << endl;
clog << endl << "Docker command:" << endl << command << endl << endl;
}
//Invoke docker
return system(command.c_str());
}
catch (std::runtime_error& e)
{
clog << "Error: " << e.what() << endl << endl;
return 1;
}
}
else
{
clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl;
clog << "The first line of the script file should be a normal Unix shebang line." << endl;
clog << "The second line of the script file should be:" << endl;
clog << "#!<IMAGE> <INTERPRETER>" << endl << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>input size added to benchmark<commit_after><|endoftext|>
|
<commit_before>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "pid.h"
#include "process.h"
#include "swap.h"
using namespace std;
int main(int argc, char* argv[])
{
vector<ProcessInfo> procs;
if (argc == 1)
{
// no pid: collect all processes
procs = get_process_info();
}
else
{
const string pidarg = argv[1];
if (pidarg == "-h" || pidarg == "--help")
{
cerr << "Usage: swapusage [pid]" << endl;
return EXIT_SUCCESS;
}
int pid = to_pid(pidarg);
if (pid == UNKNOWN_PID)
{
cerr << "Not a process id: " << pidarg << endl;
return EXIT_FAILURE;
}
ProcessInfo proc = get_process_info(pid);
if (proc.name == UNKNOWN_PROCESS_NAME)
{
cerr << "No such process: " << pid << endl;
return EXIT_FAILURE;
}
if (proc.swap == UNKNOWN_SWAP)
{
cerr << "Cannot read swap for pid: " << pid << endl;
return EXIT_FAILURE;
}
// finally collect valid process info
if (proc.swap > 0)
{
procs.push_back(proc);
}
}
if (procs.empty())
{
cout << "No swap used." << endl ;
}
else
{
auto orderBySwap = [](ProcessInfo& first, ProcessInfo& second)
{
return first.swap > second.swap;
};
sort(procs.begin(), procs.end(), orderBySwap);
cout << "====================================" << endl;
cout << "KB\tpid\tname" << endl;
cout << "====================================" << endl;
long swap = 0;
for (ProcessInfo& p: procs)
{
cout << p.swap << "\t"<< p.pid << "\t" << p.name << endl;
swap += p.swap;
}
cout << "------------------------------------" << endl;
cout << "Overall Swap used: " << swap << " KB" << endl;
}
return EXIT_SUCCESS;
}
<commit_msg>lambda args can be const<commit_after>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "pid.h"
#include "process.h"
#include "swap.h"
using namespace std;
int main(int argc, char* argv[])
{
vector<ProcessInfo> procs;
if (argc == 1)
{
// no pid: collect all processes
procs = get_process_info();
}
else
{
const string pidarg = argv[1];
if (pidarg == "-h" || pidarg == "--help")
{
cerr << "Usage: swapusage [pid]" << endl;
return EXIT_SUCCESS;
}
int pid = to_pid(pidarg);
if (pid == UNKNOWN_PID)
{
cerr << "Not a process id: " << pidarg << endl;
return EXIT_FAILURE;
}
ProcessInfo proc = get_process_info(pid);
if (proc.name == UNKNOWN_PROCESS_NAME)
{
cerr << "No such process: " << pid << endl;
return EXIT_FAILURE;
}
if (proc.swap == UNKNOWN_SWAP)
{
cerr << "Cannot read swap for pid: " << pid << endl;
return EXIT_FAILURE;
}
// finally collect valid process info
if (proc.swap > 0)
{
procs.push_back(proc);
}
}
if (procs.empty())
{
cout << "No swap used." << endl ;
}
else
{
auto orderBySwap = [](const ProcessInfo& first, const ProcessInfo& second)
{
return first.swap > second.swap;
};
sort(procs.begin(), procs.end(), orderBySwap);
cout << "====================================" << endl;
cout << "KB\tpid\tname" << endl;
cout << "====================================" << endl;
long swap = 0;
for (ProcessInfo& p: procs)
{
cout << p.swap << "\t"<< p.pid << "\t" << p.name << endl;
swap += p.swap;
}
cout << "------------------------------------" << endl;
cout << "Overall Swap used: " << swap << " KB" << endl;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_CONVERT_HPP
#define FLUSSPFERD_CONVERT_HPP
#include "value.hpp"
#include "object.hpp"
#include "string.hpp"
#include "function.hpp"
#include "root_value.hpp"
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
#include <limits>
namespace flusspferd {
namespace detail {
template<typename T, typename Condition = void>
struct convert
{};
template<>
struct convert<value, void> {
value const &to_value(value const &v) {
return v;
}
value const &from_value(value const &v) {
return v;
}
};
template<>
struct convert<bool, void> {
value to_value(bool x) {
return value(x);
}
bool from_value(value const &v) {
return v.to_boolean();
}
};
template<>
struct convert<object, void> {
value to_value(object const &o) {
return value(o);
}
object from_value(value const &v) {
object o = v.to_object();
root = boost::in_place(value(o));
return o;
}
boost::optional<root_value> root;
};
template<>
struct convert<string, void> {
value to_value(string const &x) {
return value(x);
}
string from_value(value const &v) {
string s = v.to_string();
root = boost::in_place(value(s));
return s;
}
boost::optional<root_value> root;
};
template<>
struct convert<function, void> {
value to_value(function const &x) {
return value(object(x));
}
function from_value(value const &v) {
function f(v.to_object());
root = boost::in_place(value(object(f)));
return f;
}
boost::optional<root_value> root;
};
template<>
struct convert<char const *, void> {
value to_value(char const *x) {
return value(string(x));
}
char const *from_value(value const &v) {
string s = v.to_string();
root = boost::in_place(value(s));
return s.c_str();
}
boost::optional<root_value> root;
};
template<>
struct convert<std::string, void> {
value to_value(std::string const &x) {
return value(string(x));
}
std::string from_value(value const &v) {
string s = v.to_string();
return s.to_string();
}
};
template<>
struct convert<std::basic_string<char16_t>, void> {
typedef std::basic_string<char16_t> string_t;
value to_value(string_t const &x) {
return value(string(x));
}
string_t from_value(value const &v) {
string s = v.to_string();
return s.to_utf16_string();
}
};
template<typename T>
struct convert<
T,
typename boost::enable_if<boost::is_arithmetic<T> >::type
>
{
typedef std::numeric_limits<T> limits;
value to_value(T const &x) {
return value(x);
};
T from_value(value const &v) {
if (limits::is_integer)
return v.to_integral_number(limits::digits, limits::is_signed);
else
return v.to_number();
}
};
}
template<typename T>
struct convert : private detail::convert<T>, private boost::noncopyable {
using detail::convert<T>::to_value;
using detail::convert<T>::from_value;
};
}
#endif
<commit_msg>split number conversions<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_CONVERT_HPP
#define FLUSSPFERD_CONVERT_HPP
#include "value.hpp"
#include "object.hpp"
#include "string.hpp"
#include "function.hpp"
#include "root_value.hpp"
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_float.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <limits>
namespace flusspferd {
namespace detail {
template<typename T, typename Condition = void>
struct convert;
template<>
struct convert<value, void> {
value const &to_value(value const &v) {
return v;
}
value const &from_value(value const &v) {
return v;
}
};
template<>
struct convert<bool, void> {
value to_value(bool x) {
return value(x);
}
bool from_value(value const &v) {
return v.to_boolean();
}
};
template<>
struct convert<object, void> {
value to_value(object const &o) {
return value(o);
}
object from_value(value const &v) {
object o = v.to_object();
root = boost::in_place(value(o));
return o;
}
boost::optional<root_value> root;
};
template<>
struct convert<string, void> {
value to_value(string const &x) {
return value(x);
}
string from_value(value const &v) {
string s = v.to_string();
root = boost::in_place(value(s));
return s;
}
boost::optional<root_value> root;
};
template<>
struct convert<function, void> {
value to_value(function const &x) {
return value(object(x));
}
function from_value(value const &v) {
function f(v.to_object());
root = boost::in_place(value(object(f)));
return f;
}
boost::optional<root_value> root;
};
template<>
struct convert<char const *, void> {
value to_value(char const *x) {
return value(string(x));
}
char const *from_value(value const &v) {
string s = v.to_string();
root = boost::in_place(value(s));
return s.c_str();
}
boost::optional<root_value> root;
};
template<>
struct convert<std::string, void> {
value to_value(std::string const &x) {
return value(string(x));
}
std::string from_value(value const &v) {
string s = v.to_string();
return s.to_string();
}
};
template<>
struct convert<std::basic_string<char16_t>, void> {
typedef std::basic_string<char16_t> string_t;
value to_value(string_t const &x) {
return value(string(x));
}
string_t from_value(value const &v) {
string s = v.to_string();
return s.to_utf16_string();
}
};
template<typename T>
struct convert<
T,
typename boost::enable_if<boost::is_integral<T> >::type
>
{
typedef std::numeric_limits<T> limits;
value to_value(T const &x) {
return value(x);
};
T from_value(value const &v) {
return v.to_integral_number(limits::digits, limits::is_signed);
}
};
template<typename T>
struct convert<
T,
typename boost::enable_if<boost::is_float<T> >::type
>
{
value to_value(T const &x) {
return value(double(x));
}
T from_value(value const &v) {
return v.to_number();
}
};
}
template<typename T>
struct convert : private detail::convert<T>, private boost::noncopyable {
using detail::convert<T>::to_value;
using detail::convert<T>::from_value;
};
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>More loplugin:simplifybool<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include "../util.h"
#include <glm/glm.hpp>
#include <vector>
#include "imgui.h"
namespace mtao { namespace opengl {
class Camera {
public:
virtual glm::mat4 m() const {return m_model; }
glm::mat4& m() { return m_model; }
//MTAO_ACCESSORS(glm::mat4,m,m_model)
MTAO_ACCESSORS(glm::mat4,v,m_view)
MTAO_ACCESSORS(glm::mat4,p,m_perspective)
MTAO_ACCESSORS(float,zNear,m_zRange[0]);
MTAO_ACCESSORS(float,zFar,m_zRange[1]);
MTAO_ACCESSOR_CONST(glm::ivec2,shape,m_shape);
glm::mat4 mv() const;
glm::mat4 mvp() const;
glm::mat4 mvp_inv_trans() const;
void set_shape(int w, int h);
float aspect() const;
void ortho(float scale=1.0f);
void perspective(float fovy=45.0);
glm::vec2 get_zRange(const std::vector<glm::vec3>& ) const;
void set_zRange(const glm::vec2& range ) ;
void set_zRange(const std::vector<glm::vec3>& ) ;
glm::vec2 mouse_pos(const glm::vec2& p) const;
glm::vec2 mouse_pos(float x, float y) const;
glm::vec2 mouse_pos(const ImVec2& mp) const;
glm::vec2 mouse_pos() const;
private:
glm::mat4 m_model,m_view,m_perspective;
glm::ivec2 m_shape;
glm::vec2 m_zRange = glm::vec2(-1.0f,1.0f);
};
class Camera2D: public Camera {
public:
float& scale() { return m_scale; }
float scale() const { return m_scale; }
void set_scale(float scale);
void update();
void pan();
void enableDrag() { m_dragMode = true;}
void disableDrag() { m_dragMode = false; }
void reset();
glm::mat4 m() const;
private:
float m_scale = 1.0;
bool m_dragMode = false;
glm::vec2 m_translation;
};
class Camera3D: public Camera {
public:
glm::vec3& camera_pos() { return m_camera_pos; }
glm::vec3& target_pos() { return m_target_pos; }
glm::vec3& camera_up() { return m_camera_up; }
const glm::vec3& camera_pos() const { return m_camera_pos; }
const glm::vec3& target_pos() const { return m_target_pos; }
const glm::vec3& camera_up() const { return m_camera_up; }
void set_distance(float distance);
void update();
void pan();
void enableDrag() { m_dragMode = true;}
void disableDrag() { m_dragMode = false; }
void enableAngularDrag() { m_angularDragMode = true;}
void disableAngularDrag() { m_angularDragMode = false; }
void reset();
glm::mat4 m() const;
private:
float m_scale = 1.0;
glm::vec3 m_camera_pos = glm::vec3(0,0,5);
glm::vec3 m_target_pos = glm::vec3(0,0,0);
glm::vec3 m_camera_up = glm::vec3(0,1,0);
bool m_dragMode = false;
bool m_angularDragMode = false;
float m_fov_y = 45.0;
glm::vec3 m_translation;
glm::vec3 m_rotation;
};
}}
#undef ACCESSOR
<commit_msg>minor model matrix accessor change<commit_after>#pragma once
#include "../util.h"
#include <glm/glm.hpp>
#include <vector>
#include "imgui.h"
namespace mtao { namespace opengl {
class Camera {
public:
virtual glm::mat4 m() const {return m_model; }
glm::mat4& m() { return m_model; }
void set_m(const glm::mat4& a) { m_model = a; }
//MTAO_ACCESSORS(glm::mat4,m,m_model)
MTAO_ACCESSORS(glm::mat4,v,m_view)
MTAO_ACCESSORS(glm::mat4,p,m_perspective)
MTAO_ACCESSORS(float,zNear,m_zRange[0]);
MTAO_ACCESSORS(float,zFar,m_zRange[1]);
MTAO_ACCESSOR_CONST(glm::ivec2,shape,m_shape);
glm::mat4 mv() const;
glm::mat4 mvp() const;
glm::mat4 mvp_inv_trans() const;
void set_shape(int w, int h);
float aspect() const;
void ortho(float scale=1.0f);
void perspective(float fovy=45.0);
glm::vec2 get_zRange(const std::vector<glm::vec3>& ) const;
void set_zRange(const glm::vec2& range ) ;
void set_zRange(const std::vector<glm::vec3>& ) ;
glm::vec2 mouse_pos(const glm::vec2& p) const;
glm::vec2 mouse_pos(float x, float y) const;
glm::vec2 mouse_pos(const ImVec2& mp) const;
glm::vec2 mouse_pos() const;
private:
glm::mat4 m_model,m_view,m_perspective;
glm::ivec2 m_shape;
glm::vec2 m_zRange = glm::vec2(-1.0f,1.0f);
};
class Camera2D: public Camera {
public:
float& scale() { return m_scale; }
float scale() const { return m_scale; }
void set_scale(float scale);
void update();
void pan();
void enableDrag() { m_dragMode = true;}
void disableDrag() { m_dragMode = false; }
void reset();
glm::mat4 m() const;
private:
float m_scale = 1.0;
bool m_dragMode = false;
glm::vec2 m_translation;
};
class Camera3D: public Camera {
public:
glm::vec3& camera_pos() { return m_camera_pos; }
glm::vec3& target_pos() { return m_target_pos; }
glm::vec3& camera_up() { return m_camera_up; }
const glm::vec3& camera_pos() const { return m_camera_pos; }
const glm::vec3& target_pos() const { return m_target_pos; }
const glm::vec3& camera_up() const { return m_camera_up; }
void set_distance(float distance);
void update();
void pan();
void enableDrag() { m_dragMode = true;}
void disableDrag() { m_dragMode = false; }
void enableAngularDrag() { m_angularDragMode = true;}
void disableAngularDrag() { m_angularDragMode = false; }
void reset();
glm::mat4 m() const;
private:
float m_scale = 1.0;
glm::vec3 m_camera_pos = glm::vec3(0,0,5);
glm::vec3 m_target_pos = glm::vec3(0,0,0);
glm::vec3 m_camera_up = glm::vec3(0,1,0);
bool m_dragMode = false;
bool m_angularDragMode = false;
float m_fov_y = 45.0;
glm::vec3 m_translation;
glm::vec3 m_rotation;
};
}}
#undef ACCESSOR
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code. Currently this tests:
// Flash
// Real
// QuickTime
// Windows Media Player
// -this includes both WMP plugins. npdsplay.dll is the older one that
// comes with XP. np-mswmp.dll can be downloaded from Microsoft and
// needs SP2 or Vista.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"
#if defined(OS_WIN)
#include "base/registry.h"
// TODO(port) ?
#include "webkit/default_plugin/plugin_impl.h"
#endif
class PluginTest : public UITest {
protected:
#if defined(OS_WIN)
virtual void SetUp() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
// The installer adds our process names to the registry key below. Since
// the installer might not have run on this machine, add it manually.
RegKey regkey;
if (regkey.Open(HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
KEY_WRITE)) {
regkey.CreateKey(L"CHROME.EXE", KEY_READ);
}
} else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
// When testing the old WMP plugin, we need to force Chrome to not load
// the new plugin.
launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
} else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
L"security_tests.dll");
}
UITest::SetUp();
}
#endif // defined(OS_WIN)
void TestPlugin(const std::string& test_case,
int timeout,
bool mock_http) {
GURL url = GetTestUrl(test_case, mock_http);
NavigateToURL(url);
WaitForFinish(timeout, mock_http);
}
// Generate the URL for testing a particular test.
// HTML for the tests is all located in test_directory\plugin\<testcase>
// Set |mock_http| to true to use mock HTTP server.
GURL GetTestUrl(const std::string &test_case, bool mock_http) {
static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin");
if (mock_http) {
FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case);
return URLRequestMockHTTPJob::GetMockUrl(plugin_path);
}
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.Append(kPluginPath).AppendASCII(test_case);
return net::FilePathToFileURL(path);
}
// Waits for the test case to finish.
void WaitForFinish(const int wait_time, bool mock_http) {
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
GURL url = GetTestUrl("done", mock_http);
scoped_refptr<TabProxy> tab(GetActiveTab());
const std::string result =
WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time);
ASSERT_EQ(kTestCompleteSuccess, result);
}
};
TEST_F(PluginTest, Flash) {
// Note: This does not work with the npwrapper on 64-bit Linux. Install the
// native 64-bit Flash to run the test.
// TODO(thestig) Update this list if we decide to only test against internal
// Flash plugin in the future?
std::string kFlashQuery =
#if defined(OS_WIN)
"npswf32.dll"
#elif defined(OS_MACOSX)
"Flash Player.plugin"
#elif defined(OS_POSIX)
"libflashplayer.so"
#endif
;
TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false);
}
#if defined(OS_WIN)
// Windows only test
TEST_F(PluginTest, FlashSecurity) {
TestPlugin("flash.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
#if defined(OS_WIN)
// TODO(port) Port the following tests to platforms that have the required
// plugins.
TEST_F(PluginTest, Quicktime) {
TestPlugin("quicktime.html", action_max_timeout_ms(), false);
}
// Disabled on Release bots - http://crbug.com/44662
#if !defined(NDEBUG)
#define MediaPlayerNew DISABLED_MediaPlayerNew
#endif
TEST_F(PluginTest, MediaPlayerNew) {
TestPlugin("wmp_new.html", action_max_timeout_ms(), false);
}
// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
TestPlugin("wmp_old.html", action_max_timeout_ms(), false);
}
#if !defined(NDEBUG)
#define Real DISABLED_Real
#endif
// Disabled on Release bots - http://crbug.com/44673
TEST_F(PluginTest, Real) {
TestPlugin("real.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, FlashOctetStream) {
TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false);
}
// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true);
}
// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
TestPlugin("Java.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, Silverlight) {
TestPlugin("silverlight.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
<commit_msg>Fix the incorrect logic from r47842. Too many not's.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code. Currently this tests:
// Flash
// Real
// QuickTime
// Windows Media Player
// -this includes both WMP plugins. npdsplay.dll is the older one that
// comes with XP. np-mswmp.dll can be downloaded from Microsoft and
// needs SP2 or Vista.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"
#if defined(OS_WIN)
#include "base/registry.h"
// TODO(port) ?
#include "webkit/default_plugin/plugin_impl.h"
#endif
class PluginTest : public UITest {
protected:
#if defined(OS_WIN)
virtual void SetUp() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
// The installer adds our process names to the registry key below. Since
// the installer might not have run on this machine, add it manually.
RegKey regkey;
if (regkey.Open(HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
KEY_WRITE)) {
regkey.CreateKey(L"CHROME.EXE", KEY_READ);
}
} else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
// When testing the old WMP plugin, we need to force Chrome to not load
// the new plugin.
launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
} else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
L"security_tests.dll");
}
UITest::SetUp();
}
#endif // defined(OS_WIN)
void TestPlugin(const std::string& test_case,
int timeout,
bool mock_http) {
GURL url = GetTestUrl(test_case, mock_http);
NavigateToURL(url);
WaitForFinish(timeout, mock_http);
}
// Generate the URL for testing a particular test.
// HTML for the tests is all located in test_directory\plugin\<testcase>
// Set |mock_http| to true to use mock HTTP server.
GURL GetTestUrl(const std::string &test_case, bool mock_http) {
static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin");
if (mock_http) {
FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case);
return URLRequestMockHTTPJob::GetMockUrl(plugin_path);
}
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.Append(kPluginPath).AppendASCII(test_case);
return net::FilePathToFileURL(path);
}
// Waits for the test case to finish.
void WaitForFinish(const int wait_time, bool mock_http) {
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
GURL url = GetTestUrl("done", mock_http);
scoped_refptr<TabProxy> tab(GetActiveTab());
const std::string result =
WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time);
ASSERT_EQ(kTestCompleteSuccess, result);
}
};
TEST_F(PluginTest, Flash) {
// Note: This does not work with the npwrapper on 64-bit Linux. Install the
// native 64-bit Flash to run the test.
// TODO(thestig) Update this list if we decide to only test against internal
// Flash plugin in the future?
std::string kFlashQuery =
#if defined(OS_WIN)
"npswf32.dll"
#elif defined(OS_MACOSX)
"Flash Player.plugin"
#elif defined(OS_POSIX)
"libflashplayer.so"
#endif
;
TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false);
}
#if defined(OS_WIN)
// Windows only test
TEST_F(PluginTest, FlashSecurity) {
TestPlugin("flash.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
#if defined(OS_WIN)
// TODO(port) Port the following tests to platforms that have the required
// plugins.
TEST_F(PluginTest, Quicktime) {
TestPlugin("quicktime.html", action_max_timeout_ms(), false);
}
// Disabled on Release bots - http://crbug.com/44662
#if defined(NDEBUG)
#define MediaPlayerNew DISABLED_MediaPlayerNew
#endif
TEST_F(PluginTest, MediaPlayerNew) {
TestPlugin("wmp_new.html", action_max_timeout_ms(), false);
}
// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
TestPlugin("wmp_old.html", action_max_timeout_ms(), false);
}
#if defined(NDEBUG)
#define Real DISABLED_Real
#endif
// Disabled on Release bots - http://crbug.com/44673
TEST_F(PluginTest, Real) {
TestPlugin("real.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, FlashOctetStream) {
TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false);
}
// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true);
}
// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
TestPlugin("Java.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, Silverlight) {
TestPlugin("silverlight.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
<|endoftext|>
|
<commit_before>#ifndef NANO_SIGNAL_SLOT_HPP
#define NANO_SIGNAL_SLOT_HPP
#include "nano_function.hpp"
#include "nano_observer.hpp"
namespace Nano
{
template <typename RT> class Signal;
template <typename RT, typename... Args>
class Signal<RT(Args...)> : private Observer
{
template <typename T>
void insert_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::insert(key, instance);
instance->insert(key, this);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::remove(key);
instance->remove(key);
}
template <typename T>
void insert_sfinae(DelegateKey const& key, ...)
{
Observer::insert(key);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, ...)
{
Observer::remove(key);
}
public:
using Delegate = Function<RT(Args...)>;
//-------------------------------------------------------------------CONNECT
template <typename L>
void connect(L* instance)
{
Observer::insert(Delegate::template bind (instance));
}
template <RT (*fun_ptr)(Args...)>
void connect()
{
Observer::insert(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::*mem_ptr)(Args...)>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::*mem_ptr)(Args...) const>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::*mem_ptr)(Args...)>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::*mem_ptr)(Args...) const>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------------------DISCONNECT
template <typename L>
void disconnect(L* instance)
{
Observer::remove(Delegate::template bind (instance));
}
template <RT (*fun_ptr)(Args...)>
void disconnect()
{
Observer::remove(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::*mem_ptr)(Args...)>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::*mem_ptr)(Args...) const>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::*mem_ptr)(Args...)>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::*mem_ptr)(Args...) const>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------------------------EMIT
template <typename... Uref>
void emit(Uref&&... args)
{
Observer::onEach<Delegate>(std::forward<Uref>(args)...);
}
template <typename Accumulate, typename... Uref>
void emit_accumulate(Accumulate&& accumulator, Uref&&... args)
{
Observer::onEach_Accumulate<Delegate, Accumulate>
(std::forward<Accumulate>(accumulator), std::forward<Uref>(args)...);
}
};
} // namespace Nano ------------------------------------------------------------
#endif // NANO_SIGNAL_SLOT_HPP
<commit_msg>added convenience overloads for function objects<commit_after>#ifndef NANO_SIGNAL_SLOT_HPP
#define NANO_SIGNAL_SLOT_HPP
#include "nano_function.hpp"
#include "nano_observer.hpp"
namespace Nano
{
template <typename RT> class Signal;
template <typename RT, typename... Args>
class Signal<RT(Args...)> : private Observer
{
template <typename T>
void insert_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::insert(key, instance);
instance->insert(key, this);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::remove(key);
instance->remove(key);
}
template <typename T>
void insert_sfinae(DelegateKey const& key, ...)
{
Observer::insert(key);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, ...)
{
Observer::remove(key);
}
public:
using Delegate = Function<RT(Args...)>;
//-------------------------------------------------------------------CONNECT
template <typename L>
void connect(L* instance)
{
Observer::insert(Delegate::template bind (instance));
}
template <typename L>
void connect(L& instance)
{
connect(std::addressof(instance));
}
template <RT (* fun_ptr)(Args...)>
void connect()
{
Observer::insert(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------------------DISCONNECT
template <typename L>
void disconnect(L* instance)
{
Observer::remove(Delegate::template bind (instance));
}
template <typename L>
void disconnect(L& instance)
{
disconnect(std::addressof(instance));
}
template <RT (* fun_ptr)(Args...)>
void disconnect()
{
Observer::remove(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------EMIT / EMIT ACCUMULATE
template <typename... Uref>
void emit (Uref &&... args)
{
Observer::onEach<Delegate>(std::forward<Uref>(args)...);
}
template <typename Accumulate, typename... Uref>
void emit_accumulate(Accumulate&& accumulator, Uref&&... args)
{
Observer::onEach_Accumulate<Delegate, Accumulate>
(std::forward<Accumulate>(accumulator), std::forward<Uref>(args)...);
}
};
} // namespace Nano ------------------------------------------------------------
#endif // NANO_SIGNAL_SLOT_HPP
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef EDDI_GRAMMAR_H
#define EDDI_GRAMMAR_H
#include <boost/spirit/include/qi.hpp>
#include "lexer/SpiritLexer.hpp"
#include "ast/SourceFile.hpp"
#include "parser/ValueGrammar.hpp"
#include "parser/BooleanGrammar.hpp"
#include "parser/TypeGrammar.hpp"
namespace qi = boost::spirit::qi;
namespace eddic {
namespace parser {
/*!
* \class EDDIGrammar
* \brief Grammar representing the whole EDDI syntax.
*/
struct EddiGrammar : qi::grammar<lexer::Iterator, ast::SourceFile()> {
EddiGrammar(const lexer::Lexer& lexer);
qi::rule<lexer::Iterator, ast::SourceFile()> program;
qi::rule<lexer::Iterator, ast::GlobalVariableDeclaration()> globalDeclaration;
qi::rule<lexer::Iterator, ast::GlobalArrayDeclaration()> globalArrayDeclaration;
qi::rule<lexer::Iterator, ast::FunctionDeclaration()> function;
qi::rule<lexer::Iterator, ast::FunctionParameter()> arg;
qi::rule<lexer::Iterator, ast::Instruction()> instruction;
qi::rule<lexer::Iterator, ast::Instruction()> repeatable_instruction;
qi::rule<lexer::Iterator, ast::Swap()> swap;
qi::rule<lexer::Iterator, ast::VariableDeclaration()> declaration;
qi::rule<lexer::Iterator, ast::ArrayDeclaration()> arrayDeclaration;
qi::rule<lexer::Iterator, ast::Assignment()> assignment;
qi::rule<lexer::Iterator, ast::Return()> return_;
qi::rule<lexer::Iterator, ast::ArrayAssignment()> arrayAssignment;
qi::rule<lexer::Iterator, ast::While()> while_;
qi::rule<lexer::Iterator, ast::For()> for_;
qi::rule<lexer::Iterator, ast::Foreach()> foreach_;
qi::rule<lexer::Iterator, ast::ForeachIn()> foreachin_;
qi::rule<lexer::Iterator, ast::If()> if_;
qi::rule<lexer::Iterator, ast::Else()> else_;
qi::rule<lexer::Iterator, ast::ElseIf()> else_if_;
qi::rule<lexer::Iterator, ast::StandardImport()> standardImport;
qi::rule<lexer::Iterator, ast::Import()> import;
qi::rule<lexer::Iterator, bool()> const_;
ValueGrammar value;
BooleanGrammar condition;
TypeGrammar type;
};
} //end of parser
} //end of eddic
#endif
<commit_msg>Remove the old BooleanGrammar from the grammar<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef EDDI_GRAMMAR_H
#define EDDI_GRAMMAR_H
#include <boost/spirit/include/qi.hpp>
#include "lexer/SpiritLexer.hpp"
#include "ast/SourceFile.hpp"
#include "parser/ValueGrammar.hpp"
#include "parser/TypeGrammar.hpp"
namespace qi = boost::spirit::qi;
namespace eddic {
namespace parser {
/*!
* \class EDDIGrammar
* \brief Grammar representing the whole EDDI syntax.
*/
struct EddiGrammar : qi::grammar<lexer::Iterator, ast::SourceFile()> {
EddiGrammar(const lexer::Lexer& lexer);
qi::rule<lexer::Iterator, ast::SourceFile()> program;
qi::rule<lexer::Iterator, ast::GlobalVariableDeclaration()> globalDeclaration;
qi::rule<lexer::Iterator, ast::GlobalArrayDeclaration()> globalArrayDeclaration;
qi::rule<lexer::Iterator, ast::FunctionDeclaration()> function;
qi::rule<lexer::Iterator, ast::FunctionParameter()> arg;
qi::rule<lexer::Iterator, ast::Instruction()> instruction;
qi::rule<lexer::Iterator, ast::Instruction()> repeatable_instruction;
qi::rule<lexer::Iterator, ast::Swap()> swap;
qi::rule<lexer::Iterator, ast::VariableDeclaration()> declaration;
qi::rule<lexer::Iterator, ast::ArrayDeclaration()> arrayDeclaration;
qi::rule<lexer::Iterator, ast::Assignment()> assignment;
qi::rule<lexer::Iterator, ast::Return()> return_;
qi::rule<lexer::Iterator, ast::ArrayAssignment()> arrayAssignment;
qi::rule<lexer::Iterator, ast::While()> while_;
qi::rule<lexer::Iterator, ast::For()> for_;
qi::rule<lexer::Iterator, ast::Foreach()> foreach_;
qi::rule<lexer::Iterator, ast::ForeachIn()> foreachin_;
qi::rule<lexer::Iterator, ast::If()> if_;
qi::rule<lexer::Iterator, ast::Else()> else_;
qi::rule<lexer::Iterator, ast::ElseIf()> else_if_;
qi::rule<lexer::Iterator, ast::StandardImport()> standardImport;
qi::rule<lexer::Iterator, ast::Import()> import;
qi::rule<lexer::Iterator, bool()> const_;
ValueGrammar value;
TypeGrammar type;
};
} //end of parser
} //end of eddic
#endif
<|endoftext|>
|
<commit_before>AliMultSelectionTask *AddTaskMultSelection( Bool_t lCalibration = kFALSE, TString lExtraOptions = "", Int_t lNDebugEstimators = 1, const TString lMasterJobSessionFlag = "")
{
// Creates, configures and attaches to the train a Multiplicity Selection Task
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskMultSelection", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskMultSelection", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Create and configure the task
//Special options interpreting: will be taken care of by the task
// A - Add Extra AliCentrality V0M branch for cross-checks
// A - Add Extra AliPPVsMultUtils V0M branch for cross-checks
AliMultSelectionTask *taskMultSelection = new AliMultSelectionTask("taskMultSelection", lExtraOptions.Data(), lCalibration, lNDebugEstimators);
mgr->AddTask(taskMultSelection);
TString outputFileName = AliAnalysisManager::GetCommonFileName();
outputFileName += ":MultSelection";
if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";
Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *coutputList = mgr->CreateContainer("cListMultSelection",
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName );
if ( lCalibration ){
AliAnalysisDataContainer *coutputTree = mgr->CreateContainer("cCalibrationTree",
TTree::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName );
//This one you should merge in file-resident ways...
coutputTree->SetSpecialOutput();
}
//Recommendation: Tree as a single output slot
mgr->ConnectInput (taskMultSelection, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskMultSelection, 1, coutputList);
if ( lCalibration ) mgr->ConnectOutput(taskMultSelection, 2, coutputTree);
return taskMultSelection;
}
<commit_msg>Fix for ROOT6<commit_after>AliMultSelectionTask *AddTaskMultSelection( Bool_t lCalibration = kFALSE, TString lExtraOptions = "", Int_t lNDebugEstimators = 1, const TString lMasterJobSessionFlag = "")
{
// Creates, configures and attaches to the train a Multiplicity Selection Task
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskMultSelection", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskMultSelection", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Create and configure the task
//Special options interpreting: will be taken care of by the task
// A - Add Extra AliCentrality V0M branch for cross-checks
// A - Add Extra AliPPVsMultUtils V0M branch for cross-checks
AliMultSelectionTask *taskMultSelection = new AliMultSelectionTask("taskMultSelection", lExtraOptions.Data(), lCalibration, lNDebugEstimators);
mgr->AddTask(taskMultSelection);
TString outputFileName = AliAnalysisManager::GetCommonFileName();
outputFileName += ":MultSelection";
if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";
Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *coutputList = mgr->CreateContainer("cListMultSelection",
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName );
//Recommendation: Tree as a single output slot
mgr->ConnectInput (taskMultSelection, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskMultSelection, 1, coutputList);
if ( lCalibration ) {
AliAnalysisDataContainer *coutputTree = mgr->CreateContainer("cCalibrationTree",
TTree::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName );
//This one you should merge in file-resident ways...
coutputTree->SetSpecialOutput();
mgr->ConnectOutput(taskMultSelection, 2, coutputTree);
}
return taskMultSelection;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
#include <vector>
#include <algorithm>
#include "reflection_info.hpp"
#include "info_iterator.hpp"
#include "api_info_types.hpp"
namespace shadow
{
class reflection_manager
{
public:
template <class Derived>
friend class get_type_policy;
template <class Derived>
friend class get_parameter_types_policy;
template <class Derived>
friend class get_from_type_policy;
template <class Derived>
friend class get_to_type_policy;
template <class Derived>
friend class get_return_type_policy;
template <class Derived>
friend class get_object_type_policy;
typedef type_ type;
typedef info_iterator_<const type_info, const type> const_type_iterator;
typedef constructor_ constructor;
typedef info_iterator_<const constructor_info, const constructor>
const_constructor_iterator;
typedef indexed_info_iterator_<const constructor_info, const constructor>
const_indexed_constructor_iterator;
typedef type_conversion_ type_conversion;
typedef info_iterator_<const conversion_info, const type_conversion>
const_conversion_iterator;
typedef indexed_info_iterator_<const conversion_info, const type_conversion>
const_indexed_conversion_iterator;
typedef free_function_ free_function;
typedef info_iterator_<const free_function_info, const free_function>
const_free_function_iterator;
typedef member_function_ member_function;
typedef info_iterator_<const member_function_info, const member_function>
const_member_function_iterator;
typedef member_variable_ member_variable;
typedef info_iterator_<const member_variable_info, const member_variable>
const_member_variable_iterator;
typedef string_serializer_ string_serializer;
typedef info_iterator_<const string_serialization_info,
const string_serializer>
const_string_serializer_iterator;
public:
reflection_manager();
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
reflection_manager(TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder);
private:
template <class ArrayHolderType>
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
initialize_range(ArrayHolderType);
template <class ArrayHolderType>
std::size_t array_size(ArrayHolderType);
template <class ValueType, class TypeInfoArrayHolder, class Fun>
std::vector<std::vector<ValueType>>
buckets_by_index(const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun index_extractor);
template <class ValueType, class TypeInfoArrayHolder, class Fun>
std::vector<std::vector<std::size_t>>
indices_by_type(const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun type_index_extractor);
type type_by_index(std::size_t index) const;
public:
////////////////////////////////////////////////////////////////////////////
// main api interface for interacting with the reflection system
std::pair<const_type_iterator, const_type_iterator> types() const;
std::pair<const_constructor_iterator, const_constructor_iterator>
constructors() const;
std::pair<const_indexed_constructor_iterator,
const_indexed_constructor_iterator>
constructors_by_type(const type& tp) const;
std::pair<const_conversion_iterator, const_conversion_iterator>
type_conversions() const;
std::pair<const_indexed_conversion_iterator,
const_indexed_conversion_iterator>
type_conversions_by_type(const type& tp) const;
std::pair<const_free_function_iterator, const_free_function_iterator>
free_functions() const;
std::pair<const_member_function_iterator, const_member_function_iterator>
member_functions() const;
std::pair<const_member_variable_iterator, const_member_variable_iterator>
member_variables() const;
std::pair<const_string_serializer_iterator,
const_string_serializer_iterator>
string_serializers() const;
private:
// pairs hold iterators to beginning and end of arrays of information
// generated at compile time
std::pair<const type_info*, const type_info*> type_info_range_;
std::pair<const constructor_info*, const constructor_info*>
constructor_info_range_;
std::pair<const conversion_info*, const conversion_info*>
conversion_info_range_;
std::pair<const string_serialization_info*,
const string_serialization_info*>
string_serialization_info_range_;
std::pair<const free_function_info*, const free_function_info*>
free_function_info_range_;
std::pair<const member_function_info*, const member_function_info*>
member_function_info_range_;
std::pair<const member_variable_info*, const member_variable_info*>
member_variable_info_range_;
// sorted information
std::vector<std::vector<conversion_info>> conversion_info_by_index_;
std::vector<std::vector<member_function_info>>
member_function_info_by_index_;
std::vector<std::vector<member_variable_info>>
member_variable_info_by_index_;
std::vector<string_serialization_info> string_serializer_info_by_index_;
// sorted index information
std::vector<std::vector<std::size_t>> constructor_info_indices_by_type_;
std::vector<std::vector<std::size_t>> conversion_info_indices_by_type_;
};
}
////////////////////////////////////////////////////////////////////////////////
// DEFINITIONS
namespace shadow
{
inline reflection_manager::reflection_manager() = default;
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
inline reflection_manager::reflection_manager(
TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder)
: type_info_range_(initialize_range(TypeInfoArrayHolder())),
constructor_info_range_(initialize_range(ConstructorInfoArrayHolder())),
conversion_info_range_(initialize_range(ConversionInfoArrayHolder())),
string_serialization_info_range_(
initialize_range(StringSerializationInfoArrayHolder())),
free_function_info_range_(
initialize_range(FreeFunctionInfoArrayHolder())),
member_function_info_range_(
initialize_range(MemberFunctionInfoArrayHolder())),
member_variable_info_range_(
initialize_range(MemberVariableInfoArrayHolder())),
conversion_info_by_index_(buckets_by_index(
conversion_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.from_type_index; })),
member_function_info_by_index_(buckets_by_index(
member_function_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.object_type_index; })),
member_variable_info_by_index_(buckets_by_index(
member_variable_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.object_type_index; })),
string_serializer_info_by_index_(array_size(TypeInfoArrayHolder())),
constructor_info_indices_by_type_(
indices_by_type(constructor_info_range_,
TypeInfoArrayHolder(),
[](const auto& ci) { return ci.type_index; })),
conversion_info_indices_by_type_(indices_by_type(
conversion_info_range_, TypeInfoArrayHolder(), [](const auto& ci) {
return ci.from_type_index;
}))
{
std::for_each(string_serialization_info_range_.first,
string_serialization_info_range_.second,
[this](const auto& info) {
string_serializer_info_by_index_[info.type_index] = info;
});
}
// clang complains here due to the comparison of decayed array and
// nullptr, since in the case ArrayHolderType::value was an array, this
// would always evaluate to true. The fact is that
// ArrayHolderType::value may be a pointer to nullptr for some cases of
// ArrayHolderType.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
template <class ArrayHolderType>
inline std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
reflection_manager::initialize_range(ArrayHolderType)
{
if(ArrayHolderType::value != nullptr)
{
return std::make_pair(std::begin(ArrayHolderType::value),
std::end(ArrayHolderType::value));
}
else
{
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
out(nullptr, nullptr);
return out;
}
}
template <class ArrayHolderType>
inline std::size_t reflection_manager::array_size(ArrayHolderType)
{
if(ArrayHolderType::value == nullptr)
{
return 0;
}
else
{
return std::extent<decltype(ArrayHolderType::value)>::value;
}
}
template <class ValueType, class TypeInfoArrayHolder, class Fun>
inline std::vector<std::vector<ValueType>>
reflection_manager::buckets_by_index(
const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun index_extractor)
{
if(range.first != nullptr && range.second != nullptr)
{
std::vector<std::vector<ValueType>> out(
array_size(TypeInfoArrayHolder()));
std::for_each(range.first,
range.second,
[&out, index_extractor](const auto& info) {
out[index_extractor(info)].push_back(info);
});
return out;
}
else
{
return std::vector<std::vector<ValueType>>();
}
}
template <class ValueType, class TypeInfoArrayHolder, class Fun>
inline std::vector<std::vector<std::size_t>>
reflection_manager::indices_by_type(
const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun type_index_extractor)
{
if(range.first != nullptr && range.second != nullptr)
{
std::vector<std::vector<std::size_t>> out(
array_size(TypeInfoArrayHolder()));
for(auto i = 0ul; i < range.second - range.first; ++i)
{
out[type_index_extractor(range.first[i])].push_back(i);
}
return out;
}
else
{
return std::vector<std::vector<std::size_t>>();
}
}
#pragma clang diagnostic pop
inline reflection_manager::type
reflection_manager::type_by_index(std::size_t index) const
{
return type(type_info_range_.first + index, this);
}
inline std::pair<reflection_manager::const_type_iterator,
reflection_manager::const_type_iterator>
reflection_manager::types() const
{
return std::make_pair(const_type_iterator(type_info_range_.first, this),
const_type_iterator(type_info_range_.second, this));
}
inline std::pair<reflection_manager::const_constructor_iterator,
reflection_manager::const_constructor_iterator>
reflection_manager::constructors() const
{
return std::make_pair(
const_constructor_iterator(constructor_info_range_.first, this),
const_constructor_iterator(constructor_info_range_.second, this));
}
inline std::pair<reflection_manager::const_indexed_constructor_iterator,
reflection_manager::const_indexed_constructor_iterator>
reflection_manager::constructors_by_type(const type& tp) const
{
const auto index_of_type = tp.info_ - type_info_range_.first;
return std::make_pair(
const_indexed_constructor_iterator(
0,
constructor_info_indices_by_type_[index_of_type].data(),
constructor_info_range_.first,
this),
const_indexed_constructor_iterator(
constructor_info_indices_by_type_[index_of_type].size(),
constructor_info_indices_by_type_[index_of_type].data(),
constructor_info_range_.first,
this));
}
inline std::pair<reflection_manager::const_conversion_iterator,
reflection_manager::const_conversion_iterator>
reflection_manager::type_conversions() const
{
return std::make_pair(
const_conversion_iterator(conversion_info_range_.first, this),
const_conversion_iterator(conversion_info_range_.second, this));
}
inline std::pair<reflection_manager::const_indexed_conversion_iterator,
reflection_manager::const_indexed_conversion_iterator>
reflection_manager::type_conversions_by_type(const type& tp) const
{
const auto index_of_type = tp.info_ - type_info_range_.first;
return std::make_pair(
const_indexed_conversion_iterator(
0,
conversion_info_indices_by_type_[index_of_type].data(),
conversion_info_range_.first,
this),
const_indexed_conversion_iterator(
conversion_info_indices_by_type_[index_of_type].size(),
conversion_info_indices_by_type_[index_of_type].data(),
conversion_info_range_.first,
this));
}
inline std::pair<reflection_manager::const_free_function_iterator,
reflection_manager::const_free_function_iterator>
reflection_manager::free_functions() const
{
return std::make_pair(
const_free_function_iterator(free_function_info_range_.first, this),
const_free_function_iterator(free_function_info_range_.second, this));
}
inline std::pair<reflection_manager::const_member_function_iterator,
reflection_manager::const_member_function_iterator>
reflection_manager::member_functions() const
{
return std::make_pair(
const_member_function_iterator(member_function_info_range_.first, this),
const_member_function_iterator(member_function_info_range_.second,
this));
}
inline std::pair<reflection_manager::const_member_variable_iterator,
reflection_manager::const_member_variable_iterator>
reflection_manager::member_variables() const
{
return std::make_pair(
const_member_variable_iterator(member_variable_info_range_.first, this),
const_member_variable_iterator(member_variable_info_range_.second,
this));
}
inline std::pair<reflection_manager::const_string_serializer_iterator,
reflection_manager::const_string_serializer_iterator>
reflection_manager::string_serializers() const
{
return std::make_pair(const_string_serializer_iterator(
string_serialization_info_range_.first, this),
const_string_serializer_iterator(
string_serialization_info_range_.second, this));
}
}
////////////////////////////////////////////////////////////////////////////////
// DEFINITIONS for policies
namespace shadow
{
template <class Derived>
inline std::pair<
typename get_parameter_types_policy<Derived>::const_parameter_type_iterator,
typename get_parameter_types_policy<Derived>::const_parameter_type_iterator>
get_parameter_types_policy<Derived>::parameter_types() const
{
const auto num_parameters =
static_cast<const Derived*>(this)->info_->num_parameters;
const std::size_t* param_type_index_buffer =
static_cast<const Derived*>(this)->info_->parameter_type_indices;
const reflection_manager* manager =
static_cast<const Derived*>(this)->manager_;
return std::make_pair(
const_parameter_type_iterator(0,
param_type_index_buffer,
manager->type_info_range_.first,
manager),
const_parameter_type_iterator(num_parameters,
param_type_index_buffer,
manager->type_info_range_.first,
manager));
}
}
<commit_msg>Remove conversion_info_by_type_. modified: include/reflection_manager.hpp<commit_after>#pragma once
#include <utility>
#include <vector>
#include <algorithm>
#include "reflection_info.hpp"
#include "info_iterator.hpp"
#include "api_info_types.hpp"
namespace shadow
{
class reflection_manager
{
public:
template <class Derived>
friend class get_type_policy;
template <class Derived>
friend class get_parameter_types_policy;
template <class Derived>
friend class get_from_type_policy;
template <class Derived>
friend class get_to_type_policy;
template <class Derived>
friend class get_return_type_policy;
template <class Derived>
friend class get_object_type_policy;
typedef type_ type;
typedef info_iterator_<const type_info, const type> const_type_iterator;
typedef constructor_ constructor;
typedef info_iterator_<const constructor_info, const constructor>
const_constructor_iterator;
typedef indexed_info_iterator_<const constructor_info, const constructor>
const_indexed_constructor_iterator;
typedef type_conversion_ type_conversion;
typedef info_iterator_<const conversion_info, const type_conversion>
const_conversion_iterator;
typedef indexed_info_iterator_<const conversion_info, const type_conversion>
const_indexed_conversion_iterator;
typedef free_function_ free_function;
typedef info_iterator_<const free_function_info, const free_function>
const_free_function_iterator;
typedef member_function_ member_function;
typedef info_iterator_<const member_function_info, const member_function>
const_member_function_iterator;
typedef member_variable_ member_variable;
typedef info_iterator_<const member_variable_info, const member_variable>
const_member_variable_iterator;
typedef string_serializer_ string_serializer;
typedef info_iterator_<const string_serialization_info,
const string_serializer>
const_string_serializer_iterator;
public:
reflection_manager();
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
reflection_manager(TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder);
private:
template <class ArrayHolderType>
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
initialize_range(ArrayHolderType);
template <class ArrayHolderType>
std::size_t array_size(ArrayHolderType);
template <class ValueType, class TypeInfoArrayHolder, class Fun>
std::vector<std::vector<ValueType>>
buckets_by_index(const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun index_extractor);
template <class ValueType, class TypeInfoArrayHolder, class Fun>
std::vector<std::vector<std::size_t>>
indices_by_type(const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun type_index_extractor);
type type_by_index(std::size_t index) const;
public:
////////////////////////////////////////////////////////////////////////////
// main api interface for interacting with the reflection system
std::pair<const_type_iterator, const_type_iterator> types() const;
std::pair<const_constructor_iterator, const_constructor_iterator>
constructors() const;
std::pair<const_indexed_constructor_iterator,
const_indexed_constructor_iterator>
constructors_by_type(const type& tp) const;
std::pair<const_conversion_iterator, const_conversion_iterator>
type_conversions() const;
std::pair<const_indexed_conversion_iterator,
const_indexed_conversion_iterator>
type_conversions_by_type(const type& tp) const;
std::pair<const_free_function_iterator, const_free_function_iterator>
free_functions() const;
std::pair<const_member_function_iterator, const_member_function_iterator>
member_functions() const;
std::pair<const_member_variable_iterator, const_member_variable_iterator>
member_variables() const;
std::pair<const_string_serializer_iterator,
const_string_serializer_iterator>
string_serializers() const;
private:
// pairs hold iterators to beginning and end of arrays of information
// generated at compile time
std::pair<const type_info*, const type_info*> type_info_range_;
std::pair<const constructor_info*, const constructor_info*>
constructor_info_range_;
std::pair<const conversion_info*, const conversion_info*>
conversion_info_range_;
std::pair<const string_serialization_info*,
const string_serialization_info*>
string_serialization_info_range_;
std::pair<const free_function_info*, const free_function_info*>
free_function_info_range_;
std::pair<const member_function_info*, const member_function_info*>
member_function_info_range_;
std::pair<const member_variable_info*, const member_variable_info*>
member_variable_info_range_;
// sorted information
std::vector<std::vector<member_function_info>>
member_function_info_by_index_;
std::vector<std::vector<member_variable_info>>
member_variable_info_by_index_;
std::vector<string_serialization_info> string_serializer_info_by_index_;
// sorted index information
std::vector<std::vector<std::size_t>> constructor_info_indices_by_type_;
std::vector<std::vector<std::size_t>> conversion_info_indices_by_type_;
};
}
////////////////////////////////////////////////////////////////////////////////
// DEFINITIONS
namespace shadow
{
inline reflection_manager::reflection_manager() = default;
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
inline reflection_manager::reflection_manager(
TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder)
: type_info_range_(initialize_range(TypeInfoArrayHolder())),
constructor_info_range_(initialize_range(ConstructorInfoArrayHolder())),
conversion_info_range_(initialize_range(ConversionInfoArrayHolder())),
string_serialization_info_range_(
initialize_range(StringSerializationInfoArrayHolder())),
free_function_info_range_(
initialize_range(FreeFunctionInfoArrayHolder())),
member_function_info_range_(
initialize_range(MemberFunctionInfoArrayHolder())),
member_variable_info_range_(
initialize_range(MemberVariableInfoArrayHolder())),
member_function_info_by_index_(buckets_by_index(
member_function_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.object_type_index; })),
member_variable_info_by_index_(buckets_by_index(
member_variable_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.object_type_index; })),
string_serializer_info_by_index_(array_size(TypeInfoArrayHolder())),
constructor_info_indices_by_type_(
indices_by_type(constructor_info_range_,
TypeInfoArrayHolder(),
[](const auto& ci) { return ci.type_index; })),
conversion_info_indices_by_type_(indices_by_type(
conversion_info_range_, TypeInfoArrayHolder(), [](const auto& ci) {
return ci.from_type_index;
}))
{
std::for_each(string_serialization_info_range_.first,
string_serialization_info_range_.second,
[this](const auto& info) {
string_serializer_info_by_index_[info.type_index] = info;
});
}
// clang complains here due to the comparison of decayed array and
// nullptr, since in the case ArrayHolderType::value was an array, this
// would always evaluate to true. The fact is that
// ArrayHolderType::value may be a pointer to nullptr for some cases of
// ArrayHolderType.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
template <class ArrayHolderType>
inline std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
reflection_manager::initialize_range(ArrayHolderType)
{
if(ArrayHolderType::value != nullptr)
{
return std::make_pair(std::begin(ArrayHolderType::value),
std::end(ArrayHolderType::value));
}
else
{
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
out(nullptr, nullptr);
return out;
}
}
template <class ArrayHolderType>
inline std::size_t reflection_manager::array_size(ArrayHolderType)
{
if(ArrayHolderType::value == nullptr)
{
return 0;
}
else
{
return std::extent<decltype(ArrayHolderType::value)>::value;
}
}
template <class ValueType, class TypeInfoArrayHolder, class Fun>
inline std::vector<std::vector<ValueType>>
reflection_manager::buckets_by_index(
const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun index_extractor)
{
if(range.first != nullptr && range.second != nullptr)
{
std::vector<std::vector<ValueType>> out(
array_size(TypeInfoArrayHolder()));
std::for_each(range.first,
range.second,
[&out, index_extractor](const auto& info) {
out[index_extractor(info)].push_back(info);
});
return out;
}
else
{
return std::vector<std::vector<ValueType>>();
}
}
template <class ValueType, class TypeInfoArrayHolder, class Fun>
inline std::vector<std::vector<std::size_t>>
reflection_manager::indices_by_type(
const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun type_index_extractor)
{
if(range.first != nullptr && range.second != nullptr)
{
std::vector<std::vector<std::size_t>> out(
array_size(TypeInfoArrayHolder()));
for(auto i = 0ul; i < range.second - range.first; ++i)
{
out[type_index_extractor(range.first[i])].push_back(i);
}
return out;
}
else
{
return std::vector<std::vector<std::size_t>>();
}
}
#pragma clang diagnostic pop
inline reflection_manager::type
reflection_manager::type_by_index(std::size_t index) const
{
return type(type_info_range_.first + index, this);
}
inline std::pair<reflection_manager::const_type_iterator,
reflection_manager::const_type_iterator>
reflection_manager::types() const
{
return std::make_pair(const_type_iterator(type_info_range_.first, this),
const_type_iterator(type_info_range_.second, this));
}
inline std::pair<reflection_manager::const_constructor_iterator,
reflection_manager::const_constructor_iterator>
reflection_manager::constructors() const
{
return std::make_pair(
const_constructor_iterator(constructor_info_range_.first, this),
const_constructor_iterator(constructor_info_range_.second, this));
}
inline std::pair<reflection_manager::const_indexed_constructor_iterator,
reflection_manager::const_indexed_constructor_iterator>
reflection_manager::constructors_by_type(const type& tp) const
{
const auto index_of_type = tp.info_ - type_info_range_.first;
return std::make_pair(
const_indexed_constructor_iterator(
0,
constructor_info_indices_by_type_[index_of_type].data(),
constructor_info_range_.first,
this),
const_indexed_constructor_iterator(
constructor_info_indices_by_type_[index_of_type].size(),
constructor_info_indices_by_type_[index_of_type].data(),
constructor_info_range_.first,
this));
}
inline std::pair<reflection_manager::const_conversion_iterator,
reflection_manager::const_conversion_iterator>
reflection_manager::type_conversions() const
{
return std::make_pair(
const_conversion_iterator(conversion_info_range_.first, this),
const_conversion_iterator(conversion_info_range_.second, this));
}
inline std::pair<reflection_manager::const_indexed_conversion_iterator,
reflection_manager::const_indexed_conversion_iterator>
reflection_manager::type_conversions_by_type(const type& tp) const
{
const auto index_of_type = tp.info_ - type_info_range_.first;
return std::make_pair(
const_indexed_conversion_iterator(
0,
conversion_info_indices_by_type_[index_of_type].data(),
conversion_info_range_.first,
this),
const_indexed_conversion_iterator(
conversion_info_indices_by_type_[index_of_type].size(),
conversion_info_indices_by_type_[index_of_type].data(),
conversion_info_range_.first,
this));
}
inline std::pair<reflection_manager::const_free_function_iterator,
reflection_manager::const_free_function_iterator>
reflection_manager::free_functions() const
{
return std::make_pair(
const_free_function_iterator(free_function_info_range_.first, this),
const_free_function_iterator(free_function_info_range_.second, this));
}
inline std::pair<reflection_manager::const_member_function_iterator,
reflection_manager::const_member_function_iterator>
reflection_manager::member_functions() const
{
return std::make_pair(
const_member_function_iterator(member_function_info_range_.first, this),
const_member_function_iterator(member_function_info_range_.second,
this));
}
inline std::pair<reflection_manager::const_member_variable_iterator,
reflection_manager::const_member_variable_iterator>
reflection_manager::member_variables() const
{
return std::make_pair(
const_member_variable_iterator(member_variable_info_range_.first, this),
const_member_variable_iterator(member_variable_info_range_.second,
this));
}
inline std::pair<reflection_manager::const_string_serializer_iterator,
reflection_manager::const_string_serializer_iterator>
reflection_manager::string_serializers() const
{
return std::make_pair(const_string_serializer_iterator(
string_serialization_info_range_.first, this),
const_string_serializer_iterator(
string_serialization_info_range_.second, this));
}
}
////////////////////////////////////////////////////////////////////////////////
// DEFINITIONS for policies
namespace shadow
{
template <class Derived>
inline std::pair<
typename get_parameter_types_policy<Derived>::const_parameter_type_iterator,
typename get_parameter_types_policy<Derived>::const_parameter_type_iterator>
get_parameter_types_policy<Derived>::parameter_types() const
{
const auto num_parameters =
static_cast<const Derived*>(this)->info_->num_parameters;
const std::size_t* param_type_index_buffer =
static_cast<const Derived*>(this)->info_->parameter_type_indices;
const reflection_manager* manager =
static_cast<const Derived*>(this)->manager_;
return std::make_pair(
const_parameter_type_iterator(0,
param_type_index_buffer,
manager->type_info_range_.first,
manager),
const_parameter_type_iterator(num_parameters,
param_type_index_buffer,
manager->type_info_range_.first,
manager));
}
}
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/future.hh>
#include <exception>
#include <functional>
#include <cassert>
namespace seastar {
// A stream/subscription pair is similar to a promise/future pair,
// but apply to a sequence of values instead of a single value.
//
// A stream<> is the producer side. It may call produce() as long
// as the future<> returned from the previous invocation is ready.
// To signify no more data is available, call close().
//
// A subscription<> is the consumer side. It is created by a call
// to stream::listen(). Calling subscription::start(),
// which registers the data processing callback, starts processing
// events. It may register for end-of-stream notifications by
// chaining the when_done() future, which also delivers error
// events (as exceptions).
//
// The consumer can pause generation of new data by returning
// a non-ready future; when the future becomes ready, the producer
// will resume processing.
template <typename... T>
class stream;
template <typename... T>
class subscription;
template <typename... T>
class stream {
public:
using next_fn = std::function<future<> (T...)>;
private:
subscription<T...>* _sub = nullptr;
promise<> _done;
promise<> _ready;
next_fn _next;
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(next_fn next);
public:
stream() = default;
stream(const stream&) = delete;
stream(stream&&) = delete;
~stream();
void operator=(const stream&) = delete;
void operator=(stream&&) = delete;
// Returns a subscription that reads value from this
// stream.
subscription<T...> listen();
// Returns a subscription that reads value from this
// stream, and also sets up the listen function.
subscription<T...> listen(next_fn next);
// Becomes ready when the listener is ready to accept
// values. Call only once, when beginning to produce
// values.
future<> started();
// Produce a value. Call only after started(), and after
// a previous produce() is ready.
future<> produce(T... data);
// End the stream. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
void close();
// Signal an error. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
template <typename E>
void set_exception(E ex);
friend class subscription<T...>;
};
template <typename... T>
class subscription {
public:
using next_fn = typename stream<T...>::next_fn;
private:
stream<T...>* _stream;
future<> _done;
private:
explicit subscription(stream<T...>* s);
public:
subscription(subscription&& x);
~subscription();
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(next_fn next) {
return _stream->start(std::move(next));
}
// Becomes ready when the stream is empty, or when an error
// happens (in that case, an exception is held).
future<> done() {
return std::move(_done);
}
friend class stream<T...>;
};
template <typename... T>
inline
stream<T...>::~stream() {
if (_sub) {
_sub->_stream = nullptr;
}
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen() {
return subscription<T...>(this);
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen(next_fn next) {
auto sub = subscription<T...>(this);
sub.start(std::move(next));
return sub;
}
template <typename... T>
inline
future<>
stream<T...>::started() {
return _ready.get_future();
}
template <typename... T>
inline
future<>
stream<T...>::produce(T... data) {
auto ret = futurize<void>::apply(_next, std::move(data)...);
if (ret.available() && !ret.failed()) {
// Native network stack depends on stream::produce() returning
// a ready future to push packets along without dropping. As
// a temporary workaround, special case a ready, unfailed future
// and return it immediately, so that then_wrapped(), below,
// doesn't convert a ready future to an unready one.
return ret;
}
return ret.then_wrapped([this] (auto&& f) {
try {
f.get();
} catch (...) {
_done.set_exception(std::current_exception());
// FIXME: tell the producer to stop producing
throw;
}
});
}
template <typename... T>
inline
void
stream<T...>::close() {
_done.set_value();
}
template <typename... T>
template <typename E>
inline
void
stream<T...>::set_exception(E ex) {
_done.set_exception(ex);
}
template <typename... T>
inline
subscription<T...>::subscription(stream<T...>* s)
: _stream(s), _done(s->_done.get_future()) {
assert(!_stream->_sub);
_stream->_sub = this;
}
template <typename... T>
inline
void
stream<T...>::start(next_fn next) {
_next = std::move(next);
_ready.set_value();
}
template <typename... T>
inline
subscription<T...>::~subscription() {
if (_stream) {
_stream->_sub = nullptr;
}
}
template <typename... T>
inline
subscription<T...>::subscription(subscription&& x)
: _stream(x._stream), _done(std::move(x._done)) {
x._stream = nullptr;
if (_stream) {
_stream->_sub = this;
}
}
}
<commit_msg>stream: Simplify stream::listen<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/future.hh>
#include <exception>
#include <functional>
#include <cassert>
namespace seastar {
// A stream/subscription pair is similar to a promise/future pair,
// but apply to a sequence of values instead of a single value.
//
// A stream<> is the producer side. It may call produce() as long
// as the future<> returned from the previous invocation is ready.
// To signify no more data is available, call close().
//
// A subscription<> is the consumer side. It is created by a call
// to stream::listen(). Calling subscription::start(),
// which registers the data processing callback, starts processing
// events. It may register for end-of-stream notifications by
// chaining the when_done() future, which also delivers error
// events (as exceptions).
//
// The consumer can pause generation of new data by returning
// a non-ready future; when the future becomes ready, the producer
// will resume processing.
template <typename... T>
class stream;
template <typename... T>
class subscription;
template <typename... T>
class stream {
public:
using next_fn = std::function<future<> (T...)>;
private:
subscription<T...>* _sub = nullptr;
promise<> _done;
promise<> _ready;
next_fn _next;
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(next_fn next);
public:
stream() = default;
stream(const stream&) = delete;
stream(stream&&) = delete;
~stream();
void operator=(const stream&) = delete;
void operator=(stream&&) = delete;
// Returns a subscription that reads value from this
// stream.
subscription<T...> listen();
// Returns a subscription that reads value from this
// stream, and also sets up the listen function.
subscription<T...> listen(next_fn next);
// Becomes ready when the listener is ready to accept
// values. Call only once, when beginning to produce
// values.
future<> started();
// Produce a value. Call only after started(), and after
// a previous produce() is ready.
future<> produce(T... data);
// End the stream. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
void close();
// Signal an error. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
template <typename E>
void set_exception(E ex);
friend class subscription<T...>;
};
template <typename... T>
class subscription {
public:
using next_fn = typename stream<T...>::next_fn;
private:
stream<T...>* _stream;
future<> _done;
private:
explicit subscription(stream<T...>* s);
public:
subscription(subscription&& x);
~subscription();
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(next_fn next) {
return _stream->start(std::move(next));
}
// Becomes ready when the stream is empty, or when an error
// happens (in that case, an exception is held).
future<> done() {
return std::move(_done);
}
friend class stream<T...>;
};
template <typename... T>
inline
stream<T...>::~stream() {
if (_sub) {
_sub->_stream = nullptr;
}
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen() {
return subscription<T...>(this);
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen(next_fn next) {
start(std::move(next));
return subscription<T...>(this);
}
template <typename... T>
inline
future<>
stream<T...>::started() {
return _ready.get_future();
}
template <typename... T>
inline
future<>
stream<T...>::produce(T... data) {
auto ret = futurize<void>::apply(_next, std::move(data)...);
if (ret.available() && !ret.failed()) {
// Native network stack depends on stream::produce() returning
// a ready future to push packets along without dropping. As
// a temporary workaround, special case a ready, unfailed future
// and return it immediately, so that then_wrapped(), below,
// doesn't convert a ready future to an unready one.
return ret;
}
return ret.then_wrapped([this] (auto&& f) {
try {
f.get();
} catch (...) {
_done.set_exception(std::current_exception());
// FIXME: tell the producer to stop producing
throw;
}
});
}
template <typename... T>
inline
void
stream<T...>::close() {
_done.set_value();
}
template <typename... T>
template <typename E>
inline
void
stream<T...>::set_exception(E ex) {
_done.set_exception(ex);
}
template <typename... T>
inline
subscription<T...>::subscription(stream<T...>* s)
: _stream(s), _done(s->_done.get_future()) {
assert(!_stream->_sub);
_stream->_sub = this;
}
template <typename... T>
inline
void
stream<T...>::start(next_fn next) {
_next = std::move(next);
_ready.set_value();
}
template <typename... T>
inline
subscription<T...>::~subscription() {
if (_stream) {
_stream->_sub = nullptr;
}
}
template <typename... T>
inline
subscription<T...>::subscription(subscription&& x)
: _stream(x._stream), _done(std::move(x._done)) {
x._stream = nullptr;
if (_stream) {
_stream->_sub = this;
}
}
}
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/future.hh>
#include <exception>
#include <functional>
#include <cassert>
namespace seastar {
// A stream/subscription pair is similar to a promise/future pair,
// but apply to a sequence of values instead of a single value.
//
// A stream<> is the producer side. It may call produce() as long
// as the future<> returned from the previous invocation is ready.
// To signify no more data is available, call close().
//
// A subscription<> is the consumer side. It is created by a call
// to stream::listen(). Calling subscription::start(),
// which registers the data processing callback, starts processing
// events. It may register for end-of-stream notifications by
// chaining the when_done() future, which also delivers error
// events (as exceptions).
//
// The consumer can pause generation of new data by returning
// a non-ready future; when the future becomes ready, the producer
// will resume processing.
template <typename... T>
class stream;
template <typename... T>
class subscription;
template <typename... T>
class stream {
public:
using next_fn = std::function<future<> (T...)>;
private:
subscription<T...>* _sub = nullptr;
promise<> _done;
promise<> _ready;
next_fn _next;
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(std::function<future<> (T...)> next);
public:
stream() = default;
stream(const stream&) = delete;
stream(stream&&) = delete;
~stream();
void operator=(const stream&) = delete;
void operator=(stream&&) = delete;
// Returns a subscription that reads value from this
// stream.
subscription<T...> listen();
// Returns a subscription that reads value from this
// stream, and also sets up the listen function.
subscription<T...> listen(next_fn next);
// Becomes ready when the listener is ready to accept
// values. Call only once, when beginning to produce
// values.
future<> started();
// Produce a value. Call only after started(), and after
// a previous produce() is ready.
future<> produce(T... data);
// End the stream. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
void close();
// Signal an error. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
template <typename E>
void set_exception(E ex);
friend class subscription<T...>;
};
template <typename... T>
class subscription {
public:
using next_fn = typename stream<T...>::next_fn;
private:
stream<T...>* _stream;
future<> _done;
private:
explicit subscription(stream<T...>* s);
public:
subscription(subscription&& x);
~subscription();
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(std::function<future<> (T...)> next) {
return _stream->start(std::move(next));
}
// Becomes ready when the stream is empty, or when an error
// happens (in that case, an exception is held).
future<> done() {
return std::move(_done);
}
friend class stream<T...>;
};
template <typename... T>
inline
stream<T...>::~stream() {
if (_sub) {
_sub->_stream = nullptr;
}
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen() {
return subscription<T...>(this);
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen(next_fn next) {
auto sub = subscription<T...>(this);
sub.start(std::move(next));
return sub;
}
template <typename... T>
inline
future<>
stream<T...>::started() {
return _ready.get_future();
}
template <typename... T>
inline
future<>
stream<T...>::produce(T... data) {
auto ret = futurize<void>::apply(_next, std::move(data)...);
if (ret.available() && !ret.failed()) {
// Native network stack depends on stream::produce() returning
// a ready future to push packets along without dropping. As
// a temporary workaround, special case a ready, unfailed future
// and return it immediately, so that then_wrapped(), below,
// doesn't convert a ready future to an unready one.
return ret;
}
return ret.then_wrapped([this] (auto&& f) {
try {
f.get();
} catch (...) {
_done.set_exception(std::current_exception());
// FIXME: tell the producer to stop producing
throw;
}
});
}
template <typename... T>
inline
void
stream<T...>::close() {
_done.set_value();
}
template <typename... T>
template <typename E>
inline
void
stream<T...>::set_exception(E ex) {
_done.set_exception(ex);
}
template <typename... T>
inline
subscription<T...>::subscription(stream<T...>* s)
: _stream(s), _done(s->_done.get_future()) {
assert(!_stream->_sub);
_stream->_sub = this;
}
template <typename... T>
inline
void
stream<T...>::start(std::function<future<> (T...)> next) {
_next = std::move(next);
_ready.set_value();
}
template <typename... T>
inline
subscription<T...>::~subscription() {
if (_stream) {
_stream->_sub = nullptr;
}
}
template <typename... T>
inline
subscription<T...>::subscription(subscription&& x)
: _stream(x._stream), _done(std::move(x._done)) {
x._stream = nullptr;
if (_stream) {
_stream->_sub = this;
}
}
}
<commit_msg>stream: use next_fn everywhere<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/future.hh>
#include <exception>
#include <functional>
#include <cassert>
namespace seastar {
// A stream/subscription pair is similar to a promise/future pair,
// but apply to a sequence of values instead of a single value.
//
// A stream<> is the producer side. It may call produce() as long
// as the future<> returned from the previous invocation is ready.
// To signify no more data is available, call close().
//
// A subscription<> is the consumer side. It is created by a call
// to stream::listen(). Calling subscription::start(),
// which registers the data processing callback, starts processing
// events. It may register for end-of-stream notifications by
// chaining the when_done() future, which also delivers error
// events (as exceptions).
//
// The consumer can pause generation of new data by returning
// a non-ready future; when the future becomes ready, the producer
// will resume processing.
template <typename... T>
class stream;
template <typename... T>
class subscription;
template <typename... T>
class stream {
public:
using next_fn = std::function<future<> (T...)>;
private:
subscription<T...>* _sub = nullptr;
promise<> _done;
promise<> _ready;
next_fn _next;
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(next_fn next);
public:
stream() = default;
stream(const stream&) = delete;
stream(stream&&) = delete;
~stream();
void operator=(const stream&) = delete;
void operator=(stream&&) = delete;
// Returns a subscription that reads value from this
// stream.
subscription<T...> listen();
// Returns a subscription that reads value from this
// stream, and also sets up the listen function.
subscription<T...> listen(next_fn next);
// Becomes ready when the listener is ready to accept
// values. Call only once, when beginning to produce
// values.
future<> started();
// Produce a value. Call only after started(), and after
// a previous produce() is ready.
future<> produce(T... data);
// End the stream. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
void close();
// Signal an error. Call only after started(), and after
// a previous produce() is ready. No functions may be called
// after this.
template <typename E>
void set_exception(E ex);
friend class subscription<T...>;
};
template <typename... T>
class subscription {
public:
using next_fn = typename stream<T...>::next_fn;
private:
stream<T...>* _stream;
future<> _done;
private:
explicit subscription(stream<T...>* s);
public:
subscription(subscription&& x);
~subscription();
/// \brief Start receiving events from the stream.
///
/// \param next Callback to call for each event
void start(next_fn next) {
return _stream->start(std::move(next));
}
// Becomes ready when the stream is empty, or when an error
// happens (in that case, an exception is held).
future<> done() {
return std::move(_done);
}
friend class stream<T...>;
};
template <typename... T>
inline
stream<T...>::~stream() {
if (_sub) {
_sub->_stream = nullptr;
}
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen() {
return subscription<T...>(this);
}
template <typename... T>
inline
subscription<T...>
stream<T...>::listen(next_fn next) {
auto sub = subscription<T...>(this);
sub.start(std::move(next));
return sub;
}
template <typename... T>
inline
future<>
stream<T...>::started() {
return _ready.get_future();
}
template <typename... T>
inline
future<>
stream<T...>::produce(T... data) {
auto ret = futurize<void>::apply(_next, std::move(data)...);
if (ret.available() && !ret.failed()) {
// Native network stack depends on stream::produce() returning
// a ready future to push packets along without dropping. As
// a temporary workaround, special case a ready, unfailed future
// and return it immediately, so that then_wrapped(), below,
// doesn't convert a ready future to an unready one.
return ret;
}
return ret.then_wrapped([this] (auto&& f) {
try {
f.get();
} catch (...) {
_done.set_exception(std::current_exception());
// FIXME: tell the producer to stop producing
throw;
}
});
}
template <typename... T>
inline
void
stream<T...>::close() {
_done.set_value();
}
template <typename... T>
template <typename E>
inline
void
stream<T...>::set_exception(E ex) {
_done.set_exception(ex);
}
template <typename... T>
inline
subscription<T...>::subscription(stream<T...>* s)
: _stream(s), _done(s->_done.get_future()) {
assert(!_stream->_sub);
_stream->_sub = this;
}
template <typename... T>
inline
void
stream<T...>::start(next_fn next) {
_next = std::move(next);
_ready.set_value();
}
template <typename... T>
inline
subscription<T...>::~subscription() {
if (_stream) {
_stream->_sub = nullptr;
}
}
template <typename... T>
inline
subscription<T...>::subscription(subscription&& x)
: _stream(x._stream), _done(std::move(x._done)) {
x._stream = nullptr;
if (_stream) {
_stream->_sub = this;
}
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesOperator.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqNonEditableStyledItemDelegate.h>
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <pqView.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkPVDataSetAttributesInformation.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkAlgorithm.h>
#include <vtkDataArray.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkSMSourceProxy.h>
#include <QDebug>
#include <QDoubleValidator>
#include <QMainWindow>
namespace tomviz {
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: QWidget(parentObject), m_ui(new Ui::DataPropertiesPanel)
{
m_ui->setupUi(this);
m_ui->xLengthBox->setValidator(new QDoubleValidator(m_ui->xLengthBox));
m_ui->yLengthBox->setValidator(new QDoubleValidator(m_ui->yLengthBox));
m_ui->zLengthBox->setValidator(new QDoubleValidator(m_ui->zLengthBox));
QVBoxLayout* l = m_ui->verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", this);
l->insertWidget(l->indexOf(m_ui->FileName), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->DataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Units and Size", this);
l->insertWidget(l->indexOf(m_ui->LengthWidget), separator);
m_tiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", this);
l->insertWidget(l->indexOf(m_ui->SetTiltAnglesButton), m_tiltAnglesSeparator);
clear();
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(updateAxesGridLabels()));
connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),
SLOT(updateAxesGridLabels()));
connect(m_ui->SetTiltAnglesButton, SIGNAL(clicked()), SLOT(setTiltAngles()));
connect(m_ui->unitBox, SIGNAL(editingFinished()), SLOT(updateUnits()));
connect(m_ui->xLengthBox, SIGNAL(editingFinished()), SLOT(updateXLength()));
connect(m_ui->yLengthBox, SIGNAL(editingFinished()), SLOT(updateYLength()));
connect(m_ui->zLengthBox, SIGNAL(editingFinished()), SLOT(updateZLength()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent* e)
{
updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (m_currentDataSource) {
disconnect(m_currentDataSource);
}
m_currentDataSource = dsource;
if (dsource) {
connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
scheduleUpdate();
}
namespace {
QString getDataDimensionsString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString =
QString("Dimensions: %1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
return extentString;
}
} // namespace
void DataPropertiesPanel::updateInformationWidget(
QTreeWidget* infoTreeWidget, vtkPVDataInformation* dataInfo)
{
infoTreeWidget->clear();
vtkPVDataSetAttributesInformation* pointDataInfo =
dataInfo->GetPointDataInformation();
if (pointDataInfo) {
QPixmap pointDataPixmap(":/pqWidgets/Icons/pqPointData16.png");
int numArrays = pointDataInfo->GetNumberOfArrays();
for (int i = 0; i < numArrays; i++) {
vtkPVArrayInformation* arrayInfo;
arrayInfo = pointDataInfo->GetArrayInformation(i);
// name, type, data range, data type
QTreeWidgetItem* item = new QTreeWidgetItem(infoTreeWidget);
item->setData(0, Qt::DisplayRole, arrayInfo->GetName());
QString dataType = vtkImageScalarTypeNameMacro(arrayInfo->GetDataType());
item->setData(2, Qt::DisplayRole, dataType);
int numComponents = arrayInfo->GetNumberOfComponents();
QString dataRange;
double range[2];
for (int j = 0; j < numComponents; j++) {
if (j != 0) {
dataRange.append(", ");
}
arrayInfo->GetComponentRange(j, range);
QString componentRange =
QString("[%1, %2]").arg(range[0]).arg(range[1]);
dataRange.append(componentRange);
}
item->setData(1, Qt::DisplayRole,
dataType == "string" ? tr("NA") : dataRange);
item->setData(1, Qt::ToolTipRole, dataRange);
item->setFlags(item->flags() | Qt::ItemIsEditable);
if (arrayInfo->GetIsPartial()) {
item->setForeground(0, QBrush(QColor("darkBlue")));
item->setData(0, Qt::DisplayRole,
QString("%1 (partial)").arg(arrayInfo->GetName()));
} else {
item->setForeground(0, QBrush(QColor("darkGreen")));
}
}
}
infoTreeWidget->header()->resizeSections(QHeaderView::ResizeToContents);
infoTreeWidget->setItemDelegate(new pqNonEditableStyledItemDelegate(this));
}
void DataPropertiesPanel::updateData()
{
if (!m_updateNeeded) {
return;
}
disconnect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
clear();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
m_ui->FileName->setText(dsource->filename());
m_ui->OriginalDataRange->setText(
getDataDimensionsString(dsource->dataSourceProxy()));
m_ui->TransformedDataRange->setText(
getDataDimensionsString(dsource->producer()));
int extent[6];
double spacing[3];
dsource->getExtent(extent);
dsource->getSpacing(spacing);
m_ui->xLengthBox->setText(
QString("%1").arg(spacing[0] * (extent[1] - extent[0])));
m_ui->yLengthBox->setText(
QString("%1").arg(spacing[1] * (extent[3] - extent[2])));
m_ui->zLengthBox->setText(
QString("%1").arg(spacing[2] * (extent[5] - extent[4])));
m_ui->unitBox->setText(m_currentDataSource->getUnits(0));
vtkSMSourceProxy* sourceProxy =
vtkSMSourceProxy::SafeDownCast(dsource->originalDataSource());
if (sourceProxy) {
updateInformationWidget(m_ui->OriginalDataTreeWidget,
sourceProxy->GetDataInformation());
}
sourceProxy = vtkSMSourceProxy::SafeDownCast(dsource->producer());
if (sourceProxy) {
updateInformationWidget(m_ui->TransformedDataTreeWidget,
sourceProxy->GetDataInformation());
}
// display tilt series data
if (dsource->type() == DataSource::TiltSeries) {
m_tiltAnglesSeparator->show();
m_ui->SetTiltAnglesButton->show();
m_ui->TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
m_ui->TiltAnglesTable->setRowCount(tiltAngles.size());
m_ui->TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i) {
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
m_ui->TiltAnglesTable->setItem(i, 0, item);
}
} else {
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->hide();
}
connect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
m_updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = m_currentDataSource;
// The table shouldn't be shown if this is not true, so this slot shouldn't be
// called
Q_ASSERT(dsource->type() == DataSource::TiltSeries);
QTableWidgetItem* item = m_ui->TiltAnglesTable->item(row, column);
auto ok = false;
auto value = item->data(Qt::DisplayRole).toDouble(&ok);
if (ok) {
auto needToAdd = false;
SetTiltAnglesOperator* op = nullptr;
if (dsource->operators().size() > 0) {
op = qobject_cast<SetTiltAnglesOperator*>(dsource->operators().last());
}
if (!op) {
op = new SetTiltAnglesOperator;
op->setParent(dsource);
needToAdd = true;
}
auto tiltAngles = op->tiltAngles();
tiltAngles[row] = value;
op->setTiltAngles(tiltAngles);
if (needToAdd) {
dsource->addOperator(op);
}
} else {
std::cerr << "Invalid tilt angle." << std::endl;
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = m_currentDataSource;
auto mainWindow = qobject_cast<QMainWindow*>(window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
m_updateNeeded = true;
if (isVisible()) {
updateData();
}
}
void DataPropertiesPanel::updateUnits()
{
if (m_currentDataSource) {
const QString& text = m_ui->unitBox->text();
m_currentDataSource->setUnits(text);
updateAxesGridLabels();
}
}
void DataPropertiesPanel::updateXLength()
{
const QString& text = m_ui->xLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse X Length string";
return;
}
updateSpacing(0, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateYLength()
{
const QString& text = m_ui->yLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Y Length string";
return;
}
updateSpacing(1, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateZLength()
{
const QString& text = m_ui->zLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Z Length string";
return;
}
updateSpacing(2, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateAxesGridLabels()
{
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
return;
}
auto axesGrid = vtkSMPropertyHelper(view, "AxesGrid", true).GetAsProxy();
DataSource* ds = ActiveObjects::instance().activeDataSource();
if (!axesGrid || !ds) {
return;
}
QString xTitle = QString("X (%1)").arg(ds->getUnits(0));
QString yTitle = QString("Y (%1)").arg(ds->getUnits(1));
QString zTitle = QString("Z (%1)").arg(ds->getUnits(2));
vtkSMPropertyHelper(axesGrid, "XTitle").Set(xTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "YTitle").Set(yTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "ZTitle").Set(zTitle.toUtf8().data());
axesGrid->UpdateVTKObjects();
pqView* qtView =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (qtView) {
qtView->render();
}
}
void DataPropertiesPanel::clear()
{
m_ui->FileName->setText("");
m_ui->DataRange->setText("");
m_ui->DataTreeWidget->clear();
if (m_colorMapWidget) {
m_ui->verticalLayout->removeWidget(m_colorMapWidget);
delete m_colorMapWidget;
}
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->clear();
m_ui->TiltAnglesTable->setRowCount(0);
m_ui->TiltAnglesTable->hide();
}
void DataPropertiesPanel::updateSpacing(int axis, double newLength)
{
if (!m_currentDataSource) {
return;
}
int extent[6];
double spacing[3];
m_currentDataSource->getExtent(extent);
m_currentDataSource->getSpacing(spacing);
spacing[axis] = newLength / (extent[2 * axis + 1] - extent[2 * axis]);
m_currentDataSource->setSpacing(spacing);
}
}
<commit_msg>Fix up DataPropertiesPanel changes<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesOperator.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqNonEditableStyledItemDelegate.h>
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <pqView.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkPVDataSetAttributesInformation.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkAlgorithm.h>
#include <vtkDataArray.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkSMSourceProxy.h>
#include <QDebug>
#include <QDoubleValidator>
#include <QMainWindow>
namespace tomviz {
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: QWidget(parentObject), m_ui(new Ui::DataPropertiesPanel)
{
m_ui->setupUi(this);
m_ui->xLengthBox->setValidator(new QDoubleValidator(m_ui->xLengthBox));
m_ui->yLengthBox->setValidator(new QDoubleValidator(m_ui->yLengthBox));
m_ui->zLengthBox->setValidator(new QDoubleValidator(m_ui->zLengthBox));
QVBoxLayout* l = m_ui->verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", this);
l->insertWidget(l->indexOf(m_ui->FileName), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->DataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Units and Size", this);
l->insertWidget(l->indexOf(m_ui->LengthWidget), separator);
m_tiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", this);
l->insertWidget(l->indexOf(m_ui->SetTiltAnglesButton), m_tiltAnglesSeparator);
clear();
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(updateAxesGridLabels()));
connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),
SLOT(updateAxesGridLabels()));
connect(m_ui->SetTiltAnglesButton, SIGNAL(clicked()), SLOT(setTiltAngles()));
connect(m_ui->unitBox, SIGNAL(editingFinished()), SLOT(updateUnits()));
connect(m_ui->xLengthBox, SIGNAL(editingFinished()), SLOT(updateXLength()));
connect(m_ui->yLengthBox, SIGNAL(editingFinished()), SLOT(updateYLength()));
connect(m_ui->zLengthBox, SIGNAL(editingFinished()), SLOT(updateZLength()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent* e)
{
updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (m_currentDataSource) {
disconnect(m_currentDataSource);
}
m_currentDataSource = dsource;
if (dsource) {
connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
scheduleUpdate();
}
namespace {
QString getDataDimensionsString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString =
QString("Dimensions: %1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
return extentString;
}
} // namespace
void DataPropertiesPanel::updateInformationWidget(
QTreeWidget* infoTreeWidget, vtkPVDataInformation* dataInfo)
{
infoTreeWidget->clear();
vtkPVDataSetAttributesInformation* pointDataInfo =
dataInfo->GetPointDataInformation();
if (pointDataInfo) {
QPixmap pointDataPixmap(":/pqWidgets/Icons/pqPointData16.png");
int numArrays = pointDataInfo->GetNumberOfArrays();
for (int i = 0; i < numArrays; i++) {
vtkPVArrayInformation* arrayInfo;
arrayInfo = pointDataInfo->GetArrayInformation(i);
// name, type, data range, data type
QTreeWidgetItem* item = new QTreeWidgetItem(infoTreeWidget);
item->setData(0, Qt::DisplayRole, arrayInfo->GetName());
QString dataType = vtkImageScalarTypeNameMacro(arrayInfo->GetDataType());
item->setData(2, Qt::DisplayRole, dataType);
int numComponents = arrayInfo->GetNumberOfComponents();
QString dataRange;
double range[2];
for (int j = 0; j < numComponents; j++) {
if (j != 0) {
dataRange.append(", ");
}
arrayInfo->GetComponentRange(j, range);
QString componentRange =
QString("[%1, %2]").arg(range[0]).arg(range[1]);
dataRange.append(componentRange);
}
item->setData(1, Qt::DisplayRole,
dataType == "string" ? tr("NA") : dataRange);
item->setData(1, Qt::ToolTipRole, dataRange);
item->setFlags(item->flags() | Qt::ItemIsEditable);
if (arrayInfo->GetIsPartial()) {
item->setForeground(0, QBrush(QColor("darkBlue")));
item->setData(0, Qt::DisplayRole,
QString("%1 (partial)").arg(arrayInfo->GetName()));
} else {
item->setForeground(0, QBrush(QColor("darkGreen")));
}
}
}
infoTreeWidget->header()->resizeSections(QHeaderView::ResizeToContents);
infoTreeWidget->setItemDelegate(new pqNonEditableStyledItemDelegate(this));
}
void DataPropertiesPanel::updateData()
{
if (!m_updateNeeded) {
return;
}
disconnect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
clear();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
m_ui->FileName->setText(dsource->filename());
m_ui->DataRange->setText(
getDataDimensionsString(dsource->dataSourceProxy()));
int extent[6];
double spacing[3];
dsource->getExtent(extent);
dsource->getSpacing(spacing);
m_ui->xLengthBox->setText(
QString("%1").arg(spacing[0] * (extent[1] - extent[0])));
m_ui->yLengthBox->setText(
QString("%1").arg(spacing[1] * (extent[3] - extent[2])));
m_ui->zLengthBox->setText(
QString("%1").arg(spacing[2] * (extent[5] - extent[4])));
m_ui->unitBox->setText(m_currentDataSource->getUnits(0));
vtkSMSourceProxy* sourceProxy =
vtkSMSourceProxy::SafeDownCast(dsource->dataSourceProxy());
if (sourceProxy) {
updateInformationWidget(m_ui->DataTreeWidget,
sourceProxy->GetDataInformation());
}
// display tilt series data
if (dsource->type() == DataSource::TiltSeries) {
m_tiltAnglesSeparator->show();
m_ui->SetTiltAnglesButton->show();
m_ui->TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
m_ui->TiltAnglesTable->setRowCount(tiltAngles.size());
m_ui->TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i) {
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
m_ui->TiltAnglesTable->setItem(i, 0, item);
}
} else {
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->hide();
}
connect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
m_updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = m_currentDataSource;
// The table shouldn't be shown if this is not true, so this slot shouldn't be
// called
Q_ASSERT(dsource->type() == DataSource::TiltSeries);
QTableWidgetItem* item = m_ui->TiltAnglesTable->item(row, column);
auto ok = false;
auto value = item->data(Qt::DisplayRole).toDouble(&ok);
if (ok) {
auto needToAdd = false;
SetTiltAnglesOperator* op = nullptr;
if (dsource->operators().size() > 0) {
op = qobject_cast<SetTiltAnglesOperator*>(dsource->operators().last());
}
if (!op) {
op = new SetTiltAnglesOperator;
op->setParent(dsource);
needToAdd = true;
}
auto tiltAngles = op->tiltAngles();
tiltAngles[row] = value;
op->setTiltAngles(tiltAngles);
if (needToAdd) {
dsource->addOperator(op);
}
} else {
std::cerr << "Invalid tilt angle." << std::endl;
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = m_currentDataSource;
auto mainWindow = qobject_cast<QMainWindow*>(window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
m_updateNeeded = true;
if (isVisible()) {
updateData();
}
}
void DataPropertiesPanel::updateUnits()
{
if (m_currentDataSource) {
const QString& text = m_ui->unitBox->text();
m_currentDataSource->setUnits(text);
updateAxesGridLabels();
}
}
void DataPropertiesPanel::updateXLength()
{
const QString& text = m_ui->xLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse X Length string";
return;
}
updateSpacing(0, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateYLength()
{
const QString& text = m_ui->yLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Y Length string";
return;
}
updateSpacing(1, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateZLength()
{
const QString& text = m_ui->zLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Z Length string";
return;
}
updateSpacing(2, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateAxesGridLabels()
{
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
return;
}
auto axesGrid = vtkSMPropertyHelper(view, "AxesGrid", true).GetAsProxy();
DataSource* ds = ActiveObjects::instance().activeDataSource();
if (!axesGrid || !ds) {
return;
}
QString xTitle = QString("X (%1)").arg(ds->getUnits(0));
QString yTitle = QString("Y (%1)").arg(ds->getUnits(1));
QString zTitle = QString("Z (%1)").arg(ds->getUnits(2));
vtkSMPropertyHelper(axesGrid, "XTitle").Set(xTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "YTitle").Set(yTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "ZTitle").Set(zTitle.toUtf8().data());
axesGrid->UpdateVTKObjects();
pqView* qtView =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (qtView) {
qtView->render();
}
}
void DataPropertiesPanel::clear()
{
m_ui->FileName->setText("");
m_ui->DataRange->setText("");
m_ui->DataTreeWidget->clear();
if (m_colorMapWidget) {
m_ui->verticalLayout->removeWidget(m_colorMapWidget);
delete m_colorMapWidget;
}
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->clear();
m_ui->TiltAnglesTable->setRowCount(0);
m_ui->TiltAnglesTable->hide();
}
void DataPropertiesPanel::updateSpacing(int axis, double newLength)
{
if (!m_currentDataSource) {
return;
}
int extent[6];
double spacing[3];
m_currentDataSource->getExtent(extent);
m_currentDataSource->getSpacing(spacing);
spacing[axis] = newLength / (extent[2 * axis + 1] - extent[2 * axis]);
m_currentDataSource->setSpacing(spacing);
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesOperator.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <pqView.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkAlgorithm.h>
#include <vtkDataArray.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkSMSourceProxy.h>
#include <QDebug>
#include <QDoubleValidator>
#include <QMainWindow>
namespace tomviz {
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: QWidget(parentObject), m_ui(new Ui::DataPropertiesPanel)
{
m_ui->setupUi(this);
m_ui->xLengthBox->setValidator(new QDoubleValidator(m_ui->xLengthBox));
m_ui->yLengthBox->setValidator(new QDoubleValidator(m_ui->yLengthBox));
m_ui->zLengthBox->setValidator(new QDoubleValidator(m_ui->zLengthBox));
QVBoxLayout* l = m_ui->verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", this);
l->insertWidget(l->indexOf(m_ui->FileName), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Original Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->OriginalDataRange), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Transformed Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->TransformedDataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Units and Size", this);
l->insertWidget(l->indexOf(m_ui->LengthWidget), separator);
m_tiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", this);
l->insertWidget(l->indexOf(m_ui->SetTiltAnglesButton), m_tiltAnglesSeparator);
clear();
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(updateAxesGridLabels()));
connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),
SLOT(updateAxesGridLabels()));
connect(m_ui->SetTiltAnglesButton, SIGNAL(clicked()), SLOT(setTiltAngles()));
connect(m_ui->unitBox, SIGNAL(editingFinished()), SLOT(updateUnits()));
connect(m_ui->xLengthBox, SIGNAL(editingFinished()), SLOT(updateXLength()));
connect(m_ui->yLengthBox, SIGNAL(editingFinished()), SLOT(updateYLength()));
connect(m_ui->zLengthBox, SIGNAL(editingFinished()), SLOT(updateZLength()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent* e)
{
updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (m_currentDataSource) {
disconnect(m_currentDataSource);
}
m_currentDataSource = dsource;
if (dsource) {
connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
scheduleUpdate();
}
namespace {
QString getDataExtentAndRangeString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString =
QString("%1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
if (vtkPVArrayInformation* scalarInfo =
tomviz::scalarArrayInformation(proxy)) {
return QString("(%1)\t%2 : %3")
.arg(extentString)
.arg(scalarInfo->GetComponentRange(0)[0])
.arg(scalarInfo->GetComponentRange(0)[1]);
} else {
return QString("(%1)\t? : ? (type: ?)").arg(extentString);
}
}
QString getDataTypeString(vtkSMSourceProxy* proxy)
{
if (vtkPVArrayInformation* scalarInfo =
tomviz::scalarArrayInformation(proxy)) {
return QString("Type: %1")
.arg(vtkImageScalarTypeNameMacro(scalarInfo->GetDataType()));
} else {
return QString("Type: ?");
}
}
}
void DataPropertiesPanel::updateData()
{
if (!m_updateNeeded) {
return;
}
disconnect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
clear();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
m_ui->FileName->setText(dsource->filename());
m_ui->OriginalDataRange->setText(
getDataExtentAndRangeString(dsource->originalDataSource()));
m_ui->OriginalDataType->setText(
getDataTypeString(dsource->originalDataSource()));
m_ui->TransformedDataRange->setText(
getDataExtentAndRangeString(dsource->producer()));
m_ui->TransformedDataType->setText(getDataTypeString(dsource->producer()));
int extent[6];
double spacing[3];
dsource->getExtent(extent);
dsource->getSpacing(spacing);
m_ui->xLengthBox->setText(
QString("%1").arg(spacing[0] * (extent[1] - extent[0] + 1)));
m_ui->yLengthBox->setText(
QString("%1").arg(spacing[1] * (extent[3] - extent[2] + 1)));
m_ui->zLengthBox->setText(
QString("%1").arg(spacing[2] * (extent[5] - extent[4] + 1)));
m_ui->unitBox->setText(m_currentDataSource->getUnits(0));
// display tilt series data
if (dsource->type() == DataSource::TiltSeries) {
m_tiltAnglesSeparator->show();
m_ui->SetTiltAnglesButton->show();
m_ui->TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
m_ui->TiltAnglesTable->setRowCount(tiltAngles.size());
m_ui->TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i) {
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
m_ui->TiltAnglesTable->setItem(i, 0, item);
}
} else {
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->hide();
}
connect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
m_updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = m_currentDataSource;
// The table shouldn't be shown if this is not true, so this slot shouldn't be
// called
Q_ASSERT(dsource->type() == DataSource::TiltSeries);
QTableWidgetItem* item = m_ui->TiltAnglesTable->item(row, column);
auto ok = false;
auto value = item->data(Qt::DisplayRole).toDouble(&ok);
if (ok) {
auto needToAdd = false;
SetTiltAnglesOperator* op = nullptr;
if (dsource->operators().size() > 0) {
op = qobject_cast<SetTiltAnglesOperator*>(dsource->operators().last());
}
if (!op) {
op = new SetTiltAnglesOperator;
op->setParent(dsource);
needToAdd = true;
}
auto tiltAngles = op->tiltAngles();
tiltAngles[row] = value;
op->setTiltAngles(tiltAngles);
if (needToAdd) {
dsource->addOperator(op);
}
} else {
std::cerr << "Invalid tilt angle." << std::endl;
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = m_currentDataSource;
auto mainWindow = qobject_cast<QMainWindow*>(window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
m_updateNeeded = true;
if (isVisible()) {
updateData();
}
}
void DataPropertiesPanel::updateUnits()
{
const QString& text = m_ui->unitBox->text();
m_currentDataSource->setUnits(text);
updateAxesGridLabels();
}
void DataPropertiesPanel::updateXLength()
{
const QString& text = m_ui->xLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse X Length string";
return;
}
updateSpacing(0, newLength);
updateData();
}
void DataPropertiesPanel::updateYLength()
{
const QString& text = m_ui->yLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Y Length string";
return;
}
updateSpacing(1, newLength);
updateData();
}
void DataPropertiesPanel::updateZLength()
{
const QString& text = m_ui->zLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Z Length string";
return;
}
updateSpacing(2, newLength);
updateData();
}
void DataPropertiesPanel::updateAxesGridLabels()
{
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
return;
}
auto axesGrid = vtkSMPropertyHelper(view, "AxesGrid", true).GetAsProxy();
DataSource* ds = ActiveObjects::instance().activeDataSource();
if (!axesGrid || !ds) {
return;
}
QString xTitle = QString("X (%1)").arg(ds->getUnits(0));
QString yTitle = QString("Y (%1)").arg(ds->getUnits(1));
QString zTitle = QString("Z (%1)").arg(ds->getUnits(2));
vtkSMPropertyHelper(axesGrid, "XTitle").Set(xTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "YTitle").Set(yTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "ZTitle").Set(zTitle.toUtf8().data());
axesGrid->UpdateVTKObjects();
pqView* qtView =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (qtView) {
qtView->render();
}
}
void DataPropertiesPanel::clear()
{
m_ui->FileName->setText("");
m_ui->OriginalDataRange->setText("");
m_ui->OriginalDataType->setText("Type:");
m_ui->TransformedDataRange->setText("");
m_ui->TransformedDataType->setText("Type:");
if (m_colorMapWidget) {
m_ui->verticalLayout->removeWidget(m_colorMapWidget);
delete m_colorMapWidget;
}
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->clear();
m_ui->TiltAnglesTable->setRowCount(0);
m_ui->TiltAnglesTable->hide();
}
void DataPropertiesPanel::updateSpacing(int axis, double newLength)
{
if (!m_currentDataSource) {
return;
}
int extent[6];
double spacing[3];
m_currentDataSource->getExtent(extent);
m_currentDataSource->getSpacing(spacing);
spacing[axis] = newLength / (extent[2 * axis + 1] - extent[2 * axis] + 1);
m_currentDataSource->setSpacing(spacing);
}
}
<commit_msg>Check that there is an active data source when setting units<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesOperator.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <pqView.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkAlgorithm.h>
#include <vtkDataArray.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkSMSourceProxy.h>
#include <QDebug>
#include <QDoubleValidator>
#include <QMainWindow>
namespace tomviz {
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: QWidget(parentObject), m_ui(new Ui::DataPropertiesPanel)
{
m_ui->setupUi(this);
m_ui->xLengthBox->setValidator(new QDoubleValidator(m_ui->xLengthBox));
m_ui->yLengthBox->setValidator(new QDoubleValidator(m_ui->yLengthBox));
m_ui->zLengthBox->setValidator(new QDoubleValidator(m_ui->zLengthBox));
QVBoxLayout* l = m_ui->verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", this);
l->insertWidget(l->indexOf(m_ui->FileName), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Original Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->OriginalDataRange), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Transformed Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->TransformedDataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Units and Size", this);
l->insertWidget(l->indexOf(m_ui->LengthWidget), separator);
m_tiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", this);
l->insertWidget(l->indexOf(m_ui->SetTiltAnglesButton), m_tiltAnglesSeparator);
clear();
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(updateAxesGridLabels()));
connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),
SLOT(updateAxesGridLabels()));
connect(m_ui->SetTiltAnglesButton, SIGNAL(clicked()), SLOT(setTiltAngles()));
connect(m_ui->unitBox, SIGNAL(editingFinished()), SLOT(updateUnits()));
connect(m_ui->xLengthBox, SIGNAL(editingFinished()), SLOT(updateXLength()));
connect(m_ui->yLengthBox, SIGNAL(editingFinished()), SLOT(updateYLength()));
connect(m_ui->zLengthBox, SIGNAL(editingFinished()), SLOT(updateZLength()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent* e)
{
updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (m_currentDataSource) {
disconnect(m_currentDataSource);
}
m_currentDataSource = dsource;
if (dsource) {
connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
scheduleUpdate();
}
namespace {
QString getDataExtentAndRangeString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString =
QString("%1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
if (vtkPVArrayInformation* scalarInfo =
tomviz::scalarArrayInformation(proxy)) {
return QString("(%1)\t%2 : %3")
.arg(extentString)
.arg(scalarInfo->GetComponentRange(0)[0])
.arg(scalarInfo->GetComponentRange(0)[1]);
} else {
return QString("(%1)\t? : ? (type: ?)").arg(extentString);
}
}
QString getDataTypeString(vtkSMSourceProxy* proxy)
{
if (vtkPVArrayInformation* scalarInfo =
tomviz::scalarArrayInformation(proxy)) {
return QString("Type: %1")
.arg(vtkImageScalarTypeNameMacro(scalarInfo->GetDataType()));
} else {
return QString("Type: ?");
}
}
}
void DataPropertiesPanel::updateData()
{
if (!m_updateNeeded) {
return;
}
disconnect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
clear();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
m_ui->FileName->setText(dsource->filename());
m_ui->OriginalDataRange->setText(
getDataExtentAndRangeString(dsource->originalDataSource()));
m_ui->OriginalDataType->setText(
getDataTypeString(dsource->originalDataSource()));
m_ui->TransformedDataRange->setText(
getDataExtentAndRangeString(dsource->producer()));
m_ui->TransformedDataType->setText(getDataTypeString(dsource->producer()));
int extent[6];
double spacing[3];
dsource->getExtent(extent);
dsource->getSpacing(spacing);
m_ui->xLengthBox->setText(
QString("%1").arg(spacing[0] * (extent[1] - extent[0] + 1)));
m_ui->yLengthBox->setText(
QString("%1").arg(spacing[1] * (extent[3] - extent[2] + 1)));
m_ui->zLengthBox->setText(
QString("%1").arg(spacing[2] * (extent[5] - extent[4] + 1)));
m_ui->unitBox->setText(m_currentDataSource->getUnits(0));
// display tilt series data
if (dsource->type() == DataSource::TiltSeries) {
m_tiltAnglesSeparator->show();
m_ui->SetTiltAnglesButton->show();
m_ui->TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
m_ui->TiltAnglesTable->setRowCount(tiltAngles.size());
m_ui->TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i) {
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
m_ui->TiltAnglesTable->setItem(i, 0, item);
}
} else {
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->hide();
}
connect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
m_updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = m_currentDataSource;
// The table shouldn't be shown if this is not true, so this slot shouldn't be
// called
Q_ASSERT(dsource->type() == DataSource::TiltSeries);
QTableWidgetItem* item = m_ui->TiltAnglesTable->item(row, column);
auto ok = false;
auto value = item->data(Qt::DisplayRole).toDouble(&ok);
if (ok) {
auto needToAdd = false;
SetTiltAnglesOperator* op = nullptr;
if (dsource->operators().size() > 0) {
op = qobject_cast<SetTiltAnglesOperator*>(dsource->operators().last());
}
if (!op) {
op = new SetTiltAnglesOperator;
op->setParent(dsource);
needToAdd = true;
}
auto tiltAngles = op->tiltAngles();
tiltAngles[row] = value;
op->setTiltAngles(tiltAngles);
if (needToAdd) {
dsource->addOperator(op);
}
} else {
std::cerr << "Invalid tilt angle." << std::endl;
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = m_currentDataSource;
auto mainWindow = qobject_cast<QMainWindow*>(window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
m_updateNeeded = true;
if (isVisible()) {
updateData();
}
}
void DataPropertiesPanel::updateUnits()
{
if (m_currentDataSource) {
const QString& text = m_ui->unitBox->text();
m_currentDataSource->setUnits(text);
updateAxesGridLabels();
}
}
void DataPropertiesPanel::updateXLength()
{
const QString& text = m_ui->xLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse X Length string";
return;
}
updateSpacing(0, newLength);
updateData();
}
void DataPropertiesPanel::updateYLength()
{
const QString& text = m_ui->yLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Y Length string";
return;
}
updateSpacing(1, newLength);
updateData();
}
void DataPropertiesPanel::updateZLength()
{
const QString& text = m_ui->zLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Z Length string";
return;
}
updateSpacing(2, newLength);
updateData();
}
void DataPropertiesPanel::updateAxesGridLabels()
{
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
return;
}
auto axesGrid = vtkSMPropertyHelper(view, "AxesGrid", true).GetAsProxy();
DataSource* ds = ActiveObjects::instance().activeDataSource();
if (!axesGrid || !ds) {
return;
}
QString xTitle = QString("X (%1)").arg(ds->getUnits(0));
QString yTitle = QString("Y (%1)").arg(ds->getUnits(1));
QString zTitle = QString("Z (%1)").arg(ds->getUnits(2));
vtkSMPropertyHelper(axesGrid, "XTitle").Set(xTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "YTitle").Set(yTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "ZTitle").Set(zTitle.toUtf8().data());
axesGrid->UpdateVTKObjects();
pqView* qtView =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (qtView) {
qtView->render();
}
}
void DataPropertiesPanel::clear()
{
m_ui->FileName->setText("");
m_ui->OriginalDataRange->setText("");
m_ui->OriginalDataType->setText("Type:");
m_ui->TransformedDataRange->setText("");
m_ui->TransformedDataType->setText("Type:");
if (m_colorMapWidget) {
m_ui->verticalLayout->removeWidget(m_colorMapWidget);
delete m_colorMapWidget;
}
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->clear();
m_ui->TiltAnglesTable->setRowCount(0);
m_ui->TiltAnglesTable->hide();
}
void DataPropertiesPanel::updateSpacing(int axis, double newLength)
{
if (!m_currentDataSource) {
return;
}
int extent[6];
double spacing[3];
m_currentDataSource->getExtent(extent);
m_currentDataSource->getSpacing(spacing);
spacing[axis] = newLength / (extent[2 * axis + 1] - extent[2 * axis] + 1);
m_currentDataSource->setSpacing(spacing);
}
}
<|endoftext|>
|
<commit_before>// -*- C++ -*-
// Unit Tests for: ????
//
// Copyright (C) 2011 by John Weiss
// This program is free software; you can redistribute it and/or modify
// it under the terms of the Artistic License, included as the file
// "LICENSE" in the source code archive.
//
// 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.
//
// You should have received a copy of the file "LICENSE", containing
// the License John Weiss originally placed this program under.
//
static const char* const
xFOOx_cc__="$Id$";
// Includes
//
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/test/minimal.hpp>
#include <boost/lexical_cast.hpp>
//#include <boost/something.hpp>
#include "RandomDataSrc.h"
#include "TestException.h"
#include "xFOOx.h"
//
// Using Decls.
//
using std::string;
using std::vector;
using std::exception;
using std::cerr;
using std::cout;
using std::endl;
using std::flush;
using jpwTools::random::RandomDataSrc;
//
// Typedefs
//
//
// Static variables
//
namespace marker {
const char* const testSep="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
const char* const testHeaderLHS="%%%% ";
const char* const testHeaderRHS=" %%%%";
const char* const sub_dot_dash="_._._._._._._._._._._._._._._."
"_._._._._._._._._._._._._._._";
const char* const sub_dbl_dash="=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"
"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=";
}; // end namespace marker
namespace {
const string::size_type LINE_LENGTH(78);
};
//////////////////////////////////////////////////////////////////////////////
//
// Utility Inlines
//
inline void markTestEnd()
{
cout << endl << endl << marker::testSep << endl;
}
inline void markTestStart(const string& testName)
{
static const string::size_type HDR_LEN(LINE_LENGTH-16);
string::size_type spaceLen=((HDR_LEN-16-testName.length())/2);
if((spaceLen > 30) /*|| (spaceLen < 0)*/) {
spaceLen=0;
}
cout << marker::testHeaderLHS;
if(spaceLen) {
string spacer(spaceLen, ' ');
cout << spacer<< testName << spacer;
} else {
cout << testName;
}
cout << marker::testHeaderRHS << endl << endl;
}
inline void markTest(const string& testName)
{
markTestEnd();
markTestStart(testName);
}
inline void dottedSeparator(const char* subtestName=0)
{
static const char* const dotted=
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7";
cout << dotted << endl;
if(subtestName) {
cout << '\t' << subtestName << endl << endl;
}
}
inline void dotdashSeparator(const char* subtestName=0)
{
static const char* const dot_dash="\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7";
cout << dot_dash << endl;
if(subtestName) {
cout << '\t' << subtestName << endl << endl;
}
}
inline void separator(unsigned n, const char* subtestName=0)
{
cout << marker::sub_dbl_dash << '[' << n << ']' << endl;
if(subtestName) {
cout << '\t' << subtestName << endl << endl;
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Utility Class: TestFoo
//
//////////////////////////////////////////////////////////////////////////////
//
// General Function Definitions
//
void processParams(const vector<string>& argv, RandomDataSrc& xi)
{
using std::hex;
using std::dec;
bool hasSeed(false);
unsigned long elSeed(0);
// This is just a crude sample. You can process args however you wish.
typedef vector<string>::const_iterator vec_iter_t;
for(vec_iter_t argIter=argv.begin(); argIter!=argv.end(); ++argIter)
{
if((*argIter == "--seed") || (*argIter == "-s")) {
++argIter;
if(argIter == argv.end()) {
// Error:
cerr << "Error: --seed passed without a value" << endl;
return;
} // else
hasSeed = true;
bool hasLeading_x = ( (((*argIter)[0] & 0xDF) == 'X') ||
(((*argIter)[1] & 0xDF) == 'X') );
bool hasLeading_nil = (((*argIter)[0] == '0') ||
((*argIter)[0] == '\\'));
std::stringstream iss(*argIter);
if(hasLeading_nil) {
char trash;
iss >> trash;
}
if(hasLeading_x) {
char trash;
iss >> trash;
}
iss >> hex >> elSeed;
//elSeed = lexical_cast<unsigned long>(*argIter);
}
}
// Use the seed if provided.
if(hasSeed) {
cout << "Using provided seed: 0x" << hex << elSeed << dec << endl;
xi.seed(elSeed);
} else {
cout << "Seed: 0x" << hex << xi.seed() << dec << endl;
}
}
/////////////////////////
//
// Functions "tst_main()" and "cxx_main()"
//
// This is where all of your main handling should go.
int cxx_main(const string& myName,
const string& myPath,
const vector<string>& argv)
{
RandomDataSrc xi;
// Also sets the seed if provided amongst the cmdline args.
processParams(argv, xi);
markTestStart("testName or testFnName()");
cout << "Doing test blah blah blah" << endl;
markTest("testName or testFnName()");
cout << "Doing next test blah blah blah" << endl;
markTestEnd();
return 0;
}
int test_main(int argc, char* argv[])
{
// Split off the name of the executable from its path.
string myName(argv[0]);
string::size_type last_pathsep = myName.find_last_of('/');
string myPath;
if(last_pathsep != string::npos) {
myPath = myName.substr(0, last_pathsep+1);
myName.erase(0, last_pathsep+1);
}
// Build a vector of strings for the arg list, which is much easier to
// handle than the old-style char** argv.
vector<string> argVec;
argVec.reserve(argc);
for(int i=1; i < argc; ++i) {
argVec.push_back(string(argv[i]));
}
// Call cxx_main(), which is where almost all of your code should go.
#if GUARD_AGAINST_UNSUPPORTED_EXCEPTIONS_OR_DELETE_ME
try {
return cxx_main(myName, myPath, argVec);
} catch(FooException& ex) {
cerr << "Caught Foo: " << ex.what() << endl;
return 3;
}
// Don't catch generic exceptions; let the Boost Test Framework do that.
return -1;
#else // Delete if you want/need to guard against certain exceptions.
// Don't catch exceptions; let the Boost Test Framework do that.
return cxx_main(myName, myPath, argVec);
#fi
}
/////////////////////////
//
// End
<commit_msg>- "processParams()" now uses the new 'parse_seed()' features of "RandomDataSrc".<commit_after>// -*- C++ -*-
// Unit Tests for: ????
//
// Copyright (C) 2011 by John Weiss
// This program is free software; you can redistribute it and/or modify
// it under the terms of the Artistic License, included as the file
// "LICENSE" in the source code archive.
//
// 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.
//
// You should have received a copy of the file "LICENSE", containing
// the License John Weiss originally placed this program under.
//
static const char* const
xFOOx_cc__="$Id$";
// Includes
//
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/test/minimal.hpp>
#include <boost/lexical_cast.hpp>
//#include <boost/something.hpp>
#include "RandomDataSrc.h"
#include "TestException.h"
#include "xFOOx.h"
//
// Using Decls.
//
using std::string;
using std::vector;
using std::exception;
using std::cerr;
using std::cout;
using std::endl;
using std::flush;
using jpwTools::random::RandomDataSrc;
//
// Typedefs
//
//
// Static variables
//
namespace marker {
const char* const testSep="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
const char* const testHeaderLHS="%%%% ";
const char* const testHeaderRHS=" %%%%";
const char* const sub_dot_dash="_._._._._._._._._._._._._._._."
"_._._._._._._._._._._._._._._";
const char* const sub_dbl_dash="=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"
"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=";
}; // end namespace marker
namespace {
const string::size_type LINE_LENGTH(78);
};
//////////////////////////////////////////////////////////////////////////////
//
// Utility Inlines
//
inline void markTestEnd()
{
cout << endl << endl << marker::testSep << endl;
}
inline void markTestStart(const string& testName)
{
static const string::size_type HDR_LEN(LINE_LENGTH-16);
string::size_type spaceLen=((HDR_LEN-16-testName.length())/2);
if((spaceLen > 30) /*|| (spaceLen < 0)*/) {
spaceLen=0;
}
cout << marker::testHeaderLHS;
if(spaceLen) {
string spacer(spaceLen, ' ');
cout << spacer<< testName << spacer;
} else {
cout << testName;
}
cout << marker::testHeaderRHS << endl << endl;
}
inline void markTest(const string& testName)
{
markTestEnd();
markTestStart(testName);
}
inline void dottedSeparator(const char* subtestName=0)
{
static const char* const dotted=
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7"
"\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7";
cout << dotted << endl;
if(subtestName) {
cout << '\t' << subtestName << endl << endl;
}
}
inline void dotdashSeparator(const char* subtestName=0)
{
static const char* const dot_dash="\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-\u00B7-"
"\u00B7-\u00B7-\u00B7";
cout << dot_dash << endl;
if(subtestName) {
cout << '\t' << subtestName << endl << endl;
}
}
inline void separator(unsigned n, const char* subtestName=0)
{
cout << marker::sub_dbl_dash << '[' << n << ']' << endl;
if(subtestName) {
cout << '\t' << subtestName << endl << endl;
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Utility Class: TestFoo
//
//////////////////////////////////////////////////////////////////////////////
//
// General Function Definitions
//
void processParams(const vector<string>& argv, RandomDataSrc& xi)
{
bool hasSeed(false);
// This is just a crude sample. You can process args however you wish.
typedef vector<string>::const_iterator vec_iter_t;
for(vec_iter_t argIter=argv.begin(); argIter!=argv.end(); ++argIter)
{
if((*argIter == "--seed") || (*argIter == "-s")) {
++argIter;
if(argIter == argv.end()) {
// Error:
cerr << "Error: --seed passed without a value" << endl;
return;
} // else
// Parse, then check for incomplete or failed reads:
if( xi.parse_seed(*argIter) ) {
hasSeed = true;
} else {
cout << "ERROR! Failed to parse seed value: \""
<< (*argIter) << "\"" << endl
<< "Using autogenerated seed instead..." << endl;
}
}
}
// Use the seed if provided.
cout << (hasSeed ? "Using provided seed: " : "Seed: ")
<< xi.print_seed() << endl;
}
/////////////////////////
//
// Functions "tst_main()" and "cxx_main()"
//
// This is where all of your main handling should go.
int cxx_main(const string& myName,
const string& myPath,
const vector<string>& argv)
{
RandomDataSrc xi;
// Also sets the seed if provided amongst the cmdline args.
processParams(argv, xi);
markTestStart("testName or testFnName()");
cout << "Doing test blah blah blah" << endl;
markTest("testName or testFnName()");
cout << "Doing next test blah blah blah" << endl;
markTestEnd();
return 0;
}
int test_main(int argc, char* argv[])
{
// Split off the name of the executable from its path.
string myName(argv[0]);
string::size_type last_pathsep = myName.find_last_of('/');
string myPath;
if(last_pathsep != string::npos) {
myPath = myName.substr(0, last_pathsep+1);
myName.erase(0, last_pathsep+1);
}
// Build a vector of strings for the arg list, which is much easier to
// handle than the old-style char** argv.
vector<string> argVec;
argVec.reserve(argc);
for(int i=1; i < argc; ++i) {
argVec.push_back(string(argv[i]));
}
// Call cxx_main(), which is where almost all of your code should go.
#if GUARD_AGAINST_UNSUPPORTED_EXCEPTIONS_OR_DELETE_ME
try {
return cxx_main(myName, myPath, argVec);
} catch(FooException& ex) {
cerr << "Caught Foo: " << ex.what() << endl;
return 3;
}
// Don't catch generic exceptions; let the Boost Test Framework do that.
return -1;
#else // Delete if you want/need to guard against certain exceptions.
// Don't catch exceptions; let the Boost Test Framework do that.
return cxx_main(myName, myPath, argVec);
#endif
}
/////////////////////////
//
// End
<|endoftext|>
|
<commit_before>/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/partial_sum_op.h"
#include <memory>
#include <string>
#include <vector>
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
class PartialSumOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE_GE(ctx->Inputs("X").size(), 1UL,
platform::errors::InvalidArgument(
"Inputs(X) of PartialSumOp should not be empty."));
PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
platform::errors::InvalidArgument(
"Output(Out) of PartialSumOp should not be null."));
auto inputs_dims = ctx->GetInputsDim("X");
const size_t inputs_num = inputs_dims.size();
PADDLE_ENFORCE_GT(inputs_num, 0,
platform::errors::InvalidArgument(
"ShapeError: Input tensors count should > 0. But "
"recevied inputs' length is 0."));
if (inputs_num == 1) {
VLOG(3) << "Warning: partial_sum op have only one input, may be useless";
}
int start_index = ctx->Attrs().Get<int>("start_index");
int length = ctx->Attrs().Get<int>("length");
// Only suppert two dimensions now, should be extended later
// when length is -1, need make sure all dimensions to be added are the same
int64_t batch_size = -1;
int64_t input_len = -1;
for (size_t i = 0; i < inputs_num; ++i) {
PADDLE_ENFORCE_EQ(inputs_dims[i].size(), 2,
platform::errors::InvalidArgument(
"Only suppert two dimensions input now."));
if (i == 0) {
batch_size = inputs_dims[0][0];
input_len = inputs_dims[0][1];
} else {
PADDLE_ENFORCE_EQ(inputs_dims[i][0], batch_size,
platform::errors::InvalidArgument(
"The batch size of all inputs must be same"));
PADDLE_ENFORCE_EQ(inputs_dims[i][1], input_len,
platform::errors::InvalidArgument(
"The input len of all inputs must be same"));
}
}
PADDLE_ENFORCE_GT(input_len, start_index,
platform::errors::OutOfRange(
"start_index must be less than input len"));
if (length > 0) {
PADDLE_ENFORCE_GE(
input_len, start_index + length,
platform::errors::OutOfRange(
"start_index + length is larger than input length"));
}
std::vector<int64_t> out_dims(2);
out_dims[0] = batch_size;
out_dims[1] = (length == -1) ? input_len - start_index : length;
ctx->SetOutputDim("Out", framework::make_ddim(out_dims));
ctx->ShareLoD("X", /*->*/ "Out");
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
auto inputs = ctx.MultiInput<Tensor>("X");
auto input_data_type = framework::proto::VarType::Type(0);
bool flag = 0;
for (auto *input : inputs) {
if (input->IsInitialized() && input->numel() > 0) {
input_data_type = input->type();
flag = 1;
break;
}
}
PADDLE_ENFORCE_EQ(flag, 1, platform::errors::InvalidArgument(
"All Inputs of PartialSum OP are Empty!"));
return framework::OpKernelType(input_data_type, platform::CPUPlace());
}
};
class PartialSumGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
auto in_x = "X";
auto out_x_g_n = framework::GradVarName(in_x);
ctx->SetOutputsDim(out_x_g_n, ctx->GetInputsDim(in_x));
auto in_names = ctx->Inputs(in_x);
auto out_names = ctx->Outputs(out_x_g_n);
PADDLE_ENFORCE_EQ(
in_names.size(), out_names.size(),
platform::errors::InvalidArgument(
"The number of arguments in %s[%d] and %s[%d] is not equal.", in_x,
in_names.size(), out_x_g_n, out_names.size()));
for (size_t i = 0; i < in_names.size(); ++i) {
if (out_names[i] != framework::kEmptyVarName) {
ctx->ShareLoD(in_x, out_x_g_n, i, i);
}
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out")),
ctx.device_context());
}
};
class PartialSumOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "Input tensors of partial_sum operator.").AsDuplicable();
AddOutput("Out", "Output tensor of partial_sum operator.");
AddAttr<bool>(
"use_mkldnn",
"(bool, default false) Indicates if MKL-DNN kernel will be used")
.SetDefault(false);
AddAttr<int>("start_index", "The start index of tensor wanted to be added.")
.SetDefault(0);
AddAttr<int>("length", "The length of tensor wanted to be added.")
.SetDefault(-1);
AddComment(R"DOC(
PartialSum Operator.
This Op can sum the vars by specifying the initial position(start_index) and length(length).
This OP exists in contrib, which means that it is not shown to the public.
Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be
performed along the second dimension.
Examples:
Input[0] = [[1,2,3],[3,4,5]]
Input[1] = [[5,6,7],[7,8,9]]
start_index = 0
length = 2
Output = [[6,8],
[10,12]]
)DOC");
}
};
template <typename T>
class PartialSumGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("partial_sum_grad");
op->SetInput("X", this->Input("X"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X", false));
op->SetAttr("start_index", this->GetAttr("start_index"));
op->SetAttr("length", this->GetAttr("length"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(partial_sum, ops::PartialSumOp, ops::PartialSumOpMaker,
ops::PartialSumGradMaker<paddle::framework::OpDesc>,
ops::PartialSumGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(partial_sum_grad, ops::PartialSumGradOp);
REGISTER_OP_CPU_KERNEL(
partial_sum,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, float>,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, int>,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, double>,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, int64_t>);
REGISTER_OP_CPU_KERNEL(partial_sum_grad, ops::PartialSumGradientOpKernel<float>,
ops::PartialSumGradientOpKernel<int>,
ops::PartialSumGradientOpKernel<double>,
ops::PartialSumGradientOpKernel<int64_t>);
<commit_msg>add AsExtra to partial_sum op (#35381)<commit_after>/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/partial_sum_op.h"
#include <memory>
#include <string>
#include <vector>
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
class PartialSumOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE_GE(ctx->Inputs("X").size(), 1UL,
platform::errors::InvalidArgument(
"Inputs(X) of PartialSumOp should not be empty."));
PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
platform::errors::InvalidArgument(
"Output(Out) of PartialSumOp should not be null."));
auto inputs_dims = ctx->GetInputsDim("X");
const size_t inputs_num = inputs_dims.size();
PADDLE_ENFORCE_GT(inputs_num, 0,
platform::errors::InvalidArgument(
"ShapeError: Input tensors count should > 0. But "
"recevied inputs' length is 0."));
if (inputs_num == 1) {
VLOG(3) << "Warning: partial_sum op have only one input, may be useless";
}
int start_index = ctx->Attrs().Get<int>("start_index");
int length = ctx->Attrs().Get<int>("length");
// Only suppert two dimensions now, should be extended later
// when length is -1, need make sure all dimensions to be added are the same
int64_t batch_size = -1;
int64_t input_len = -1;
for (size_t i = 0; i < inputs_num; ++i) {
PADDLE_ENFORCE_EQ(inputs_dims[i].size(), 2,
platform::errors::InvalidArgument(
"Only suppert two dimensions input now."));
if (i == 0) {
batch_size = inputs_dims[0][0];
input_len = inputs_dims[0][1];
} else {
PADDLE_ENFORCE_EQ(inputs_dims[i][0], batch_size,
platform::errors::InvalidArgument(
"The batch size of all inputs must be same"));
PADDLE_ENFORCE_EQ(inputs_dims[i][1], input_len,
platform::errors::InvalidArgument(
"The input len of all inputs must be same"));
}
}
PADDLE_ENFORCE_GT(input_len, start_index,
platform::errors::OutOfRange(
"start_index must be less than input len"));
if (length > 0) {
PADDLE_ENFORCE_GE(
input_len, start_index + length,
platform::errors::OutOfRange(
"start_index + length is larger than input length"));
}
std::vector<int64_t> out_dims(2);
out_dims[0] = batch_size;
out_dims[1] = (length == -1) ? input_len - start_index : length;
ctx->SetOutputDim("Out", framework::make_ddim(out_dims));
ctx->ShareLoD("X", /*->*/ "Out");
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
auto inputs = ctx.MultiInput<Tensor>("X");
auto input_data_type = framework::proto::VarType::Type(0);
bool flag = 0;
for (auto *input : inputs) {
if (input->IsInitialized() && input->numel() > 0) {
input_data_type = input->type();
flag = 1;
break;
}
}
PADDLE_ENFORCE_EQ(flag, 1, platform::errors::InvalidArgument(
"All Inputs of PartialSum OP are Empty!"));
return framework::OpKernelType(input_data_type, platform::CPUPlace());
}
};
class PartialSumGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
auto in_x = "X";
auto out_x_g_n = framework::GradVarName(in_x);
ctx->SetOutputsDim(out_x_g_n, ctx->GetInputsDim(in_x));
auto in_names = ctx->Inputs(in_x);
auto out_names = ctx->Outputs(out_x_g_n);
PADDLE_ENFORCE_EQ(
in_names.size(), out_names.size(),
platform::errors::InvalidArgument(
"The number of arguments in %s[%d] and %s[%d] is not equal.", in_x,
in_names.size(), out_x_g_n, out_names.size()));
for (size_t i = 0; i < in_names.size(); ++i) {
if (out_names[i] != framework::kEmptyVarName) {
ctx->ShareLoD(in_x, out_x_g_n, i, i);
}
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out")),
ctx.device_context());
}
};
class PartialSumOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "Input tensors of partial_sum operator.").AsDuplicable();
AddOutput("Out", "Output tensor of partial_sum operator.");
AddAttr<bool>(
"use_mkldnn",
"(bool, default false) Indicates if MKL-DNN kernel will be used")
.SetDefault(false)
.AsExtra();
AddAttr<int>("start_index", "The start index of tensor wanted to be added.")
.SetDefault(0);
AddAttr<int>("length", "The length of tensor wanted to be added.")
.SetDefault(-1);
AddComment(R"DOC(
PartialSum Operator.
This Op can sum the vars by specifying the initial position(start_index) and length(length).
This OP exists in contrib, which means that it is not shown to the public.
Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be
performed along the second dimension.
Examples:
Input[0] = [[1,2,3],[3,4,5]]
Input[1] = [[5,6,7],[7,8,9]]
start_index = 0
length = 2
Output = [[6,8],
[10,12]]
)DOC");
}
};
template <typename T>
class PartialSumGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("partial_sum_grad");
op->SetInput("X", this->Input("X"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X", false));
op->SetAttr("start_index", this->GetAttr("start_index"));
op->SetAttr("length", this->GetAttr("length"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(partial_sum, ops::PartialSumOp, ops::PartialSumOpMaker,
ops::PartialSumGradMaker<paddle::framework::OpDesc>,
ops::PartialSumGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(partial_sum_grad, ops::PartialSumGradOp);
REGISTER_OP_CPU_KERNEL(
partial_sum,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, float>,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, int>,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, double>,
ops::PartialSumKernel<paddle::platform::CPUDeviceContext, int64_t>);
REGISTER_OP_CPU_KERNEL(partial_sum_grad, ops::PartialSumGradientOpKernel<float>,
ops::PartialSumGradientOpKernel<int>,
ops::PartialSumGradientOpKernel<double>,
ops::PartialSumGradientOpKernel<int64_t>);
<|endoftext|>
|
<commit_before>#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "parser.h"
static paramtype paramtypes[] =
{
{ "float", PARAM_FLOAT },
{ "float2", PARAM_FLOAT2 },
{ "float3", PARAM_FLOAT3 },
{ "float4", PARAM_FLOAT4 },
{ "float4x4", PARAM_FLOAT4x4 },
{ "sampler1D", PARAM_SAMPLER1D },
{ "sampler2D", PARAM_SAMPLER2D },
{ "sampler3D", PARAM_SAMPLER3D },
{ "samplerCUBE", PARAM_SAMPLERCUBE },
{ "samplerRECT", PARAM_SAMPLERRECT },
};
static const u32 PARAM_TYPE_CNT = sizeof(paramtypes)/sizeof(struct _paramtype);
CParser::CParser()
{
m_nOption = 0;
m_nInstructions = 0;
}
CParser::~CParser()
{
if(m_pInstructions) delete [] m_pInstructions;
}
void CParser::ParseComment(const char *line)
{
param p;
if(!line) return;
line++;
if(strncasecmp(line,"var",3)==0) {
char *token = SkipSpaces(strtok((char*)(line+3)," :"));
p.type = GetParamType(token);
p.is_const = 0;
p.is_internal = 0;
p.count = 1;
p.name = SkipSpaces(strtok(NULL," :"));
token = SkipSpaces(strtok(NULL," :"));
if(strstr(token,"$vin")) {
token = SkipSpaces(strtok(NULL," :"));
if(strncasecmp(token,"ATTR",4)==0)
p.index = atoi(token+4);
else
p.index = ConvertInputReg(token);
} else if(strstr(token,"texunit")) {
token = SkipSpaces(strtok(NULL," :"));
p.index = atoi(token);
} else if(token[0]=='c') {
p.is_const = 1;
p.index = atoi(token+2);
token = strtok(NULL," ,");
if(isdigit(*token)) p.count = atoi(token);
} else
return;
InitParameter(&p);
m_lParameters.push_back(p);
} else if(strncasecmp(line,"const",5)==0) {
char *token = SkipSpaces(strtok((char*)(line+5)," "));
p.is_const = 1;
p.is_internal = 1;
p.type = PARAM_FLOAT4;
p.count = 1;
InitParameter(&p);
if(token[0]=='c' && token[1]=='[') {
u32 i;
f32 *pVal = p.values[0];
p.index = atoi(token+2);
for(i=0;i<4;i++) {
token = strtok(NULL," =");
if(token)
pVal[i] = (f32)atof(token);
else
pVal[i] = 0.0f;
}
} else
return;
m_lParameters.push_back(p);
}
}
void CParser::InitParameter(param *p)
{
if(!p) return;
p->values = (f32(*)[4])calloc(p->count*4,sizeof(f32));
switch(p->type) {
case PARAM_FLOAT4x4:
p->values[0][0] = 1.0f;
p->values[1][1] = 1.0f;
p->values[2][2] = 1.0f;
p->values[3][3] = 1.0f;
break;
default:
break;
}
}
const char* CParser::ConvertCond(const char *token,struct nvfx_insn *insn)
{
if(strncasecmp(token,"FL",2)==0)
insn->cc_cond = NVFX_COND_FL;
else if(strncasecmp(token,"LT",2)==0)
insn->cc_cond = NVFX_COND_LT;
else if(strncasecmp(token,"EQ",2)==0)
insn->cc_cond = NVFX_COND_EQ;
else if(strncasecmp(token,"LE",2)==0)
insn->cc_cond = NVFX_COND_LE;
else if(strncasecmp(token,"GT",2)==0)
insn->cc_cond = NVFX_COND_GT;
else if(strncasecmp(token,"NE",2)==0)
insn->cc_cond = NVFX_COND_NE;
else if(strncasecmp(token,"GE",2)==0)
insn->cc_cond = NVFX_COND_GE;
else if(strncasecmp(token,"TR",2)==0)
insn->cc_cond = NVFX_COND_TR;
token += 2;
if(isdigit(*token)) {
insn->cc_test_reg = atoi(token);
token++;
}
insn->cc_test = 1;
return token;
}
void CParser::InitInstruction(struct nvfx_insn *insn,u8 op)
{
insn->op = op;
insn->scale = 0;
insn->unit = -1;
insn->precision = FLOAT32;
insn->mask = NVFX_VP_MASK_ALL;
insn->cc_swz[0] = 0; insn->cc_swz[1] = 1; insn->cc_swz[2] = 2; insn->cc_swz[3] = 3;
insn->sat = FALSE;
insn->cc_update = FALSE;
insn->cc_update_reg = 0;
insn->cc_cond = NVFX_COND_TR;
insn->cc_test = 0;
insn->cc_test_reg = 0;
insn->dst = nvfx_reg(NVFXSR_NONE,0);
insn->src[0] = nvfx_src(nvfx_reg(NVFXSR_NONE,0)); insn->src[1] = nvfx_src(nvfx_reg(NVFXSR_NONE,0)); insn->src[2] = nvfx_src(nvfx_reg(NVFXSR_NONE,0));
}
bool CParser::isLetter(int c)
{
return ((c>='a' && c<='z') || (c>='A' && c<='Z'));
}
bool CParser::isDigit(int c)
{
return (c>='0' && c<='9');
}
bool CParser::isWhitespace(int c)
{
return (c==' ' || c=='\t' || c=='\n' || c=='\r');
}
s32 CParser::GetParamType(const char *param_str)
{
u32 i;
for(i=0;i<PARAM_TYPE_CNT;i++) {
if(strcasecmp(param_str,paramtypes[i].ident)==0)
return (s32)paramtypes[i].type;
}
return -1;
}
const char* CParser::ParseTempReg(const char *token,s32 *reg)
{
const char *p;
if(token[0]!='R')
return NULL;
if(!isdigit(token[1]))
return token;
p = token + 1;
while(isdigit(*p)) p++;
*reg = atoi(token+1);
return p;
}
const char* CParser::ParseMaskedDstRegExt(const char *token,struct nvfx_insn *insn)
{
token = ParseOutputMask(token,&insn->mask);
if(token && *token!='\0') {
if(token[0]=='(') {
token = ParseCond(&token[1],insn);
token++;
}
}
return token;
}
const char* CParser::ParseCond(const char *token,struct nvfx_insn *insn)
{
token = ConvertCond(&token[1],insn);
if(token[0]=='.') {
s32 k = 0;
token++;
insn->cc_swz[0] = insn->cc_swz[1] = insn->cc_swz[2] = insn->cc_swz[3] = 0;
for(k=0;token[k] && token[k]!=')' && k<4;k++) {
if(token[k]=='x')
insn->cc_swz[k] = NVFX_SWZ_X;
else if(token[k]=='y')
insn->cc_swz[k] = NVFX_SWZ_Y;
else if(token[k]=='z')
insn->cc_swz[k] = NVFX_SWZ_Z;
else if(token[k]=='w')
insn->cc_swz[k] = NVFX_SWZ_W;
}
if(k && k<4) {
u8 lastswz = insn->cc_swz[k - 1];
while(k<4) {
insn->cc_swz[k] = lastswz;
k++;
}
}
token += k;
}
return token;
}
<commit_msg>copy-pasta error<commit_after>#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "parser.h"
static paramtype paramtypes[] =
{
{ "float", PARAM_FLOAT },
{ "float2", PARAM_FLOAT2 },
{ "float3", PARAM_FLOAT3 },
{ "float4", PARAM_FLOAT4 },
{ "float4x4", PARAM_FLOAT4x4 },
{ "sampler1D", PARAM_SAMPLER1D },
{ "sampler2D", PARAM_SAMPLER2D },
{ "sampler3D", PARAM_SAMPLER3D },
{ "samplerCUBE", PARAM_SAMPLERCUBE },
{ "samplerRECT", PARAM_SAMPLERRECT },
};
static const u32 PARAM_TYPE_CNT = sizeof(paramtypes)/sizeof(struct _paramtype);
CParser::CParser()
{
m_nOption = 0;
m_nInstructions = 0;
}
CParser::~CParser()
{
if(m_pInstructions) delete [] m_pInstructions;
}
void CParser::ParseComment(const char *line)
{
param p;
if(!line) return;
line++;
if(strncasecmp(line,"var",3)==0) {
char *token = SkipSpaces(strtok((char*)(line+3)," :"));
p.type = GetParamType(token);
p.is_const = 0;
p.is_internal = 0;
p.count = 1;
p.name = SkipSpaces(strtok(NULL," :"));
token = SkipSpaces(strtok(NULL," :"));
if(strstr(token,"$vin")) {
token = SkipSpaces(strtok(NULL," :"));
if(strncasecmp(token,"ATTR",4)==0)
p.index = atoi(token+4);
else
p.index = ConvertInputReg(token);
} else if(strstr(token,"texunit")) {
token = SkipSpaces(strtok(NULL," :"));
p.index = atoi(token);
} else if(token[0]=='c') {
p.is_const = 1;
p.index = atoi(token+2);
token = strtok(NULL," ,");
if(isdigit(*token)) p.count = atoi(token);
} else
return;
InitParameter(&p);
m_lParameters.push_back(p);
} else if(strncasecmp(line,"const",5)==0) {
char *token = SkipSpaces(strtok((char*)(line+5)," "));
p.is_const = 1;
p.is_internal = 1;
p.type = PARAM_FLOAT4;
p.count = 1;
InitParameter(&p);
if(token[0]=='c' && token[1]=='[') {
u32 i;
f32 *pVal = p.values[0];
p.index = atoi(token+2);
for(i=0;i<4;i++) {
token = strtok(NULL," =");
if(token)
pVal[i] = (f32)atof(token);
else
pVal[i] = 0.0f;
}
} else
return;
m_lParameters.push_back(p);
}
}
void CParser::InitParameter(param *p)
{
if(!p) return;
p->values = (f32(*)[4])calloc(p->count*4,sizeof(f32));
switch(p->type) {
case PARAM_FLOAT4x4:
p->values[0][0] = 1.0f;
p->values[1][1] = 1.0f;
p->values[2][2] = 1.0f;
p->values[3][3] = 1.0f;
break;
default:
break;
}
}
const char* CParser::ConvertCond(const char *token,struct nvfx_insn *insn)
{
if(strncasecmp(token,"FL",2)==0)
insn->cc_cond = NVFX_COND_FL;
else if(strncasecmp(token,"LT",2)==0)
insn->cc_cond = NVFX_COND_LT;
else if(strncasecmp(token,"EQ",2)==0)
insn->cc_cond = NVFX_COND_EQ;
else if(strncasecmp(token,"LE",2)==0)
insn->cc_cond = NVFX_COND_LE;
else if(strncasecmp(token,"GT",2)==0)
insn->cc_cond = NVFX_COND_GT;
else if(strncasecmp(token,"NE",2)==0)
insn->cc_cond = NVFX_COND_NE;
else if(strncasecmp(token,"GE",2)==0)
insn->cc_cond = NVFX_COND_GE;
else if(strncasecmp(token,"TR",2)==0)
insn->cc_cond = NVFX_COND_TR;
token += 2;
if(isdigit(*token)) {
insn->cc_test_reg = atoi(token);
token++;
}
insn->cc_test = 1;
return token;
}
void CParser::InitInstruction(struct nvfx_insn *insn,u8 op)
{
insn->op = op;
insn->scale = 0;
insn->unit = -1;
insn->precision = FLOAT32;
insn->mask = NVFX_VP_MASK_ALL;
insn->cc_swz[0] = 0; insn->cc_swz[1] = 1; insn->cc_swz[2] = 2; insn->cc_swz[3] = 3;
insn->sat = FALSE;
insn->cc_update = FALSE;
insn->cc_update_reg = 0;
insn->cc_cond = NVFX_COND_TR;
insn->cc_test = 0;
insn->cc_test_reg = 0;
insn->dst = nvfx_reg(NVFXSR_NONE,0);
insn->src[0] = nvfx_src(nvfx_reg(NVFXSR_NONE,0)); insn->src[1] = nvfx_src(nvfx_reg(NVFXSR_NONE,0)); insn->src[2] = nvfx_src(nvfx_reg(NVFXSR_NONE,0));
}
bool CParser::isLetter(int c)
{
return ((c>='a' && c<='z') || (c>='A' && c<='Z'));
}
bool CParser::isDigit(int c)
{
return (c>='0' && c<='9');
}
bool CParser::isWhitespace(int c)
{
return (c==' ' || c=='\t' || c=='\n' || c=='\r');
}
s32 CParser::GetParamType(const char *param_str)
{
u32 i;
for(i=0;i<PARAM_TYPE_CNT;i++) {
if(strcasecmp(param_str,paramtypes[i].ident)==0)
return (s32)paramtypes[i].type;
}
return -1;
}
const char* CParser::ParseTempReg(const char *token,s32 *reg)
{
const char *p;
if(token[0]!='R')
return NULL;
if(!isdigit(token[1]))
return token;
p = token + 1;
while(isdigit(*p)) p++;
*reg = atoi(token+1);
return p;
}
const char* CParser::ParseMaskedDstRegExt(const char *token,struct nvfx_insn *insn)
{
token = ParseOutputMask(token,&insn->mask);
if(token && *token!='\0') {
if(token[0]=='(') {
token = ParseCond(&token[1],insn);
token++;
}
}
return token;
}
const char* CParser::ParseCond(const char *token,struct nvfx_insn *insn)
{
token = ConvertCond(token,insn);
if(token[0]=='.') {
s32 k = 0;
token++;
insn->cc_swz[0] = insn->cc_swz[1] = insn->cc_swz[2] = insn->cc_swz[3] = 0;
for(k=0;token[k] && token[k]!=')' && k<4;k++) {
if(token[k]=='x')
insn->cc_swz[k] = NVFX_SWZ_X;
else if(token[k]=='y')
insn->cc_swz[k] = NVFX_SWZ_Y;
else if(token[k]=='z')
insn->cc_swz[k] = NVFX_SWZ_Z;
else if(token[k]=='w')
insn->cc_swz[k] = NVFX_SWZ_W;
}
if(k && k<4) {
u8 lastswz = insn->cc_swz[k - 1];
while(k<4) {
insn->cc_swz[k] = lastswz;
k++;
}
}
token += k;
}
return token;
}
<|endoftext|>
|
<commit_before>#include <Arduino.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ESP8266HTTPClient.h>
#include <LinkedList.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <BH1750.h>
#define ONE_WIRE_BUS D4
#define SDA D2
#define SCL D1
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
BH1750 lightMeter;
HTTPClient http;
struct measurement {
float temperature;
uint16_t light;
};
LinkedList<struct measurement> measurements;
int counter = 0;
void setup() {
Serial.begin(115200);
Wire.begin(SDA, SCL); // actually pretty important
sensors.begin();
lightMeter.begin();
WiFiManager wifiManager;
wifiManager.autoConnect("Wemos D1 mini");
}
bool sendMeasurementsToApi() {
StaticJsonBuffer<1024> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& data = root.createNestedArray("measurements");
for (int i = 0; i < measurements.size(); i++) {
JsonObject& nestedObject = data.createNestedObject();
struct measurement m = measurements.get(i);
nestedObject["temperature"] = m.temperature;
nestedObject["light"] = m.light;
}
char buffer[256];
root.printTo(buffer, sizeof(buffer));
int len = root.measureLength();
Serial.print("Buffer is ");
Serial.println(buffer);
http.begin("http://imegumii.space:3000/api/measurement"); //HTTP
http.addHeader("Content-Type", "application/json", true, true);
int httpCode = http.POST(buffer);
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
http.end();
return true;
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
return false;
}
void printMeasurement(struct measurement m, int i) {
Serial.print("Measured: ");
Serial.print(i);
Serial.print(" - ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
}
void loop() {
unsigned long startTime = millis();
uint16_t light = lightMeter.readLightLevel();
sensors.requestTemperatures(); // Send the command to get temperatures
float temperature = sensors.getTempCByIndex(0);
struct measurement m = {temperature, light};
Serial.print("Measured the following: ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
if (m.light > 20000) {
// discard
m.light = 0;
}
measurements.add(m);
counter++;
if (counter >= 6) {
// Serial.print("Measurements contains ");
// Serial.println(measurements.size());
// for (int i = 0; i < measurements.size(); i++) {
// printMeasurement(measurements.get(i), i);
// }
sendMeasurementsToApi();
counter = 0;
measurements.clear();
}
unsigned long delta = millis() - startTime;
delay(5000 - delta);
}
<commit_msg>Changed port<commit_after>#include <Arduino.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ESP8266HTTPClient.h>
#include <LinkedList.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <BH1750.h>
#define ONE_WIRE_BUS D4
#define SDA D2
#define SCL D1
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
BH1750 lightMeter;
HTTPClient http;
struct measurement {
float temperature;
uint16_t light;
};
LinkedList<struct measurement> measurements;
int counter = 0;
void setup() {
Serial.begin(115200);
Wire.begin(SDA, SCL); // actually pretty important
sensors.begin();
lightMeter.begin();
WiFiManager wifiManager;
wifiManager.autoConnect("Wemos D1 mini");
}
bool sendMeasurementsToApi() {
StaticJsonBuffer<1024> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& data = root.createNestedArray("measurements");
for (int i = 0; i < measurements.size(); i++) {
JsonObject& nestedObject = data.createNestedObject();
struct measurement m = measurements.get(i);
nestedObject["temperature"] = m.temperature;
nestedObject["light"] = m.light;
}
char buffer[256];
root.printTo(buffer, sizeof(buffer));
int len = root.measureLength();
Serial.print("Buffer is ");
Serial.println(buffer);
http.begin("http://imegumii.space:3030/api/measurement"); //HTTP
http.addHeader("Content-Type", "application/json", true, true);
int httpCode = http.POST(buffer);
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
http.end();
return true;
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
return false;
}
void printMeasurement(struct measurement m, int i) {
Serial.print("Measured: ");
Serial.print(i);
Serial.print(" - ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
}
void loop() {
unsigned long startTime = millis();
uint16_t light = lightMeter.readLightLevel();
sensors.requestTemperatures(); // Send the command to get temperatures
float temperature = sensors.getTempCByIndex(0);
struct measurement m = {temperature, light};
Serial.print("Measured the following: ");
Serial.print(m.temperature);
Serial.print(" ");
Serial.println(m.light);
if (m.light > 20000) {
// discard
m.light = 0;
}
measurements.add(m);
counter++;
if (counter >= 6) {
// Serial.print("Measurements contains ");
// Serial.println(measurements.size());
// for (int i = 0; i < measurements.size(); i++) {
// printMeasurement(measurements.get(i), i);
// }
sendMeasurementsToApi();
counter = 0;
measurements.clear();
}
unsigned long delta = millis() - startTime;
delay(5000 - delta);
}
<|endoftext|>
|
<commit_before>/*
* cl++.cpp
*
* Created by eholk on 12/3/10.
*
*/
#include "cl++.h"
#include <iostream>
#include <sstream>
#include <cassert>
#include <stdlib.h>
#include <unistd.h>
extern cl::device_list g_devices;
using namespace std;
using namespace cl;
// in builtin.cpp
uint64_t nanotime();
std::string device::name()
{
char n[256];
clGetDeviceInfo(id, CL_DEVICE_NAME, sizeof(n), n, NULL);
return std::string(n);
}
cl_device_type device::type()
{
cl_device_type t;
clGetDeviceInfo(id, CL_DEVICE_TYPE, sizeof(t), &t, NULL);
return t;
}
device::operator cl_device_id() const
{
return id;
}
device_list::device_list(cl_device_type type)
: type(type), num_ids(0), devices(NULL)
{
cl_int status = 0;
// Find the platforms.
cl_platform_id *platforms;
cl_uint nPlatforms = 0;
CL_CHECK(clGetPlatformIDs(0, NULL, &nPlatforms));
assert(nPlatforms > 0);
platforms = new cl_platform_id[nPlatforms];
CL_CHECK(clGetPlatformIDs(nPlatforms, platforms, &nPlatforms));
// Find out how many devices there are.
cl_uint n_dev = 0;
for(int i = 0; i < nPlatforms; ++i) {
status = clGetDeviceIDs(platforms[i], type, CL_UINT_MAX, NULL, &n_dev);
if(CL_DEVICE_NOT_FOUND == status)
continue;
CL_CHECK(status);
num_ids += n_dev;
break;
}
// Allocate memory, gather information about all the devices.
devices = new cl_device_id[num_ids];
size_t offset = 0;
for(int i = 0; i < nPlatforms; ++i) {
status = clGetDeviceIDs(platforms[i], type, CL_UINT_MAX,
devices + offset, &n_dev);
if(CL_DEVICE_NOT_FOUND == status)
continue;
CL_CHECK(status);
offset += n_dev;
}
cerr << "found " << num_ids << " devices" << endl;
delete [] platforms;
}
device_list::~device_list()
{
if(devices)
delete [] devices;
}
int device_list::count() const
{
return num_ids;
}
const cl_device_id *device_list::ids() const
{
return devices;
}
device device_list::operator[](int index)
{
assert(index < count());
return device(devices[index]);
}
context::context(device_list &devices)
{
cl_int status;
ctx = clCreateContext(0, devices.count(), devices.ids(),
sLogError, this, &status);
CL_CHECK(status);
}
context::~context()
{
clReleaseContext(ctx);
}
void context::sLogError(const char *errinfo,
const void *private_info,
size_t private_info_sz,
void *pThis)
{
((context*)pThis)->logError(errinfo, private_info, private_info_sz);
}
void context::logError(const char *errinfo,
const void *private_info,
size_t private_info_sz)
{
cerr << "OpenCL Error: " << errinfo << endl;
}
kernel::kernel(cl_kernel k)
: k(k)
{
}
kernel::~kernel()
{
clReleaseKernel(k);
}
size_t kernel::maxWorkGroupSize(cl_device_id device)
{
size_t result;
size_t ret_size;
clGetKernelWorkGroupInfo(k,
device,
CL_KERNEL_WORK_GROUP_SIZE,
sizeof(result),
&result,
&ret_size);
return result;
}
program::program(cl_program prog)
: prog(prog)
{
}
program::~program()
{
clReleaseProgram(prog);
}
string escape_path(const char *s) {
string e = "";
while(*s != '\0') {
if(*s == ' ') {
e += "\\ ";
}
else {
e += *s;
}
++s;
}
return e;
}
void program::build()
// TODO: make a variant that can compile for certain devices.
{
char *cwd = ::getcwd(NULL, 0);
string opts = "-I";
opts += escape_path(cwd);
opts += " -I/Users/eric/class/osl/dpp/svn/user/webyrd/harlan";
// opts += " -Werror";
free(cwd);
cl_int status = clBuildProgram(prog, 0, NULL, opts.c_str(), NULL, NULL);
if(status != CL_SUCCESS) {
char log[8192];
CL_CHECK(clGetProgramBuildInfo(prog,
g_devices[0],
CL_PROGRAM_BUILD_LOG,
sizeof(log),
log,
NULL));
std::cerr << log << std::endl;
}
CL_CHECK(status);
}
kernel program::createKernel(string name)
{
return kernel(clCreateKernel(prog, name.c_str(), NULL));
}
command_queue::command_queue(cl_command_queue queue)
: queue(queue), kernel_time(0)
{
}
command_queue::command_queue(const command_queue &other)
: queue(other.queue), kernel_time(other.kernel_time)
{
clRetainCommandQueue(queue);
}
command_queue::~command_queue()
{
clReleaseCommandQueue(queue);
}
void command_queue::execute(kernel &k, size_t global_size)
{
executeND(k, 1, &global_size, NULL);
}
void command_queue::execute(kernel &k, size_t global_size, size_t local_size)
{
executeND(k, 1, &global_size, &local_size);
}
void command_queue::execute2d(kernel &k, size_t dim1, size_t dim2, size_t local_size)
{
size_t global_size[] = {dim1, dim2};
size_t local_size_array[] = {local_size, local_size};
executeND(k, 2, global_size, local_size_array);
}
void command_queue::executeND(kernel &k, size_t dimensions,
size_t global_size[], size_t local_size[])
{
//cout << "Enqueuing " << dimensions << "-D kernel: (" << global_size[0];
//for(int i = 1; i < dimensions; ++i)
// cout << ", " << global_size[i];
//cout << ")" << endl;
// If any dimensions are 0, don't do anything. This may not be the
// best behavior, because it usually means something else went
// wrong in the calling program.
for(int i = 0; i < dimensions; ++i)
if(0 == global_size[i])
return;
cl_event e;
uint64_t start = nanotime();
CL_CHECK(clEnqueueNDRangeKernel(queue, k.k, dimensions, NULL,
global_size, local_size, 0, 0, &e));
//CL_CHECK(clEnqueueBarrier(queue));
CL_CHECK(clWaitForEvents(1, &e));
uint64_t stop = nanotime();
CL_CHECK(clReleaseEvent(e));
//fprintf(stderr, "Kernel took %f seconds\n",
// float(stop - start) / 1e9);
kernel_time += (stop - start);
}
program context::createProgramFromSourceFile(string filename)
{
ifstream input(filename.c_str());
return createProgramFromSourceFile(input);
}
program context::createProgramFromSourceFile(ifstream &input)
{
string src, line;
while(getline(input, line)) {
src += line;
src += "\n";
}
return createProgramFromSource(src);
}
program context::createProgramFromSource(string src)
{
const char *c_src = src.c_str();
cl_int status;
cl_program p = clCreateProgramWithSource(ctx, 1, &c_src, NULL, &status);
CL_CHECK(status);
return program(p);
}
program context::createAndBuildProgramFromSource(string src)
{
program p = createProgramFromSource(src);
p.build();
return p;
}
command_queue context::createCommandQueue(cl_device_id dev)
{
cl_int status;
cerr << "Creating queue for " << device(dev).name() << endl;
cl_command_queue q = clCreateCommandQueue(ctx,
dev,
0, // properties
&status);
CL_CHECK(status);
return command_queue(q);
}
string cl::format_status(cl_int e) {
#define STATUS_STR(x) case x: return #x;
switch(e) {
STATUS_STR(CL_SUCCESS);
STATUS_STR(CL_BUILD_PROGRAM_FAILURE);
STATUS_STR(CL_COMPILER_NOT_AVAILABLE);
STATUS_STR(CL_DEVICE_NOT_FOUND);
STATUS_STR(CL_INVALID_BINARY);
STATUS_STR(CL_INVALID_BUILD_OPTIONS);
STATUS_STR(CL_INVALID_COMMAND_QUEUE);
STATUS_STR(CL_INVALID_CONTEXT);
STATUS_STR(CL_INVALID_DEVICE);
STATUS_STR(CL_INVALID_DEVICE_TYPE);
STATUS_STR(CL_INVALID_EVENT_WAIT_LIST);
STATUS_STR(CL_INVALID_GLOBAL_OFFSET);
STATUS_STR(CL_INVALID_IMAGE_SIZE);
STATUS_STR(CL_INVALID_MEM_OBJECT);
STATUS_STR(CL_INVALID_KERNEL);
STATUS_STR(CL_INVALID_KERNEL_ARGS);
STATUS_STR(CL_INVALID_OPERATION);
STATUS_STR(CL_INVALID_PLATFORM);
STATUS_STR(CL_INVALID_PROGRAM);
STATUS_STR(CL_INVALID_PROGRAM_EXECUTABLE);
STATUS_STR(CL_INVALID_QUEUE_PROPERTIES);
STATUS_STR(CL_INVALID_VALUE);
STATUS_STR(CL_INVALID_WORK_DIMENSION);
STATUS_STR(CL_INVALID_WORK_GROUP_SIZE);
STATUS_STR(CL_INVALID_WORK_ITEM_SIZE);
STATUS_STR(CL_MEM_OBJECT_ALLOCATION_FAILURE);
STATUS_STR(CL_OUT_OF_RESOURCES);
STATUS_STR(CL_OUT_OF_HOST_MEMORY);
default:
stringstream s;
s << e;
return s.str();
}
}
void cl::handle_error(const char *code, cl_int e)
{
#define HANDLE(x) \
if(e == x) { \
cerr << code << " failed with error " \
<< format_status(e) << " (" << e << ")" << endl; \
abort(); \
}
HANDLE(CL_BUILD_PROGRAM_FAILURE);
HANDLE(CL_COMPILER_NOT_AVAILABLE);
HANDLE(CL_DEVICE_NOT_FOUND);
HANDLE(CL_INVALID_BINARY);
HANDLE(CL_INVALID_BUILD_OPTIONS);
HANDLE(CL_INVALID_COMMAND_QUEUE);
HANDLE(CL_INVALID_CONTEXT);
HANDLE(CL_INVALID_DEVICE);
HANDLE(CL_INVALID_DEVICE_TYPE);
HANDLE(CL_INVALID_EVENT_WAIT_LIST);
HANDLE(CL_INVALID_GLOBAL_OFFSET);
HANDLE(CL_INVALID_GLOBAL_WORK_SIZE);
HANDLE(CL_INVALID_IMAGE_SIZE);
HANDLE(CL_INVALID_MEM_OBJECT);
HANDLE(CL_INVALID_KERNEL);
HANDLE(CL_INVALID_KERNEL_ARGS);
HANDLE(CL_INVALID_OPERATION);
HANDLE(CL_INVALID_PLATFORM);
HANDLE(CL_INVALID_PROGRAM);
HANDLE(CL_INVALID_PROGRAM_EXECUTABLE);
HANDLE(CL_INVALID_QUEUE_PROPERTIES);
HANDLE(CL_INVALID_VALUE);
HANDLE(CL_INVALID_WORK_DIMENSION);
HANDLE(CL_INVALID_WORK_GROUP_SIZE);
HANDLE(CL_INVALID_WORK_ITEM_SIZE);
HANDLE(CL_MEM_OBJECT_ALLOCATION_FAILURE);
//HANDLE(CL_MISALIGNED_SUB_BUFFER_OFFSET);
HANDLE(CL_OUT_OF_RESOURCES);
HANDLE(CL_OUT_OF_HOST_MEMORY);
cerr << code << " failed with unknown error (" << e << ")" << endl;
abort();
}
<commit_msg>Cleaned up the error formatting code, added support for another error handler.<commit_after>/*
* cl++.cpp
*
* Created by eholk on 12/3/10.
*
*/
#include "cl++.h"
#include <iostream>
#include <sstream>
#include <cassert>
#include <stdlib.h>
#include <unistd.h>
extern cl::device_list g_devices;
using namespace std;
using namespace cl;
// in builtin.cpp
uint64_t nanotime();
std::string device::name()
{
char n[256];
clGetDeviceInfo(id, CL_DEVICE_NAME, sizeof(n), n, NULL);
return std::string(n);
}
cl_device_type device::type()
{
cl_device_type t;
clGetDeviceInfo(id, CL_DEVICE_TYPE, sizeof(t), &t, NULL);
return t;
}
device::operator cl_device_id() const
{
return id;
}
device_list::device_list(cl_device_type type)
: type(type), num_ids(0), devices(NULL)
{
cl_int status = 0;
// Find the platforms.
cl_platform_id *platforms;
cl_uint nPlatforms = 0;
CL_CHECK(clGetPlatformIDs(0, NULL, &nPlatforms));
assert(nPlatforms > 0);
platforms = new cl_platform_id[nPlatforms];
CL_CHECK(clGetPlatformIDs(nPlatforms, platforms, &nPlatforms));
// Find out how many devices there are.
cl_uint n_dev = 0;
for(int i = 0; i < nPlatforms; ++i) {
status = clGetDeviceIDs(platforms[i], type, CL_UINT_MAX, NULL, &n_dev);
if(CL_DEVICE_NOT_FOUND == status)
continue;
CL_CHECK(status);
num_ids += n_dev;
break;
}
// Allocate memory, gather information about all the devices.
devices = new cl_device_id[num_ids];
size_t offset = 0;
for(int i = 0; i < nPlatforms; ++i) {
status = clGetDeviceIDs(platforms[i], type, CL_UINT_MAX,
devices + offset, &n_dev);
if(CL_DEVICE_NOT_FOUND == status)
continue;
CL_CHECK(status);
offset += n_dev;
}
cerr << "found " << num_ids << " devices" << endl;
delete [] platforms;
}
device_list::~device_list()
{
if(devices)
delete [] devices;
}
int device_list::count() const
{
return num_ids;
}
const cl_device_id *device_list::ids() const
{
return devices;
}
device device_list::operator[](int index)
{
assert(index < count());
return device(devices[index]);
}
context::context(device_list &devices)
{
cl_int status;
ctx = clCreateContext(0, devices.count(), devices.ids(),
sLogError, this, &status);
CL_CHECK(status);
}
context::~context()
{
clReleaseContext(ctx);
}
void context::sLogError(const char *errinfo,
const void *private_info,
size_t private_info_sz,
void *pThis)
{
((context*)pThis)->logError(errinfo, private_info, private_info_sz);
}
void context::logError(const char *errinfo,
const void *private_info,
size_t private_info_sz)
{
cerr << "OpenCL Error: " << errinfo << endl;
}
kernel::kernel(cl_kernel k)
: k(k)
{
}
kernel::~kernel()
{
clReleaseKernel(k);
}
size_t kernel::maxWorkGroupSize(cl_device_id device)
{
size_t result;
size_t ret_size;
clGetKernelWorkGroupInfo(k,
device,
CL_KERNEL_WORK_GROUP_SIZE,
sizeof(result),
&result,
&ret_size);
return result;
}
program::program(cl_program prog)
: prog(prog)
{
}
program::~program()
{
clReleaseProgram(prog);
}
string escape_path(const char *s) {
string e = "";
while(*s != '\0') {
if(*s == ' ') {
e += "\\ ";
}
else {
e += *s;
}
++s;
}
return e;
}
void program::build()
// TODO: make a variant that can compile for certain devices.
{
char *cwd = ::getcwd(NULL, 0);
string opts = "-I";
opts += escape_path(cwd);
opts += " -I/Users/eric/class/osl/dpp/svn/user/webyrd/harlan";
// opts += " -Werror";
free(cwd);
cl_int status = clBuildProgram(prog, 0, NULL, opts.c_str(), NULL, NULL);
if(status != CL_SUCCESS) {
char log[8192];
CL_CHECK(clGetProgramBuildInfo(prog,
g_devices[0],
CL_PROGRAM_BUILD_LOG,
sizeof(log),
log,
NULL));
std::cerr << log << std::endl;
}
CL_CHECK(status);
}
kernel program::createKernel(string name)
{
return kernel(clCreateKernel(prog, name.c_str(), NULL));
}
command_queue::command_queue(cl_command_queue queue)
: queue(queue), kernel_time(0)
{
}
command_queue::command_queue(const command_queue &other)
: queue(other.queue), kernel_time(other.kernel_time)
{
clRetainCommandQueue(queue);
}
command_queue::~command_queue()
{
clReleaseCommandQueue(queue);
}
void command_queue::execute(kernel &k, size_t global_size)
{
executeND(k, 1, &global_size, NULL);
}
void command_queue::execute(kernel &k, size_t global_size, size_t local_size)
{
executeND(k, 1, &global_size, &local_size);
}
void command_queue::execute2d(kernel &k, size_t dim1, size_t dim2, size_t local_size)
{
size_t global_size[] = {dim1, dim2};
size_t local_size_array[] = {local_size, local_size};
executeND(k, 2, global_size, local_size_array);
}
void command_queue::executeND(kernel &k, size_t dimensions,
size_t global_size[], size_t local_size[])
{
//cout << "Enqueuing " << dimensions << "-D kernel: (" << global_size[0];
//for(int i = 1; i < dimensions; ++i)
// cout << ", " << global_size[i];
//cout << ")" << endl;
// If any dimensions are 0, don't do anything. This may not be the
// best behavior, because it usually means something else went
// wrong in the calling program.
for(int i = 0; i < dimensions; ++i)
if(0 == global_size[i])
return;
cl_event e;
uint64_t start = nanotime();
CL_CHECK(clEnqueueNDRangeKernel(queue, k.k, dimensions, NULL,
global_size, local_size, 0, 0, &e));
//CL_CHECK(clEnqueueBarrier(queue));
CL_CHECK(clWaitForEvents(1, &e));
uint64_t stop = nanotime();
CL_CHECK(clReleaseEvent(e));
//fprintf(stderr, "Kernel took %f seconds\n",
// float(stop - start) / 1e9);
kernel_time += (stop - start);
}
program context::createProgramFromSourceFile(string filename)
{
ifstream input(filename.c_str());
return createProgramFromSourceFile(input);
}
program context::createProgramFromSourceFile(ifstream &input)
{
string src, line;
while(getline(input, line)) {
src += line;
src += "\n";
}
return createProgramFromSource(src);
}
program context::createProgramFromSource(string src)
{
const char *c_src = src.c_str();
cl_int status;
cl_program p = clCreateProgramWithSource(ctx, 1, &c_src, NULL, &status);
CL_CHECK(status);
return program(p);
}
program context::createAndBuildProgramFromSource(string src)
{
program p = createProgramFromSource(src);
p.build();
return p;
}
command_queue context::createCommandQueue(cl_device_id dev)
{
cl_int status;
cerr << "Creating queue for " << device(dev).name() << endl;
cl_command_queue q = clCreateCommandQueue(ctx,
dev,
0, // properties
&status);
CL_CHECK(status);
return command_queue(q);
}
string cl::format_status(cl_int e) {
#define STATUS_STR(x) case x: return #x;
switch(e) {
STATUS_STR(CL_SUCCESS);
STATUS_STR(CL_BUILD_PROGRAM_FAILURE);
STATUS_STR(CL_COMPILER_NOT_AVAILABLE);
STATUS_STR(CL_DEVICE_NOT_AVAILABLE);
STATUS_STR(CL_DEVICE_NOT_FOUND);
STATUS_STR(CL_INVALID_BINARY);
STATUS_STR(CL_INVALID_BUILD_OPTIONS);
STATUS_STR(CL_INVALID_COMMAND_QUEUE);
STATUS_STR(CL_INVALID_CONTEXT);
STATUS_STR(CL_INVALID_DEVICE);
STATUS_STR(CL_INVALID_DEVICE_TYPE);
STATUS_STR(CL_INVALID_EVENT_WAIT_LIST);
STATUS_STR(CL_INVALID_GLOBAL_OFFSET);
STATUS_STR(CL_INVALID_IMAGE_SIZE);
STATUS_STR(CL_INVALID_MEM_OBJECT);
STATUS_STR(CL_INVALID_KERNEL);
STATUS_STR(CL_INVALID_KERNEL_ARGS);
STATUS_STR(CL_INVALID_OPERATION);
STATUS_STR(CL_INVALID_PLATFORM);
STATUS_STR(CL_INVALID_PROGRAM);
STATUS_STR(CL_INVALID_PROGRAM_EXECUTABLE);
STATUS_STR(CL_INVALID_QUEUE_PROPERTIES);
STATUS_STR(CL_INVALID_VALUE);
STATUS_STR(CL_INVALID_WORK_DIMENSION);
STATUS_STR(CL_INVALID_WORK_GROUP_SIZE);
STATUS_STR(CL_INVALID_WORK_ITEM_SIZE);
STATUS_STR(CL_MEM_OBJECT_ALLOCATION_FAILURE);
STATUS_STR(CL_OUT_OF_RESOURCES);
STATUS_STR(CL_OUT_OF_HOST_MEMORY);
default:
stringstream s;
s << "Unknown";
return s.str();
}
}
void cl::handle_error(const char *code, cl_int e)
{
cerr << code << " failed with error "
<< format_status(e) << " (" << e << ")" << endl;
abort();
}
<|endoftext|>
|
<commit_before>#include "testing/testing.hpp"
#include "partners_api/booking_api.hpp"
#include "base/scope_guard.hpp"
namespace
{
UNIT_TEST(Booking_GetHotelAvailability)
{
string const kHotelId = "98251"; // Booking hotel id for testing.
string result;
TEST(booking::RawApi::GetHotelAvailability(kHotelId, "", result), ());
TEST(!result.empty(), ());
}
UNIT_TEST(Booking_GetExtendedInfo)
{
// Test hotel is not implemented yet.
// string result;
// TEST(booking::RawApi::GetExtendedInfo(kHotelId, "", result), ());
// TEST(!result.empty(), ());
}
UNIT_TEST(Booking_GetMinPrice)
{
booking::SetBookingUrlForTesting("http://localhost:34568/booking/min_price");
MY_SCOPE_GUARD(cleanup, []() { booking::SetBookingUrlForTesting(""); });
string const kHotelId = "0000000"; // Internal hotel id for testing.
booking::Api api;
{
string price;
string currency;
string hotelId;
api.GetMinPrice(kHotelId, "" /* default currency */,
[&hotelId, &price, ¤cy](string const & id, string const & val, string const & curr) {
hotelId = id;
price = val;
currency = curr;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(hotelId, kHotelId, ());
TEST(!price.empty(), ());
TEST(!currency.empty(), ());
TEST_EQUAL(currency, "USD", ());
}
{
string price;
string currency;
string hotelId;
api.GetMinPrice(kHotelId, "RUB", [&hotelId, &price, ¤cy](string const & id, string const & val, string const & curr)
{
hotelId = id;
price = val;
currency = curr;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(hotelId, kHotelId, ());
TEST(!price.empty(), ());
TEST(!currency.empty(), ());
TEST_EQUAL(currency, "RUB", ());
}
{
string price;
string currency;
string hotelId;
api.GetMinPrice(kHotelId, "ISK", [&hotelId, &price, ¤cy](string const & id, string const & val, string const & curr)
{
hotelId = id;
price = val;
currency = curr;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(hotelId, kHotelId, ());
TEST(!price.empty(), ());
TEST(!currency.empty(), ());
TEST_EQUAL(currency, "ISK", ());
}
}
UNIT_TEST(GetHotelInfo)
{
// Test hotel is not implemented yet.
// booking::Api api;
// booking::HotelInfo info;
// api.GetHotelInfo(kHotelId, "en", [&info](booking::HotelInfo const & i)
// {
// info = i;
// testing::StopEventLoop();
// });
// testing::RunEventLoop();
// TEST_EQUAL(info.m_hotelId, kHotelId, ());
// TEST(!info.m_description.empty(), ());
// TEST_EQUAL(info.m_photos.size(), 5, ());
// TEST_EQUAL(info.m_facilities.size(), 3, ());
// TEST_EQUAL(info.m_reviews.size(), 12, ());
}
}
<commit_msg>enable booking extended infoo tests<commit_after>#include "testing/testing.hpp"
#include "partners_api/booking_api.hpp"
#include "base/scope_guard.hpp"
namespace
{
UNIT_TEST(Booking_GetHotelAvailability)
{
string const kHotelId = "98251"; // Booking hotel id for testing.
string result;
TEST(booking::RawApi::GetHotelAvailability(kHotelId, "", result), ());
TEST(!result.empty(), ());
}
UNIT_TEST(Booking_GetExtendedInfo)
{
string const kHotelId = "0000000"; // Internal hotel id for testing.
string result;
TEST(booking::RawApi::GetExtendedInfo(kHotelId, "en", result), ());
TEST(!result.empty(), ());
}
UNIT_TEST(Booking_GetMinPrice)
{
booking::SetBookingUrlForTesting("http://localhost:34568/booking/min_price");
MY_SCOPE_GUARD(cleanup, []() { booking::SetBookingUrlForTesting(""); });
string const kHotelId = "0000000"; // Internal hotel id for testing.
booking::Api api;
{
string price;
string currency;
string hotelId;
api.GetMinPrice(kHotelId, "" /* default currency */,
[&hotelId, &price, ¤cy](string const & id, string const & val, string const & curr) {
hotelId = id;
price = val;
currency = curr;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(hotelId, kHotelId, ());
TEST(!price.empty(), ());
TEST(!currency.empty(), ());
TEST_EQUAL(currency, "USD", ());
}
{
string price;
string currency;
string hotelId;
api.GetMinPrice(kHotelId, "RUB", [&hotelId, &price, ¤cy](string const & id, string const & val, string const & curr)
{
hotelId = id;
price = val;
currency = curr;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(hotelId, kHotelId, ());
TEST(!price.empty(), ());
TEST(!currency.empty(), ());
TEST_EQUAL(currency, "RUB", ());
}
{
string price;
string currency;
string hotelId;
api.GetMinPrice(kHotelId, "ISK", [&hotelId, &price, ¤cy](string const & id, string const & val, string const & curr)
{
hotelId = id;
price = val;
currency = curr;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(hotelId, kHotelId, ());
TEST(!price.empty(), ());
TEST(!currency.empty(), ());
TEST_EQUAL(currency, "ISK", ());
}
}
UNIT_TEST(GetHotelInfo)
{
string const kHotelId = "0000000"; // Internal hotel id for testing.
booking::Api api;
booking::HotelInfo info;
api.GetHotelInfo(kHotelId, "en", [&info](booking::HotelInfo const & i)
{
info = i;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(info.m_hotelId, kHotelId, ());
TEST(!info.m_description.empty(), ());
TEST_EQUAL(info.m_photos.size(), 2, ());
TEST_EQUAL(info.m_facilities.size(), 7, ());
TEST_EQUAL(info.m_reviews.size(), 4, ());
}
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "begin_native.hpp"
#include <version.h>
#include <geode/CacheLoader.hpp>
#include <geode/CacheListener.hpp>
#include <geode/FixedPartitionResolver.hpp>
#include <geode/CacheWriter.hpp>
#include <geode/GeodeTypeIds.hpp>
#include <geode/Cache.hpp>
#include <CacheImpl.hpp>
#include <CacheXmlParser.hpp>
#include <DistributedSystemImpl.hpp>
#include "end_native.hpp"
#include "Cache.hpp"
#include "Serializable.hpp"
#include "DistributedSystem.hpp"
#include "SystemProperties.hpp"
#include "CacheFactory.hpp"
#include "CacheableDate.hpp"
#include "CacheableFileName.hpp"
#include "CacheableHashMap.hpp"
#include "CacheableHashSet.hpp"
#include "CacheableHashTable.hpp"
#include "CacheableIdentityHashMap.hpp"
#include "CacheableObjectArray.hpp"
#include "CacheableString.hpp"
#include "CacheableStringArray.hpp"
#include "CacheableUndefined.hpp"
#include "CacheableVector.hpp"
#include "CacheableArrayList.hpp"
#include "CacheableStack.hpp"
#include "CacheableObject.hpp"
#include "CacheableObjectXml.hpp"
#include "CacheableBuiltins.hpp"
#include "Log.hpp"
#include "Struct.hpp"
#include "impl/MemoryPressureHandler.hpp"
#include "impl/SafeConvert.hpp"
#include "impl/PdxType.hpp"
#include "impl/EnumInfo.hpp"
#include "impl/ManagedPersistenceManager.hpp"
// disable spurious warning
#pragma warning(disable:4091)
#include <msclr/lock.h>
#pragma warning(default:4091)
using namespace System;
using namespace Apache::Geode::Client;
namespace apache
{
namespace geode
{
namespace client
{
class ManagedCacheLoaderGeneric
: public CacheLoader
{
public:
static CacheLoader* create(const char* assemblyPath,
const char* factoryFunctionName);
};
class ManagedCacheListenerGeneric
: public CacheListener
{
public:
static CacheListener* create(const char* assemblyPath,
const char* factoryFunctionName);
};
class ManagedFixedPartitionResolverGeneric
: public FixedPartitionResolver
{
public:
static PartitionResolver* create(const char* assemblyPath,
const char* factoryFunctionName);
};
class ManagedCacheWriterGeneric
: public CacheWriter
{
public:
static CacheWriter* create(const char* assemblyPath,
const char* factoryFunctionName);
};
} // namespace client
} // namespace geode
} // namespace apache
namespace Apache
{
namespace Geode
{
namespace Client
{
namespace native = apache::geode::client;
DistributedSystem^ DistributedSystem::Connect(String^ name, Cache^ cache)
{
return DistributedSystem::Connect(name, nullptr, cache);
}
DistributedSystem^ DistributedSystem::Connect(String^ name, Properties<String^, String^>^ config, Cache ^ cache)
{
// TODO AppDomain should we be able to create a DS directly?
_GF_MG_EXCEPTION_TRY2
auto nativeDistributedSystem = native::DistributedSystem::create(marshal_as<std::string>(name),
config->GetNative());
nativeDistributedSystem.connect(cache->GetNative().get());
ManagedPostConnect(cache);
return gcnew DistributedSystem(std::unique_ptr<native::DistributedSystem>(
new native::DistributedSystem(std::move(nativeDistributedSystem))));
_GF_MG_EXCEPTION_CATCH_ALL2
}
void DistributedSystem::Disconnect(Cache^ cache)
{
_GF_MG_EXCEPTION_TRY2
TypeRegistry::UnregisterNativesGeneric(cache);
DistributedSystem::UnregisterBuiltinManagedTypes(cache);
m_nativeDistributedSystem->get()->disconnect();
GC::KeepAlive(m_nativeDistributedSystem);
_GF_MG_EXCEPTION_CATCH_ALL2
}
void DistributedSystem::AppDomainInstanceInitialization(Cache^ cache)
// TODO AppDomain move this.
{
_GF_MG_EXCEPTION_TRY2
// Register wrapper types for built-in types, this are still cpp wrapper
//byte
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableByte::Create),
native::GeodeTypeIds::CacheableByte, SByte::typeid);
//boolean
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableBoolean::Create),
native::GeodeTypeIds::CacheableBoolean, Boolean::typeid);
//wide char
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableCharacter::Create),
native::GeodeTypeIds::CacheableCharacter, Char::typeid);
//double
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableDouble::Create),
native::GeodeTypeIds::CacheableDouble, Double::typeid);
//ascii string
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableString::Create),
native::GeodeTypeIds::CacheableASCIIString, String::typeid);
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableFloat::Create),
native::GeodeTypeIds::CacheableFloat, float::typeid);
//int 16
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableInt16::Create),
native::GeodeTypeIds::CacheableInt16, Int16::typeid);
//int32
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableInt32::Create),
native::GeodeTypeIds::CacheableInt32, Int32::typeid);
//int64
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableInt64::Create),
native::GeodeTypeIds::CacheableInt64, Int64::typeid);
//Now onwards all will be wrap in managed cacheable key..
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableBytes,
gcnew TypeFactoryMethodGeneric(CacheableBytes::CreateDeserializable),
Type::GetType("System.Byte[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableDoubleArray,
gcnew TypeFactoryMethodGeneric(CacheableDoubleArray::CreateDeserializable),
Type::GetType("System.Double[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableFloatArray,
gcnew TypeFactoryMethodGeneric(CacheableFloatArray::CreateDeserializable),
Type::GetType("System.Single[]"));
//TODO:
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableHashSet,
gcnew TypeFactoryMethodGeneric(CacheableHashSet::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableLinkedHashSet,
gcnew TypeFactoryMethodGeneric(CacheableLinkedHashSet::CreateDeserializable),
nullptr);
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableInt16Array,
gcnew TypeFactoryMethodGeneric(CacheableInt16Array::CreateDeserializable),
Type::GetType("System.Int16[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableInt32Array,
gcnew TypeFactoryMethodGeneric(CacheableInt32Array::CreateDeserializable),
Type::GetType("System.Int32[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableInt64Array,
gcnew TypeFactoryMethodGeneric(CacheableInt64Array::CreateDeserializable),
Type::GetType("System.Int64[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::BooleanArray,
gcnew TypeFactoryMethodGeneric(BooleanArray::CreateDeserializable),
Type::GetType("System.Boolean[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CharArray,
gcnew TypeFactoryMethodGeneric(CharArray::CreateDeserializable),
Type::GetType("System.Char[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableStringArray,
gcnew TypeFactoryMethodGeneric(CacheableStringArray::CreateDeserializable),
Type::GetType("System.String[]"));
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::Struct,
gcnew TypeFactoryMethodGeneric(Struct::CreateDeserializable),
nullptr);
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::EnumInfo,
gcnew TypeFactoryMethodGeneric(Apache::Geode::Client::Internal::EnumInfo::CreateDeserializable),
nullptr);
// End register generic wrapper types for built-in types
//if (!native::DistributedSystem::isConnected())
//{
// Set the Generic ManagedCacheLoader/Listener/Writer factory functions.
native::CacheXmlParser::managedCacheLoaderFn =
native::ManagedCacheLoaderGeneric::create;
native::CacheXmlParser::managedCacheListenerFn =
native::ManagedCacheListenerGeneric::create;
native::CacheXmlParser::managedCacheWriterFn =
native::ManagedCacheWriterGeneric::create;
// Set the Generic ManagedPartitionResolver factory function
native::CacheXmlParser::managedPartitionResolverFn =
native::ManagedFixedPartitionResolverGeneric::create;
// Set the Generic ManagedPersistanceManager factory function
native::CacheXmlParser::managedPersistenceManagerFn =
native::ManagedPersistenceManagerGeneric::create;
//}
_GF_MG_EXCEPTION_CATCH_ALL2
}
void DistributedSystem::ManagedPostConnect(Cache^ cache)
{
// The registration into the native map should be after
// native connect since it can be invoked only once
// Register other built-in types
// End register other built-in types
// Register other built-in types for generics
//c# datatime
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableDate,
gcnew TypeFactoryMethodGeneric(CacheableDate::CreateDeserializable),
Type::GetType("System.DateTime"));
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableFileName,
gcnew TypeFactoryMethodGeneric(CacheableFileName::CreateDeserializable),
nullptr);
//for generic dictionary define its type in static constructor of Serializable.hpp
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableHashMap,
gcnew TypeFactoryMethodGeneric(CacheableHashMap::CreateDeserializable),
nullptr);
//c# hashtable
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableHashTable,
gcnew TypeFactoryMethodGeneric(CacheableHashTable::CreateDeserializable),
Type::GetType("System.Collections.Hashtable"));
//Need to keep public as no counterpart in c#
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableIdentityHashMap,
gcnew TypeFactoryMethodGeneric(
CacheableIdentityHashMap::CreateDeserializable),
nullptr);
//keep as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableUndefined,
gcnew TypeFactoryMethodGeneric(CacheableUndefined::CreateDeserializable),
nullptr);
//c# arraylist
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableVector,
gcnew TypeFactoryMethodGeneric(CacheableVector::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableObjectArray,
gcnew TypeFactoryMethodGeneric(
CacheableObjectArray::CreateDeserializable),
nullptr);
//Generic::List
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableArrayList,
gcnew TypeFactoryMethodGeneric(CacheableArrayList::CreateDeserializable),
nullptr);
//c# generic stack
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableStack,
gcnew TypeFactoryMethodGeneric(CacheableStack::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
GeodeClassIds::CacheableManagedObject - 0x80000000,
gcnew TypeFactoryMethodGeneric(CacheableObject::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
GeodeClassIds::CacheableManagedObjectXml - 0x80000000,
gcnew TypeFactoryMethodGeneric(CacheableObjectXml::CreateDeserializable),
nullptr);
// End register other built-in types
// Log the version of the C# layer being used
Log::Config(".NET layer assembly version: {0}({1})", System::Reflection::
Assembly::GetExecutingAssembly()->GetName()->Version->ToString(),
System::Reflection::Assembly::GetExecutingAssembly()->ImageRuntimeVersion);
Log::Config(".NET runtime version: {0} ", System::Environment::Version);
Log::Config(".NET AppDomain: {0} - {1}",
System::AppDomain::CurrentDomain->Id,
System::AppDomain::CurrentDomain->FriendlyName);
}
void DistributedSystem::UnregisterBuiltinManagedTypes(Cache^ cache)
{
_GF_MG_EXCEPTION_TRY2
TypeRegistry::UnregisterNativesGeneric(cache);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableDate);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableFileName);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableHashMap);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableHashTable);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableIdentityHashMap);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableVector);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableObjectArray);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableArrayList);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableStack);
cache->TypeRegistry->UnregisterTypeGeneric(
GeodeClassIds::CacheableManagedObject - 0x80000000);
cache->TypeRegistry->UnregisterTypeGeneric(
GeodeClassIds::CacheableManagedObjectXml - 0x80000000);
_GF_MG_EXCEPTION_CATCH_ALL2
}
Apache::Geode::Client::SystemProperties^ DistributedSystem::SystemProperties::get()
{
_GF_MG_EXCEPTION_TRY2
return Apache::Geode::Client::SystemProperties::Create(
&(m_nativeDistributedSystem->get()->getSystemProperties()));
_GF_MG_EXCEPTION_CATCH_ALL2
}
String^ DistributedSystem::Name::get()
{
try
{
return marshal_as<String^>(m_nativeDistributedSystem->get()->getName());
}
finally
{
GC::KeepAlive(m_nativeDistributedSystem);
}
}
void DistributedSystem::HandleMemoryPressure(System::Object^ state)
{
// TODO global - Need single memory pressue event running?
ACE_Time_Value dummy(1);
MemoryPressureHandler handler;
handler.handle_timeout(dummy, nullptr);
}
DistributedSystem^ DistributedSystem::Create(native::DistributedSystem* nativeptr)
{
auto instance = gcnew DistributedSystem(nativeptr);
return instance;
}
DistributedSystem::DistributedSystem(std::unique_ptr<native::DistributedSystem> nativeDistributedSystem)
{
m_nativeDistributedSystem = gcnew native_conditional_unique_ptr<native::DistributedSystem>(std::move(nativeDistributedSystem));
}
DistributedSystem::DistributedSystem(native::DistributedSystem* nativeDistributedSystem)
{
m_nativeDistributedSystem = gcnew native_conditional_unique_ptr<native::DistributedSystem>(nativeDistributedSystem);
}
DistributedSystem::~DistributedSystem()
{
m_memoryPressureHandler->Dispose(nullptr);
}
void DistributedSystem::registerCliCallback()
{
m_cliCallBackObj = gcnew CliCallbackDelegate();
auto nativeCallback =
gcnew cliCallback(m_cliCallBackObj,
&CliCallbackDelegate::Callback);
native::DistributedSystemImpl::registerCliCallback(System::Threading::Thread::GetDomainID(),
(void (*)(apache::geode::client::Cache &cache))System::Runtime::InteropServices::
Marshal::GetFunctionPointerForDelegate(
nativeCallback).ToPointer());
}
void DistributedSystem::unregisterCliCallback()
{
native::DistributedSystemImpl::unregisterCliCallback(System::Threading::Thread::GetDomainID());
}
} // namespace Client
} // namespace Geode
} // namespace Apache
<commit_msg>GEODE-4410: Fixes .NET compile with removed cache parameter.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "begin_native.hpp"
#include <version.h>
#include <geode/CacheLoader.hpp>
#include <geode/CacheListener.hpp>
#include <geode/FixedPartitionResolver.hpp>
#include <geode/CacheWriter.hpp>
#include <geode/GeodeTypeIds.hpp>
#include <geode/Cache.hpp>
#include <CacheImpl.hpp>
#include <CacheXmlParser.hpp>
#include <DistributedSystemImpl.hpp>
#include "end_native.hpp"
#include "Cache.hpp"
#include "Serializable.hpp"
#include "DistributedSystem.hpp"
#include "SystemProperties.hpp"
#include "CacheFactory.hpp"
#include "CacheableDate.hpp"
#include "CacheableFileName.hpp"
#include "CacheableHashMap.hpp"
#include "CacheableHashSet.hpp"
#include "CacheableHashTable.hpp"
#include "CacheableIdentityHashMap.hpp"
#include "CacheableObjectArray.hpp"
#include "CacheableString.hpp"
#include "CacheableStringArray.hpp"
#include "CacheableUndefined.hpp"
#include "CacheableVector.hpp"
#include "CacheableArrayList.hpp"
#include "CacheableStack.hpp"
#include "CacheableObject.hpp"
#include "CacheableObjectXml.hpp"
#include "CacheableBuiltins.hpp"
#include "Log.hpp"
#include "Struct.hpp"
#include "impl/MemoryPressureHandler.hpp"
#include "impl/SafeConvert.hpp"
#include "impl/PdxType.hpp"
#include "impl/EnumInfo.hpp"
#include "impl/ManagedPersistenceManager.hpp"
// disable spurious warning
#pragma warning(disable:4091)
#include <msclr/lock.h>
#pragma warning(default:4091)
using namespace System;
using namespace Apache::Geode::Client;
namespace apache
{
namespace geode
{
namespace client
{
class ManagedCacheLoaderGeneric
: public CacheLoader
{
public:
static CacheLoader* create(const char* assemblyPath,
const char* factoryFunctionName);
};
class ManagedCacheListenerGeneric
: public CacheListener
{
public:
static CacheListener* create(const char* assemblyPath,
const char* factoryFunctionName);
};
class ManagedFixedPartitionResolverGeneric
: public FixedPartitionResolver
{
public:
static PartitionResolver* create(const char* assemblyPath,
const char* factoryFunctionName);
};
class ManagedCacheWriterGeneric
: public CacheWriter
{
public:
static CacheWriter* create(const char* assemblyPath,
const char* factoryFunctionName);
};
} // namespace client
} // namespace geode
} // namespace apache
namespace Apache
{
namespace Geode
{
namespace Client
{
namespace native = apache::geode::client;
DistributedSystem^ DistributedSystem::Connect(String^ name, Cache^ cache)
{
return DistributedSystem::Connect(name, nullptr, cache);
}
DistributedSystem^ DistributedSystem::Connect(String^ name, Properties<String^, String^>^ config, Cache ^ cache)
{
// TODO AppDomain should we be able to create a DS directly?
_GF_MG_EXCEPTION_TRY2
auto nativeDistributedSystem = native::DistributedSystem::create(marshal_as<std::string>(name),
config->GetNative());
nativeDistributedSystem.connect();
ManagedPostConnect(cache);
return gcnew DistributedSystem(std::unique_ptr<native::DistributedSystem>(
new native::DistributedSystem(std::move(nativeDistributedSystem))));
_GF_MG_EXCEPTION_CATCH_ALL2
}
void DistributedSystem::Disconnect(Cache^ cache)
{
_GF_MG_EXCEPTION_TRY2
TypeRegistry::UnregisterNativesGeneric(cache);
DistributedSystem::UnregisterBuiltinManagedTypes(cache);
m_nativeDistributedSystem->get()->disconnect();
GC::KeepAlive(m_nativeDistributedSystem);
_GF_MG_EXCEPTION_CATCH_ALL2
}
void DistributedSystem::AppDomainInstanceInitialization(Cache^ cache)
// TODO AppDomain move this.
{
_GF_MG_EXCEPTION_TRY2
// Register wrapper types for built-in types, this are still cpp wrapper
//byte
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableByte::Create),
native::GeodeTypeIds::CacheableByte, SByte::typeid);
//boolean
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableBoolean::Create),
native::GeodeTypeIds::CacheableBoolean, Boolean::typeid);
//wide char
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableCharacter::Create),
native::GeodeTypeIds::CacheableCharacter, Char::typeid);
//double
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableDouble::Create),
native::GeodeTypeIds::CacheableDouble, Double::typeid);
//ascii string
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableString::Create),
native::GeodeTypeIds::CacheableASCIIString, String::typeid);
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableFloat::Create),
native::GeodeTypeIds::CacheableFloat, float::typeid);
//int 16
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableInt16::Create),
native::GeodeTypeIds::CacheableInt16, Int16::typeid);
//int32
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableInt32::Create),
native::GeodeTypeIds::CacheableInt32, Int32::typeid);
//int64
TypeRegistry::RegisterWrapperGeneric(
gcnew WrapperDelegateGeneric(CacheableInt64::Create),
native::GeodeTypeIds::CacheableInt64, Int64::typeid);
//Now onwards all will be wrap in managed cacheable key..
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableBytes,
gcnew TypeFactoryMethodGeneric(CacheableBytes::CreateDeserializable),
Type::GetType("System.Byte[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableDoubleArray,
gcnew TypeFactoryMethodGeneric(CacheableDoubleArray::CreateDeserializable),
Type::GetType("System.Double[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableFloatArray,
gcnew TypeFactoryMethodGeneric(CacheableFloatArray::CreateDeserializable),
Type::GetType("System.Single[]"));
//TODO:
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableHashSet,
gcnew TypeFactoryMethodGeneric(CacheableHashSet::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableLinkedHashSet,
gcnew TypeFactoryMethodGeneric(CacheableLinkedHashSet::CreateDeserializable),
nullptr);
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableInt16Array,
gcnew TypeFactoryMethodGeneric(CacheableInt16Array::CreateDeserializable),
Type::GetType("System.Int16[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableInt32Array,
gcnew TypeFactoryMethodGeneric(CacheableInt32Array::CreateDeserializable),
Type::GetType("System.Int32[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableInt64Array,
gcnew TypeFactoryMethodGeneric(CacheableInt64Array::CreateDeserializable),
Type::GetType("System.Int64[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::BooleanArray,
gcnew TypeFactoryMethodGeneric(BooleanArray::CreateDeserializable),
Type::GetType("System.Boolean[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CharArray,
gcnew TypeFactoryMethodGeneric(CharArray::CreateDeserializable),
Type::GetType("System.Char[]"));
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableStringArray,
gcnew TypeFactoryMethodGeneric(CacheableStringArray::CreateDeserializable),
Type::GetType("System.String[]"));
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::Struct,
gcnew TypeFactoryMethodGeneric(Struct::CreateDeserializable),
nullptr);
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::EnumInfo,
gcnew TypeFactoryMethodGeneric(Apache::Geode::Client::Internal::EnumInfo::CreateDeserializable),
nullptr);
// End register generic wrapper types for built-in types
//if (!native::DistributedSystem::isConnected())
//{
// Set the Generic ManagedCacheLoader/Listener/Writer factory functions.
native::CacheXmlParser::managedCacheLoaderFn =
native::ManagedCacheLoaderGeneric::create;
native::CacheXmlParser::managedCacheListenerFn =
native::ManagedCacheListenerGeneric::create;
native::CacheXmlParser::managedCacheWriterFn =
native::ManagedCacheWriterGeneric::create;
// Set the Generic ManagedPartitionResolver factory function
native::CacheXmlParser::managedPartitionResolverFn =
native::ManagedFixedPartitionResolverGeneric::create;
// Set the Generic ManagedPersistanceManager factory function
native::CacheXmlParser::managedPersistenceManagerFn =
native::ManagedPersistenceManagerGeneric::create;
//}
_GF_MG_EXCEPTION_CATCH_ALL2
}
void DistributedSystem::ManagedPostConnect(Cache^ cache)
{
// The registration into the native map should be after
// native connect since it can be invoked only once
// Register other built-in types
// End register other built-in types
// Register other built-in types for generics
//c# datatime
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableDate,
gcnew TypeFactoryMethodGeneric(CacheableDate::CreateDeserializable),
Type::GetType("System.DateTime"));
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableFileName,
gcnew TypeFactoryMethodGeneric(CacheableFileName::CreateDeserializable),
nullptr);
//for generic dictionary define its type in static constructor of Serializable.hpp
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableHashMap,
gcnew TypeFactoryMethodGeneric(CacheableHashMap::CreateDeserializable),
nullptr);
//c# hashtable
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableHashTable,
gcnew TypeFactoryMethodGeneric(CacheableHashTable::CreateDeserializable),
Type::GetType("System.Collections.Hashtable"));
//Need to keep public as no counterpart in c#
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableIdentityHashMap,
gcnew TypeFactoryMethodGeneric(
CacheableIdentityHashMap::CreateDeserializable),
nullptr);
//keep as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableUndefined,
gcnew TypeFactoryMethodGeneric(CacheableUndefined::CreateDeserializable),
nullptr);
//c# arraylist
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableVector,
gcnew TypeFactoryMethodGeneric(CacheableVector::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableObjectArray,
gcnew TypeFactoryMethodGeneric(
CacheableObjectArray::CreateDeserializable),
nullptr);
//Generic::List
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableArrayList,
gcnew TypeFactoryMethodGeneric(CacheableArrayList::CreateDeserializable),
nullptr);
//c# generic stack
cache->TypeRegistry->RegisterTypeGeneric(
native::GeodeTypeIds::CacheableStack,
gcnew TypeFactoryMethodGeneric(CacheableStack::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
GeodeClassIds::CacheableManagedObject - 0x80000000,
gcnew TypeFactoryMethodGeneric(CacheableObject::CreateDeserializable),
nullptr);
//as it is
cache->TypeRegistry->RegisterTypeGeneric(
GeodeClassIds::CacheableManagedObjectXml - 0x80000000,
gcnew TypeFactoryMethodGeneric(CacheableObjectXml::CreateDeserializable),
nullptr);
// End register other built-in types
// Log the version of the C# layer being used
Log::Config(".NET layer assembly version: {0}({1})", System::Reflection::
Assembly::GetExecutingAssembly()->GetName()->Version->ToString(),
System::Reflection::Assembly::GetExecutingAssembly()->ImageRuntimeVersion);
Log::Config(".NET runtime version: {0} ", System::Environment::Version);
Log::Config(".NET AppDomain: {0} - {1}",
System::AppDomain::CurrentDomain->Id,
System::AppDomain::CurrentDomain->FriendlyName);
}
void DistributedSystem::UnregisterBuiltinManagedTypes(Cache^ cache)
{
_GF_MG_EXCEPTION_TRY2
TypeRegistry::UnregisterNativesGeneric(cache);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableDate);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableFileName);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableHashMap);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableHashTable);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableIdentityHashMap);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableVector);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableObjectArray);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableArrayList);
cache->TypeRegistry->UnregisterTypeGeneric(
native::GeodeTypeIds::CacheableStack);
cache->TypeRegistry->UnregisterTypeGeneric(
GeodeClassIds::CacheableManagedObject - 0x80000000);
cache->TypeRegistry->UnregisterTypeGeneric(
GeodeClassIds::CacheableManagedObjectXml - 0x80000000);
_GF_MG_EXCEPTION_CATCH_ALL2
}
Apache::Geode::Client::SystemProperties^ DistributedSystem::SystemProperties::get()
{
_GF_MG_EXCEPTION_TRY2
return Apache::Geode::Client::SystemProperties::Create(
&(m_nativeDistributedSystem->get()->getSystemProperties()));
_GF_MG_EXCEPTION_CATCH_ALL2
}
String^ DistributedSystem::Name::get()
{
try
{
return marshal_as<String^>(m_nativeDistributedSystem->get()->getName());
}
finally
{
GC::KeepAlive(m_nativeDistributedSystem);
}
}
void DistributedSystem::HandleMemoryPressure(System::Object^ state)
{
// TODO global - Need single memory pressue event running?
ACE_Time_Value dummy(1);
MemoryPressureHandler handler;
handler.handle_timeout(dummy, nullptr);
}
DistributedSystem^ DistributedSystem::Create(native::DistributedSystem* nativeptr)
{
auto instance = gcnew DistributedSystem(nativeptr);
return instance;
}
DistributedSystem::DistributedSystem(std::unique_ptr<native::DistributedSystem> nativeDistributedSystem)
{
m_nativeDistributedSystem = gcnew native_conditional_unique_ptr<native::DistributedSystem>(std::move(nativeDistributedSystem));
}
DistributedSystem::DistributedSystem(native::DistributedSystem* nativeDistributedSystem)
{
m_nativeDistributedSystem = gcnew native_conditional_unique_ptr<native::DistributedSystem>(nativeDistributedSystem);
}
DistributedSystem::~DistributedSystem()
{
m_memoryPressureHandler->Dispose(nullptr);
}
void DistributedSystem::registerCliCallback()
{
m_cliCallBackObj = gcnew CliCallbackDelegate();
auto nativeCallback =
gcnew cliCallback(m_cliCallBackObj,
&CliCallbackDelegate::Callback);
native::DistributedSystemImpl::registerCliCallback(System::Threading::Thread::GetDomainID(),
(void (*)(apache::geode::client::Cache &cache))System::Runtime::InteropServices::
Marshal::GetFunctionPointerForDelegate(
nativeCallback).ToPointer());
}
void DistributedSystem::unregisterCliCallback()
{
native::DistributedSystemImpl::unregisterCliCallback(System::Threading::Thread::GetDomainID());
}
} // namespace Client
} // namespace Geode
} // namespace Apache
<|endoftext|>
|
<commit_before>#include "pb_utils.h"
#include <google/protobuf/descriptor.h>
#include <boost/foreach.hpp>
std::string pb2xml(const google::protobuf::Message* response){
std::stringstream buffer;
std::stringstream child_buffer;
const google::protobuf::Reflection* reflection = response->GetReflection();
const google::protobuf::Descriptor* descriptor = response->GetDescriptor();
std::vector<const google::protobuf::FieldDescriptor*> field_list;
reflection->ListFields(*response, &field_list);
buffer << "<" << descriptor->name() << " ";
BOOST_FOREACH(const google::protobuf::FieldDescriptor* field, field_list){
if(field->is_repeated()) {
child_buffer << "<" << field->name() << ">";
for(int i=0; i < reflection->FieldSize(*response, field); ++i){
child_buffer << pb2xml(&reflection->GetRepeatedMessage(*response, field, i));
}
child_buffer << "</" << field->name() << ">";
}
else if(reflection->HasField(*response, field)){
if(field->type() == google::protobuf::FieldDescriptor::TYPE_STRING){
buffer << field->name() << "=\"";
buffer << reflection->GetString(*response, field) << "\" ";
}else if(field->type() == google::protobuf::FieldDescriptor::TYPE_INT32){
buffer << field->name() << "=\"";
buffer << reflection->GetInt32(*response, field) << "\" ";
}else if(field->type() == google::protobuf::FieldDescriptor::TYPE_DOUBLE){
buffer << field->name() << "=\"";
buffer << reflection->GetDouble(*response, field) << "\" ";
}else if(field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE){
child_buffer << pb2xml(&reflection->GetMessage(*response, field));
}else {
buffer << field->name() << "=\"";
buffer << "type unkown\" ";
}
}
}
std::string child = child_buffer.str();
if(child.length() > 0){
buffer << ">" << child << "</" << descriptor->name() << ">";
}else{
buffer << "/>";
}
buffer << std::endl;
return buffer.str();
}
std::string pb2json(const google::protobuf::Message* response, int depth){
std::stringstream buffer;
if(depth == 1) buffer.width(5);
buffer << "{";
const google::protobuf::Reflection* reflection = response->GetReflection();
std::vector<const google::protobuf::FieldDescriptor*> field_list;
reflection->ListFields(*response, &field_list);
bool is_first = true;
BOOST_FOREACH(const google::protobuf::FieldDescriptor* field, field_list){
if(is_first){
is_first = false;
} else {
buffer << ", ";
}
if(depth == 1) buffer << "\n ";
if(field->is_repeated()) {
buffer << "\"" << field->name() << "\": [";
if(depth == 0) buffer << "\n";
for(int i=0; i < reflection->FieldSize(*response, field); ++i){
switch(field->type()) {
case google::protobuf::FieldDescriptor::TYPE_MESSAGE:
buffer << pb2json(&reflection->GetRepeatedMessage(*response, field, i), depth+1);
break;
case google::protobuf::FieldDescriptor::TYPE_INT32:
buffer << reflection->GetRepeatedInt32(*response, field, i);
break;
default:
buffer << "other" ;
}
if(i+1 < reflection->FieldSize(*response, field)){
buffer << ", ";
if(depth == 0) buffer << "\n";
}
}
if(depth == 0) buffer << "\n";
buffer << "]";
}
else if(reflection->HasField(*response, field)){
buffer << "\"" <<field->name() << "\": ";
switch(field->type()) {
case google::protobuf::FieldDescriptor::TYPE_STRING:
buffer << "\"" << reflection->GetString(*response, field) << "\"";
break;
case google::protobuf::FieldDescriptor::TYPE_INT32:
buffer << reflection->GetInt32(*response, field);
break;
case google::protobuf::FieldDescriptor::TYPE_DOUBLE:
buffer << reflection->GetDouble(*response, field);
break;
case google::protobuf::FieldDescriptor::TYPE_MESSAGE:
buffer << pb2json(&reflection->GetMessage(*response, field), depth + 1);
break;
case google::protobuf::FieldDescriptor::TYPE_ENUM:
buffer << "\"" << reflection->GetEnum(*response, field)->name() << "\"";
break;
default:
buffer << "Other !, " ;
}
}
}
if(depth == 1) buffer << "\n }";
else buffer << "}";
return buffer.str();
}
std::unique_ptr<google::protobuf::Message> create_pb(const webservice::RequestData& request){
return create_pb(request.api);
}
std::unique_ptr<google::protobuf::Message> create_pb(const std::string &){
return std::unique_ptr<google::protobuf::Message>(new pbnavitia::Response());
}
<commit_msg>meilleurs mise en forme du json<commit_after>#include "pb_utils.h"
#include <google/protobuf/descriptor.h>
#include <boost/foreach.hpp>
std::string pb2xml(const google::protobuf::Message* response){
std::stringstream buffer;
std::stringstream child_buffer;
const google::protobuf::Reflection* reflection = response->GetReflection();
const google::protobuf::Descriptor* descriptor = response->GetDescriptor();
std::vector<const google::protobuf::FieldDescriptor*> field_list;
reflection->ListFields(*response, &field_list);
buffer << "<" << descriptor->name() << " ";
BOOST_FOREACH(const google::protobuf::FieldDescriptor* field, field_list){
if(field->is_repeated()) {
child_buffer << "<" << field->name() << ">";
for(int i=0; i < reflection->FieldSize(*response, field); ++i){
child_buffer << pb2xml(&reflection->GetRepeatedMessage(*response, field, i));
}
child_buffer << "</" << field->name() << ">";
}
else if(reflection->HasField(*response, field)){
if(field->type() == google::protobuf::FieldDescriptor::TYPE_STRING){
buffer << field->name() << "=\"";
buffer << reflection->GetString(*response, field) << "\" ";
}else if(field->type() == google::protobuf::FieldDescriptor::TYPE_INT32){
buffer << field->name() << "=\"";
buffer << reflection->GetInt32(*response, field) << "\" ";
}else if(field->type() == google::protobuf::FieldDescriptor::TYPE_DOUBLE){
buffer << field->name() << "=\"";
buffer << reflection->GetDouble(*response, field) << "\" ";
}else if(field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE){
child_buffer << pb2xml(&reflection->GetMessage(*response, field));
}else {
buffer << field->name() << "=\"";
buffer << "type unkown\" ";
}
}
}
std::string child = child_buffer.str();
if(child.length() > 0){
buffer << ">" << child << "</" << descriptor->name() << ">";
}else{
buffer << "/>";
}
buffer << std::endl;
return buffer.str();
}
void indent(std::stringstream& buffer, int depth){
for (int i = 0; i < depth; ++i) {
buffer << " ";
}
}
std::string pb2json(const google::protobuf::Message* response, int depth){
std::stringstream buffer;
buffer << "{";
const google::protobuf::Reflection* reflection = response->GetReflection();
std::vector<const google::protobuf::FieldDescriptor*> field_list;
reflection->ListFields(*response, &field_list);
bool is_first = true;
BOOST_FOREACH(const google::protobuf::FieldDescriptor* field, field_list){
if(is_first){
is_first = false;
} else {
buffer << ", ";
}
if(depth > 0){
buffer << "\n";
indent(buffer, depth);
}
if(field->is_repeated()) {
buffer << "\"" << field->name() << "\": [";
if(depth == 0) buffer << "\n";
for(int i=0; i < reflection->FieldSize(*response, field); ++i){
switch(field->type()) {
case google::protobuf::FieldDescriptor::TYPE_MESSAGE:
buffer << pb2json(&reflection->GetRepeatedMessage(*response, field, i), depth+1);
break;
case google::protobuf::FieldDescriptor::TYPE_INT32:
buffer << reflection->GetRepeatedInt32(*response, field, i);
break;
default:
buffer << "other" ;
}
if(i+1 < reflection->FieldSize(*response, field)){
buffer << ", ";
if(depth == 0) buffer << "\n";
}
}
if(depth == 0) buffer << "\n";
buffer << "]";
}
else if(reflection->HasField(*response, field)){
buffer << "\"" <<field->name() << "\": ";
switch(field->type()) {
case google::protobuf::FieldDescriptor::TYPE_STRING:
buffer << "\"" << reflection->GetString(*response, field) << "\"";
break;
case google::protobuf::FieldDescriptor::TYPE_INT32:
buffer << reflection->GetInt32(*response, field);
break;
case google::protobuf::FieldDescriptor::TYPE_DOUBLE:
buffer << reflection->GetDouble(*response, field);
break;
case google::protobuf::FieldDescriptor::TYPE_MESSAGE:
buffer << pb2json(&reflection->GetMessage(*response, field), depth + 1);
break;
case google::protobuf::FieldDescriptor::TYPE_ENUM:
buffer << "\"" << reflection->GetEnum(*response, field)->name() << "\"";
break;
default:
buffer << "Other !, " ;
}
}
}
if(depth > 0){
buffer << "\n";
indent(buffer, depth-1);
}
buffer << "}";
return buffer.str();
}
std::unique_ptr<google::protobuf::Message> create_pb(const webservice::RequestData& request){
return create_pb(request.api);
}
std::unique_ptr<google::protobuf::Message> create_pb(const std::string &){
return std::unique_ptr<google::protobuf::Message>(new pbnavitia::Response());
}
<|endoftext|>
|
<commit_before>//
// MIT License
//
// Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon
//
// 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 <iota/constants.hpp>
#include <iota/types/big_int.hpp>
namespace IOTA {
namespace Types {
BigInt::BigInt() : cpp_int(0) {
}
BigInt::BigInt(const int& value) : cpp_int(value) {
}
void
BigInt::fromTrits(const Types::Trits& trits) {
assign(0);
for (unsigned int i = 0; i < trits.size(); ++i) {
*this += trits[i] * boost::multiprecision::pow(cpp_int(3), i);
}
}
Types::Trits
BigInt::toTrits() const {
Types::Trits trits;
bool is_negative = *this < 0;
cpp_int quotient = boost::multiprecision::abs(*this);
// TODO why TritHashLength ?
for (unsigned int i = 0; i < TritHashLength; ++i) {
cpp_int remainder;
boost::multiprecision::divide_qr(quotient, cpp_int(3), quotient, remainder);
if (remainder > 1) {
quotient += 1;
remainder -= 3;
}
trits.push_back(static_cast<int8_t>(is_negative ? (-1) * remainder : remainder));
}
return trits;
}
void
BigInt::fromBytes(const std::vector<int8_t>& bytes) {
auto bytesCopy = bytes;
short sign = (bytesCopy[0] >= 0 ? 1 : -1);
if (sign == -1) {
for (int i = bytes.size() - 1; i >= 0; --i) {
int sub = (bytesCopy[i] & 0xFF) - 1;
bytesCopy[i] = (sub <= 0x7F ? sub : sub - 0x100);
if (bytesCopy[i] != -1)
break;
}
std::transform(bytesCopy.begin(), bytesCopy.end(), bytesCopy.begin(),
[](const int8_t& byte) { return ~byte; });
}
import_bits(*this, bytesCopy.begin(), bytesCopy.end(), 8, true);
*this *= sign;
}
std::vector<int8_t>
BigInt::toBytes() const {
std::vector<int8_t> exported_bytes;
export_bits(*this, std::back_inserter(exported_bytes), 8, true);
std::vector<int8_t> bytes(48 - exported_bytes.size(), 0);
bytes.insert(bytes.end(), std::make_move_iterator(exported_bytes.begin()),
std::make_move_iterator(exported_bytes.end()));
if (*this < 0) {
std::transform(bytes.begin(), bytes.end(), bytes.begin(),
[](const int8_t& byte) { return ~byte; });
for (int i = ByteHashLength - 1; i >= 0; --i) {
int add = (bytes[i] & 0xFF) + 1;
bytes[i] = (add <= 0x7F ? add : add - 0x100);
if (bytes[i] != 0)
break;
}
}
return bytes;
}
} // namespace Types
} // namespace IOTA
<commit_msg>improve performance of BigInt construction from Trits (#212)<commit_after>//
// MIT License
//
// Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon
//
// 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 <iota/constants.hpp>
#include <iota/types/big_int.hpp>
namespace IOTA {
namespace Types {
BigInt::BigInt() : cpp_int(0) {
}
BigInt::BigInt(const int& value) : cpp_int(value) {
}
void
BigInt::fromTrits(const Types::Trits& trits) {
assign(0);
cpp_int significance(1);
for (unsigned int i = 0; i < trits.size(); ++i) {
*this += trits[i] * significance;
significance *= 3;
}
}
Types::Trits
BigInt::toTrits() const {
Types::Trits trits;
bool is_negative = *this < 0;
cpp_int quotient = boost::multiprecision::abs(*this);
// TODO why TritHashLength ?
for (unsigned int i = 0; i < TritHashLength; ++i) {
cpp_int remainder;
boost::multiprecision::divide_qr(quotient, cpp_int(3), quotient, remainder);
if (remainder > 1) {
quotient += 1;
remainder -= 3;
}
trits.push_back(static_cast<int8_t>(is_negative ? (-1) * remainder : remainder));
}
return trits;
}
void
BigInt::fromBytes(const std::vector<int8_t>& bytes) {
auto bytesCopy = bytes;
short sign = (bytesCopy[0] >= 0 ? 1 : -1);
if (sign == -1) {
for (int i = bytes.size() - 1; i >= 0; --i) {
int sub = (bytesCopy[i] & 0xFF) - 1;
bytesCopy[i] = (sub <= 0x7F ? sub : sub - 0x100);
if (bytesCopy[i] != -1)
break;
}
std::transform(bytesCopy.begin(), bytesCopy.end(), bytesCopy.begin(),
[](const int8_t& byte) { return ~byte; });
}
import_bits(*this, bytesCopy.begin(), bytesCopy.end(), 8, true);
*this *= sign;
}
std::vector<int8_t>
BigInt::toBytes() const {
std::vector<int8_t> exported_bytes;
export_bits(*this, std::back_inserter(exported_bytes), 8, true);
std::vector<int8_t> bytes(48 - exported_bytes.size(), 0);
bytes.insert(bytes.end(), std::make_move_iterator(exported_bytes.begin()),
std::make_move_iterator(exported_bytes.end()));
if (*this < 0) {
std::transform(bytes.begin(), bytes.end(), bytes.begin(),
[](const int8_t& byte) { return ~byte; });
for (int i = ByteHashLength - 1; i >= 0; --i) {
int add = (bytes[i] & 0xFF) + 1;
bytes[i] = (add <= 0x7F ? add : add - 0x100);
if (bytes[i] != 0)
break;
}
}
return bytes;
}
} // namespace Types
} // namespace IOTA
<|endoftext|>
|
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include <iostream>
using namespace cv;
using namespace std;
void help(char** argv)
{
cout << "\nThis program demonstrats keypoint finding and matching between 2 images using features2d framework.\n"
<< " In one case, the 2nd image is synthesized by homography from the first, in the second case, there are 2 images\n"
<< "\n"
<< "Case1: second image is obtained from the first (given) image using random generated homography matrix\n"
<< argv[0] << " [detectorType] [descriptorType] [matcherType] [matcherFilterType] [image] [evaluate(0 or 1)]\n"
<< "Example of case1:\n"
<< "./descriptor_extractor_matcher SURF SURF FlannBased NoneFilter cola.jpg 0\n"
<< "\n"
<< "Case2: both images are given. If ransacReprojThreshold>=0 then homography matrix are calculated\n"
<< argv[0] << " [detectorType] [descriptorType] [matcherType] [matcherFilterType] [image1] [image2] [ransacReprojThreshold]\n"
<< "\n"
<< "Matches are filtered using homography matrix in case1 and case2 (if ransacReprojThreshold>=0)\n"
<< "Example of case2:\n"
<< "./descriptor_extractor_matcher SURF SURF BruteForce CrossCheckFilter cola1.jpg cola2.jpg 3\n"
<< "\n"
<< "Possible detectorType values: see in documentation on createFeatureDetector().\n"
<< "Possible descriptorType values: see in documentation on createDescriptorExtractor().\n"
<< "Possible matcherType values: see in documentation on createDescriptorMatcher().\n"
<< "Possible matcherFilterType values: NoneFilter, CrossCheckFilter." << endl;
}
#define DRAW_RICH_KEYPOINTS_MODE 0
#define DRAW_OUTLIERS_MODE 0
const string winName = "correspondences";
enum { NONE_FILTER = 0, CROSS_CHECK_FILTER = 1 };
int getMatcherFilterType( const string& str )
{
if( str == "NoneFilter" )
return NONE_FILTER;
if( str == "CrossCheckFilter" )
return CROSS_CHECK_FILTER;
CV_Error(CV_StsBadArg, "Invalid filter name");
return -1;
}
void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
vector<DMatch>& matches12 )
{
vector<DMatch> matches;
descriptorMatcher->match( descriptors1, descriptors2, matches12 );
}
void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
vector<DMatch>& filteredMatches12, int knn=1 )
{
filteredMatches12.clear();
vector<vector<DMatch> > matches12, matches21;
descriptorMatcher->knnMatch( descriptors1, descriptors2, matches12, knn );
descriptorMatcher->knnMatch( descriptors2, descriptors1, matches21, knn );
for( size_t m = 0; m < matches12.size(); m++ )
{
bool findCrossCheck = false;
for( size_t fk = 0; fk < matches12[m].size(); fk++ )
{
DMatch forward = matches12[m][fk];
for( size_t bk = 0; bk < matches21[forward.trainIdx].size(); bk++ )
{
DMatch backward = matches21[forward.trainIdx][bk];
if( backward.trainIdx == forward.queryIdx )
{
filteredMatches12.push_back(forward);
findCrossCheck = true;
break;
}
}
if( findCrossCheck ) break;
}
}
}
void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
{
H.create(3, 3, CV_32FC1);
H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);
H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);
H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;
H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);
H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);
H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;
H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);
H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);
H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);
warpPerspective( src, dst, H, src.size() );
}
void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
vector<KeyPoint>& keypoints1, const Mat& descriptors1,
Ptr<FeatureDetector>& detector, Ptr<DescriptorExtractor>& descriptorExtractor,
Ptr<DescriptorMatcher>& descriptorMatcher, int matcherFilter, bool eval,
double ransacReprojThreshold, RNG& rng )
{
assert( !img1.empty() );
Mat H12;
if( isWarpPerspective )
warpPerspectiveRand(img1, img2, H12, rng );
else
assert( !img2.empty()/* && img2.cols==img1.cols && img2.rows==img1.rows*/ );
cout << endl << "< Extracting keypoints from second image..." << endl;
vector<KeyPoint> keypoints2;
detector->detect( img2, keypoints2 );
cout << keypoints2.size() << " points" << endl << ">" << endl;
if( !H12.empty() && eval )
{
cout << "< Evaluate feature detector..." << endl;
float repeatability;
int correspCount;
evaluateFeatureDetector( img1, img2, H12, &keypoints1, &keypoints2, repeatability, correspCount );
cout << "repeatability = " << repeatability << endl;
cout << "correspCount = " << correspCount << endl;
cout << ">" << endl;
}
cout << "< Computing descriptors for keypoints from second image..." << endl;
Mat descriptors2;
descriptorExtractor->compute( img2, keypoints2, descriptors2 );
cout << ">" << endl;
cout << "< Matching descriptors..." << endl;
vector<DMatch> filteredMatches;
switch( matcherFilter )
{
case CROSS_CHECK_FILTER :
crossCheckMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches, 1 );
break;
default :
simpleMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches );
}
cout << ">" << endl;
if( !H12.empty() && eval )
{
cout << "< Evaluate descriptor matcher..." << endl;
vector<Point2f> curve;
Ptr<GenericDescriptorMatcher> gdm = new VectorDescriptorMatcher( descriptorExtractor, descriptorMatcher );
evaluateGenericDescriptorMatcher( img1, img2, H12, keypoints1, keypoints2, 0, 0, curve, gdm );
for( float l_p = 0; l_p <= 1 + FLT_EPSILON; l_p+=0.05f )
{
int nearest = getNearestPoint( curve, l_p );
if( nearest >= 0 )
cout << "1-precision = " << curve[nearest].x << "; recall = " << curve[nearest].y << endl;
}
cout << ">" << endl;
}
vector<int> queryIdxs( filteredMatches.size() ), trainIdxs( filteredMatches.size() );
for( size_t i = 0; i < filteredMatches.size(); i++ )
{
queryIdxs[i] = filteredMatches[i].queryIdx;
trainIdxs[i] = filteredMatches[i].trainIdx;
}
if( !isWarpPerspective && ransacReprojThreshold >= 0 )
{
cout << "< Computing homography (RANSAC)..." << endl;
vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
H12 = findHomography( Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold );
cout << ">" << endl;
}
Mat drawImg;
if( !H12.empty() ) // filter outliers
{
vector<char> matchesMask( filteredMatches.size(), 0 );
vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
Mat points1t; perspectiveTransform(Mat(points1), points1t, H12);
for( size_t i1 = 0; i1 < points1.size(); i1++ )
{
if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) < 4 ) // inlier
matchesMask[i1] = 1;
}
// draw inliers
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask
#if DRAW_RICH_KEYPOINTS_MODE
, DrawMatchesFlags::DRAW_RICH_KEYPOINTS
#endif
);
#if DRAW_OUTLIERS_MODE
// draw outliers
for( size_t i1 = 0; i1 < matchesMask.size(); i1++ )
matchesMask[i1] = !matchesMask[i1];
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 0, 255), CV_RGB(255, 0, 0), matchesMask,
DrawMatchesFlags::DRAW_OVER_OUTIMG | DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
#endif
}
else
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg );
imshow( winName, drawImg );
}
int main(int argc, char** argv)
{
if( argc != 7 && argc != 8 )
{
help(argv);
return -1;
}
bool isWarpPerspective = argc == 7;
double ransacReprojThreshold = -1;
if( !isWarpPerspective )
ransacReprojThreshold = atof(argv[7]);
cout << "< Creating detector, descriptor extractor and descriptor matcher ..." << endl;
Ptr<FeatureDetector> detector = FeatureDetector::create( argv[1] );
Ptr<DescriptorExtractor> descriptorExtractor = DescriptorExtractor::create( argv[2] );
Ptr<DescriptorMatcher> descriptorMatcher = DescriptorMatcher::create( argv[3] );
int mactherFilterType = getMatcherFilterType( argv[4] );
bool eval = !isWarpPerspective ? false : (atoi(argv[6]) == 0 ? false : true);
cout << ">" << endl;
if( detector.empty() || descriptorExtractor.empty() || descriptorMatcher.empty() )
{
cout << "Can not create detector or descriptor exstractor or descriptor matcher of given types" << endl;
return -1;
}
cout << "< Reading the images..." << endl;
Mat img1 = imread( argv[5] ), img2;
if( !isWarpPerspective )
img2 = imread( argv[6] );
cout << ">" << endl;
if( img1.empty() || (!isWarpPerspective && img2.empty()) )
{
cout << "Can not read images" << endl;
return -1;
}
cout << endl << "< Extracting keypoints from first image..." << endl;
vector<KeyPoint> keypoints1;
detector->detect( img1, keypoints1 );
cout << keypoints1.size() << " points" << endl << ">" << endl;
cout << "< Computing descriptors for keypoints from first image..." << endl;
Mat descriptors1;
descriptorExtractor->compute( img1, keypoints1, descriptors1 );
cout << ">" << endl;
namedWindow(winName, 1);
RNG rng = theRNG();
doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
ransacReprojThreshold, rng );
for(;;)
{
char c = (char)waitKey(0);
if( c == '\x1b' ) // esc
{
cout << "Exiting ..." << endl;
break;
}
else if( isWarpPerspective )
{
doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
ransacReprojThreshold, rng );
}
}
return 0;
}
<commit_msg>removed duplicated output, added the print of first and last points always<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include <iostream>
using namespace cv;
using namespace std;
void help(char** argv)
{
cout << "\nThis program demonstrats keypoint finding and matching between 2 images using features2d framework.\n"
<< " In one case, the 2nd image is synthesized by homography from the first, in the second case, there are 2 images\n"
<< "\n"
<< "Case1: second image is obtained from the first (given) image using random generated homography matrix\n"
<< argv[0] << " [detectorType] [descriptorType] [matcherType] [matcherFilterType] [image] [evaluate(0 or 1)]\n"
<< "Example of case1:\n"
<< "./descriptor_extractor_matcher SURF SURF FlannBased NoneFilter cola.jpg 0\n"
<< "\n"
<< "Case2: both images are given. If ransacReprojThreshold>=0 then homography matrix are calculated\n"
<< argv[0] << " [detectorType] [descriptorType] [matcherType] [matcherFilterType] [image1] [image2] [ransacReprojThreshold]\n"
<< "\n"
<< "Matches are filtered using homography matrix in case1 and case2 (if ransacReprojThreshold>=0)\n"
<< "Example of case2:\n"
<< "./descriptor_extractor_matcher SURF SURF BruteForce CrossCheckFilter cola1.jpg cola2.jpg 3\n"
<< "\n"
<< "Possible detectorType values: see in documentation on createFeatureDetector().\n"
<< "Possible descriptorType values: see in documentation on createDescriptorExtractor().\n"
<< "Possible matcherType values: see in documentation on createDescriptorMatcher().\n"
<< "Possible matcherFilterType values: NoneFilter, CrossCheckFilter." << endl;
}
#define DRAW_RICH_KEYPOINTS_MODE 0
#define DRAW_OUTLIERS_MODE 0
const string winName = "correspondences";
enum { NONE_FILTER = 0, CROSS_CHECK_FILTER = 1 };
int getMatcherFilterType( const string& str )
{
if( str == "NoneFilter" )
return NONE_FILTER;
if( str == "CrossCheckFilter" )
return CROSS_CHECK_FILTER;
CV_Error(CV_StsBadArg, "Invalid filter name");
return -1;
}
void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
vector<DMatch>& matches12 )
{
vector<DMatch> matches;
descriptorMatcher->match( descriptors1, descriptors2, matches12 );
}
void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
vector<DMatch>& filteredMatches12, int knn=1 )
{
filteredMatches12.clear();
vector<vector<DMatch> > matches12, matches21;
descriptorMatcher->knnMatch( descriptors1, descriptors2, matches12, knn );
descriptorMatcher->knnMatch( descriptors2, descriptors1, matches21, knn );
for( size_t m = 0; m < matches12.size(); m++ )
{
bool findCrossCheck = false;
for( size_t fk = 0; fk < matches12[m].size(); fk++ )
{
DMatch forward = matches12[m][fk];
for( size_t bk = 0; bk < matches21[forward.trainIdx].size(); bk++ )
{
DMatch backward = matches21[forward.trainIdx][bk];
if( backward.trainIdx == forward.queryIdx )
{
filteredMatches12.push_back(forward);
findCrossCheck = true;
break;
}
}
if( findCrossCheck ) break;
}
}
}
void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
{
H.create(3, 3, CV_32FC1);
H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);
H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);
H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;
H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);
H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);
H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;
H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);
H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);
H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);
warpPerspective( src, dst, H, src.size() );
}
void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
vector<KeyPoint>& keypoints1, const Mat& descriptors1,
Ptr<FeatureDetector>& detector, Ptr<DescriptorExtractor>& descriptorExtractor,
Ptr<DescriptorMatcher>& descriptorMatcher, int matcherFilter, bool eval,
double ransacReprojThreshold, RNG& rng )
{
assert( !img1.empty() );
Mat H12;
if( isWarpPerspective )
warpPerspectiveRand(img1, img2, H12, rng );
else
assert( !img2.empty()/* && img2.cols==img1.cols && img2.rows==img1.rows*/ );
cout << endl << "< Extracting keypoints from second image..." << endl;
vector<KeyPoint> keypoints2;
detector->detect( img2, keypoints2 );
cout << keypoints2.size() << " points" << endl << ">" << endl;
if( !H12.empty() && eval )
{
cout << "< Evaluate feature detector..." << endl;
float repeatability;
int correspCount;
evaluateFeatureDetector( img1, img2, H12, &keypoints1, &keypoints2, repeatability, correspCount );
cout << "repeatability = " << repeatability << endl;
cout << "correspCount = " << correspCount << endl;
cout << ">" << endl;
}
cout << "< Computing descriptors for keypoints from second image..." << endl;
Mat descriptors2;
descriptorExtractor->compute( img2, keypoints2, descriptors2 );
cout << ">" << endl;
cout << "< Matching descriptors..." << endl;
vector<DMatch> filteredMatches;
switch( matcherFilter )
{
case CROSS_CHECK_FILTER :
crossCheckMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches, 1 );
break;
default :
simpleMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches );
}
cout << ">" << endl;
if( !H12.empty() && eval )
{
cout << "< Evaluate descriptor matcher..." << endl;
vector<Point2f> curve;
Ptr<GenericDescriptorMatcher> gdm = new VectorDescriptorMatcher( descriptorExtractor, descriptorMatcher );
evaluateGenericDescriptorMatcher( img1, img2, H12, keypoints1, keypoints2, 0, 0, curve, gdm );
Point2f firstPoint = *curve.begin();
Point2f lastPoint = *curve.rbegin();
int prevPointIndex = -1;
cout << "1-precision = " << firstPoint.x << "; recall = " << firstPoint.y << endl;
for( float l_p = 0; l_p <= 1 + FLT_EPSILON; l_p+=0.05f )
{
int nearest = getNearestPoint( curve, l_p );
if( nearest >= 0 )
{
Point2f curPoint = curve[nearest];
if( curPoint.x > firstPoint.x && curPoint.x < lastPoint.x && nearest != prevPointIndex )
{
cout << "1-precision = " << curPoint.x << "; recall = " << curPoint.y << endl;
prevPointIndex = nearest;
}
}
}
cout << "1-precision = " << lastPoint.x << "; recall = " << lastPoint.y << endl;
cout << ">" << endl;
}
vector<int> queryIdxs( filteredMatches.size() ), trainIdxs( filteredMatches.size() );
for( size_t i = 0; i < filteredMatches.size(); i++ )
{
queryIdxs[i] = filteredMatches[i].queryIdx;
trainIdxs[i] = filteredMatches[i].trainIdx;
}
if( !isWarpPerspective && ransacReprojThreshold >= 0 )
{
cout << "< Computing homography (RANSAC)..." << endl;
vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
H12 = findHomography( Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold );
cout << ">" << endl;
}
Mat drawImg;
if( !H12.empty() ) // filter outliers
{
vector<char> matchesMask( filteredMatches.size(), 0 );
vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
Mat points1t; perspectiveTransform(Mat(points1), points1t, H12);
for( size_t i1 = 0; i1 < points1.size(); i1++ )
{
if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) < 4 ) // inlier
matchesMask[i1] = 1;
}
// draw inliers
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask
#if DRAW_RICH_KEYPOINTS_MODE
, DrawMatchesFlags::DRAW_RICH_KEYPOINTS
#endif
);
#if DRAW_OUTLIERS_MODE
// draw outliers
for( size_t i1 = 0; i1 < matchesMask.size(); i1++ )
matchesMask[i1] = !matchesMask[i1];
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 0, 255), CV_RGB(255, 0, 0), matchesMask,
DrawMatchesFlags::DRAW_OVER_OUTIMG | DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
#endif
}
else
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg );
imshow( winName, drawImg );
}
int main(int argc, char** argv)
{
if( argc != 7 && argc != 8 )
{
help(argv);
return -1;
}
bool isWarpPerspective = argc == 7;
double ransacReprojThreshold = -1;
if( !isWarpPerspective )
ransacReprojThreshold = atof(argv[7]);
cout << "< Creating detector, descriptor extractor and descriptor matcher ..." << endl;
Ptr<FeatureDetector> detector = FeatureDetector::create( argv[1] );
Ptr<DescriptorExtractor> descriptorExtractor = DescriptorExtractor::create( argv[2] );
Ptr<DescriptorMatcher> descriptorMatcher = DescriptorMatcher::create( argv[3] );
int mactherFilterType = getMatcherFilterType( argv[4] );
bool eval = !isWarpPerspective ? false : (atoi(argv[6]) == 0 ? false : true);
cout << ">" << endl;
if( detector.empty() || descriptorExtractor.empty() || descriptorMatcher.empty() )
{
cout << "Can not create detector or descriptor exstractor or descriptor matcher of given types" << endl;
return -1;
}
cout << "< Reading the images..." << endl;
Mat img1 = imread( argv[5] ), img2;
if( !isWarpPerspective )
img2 = imread( argv[6] );
cout << ">" << endl;
if( img1.empty() || (!isWarpPerspective && img2.empty()) )
{
cout << "Can not read images" << endl;
return -1;
}
cout << endl << "< Extracting keypoints from first image..." << endl;
vector<KeyPoint> keypoints1;
detector->detect( img1, keypoints1 );
cout << keypoints1.size() << " points" << endl << ">" << endl;
cout << "< Computing descriptors for keypoints from first image..." << endl;
Mat descriptors1;
descriptorExtractor->compute( img1, keypoints1, descriptors1 );
cout << ">" << endl;
namedWindow(winName, 1);
RNG rng = theRNG();
doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
ransacReprojThreshold, rng );
for(;;)
{
char c = (char)waitKey(0);
if( c == '\x1b' ) // esc
{
cout << "Exiting ..." << endl;
break;
}
else if( isWarpPerspective )
{
doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
ransacReprojThreshold, rng );
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <thread>
#include <sys/stat.h> /*for getting file size using stat()*/
#include <sys/sendfile.h> /*for sendfile()*/
#include <fcntl.h> /*for O_RDONLY*/
#include "ServerEngine.h"
#include "ConfigReader.h"
#include "NodeDb.h"
#include "NodeTimer.h"
#include "PythonGlue.h"
#define ARRO_BUFFER_SIZE 250
using namespace std;
using namespace Arro;
static thread* thrd = nullptr;
static int newsockfd = -1;
static NodeDb* nodeDb = nullptr;
static PythonGlue* pg = nullptr;
static Trace trace("ServerEngine", true);
/**
* Blocking read from socket until '\n' received. If socket is closed
* then 'terminate' is returned in string buffer.
*
* \param sockfd File descriptor for IP socket.
* \param buffer Buffer to return string into. May contain "terminate" if socket closed or EOF received.
* \param n Max nr of characters to read.
*
* \return Actual nr of characters read.
*/
static int readln(int sockfd, char* buffer, size_t n/*size*/) {
ssize_t numRead; /* # of bytes fetched by last read() */
size_t totRead; /* Total bytes read so far */
char *buf;
char ch;
if (n <= 0 || buffer == nullptr) {
errno = EINVAL;
return -1;
}
buf = buffer;
totRead = 0;
for (;;) {
numRead = read(sockfd, &ch, 1);
if (numRead == -1) {
if (errno == EINTR) /* Interrupted --> restart read() */
continue;
else {
// Make losing socket to terminate process.
strcpy(buffer, "terminate");
return strlen("terminate");
}
} else if (numRead == 0) { /* EOF */
if (totRead == 0) { /* No bytes read */
strcpy(buffer, "terminate");
return strlen("terminate");
}
else
break;
} else { /* 'numRead' must be 1 if we get here */
if (totRead < n - 1) { /* Discard > (n - 1) bytes */
totRead++;
*buf++ = ch;
}
if (ch == '\n')
break;
}
}
*buf = '\0';
return totRead;
}
/**
* Cleanup after exception of terminate command.
*/
static void cleanup()
{
if(nodeDb) {
/* 1: stop message flow */
nodeDb->stop();
/* 2: delete node database */
delete nodeDb; // will automatically stop timers etc.
nodeDb = nullptr;
}
/* 3: stop python */
if(pg) {
delete pg;
pg = nullptr;
}
/* 4: close socket - probably already closed by Eclipse client */
if(newsockfd != -1) {
close(newsockfd);
newsockfd = -1;
}
}
/**
* Server thread for Eclipse client.
* Should keep running forever and serve multiple client 'debugging' sessions.
* For duration of each 'debugging' session from client the server will keep
* open an IP socket connection. A 'debugging' session closes by sending 'terminate'
* command.
*/
static void server()
{
int sockfd, portno;
socklen_t clilen;
struct stat obj;
char command[ARRO_BUFFER_SIZE], filename[ARRO_BUFFER_SIZE];
int size;
int filehandle;
char buffer[ARRO_BUFFER_SIZE];
struct sockaddr_in serv_addr, cli_addr;
int i, n;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
trace.fatal("ERROR opening socket");
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 13000;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
/* Now bind the host address using bind() call.*/
if (::bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
trace.fatal("ERROR on binding");
}
NodeTimer::init (); //FIXME: here?
// Enter the listening loop.
while ( true )
{
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
listen(sockfd,5);
clilen = sizeof(cli_addr);
/* Accept actual connection from the client, we only accept one connection. */
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
trace.println("new socket " + newsockfd);
if (newsockfd < 0)
{
newsockfd = -1;
trace.fatal("ERROR on accept");
}
ServerEngine::console("========================");
/* If connection is established then start communicating */
bzero(buffer,ARRO_BUFFER_SIZE);
while ((n = readln( newsockfd,buffer, ARRO_BUFFER_SIZE - 1 )) != 0)
{
trace.println(string("command: ") + buffer);
sscanf(buffer, "%s", command);
if(!strcmp(command, "echo"))
{
trace.println(string("got line ") + buffer);
ServerEngine::console("ServerEngine::console echo\n");
break;
}
else if(!strcmp(command, "ls"))
{
system("ls >temps.txt");
i = 0;
stat("temps.txt",&obj);
size = obj.st_size;
send(newsockfd, &size, sizeof(int),0);
filehandle = open("temps.txt", O_RDONLY);
sendfile(newsockfd,filehandle,nullptr,size);
}
else if(!strcmp(command, "put"))
{
int c = 0;
char *f;
sscanf(buffer+strlen(command), "%s %d", filename, &size);
filehandle = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
f = (char*)malloc(size);
while(size > 0)
{
int r = recv(newsockfd, f, size, 0);
c = write(filehandle, f, r);
size -= r;
}
close(filehandle);
if(c != -1)
{
ServerEngine::console("put successful");
}
else
{
ServerEngine::console("put failed");
}
}
else if(!strcmp(command, "protobuf"))
{
system("protoc --python_out=. arro.proto");
ServerEngine::console("protobuf successful");
}
else if(!strcmp(command, "run"))
{
if(nodeDb)
{
ServerEngine::console("run failed, engine running, terminate first");
}
else
{
nodeDb = new NodeDb();
try {
pg = new PythonGlue();
ConfigReader reader(ARRO_CONFIG_FILE, *nodeDb);
ServerEngine::console("loading successful");
nodeDb->start();
ServerEngine::console("run successful");
} catch ( const std::runtime_error& e ) {
cleanup();
ServerEngine::console("run failed");
}
}
}
else if(!strcmp(command, "terminate"))
{
cleanup();
break;
}
else if(!strcmp(command, "pwd"))
{
system("pwd>temp.txt");
i = 0;
FILE*f = fopen("temp.txt","r");
while(!feof(f) && i < ARRO_BUFFER_SIZE)
buffer[i++] = fgetc(f);
buffer[i-1] = '\0';
send(newsockfd, buffer, 100, 0);
}
}
}
}
void ServerEngine::start()
{
if(!thrd) {
thrd = new std::thread(server); // spawn new thread that calls server()
}
else {
trace.fatal("Thread already present");
}
trace.println("server started...");
}
void ServerEngine::stop()
{
// synchronize threads:
thrd->join(); // pauses until finishes
delete thrd;
trace.println("server completed.");
}
void ServerEngine::console(string s)
{
if(newsockfd >= 0) {
s += "\n";
send(newsockfd, s.c_str(), s.length(), 0);
}
}
<commit_msg>Missing free for malloc.<commit_after>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <thread>
#include <sys/stat.h> /*for getting file size using stat()*/
#include <sys/sendfile.h> /*for sendfile()*/
#include <fcntl.h> /*for O_RDONLY*/
#include "ServerEngine.h"
#include "ConfigReader.h"
#include "NodeDb.h"
#include "NodeTimer.h"
#include "PythonGlue.h"
#define ARRO_BUFFER_SIZE 250
using namespace std;
using namespace Arro;
static thread* thrd = nullptr;
static int newsockfd = -1;
static NodeDb* nodeDb = nullptr;
static PythonGlue* pg = nullptr;
static Trace trace("ServerEngine", true);
/**
* Blocking read from socket until '\n' received. If socket is closed
* then 'terminate' is returned in string buffer.
*
* \param sockfd File descriptor for IP socket.
* \param buffer Buffer to return string into. May contain "terminate" if socket closed or EOF received.
* \param n Max nr of characters to read.
*
* \return Actual nr of characters read.
*/
static int readln(int sockfd, char* buffer, size_t n/*size*/) {
ssize_t numRead; /* # of bytes fetched by last read() */
size_t totRead; /* Total bytes read so far */
char *buf;
char ch;
if (n <= 0 || buffer == nullptr) {
errno = EINVAL;
return -1;
}
buf = buffer;
totRead = 0;
for (;;) {
numRead = read(sockfd, &ch, 1);
if (numRead == -1) {
if (errno == EINTR) /* Interrupted --> restart read() */
continue;
else {
// Make losing socket to terminate process.
strcpy(buffer, "terminate");
return strlen("terminate");
}
} else if (numRead == 0) { /* EOF */
if (totRead == 0) { /* No bytes read */
strcpy(buffer, "terminate");
return strlen("terminate");
}
else
break;
} else { /* 'numRead' must be 1 if we get here */
if (totRead < n - 1) { /* Discard > (n - 1) bytes */
totRead++;
*buf++ = ch;
}
if (ch == '\n')
break;
}
}
*buf = '\0';
return totRead;
}
/**
* Cleanup after exception of terminate command.
*/
static void cleanup()
{
if(nodeDb) {
/* 1: stop message flow */
nodeDb->stop();
/* 2: delete node database */
delete nodeDb; // will automatically stop timers etc.
nodeDb = nullptr;
}
/* 3: stop python */
if(pg) {
delete pg;
pg = nullptr;
}
/* 4: close socket - probably already closed by Eclipse client */
if(newsockfd != -1) {
close(newsockfd);
newsockfd = -1;
}
}
/**
* Server thread for Eclipse client.
* Should keep running forever and serve multiple client 'debugging' sessions.
* For duration of each 'debugging' session from client the server will keep
* open an IP socket connection. A 'debugging' session closes by sending 'terminate'
* command.
*/
static void server()
{
int sockfd, portno;
socklen_t clilen;
struct stat obj;
char command[ARRO_BUFFER_SIZE], filename[ARRO_BUFFER_SIZE];
int size;
int filehandle;
char buffer[ARRO_BUFFER_SIZE];
struct sockaddr_in serv_addr, cli_addr;
int i, n;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
trace.fatal("ERROR opening socket");
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 13000;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
/* Now bind the host address using bind() call.*/
if (::bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
trace.fatal("ERROR on binding");
}
NodeTimer::init (); //FIXME: here?
// Enter the listening loop.
while ( true )
{
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
listen(sockfd,5);
clilen = sizeof(cli_addr);
/* Accept actual connection from the client, we only accept one connection. */
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
trace.println("new socket " + newsockfd);
if (newsockfd < 0)
{
newsockfd = -1;
trace.fatal("ERROR on accept");
}
ServerEngine::console("========================");
/* If connection is established then start communicating */
bzero(buffer,ARRO_BUFFER_SIZE);
while ((n = readln( newsockfd,buffer, ARRO_BUFFER_SIZE - 1 )) != 0)
{
trace.println(string("command: ") + buffer);
sscanf(buffer, "%s", command);
if(!strcmp(command, "echo"))
{
trace.println(string("got line ") + buffer);
ServerEngine::console("ServerEngine::console echo\n");
break;
}
else if(!strcmp(command, "ls"))
{
system("ls >temps.txt");
i = 0;
stat("temps.txt",&obj);
size = obj.st_size;
send(newsockfd, &size, sizeof(int),0);
filehandle = open("temps.txt", O_RDONLY);
sendfile(newsockfd,filehandle,nullptr,size);
}
else if(!strcmp(command, "put"))
{
int c = 0;
char *f;
sscanf(buffer+strlen(command), "%s %d", filename, &size);
filehandle = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
f = (char*)malloc(size);
while(size > 0)
{
int r = recv(newsockfd, f, size, 0);
c = write(filehandle, f, r);
size -= r;
}
close(filehandle);
free(f);
if(c != -1)
{
ServerEngine::console("put successful");
}
else
{
ServerEngine::console("put failed");
}
}
else if(!strcmp(command, "protobuf"))
{
system("protoc --python_out=. arro.proto");
ServerEngine::console("protobuf successful");
}
else if(!strcmp(command, "run"))
{
if(nodeDb)
{
ServerEngine::console("run failed, engine running, terminate first");
}
else
{
nodeDb = new NodeDb();
try {
pg = new PythonGlue();
ConfigReader reader(ARRO_CONFIG_FILE, *nodeDb);
ServerEngine::console("loading successful");
nodeDb->start();
ServerEngine::console("run successful");
} catch ( const std::runtime_error& e ) {
cleanup();
ServerEngine::console("run failed");
}
}
}
else if(!strcmp(command, "terminate"))
{
cleanup();
break;
}
else if(!strcmp(command, "pwd"))
{
system("pwd>temp.txt");
i = 0;
FILE*f = fopen("temp.txt","r");
while(!feof(f) && i < ARRO_BUFFER_SIZE)
buffer[i++] = fgetc(f);
buffer[i-1] = '\0';
send(newsockfd, buffer, 100, 0);
}
}
}
}
void ServerEngine::start()
{
if(!thrd) {
thrd = new std::thread(server); // spawn new thread that calls server()
}
else {
trace.fatal("Thread already present");
}
trace.println("server started...");
}
void ServerEngine::stop()
{
// synchronize threads:
thrd->join(); // pauses until finishes
delete thrd;
trace.println("server completed.");
}
void ServerEngine::console(string s)
{
if(newsockfd >= 0) {
s += "\n";
send(newsockfd, s.c_str(), s.length(), 0);
}
}
<|endoftext|>
|
<commit_before>//===-- ELFDump.cpp - ELF-specific dumper -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements the ELF-specific dumper for llvm-objdump.
///
//===----------------------------------------------------------------------===//
#include "llvm-objdump.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
template<endianness target_endianness, std::size_t max_alignment, bool is64Bits>
void printProgramHeaders(
const ELFObjectFile<target_endianness, max_alignment, is64Bits> *o) {
typedef ELFObjectFile<target_endianness, max_alignment, is64Bits> ELFO;
outs() << "Program Header:\n";
for (typename ELFO::Elf_Phdr_Iter pi = o->begin_program_headers(),
pe = o->end_program_headers();
pi != pe; ++pi) {
switch (pi->p_type) {
case ELF::PT_LOAD:
outs() << " LOAD ";
break;
case ELF::PT_GNU_STACK:
outs() << " STACK ";
break;
case ELF::PT_GNU_EH_FRAME:
outs() << "EH_FRAME ";
break;
default:
outs() << " UNKNOWN ";
}
outs() << "off "
<< format(is64Bits ? "0x%016x " : "0x%08x ", pi->p_offset)
<< "vaddr "
<< format(is64Bits ? "0x%016x " : "0x%08x ", pi->p_vaddr)
<< "paddr "
<< format(is64Bits ? "0x%016x " : "0x%08x ", pi->p_paddr)
<< format("align 2**%d\n", CountTrailingZeros_32(pi->p_align))
<< " filesz "
<< format(is64Bits ? "0x%016x " : "0x%08x ", pi->p_filesz)
<< "memsz "
<< format(is64Bits ? "0x%016x " : "0x%08x ", pi->p_memsz)
<< "flags "
<< ((pi->p_flags & ELF::PF_R) ? "r" : "-")
<< ((pi->p_flags & ELF::PF_W) ? "w" : "-")
<< ((pi->p_flags & ELF::PF_X) ? "x" : "-")
<< "\n";
}
outs() << "\n";
}
void llvm::printELFFileHeader(const object::ObjectFile *Obj) {
// Little-endian 32-bit
if (const ELFObjectFile<support::little, 4, false> *ELFObj =
dyn_cast<ELFObjectFile<support::little, 4, false> >(Obj))
printProgramHeaders(ELFObj);
// Big-endian 32-bit
if (const ELFObjectFile<support::big, 4, false> *ELFObj =
dyn_cast<ELFObjectFile<support::big, 4, false> >(Obj))
printProgramHeaders(ELFObj);
// Little-endian 64-bit
if (const ELFObjectFile<support::little, 8, true> *ELFObj =
dyn_cast<ELFObjectFile<support::little, 8, true> >(Obj))
printProgramHeaders(ELFObj);
// Big-endian 64-bit
if (const ELFObjectFile<support::big, 8, true> *ELFObj =
dyn_cast<ELFObjectFile<support::big, 8, true> >(Obj))
printProgramHeaders(ELFObj);
}
<commit_msg>[objdump] Use correct format specifiers and fix C++03 variadic warning.<commit_after>//===-- ELFDump.cpp - ELF-specific dumper -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements the ELF-specific dumper for llvm-objdump.
///
//===----------------------------------------------------------------------===//
#include "llvm-objdump.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
template<endianness target_endianness, std::size_t max_alignment, bool is64Bits>
void printProgramHeaders(
const ELFObjectFile<target_endianness, max_alignment, is64Bits> *o) {
typedef ELFObjectFile<target_endianness, max_alignment, is64Bits> ELFO;
outs() << "Program Header:\n";
for (typename ELFO::Elf_Phdr_Iter pi = o->begin_program_headers(),
pe = o->end_program_headers();
pi != pe; ++pi) {
switch (pi->p_type) {
case ELF::PT_LOAD:
outs() << " LOAD ";
break;
case ELF::PT_GNU_STACK:
outs() << " STACK ";
break;
case ELF::PT_GNU_EH_FRAME:
outs() << "EH_FRAME ";
break;
default:
outs() << " UNKNOWN ";
}
const char *Fmt = is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " ";
outs() << "off "
<< format(Fmt, (uint64_t)pi->p_offset)
<< "vaddr "
<< format(Fmt, (uint64_t)pi->p_vaddr)
<< "paddr "
<< format(Fmt, (uint64_t)pi->p_paddr)
<< format("align 2**%u\n", CountTrailingZeros_64(pi->p_align))
<< " filesz "
<< format(Fmt, (uint64_t)pi->p_filesz)
<< "memsz "
<< format(Fmt, (uint64_t)pi->p_memsz)
<< "flags "
<< ((pi->p_flags & ELF::PF_R) ? "r" : "-")
<< ((pi->p_flags & ELF::PF_W) ? "w" : "-")
<< ((pi->p_flags & ELF::PF_X) ? "x" : "-")
<< "\n";
}
outs() << "\n";
}
void llvm::printELFFileHeader(const object::ObjectFile *Obj) {
// Little-endian 32-bit
if (const ELFObjectFile<support::little, 4, false> *ELFObj =
dyn_cast<ELFObjectFile<support::little, 4, false> >(Obj))
printProgramHeaders(ELFObj);
// Big-endian 32-bit
if (const ELFObjectFile<support::big, 4, false> *ELFObj =
dyn_cast<ELFObjectFile<support::big, 4, false> >(Obj))
printProgramHeaders(ELFObj);
// Little-endian 64-bit
if (const ELFObjectFile<support::little, 8, true> *ELFObj =
dyn_cast<ELFObjectFile<support::little, 8, true> >(Obj))
printProgramHeaders(ELFObj);
// Big-endian 64-bit
if (const ELFObjectFile<support::big, 8, true> *ELFObj =
dyn_cast<ELFObjectFile<support::big, 8, true> >(Obj))
printProgramHeaders(ELFObj);
}
<|endoftext|>
|
<commit_before>#ifndef PROTON_CPP_ENDPOINT_H
#define PROTON_CPP_ENDPOINT_H
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "proton/export.hpp"
#include "proton/connection.h"
namespace proton {
class handler;
class connection;
class transport;
class session;
class link;
/** endpoint is a base class for session, connection and link */
class endpoint
{
public:
/** state is a bit mask of state_bit values.
*
* A state mask is matched against an endpoint as follows: If the state mask
* contains both local and remote flags, then an exact match against those
* flags is performed. If state contains only local or only remote flags,
* then a match occurs if any of the local or remote flags are set
* respectively.
*
* @see connection::links, connection::sessions
*/
typedef int state;
/// endpoint state bit values @{
PN_CPP_EXTERN static const state LOCAL_UNINIT; ///< Local endpoint is un-initialized
PN_CPP_EXTERN static const state REMOTE_UNINIT; ///< Remote endpoint is un-initialized
PN_CPP_EXTERN static const state LOCAL_ACTIVE; ///< Local endpoint is active
PN_CPP_EXTERN static const state REMOTE_ACTIVE; ///< Remote endpoint is active
PN_CPP_EXTERN static const state LOCAL_CLOSED; ///< Local endpoint has been closed
PN_CPP_EXTERN static const state REMOTE_CLOSED; ///< Remote endpoint has been closed
PN_CPP_EXTERN static const state LOCAL_MASK; ///< Mask including all LOCAL_ bits (UNINIT, ACTIVE, CLOSED)
PN_CPP_EXTERN static const state REMOTE_MASK; ///< Mask including all REMOTE_ bits (UNINIT, ACTIVE, CLOSED)
///@}
// TODO: condition, remote_condition, update_condition, get/handler
};
///@cond INTERNAL
template <class T, class D> class iter_base {
public:
typedef T value_type;
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
operator bool() const { return ptr_; }
bool operator !() const { return !ptr_; }
iter_base<T, D>& operator++() { static_cast<D*>(this)->advance(); return *this; }
iter_base<T, D>& operator++(int) { iter_base<T, D> x(*this); ++(*this); return x; }
bool operator==(const iter_base<T, D>& x) const { return ptr_ == x.ptr_; }
bool operator!=(const iter_base<T, D>& x) const { return ptr_ != x.ptr_; }
protected:
explicit iter_base(T* p = 0, endpoint::state s = 0) : ptr_(p), state_(s) {}
T* ptr_;
endpoint::state state_;
};
template<class I> class range {
public:
typedef I iterator;
explicit range(I begin = I(), I end = I()) : begin_(begin), end_(end) {}
I begin() const { return begin_; }
I end() const { return end_; }
private:
I begin_, end_;
};
///@endcond INTERNAL
///@ An iterator for a range of sessions.
class session_iterator : public iter_base<session, session_iterator> {
public:
explicit session_iterator(session* p = 0, endpoint::state s = 0) : iter_base(p, s) {}
private:
PN_CPP_EXTERN void advance();
friend class iter_base<session, session_iterator>;
};
///@ A range of sessions.
typedef range<session_iterator> session_range;
///@ An iterator for a range of links.
class link_iterator : public iter_base<link, link_iterator> {
public:
explicit link_iterator(link* p = 0, endpoint::state s = 0) :
iter_base(p, s), session_(0) {}
explicit link_iterator(const link_iterator& i, const session *ssn) :
iter_base(i.ptr_, i.state_), session_(ssn) {}
private:
PN_CPP_EXTERN void advance();
const session* session_;
friend class iter_base<link, link_iterator>;
};
///@ A range of links.
typedef range<link_iterator> link_range;
}
#endif /*!PROTON_CPP_H*/
<commit_msg>NO-JIRA: c++: fix compile error on older c++ compilers (noticed on gcc 4.7)<commit_after>#ifndef PROTON_CPP_ENDPOINT_H
#define PROTON_CPP_ENDPOINT_H
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "proton/export.hpp"
#include "proton/connection.h"
namespace proton {
class handler;
class connection;
class transport;
class session;
class link;
/** endpoint is a base class for session, connection and link */
class endpoint
{
public:
/** state is a bit mask of state_bit values.
*
* A state mask is matched against an endpoint as follows: If the state mask
* contains both local and remote flags, then an exact match against those
* flags is performed. If state contains only local or only remote flags,
* then a match occurs if any of the local or remote flags are set
* respectively.
*
* @see connection::links, connection::sessions
*/
typedef int state;
/// endpoint state bit values @{
PN_CPP_EXTERN static const state LOCAL_UNINIT; ///< Local endpoint is un-initialized
PN_CPP_EXTERN static const state REMOTE_UNINIT; ///< Remote endpoint is un-initialized
PN_CPP_EXTERN static const state LOCAL_ACTIVE; ///< Local endpoint is active
PN_CPP_EXTERN static const state REMOTE_ACTIVE; ///< Remote endpoint is active
PN_CPP_EXTERN static const state LOCAL_CLOSED; ///< Local endpoint has been closed
PN_CPP_EXTERN static const state REMOTE_CLOSED; ///< Remote endpoint has been closed
PN_CPP_EXTERN static const state LOCAL_MASK; ///< Mask including all LOCAL_ bits (UNINIT, ACTIVE, CLOSED)
PN_CPP_EXTERN static const state REMOTE_MASK; ///< Mask including all REMOTE_ bits (UNINIT, ACTIVE, CLOSED)
///@}
// TODO: condition, remote_condition, update_condition, get/handler
};
///@cond INTERNAL
template <class T, class D> class iter_base {
public:
typedef T value_type;
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
operator bool() const { return ptr_; }
bool operator !() const { return !ptr_; }
iter_base<T, D>& operator++() { static_cast<D*>(this)->advance(); return *this; }
iter_base<T, D>& operator++(int) { iter_base<T, D> x(*this); ++(*this); return x; }
bool operator==(const iter_base<T, D>& x) const { return ptr_ == x.ptr_; }
bool operator!=(const iter_base<T, D>& x) const { return ptr_ != x.ptr_; }
protected:
explicit iter_base(T* p = 0, endpoint::state s = 0) : ptr_(p), state_(s) {}
T* ptr_;
endpoint::state state_;
};
template<class I> class range {
public:
typedef I iterator;
explicit range(I begin = I(), I end = I()) : begin_(begin), end_(end) {}
I begin() const { return begin_; }
I end() const { return end_; }
private:
I begin_, end_;
};
///@endcond INTERNAL
///@ An iterator for a range of sessions.
class session_iterator : public iter_base<session, session_iterator> {
public:
explicit session_iterator(session* p = 0, endpoint::state s = 0) :
iter_base<session, session_iterator>(p, s) {}
private:
PN_CPP_EXTERN void advance();
friend class iter_base<session, session_iterator>;
};
///@ A range of sessions.
typedef range<session_iterator> session_range;
///@ An iterator for a range of links.
class link_iterator : public iter_base<link, link_iterator> {
public:
explicit link_iterator(link* p = 0, endpoint::state s = 0) :
iter_base(p, s), session_(0) {}
explicit link_iterator(const link_iterator& i, const session *ssn) :
iter_base(i.ptr_, i.state_), session_(ssn) {}
private:
PN_CPP_EXTERN void advance();
const session* session_;
friend class iter_base<link, link_iterator>;
};
///@ A range of links.
typedef range<link_iterator> link_range;
}
#endif /*!PROTON_CPP_H*/
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PostprocessorInterface.h"
#include "FEProblem.h"
#include "Postprocessor.h"
#include "MooseTypes.h"
#include "MooseObject.h"
#include "UserObject.h"
InputParameters
PostprocessorInterface::validParams()
{
return emptyInputParameters();
}
PostprocessorInterface::PostprocessorInterface(const MooseObject * moose_object)
: _ppi_moose_object(*moose_object),
_ppi_params(_ppi_moose_object.parameters()),
_ppi_feproblem(*_ppi_params.getCheckedPointerParam<FEProblemBase *>("_fe_problem_base"))
{
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValue(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
return getPostprocessorValueHelper(param_name, index, 0);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOld(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
return getPostprocessorValueHelper(param_name, index, 1);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOlder(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
return getPostprocessorValueHelper(param_name, index, 2);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueByName(const PostprocessorName & name) const
{
return getPostprocessorValueByNameHelper(name, 0);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOldByName(const PostprocessorName & name) const
{
return getPostprocessorValueByNameHelper(name, 1);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOlderByName(const PostprocessorName & name) const
{
return getPostprocessorValueByNameHelper(name, 2);
}
bool
PostprocessorInterface::isDefaultPostprocessorValue(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
checkParam(param_name, index);
return _ppi_params.isDefaultPostprocessorValue(param_name, index);
}
bool
PostprocessorInterface::hasPostprocessor(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
if (!_ppi_feproblem.getMooseApp().actionWarehouse().isTaskComplete("add_postprocessor"))
_ppi_moose_object.mooseError(
"Cannot call hasPostprocessor() until all postprocessors have been constructed.");
// If the parameter is a default value, we don't actually create a Postprocessor object
// for it, therefore this will be false
if (isDefaultPostprocessorValue(param_name, index))
return false;
return hasPostprocessorByName(getPostprocessorName(param_name, index));
}
bool
PostprocessorInterface::hasPostprocessorByName(const PostprocessorName & name) const
{
if (!_ppi_feproblem.getMooseApp().actionWarehouse().isTaskComplete("add_postprocessor"))
_ppi_moose_object.mooseError(
"Cannot call hasPostprocessorByName() until all postprocessors have been constructed.");
return _ppi_feproblem.getReporterData().hasReporterValue<PostprocessorValue>(
ReporterName(name, "value"));
}
bool
PostprocessorInterface::hasPostprocessorObjectByName(const PostprocessorName & name) const
{
if (!_ppi_feproblem.getMooseApp().actionWarehouse().isTaskComplete("add_postprocessor"))
_ppi_moose_object.mooseError("Cannot call hasPostprocessorObjectByName() until all "
"postprocessors have been constructed.");
if (_ppi_feproblem.hasUserObject(name))
return dynamic_cast<const Postprocessor *>(&_ppi_feproblem.getUserObjectBase(name));
return false;
}
std::size_t
PostprocessorInterface::coupledPostprocessors(const std::string & param_name) const
{
checkParam(param_name);
if (_ppi_params.isType<PostprocessorName>(param_name))
return 1;
return _ppi_params.get<std::vector<PostprocessorName>>(param_name).size();
}
void
PostprocessorInterface::checkParam(
const std::string & param_name,
const unsigned int index /* = std::numeric_limits<unsigned int>::max() */) const
{
const bool check_index = index != std::numeric_limits<unsigned int>::max();
if (!_ppi_params.isParamValid(param_name))
_ppi_moose_object.mooseError(
"When getting a Postprocessor, failed to get a parameter with the name \"",
param_name,
"\".",
"\n\nKnown parameters:\n",
_ppi_moose_object.parameters());
if (_ppi_params.isType<PostprocessorName>(param_name))
{
if (check_index && index > 0)
_ppi_moose_object.paramError(param_name,
"A postprocessor was requested with index ",
index,
" but a single postprocessor is coupled.");
}
else if (_ppi_params.isType<std::vector<PostprocessorName>>(param_name))
{
const auto & names = _ppi_params.get<std::vector<PostprocessorName>>(param_name);
if (check_index && names.size() <= index)
_ppi_moose_object.paramError(param_name,
"A postprocessor was requested with index ",
index,
" but only ",
names.size(),
" postprocessors are coupled.");
}
else
{
_ppi_moose_object.mooseError(
"Supplied parameter with name \"",
param_name,
"\" of type \"",
_ppi_params.type(param_name),
"\" is not an expected type for getting a Postprocessor.\n\n",
"Allowed types are \"PostprocessorName\" and \"std::vector<PostprocessorName>\".");
}
}
const PostprocessorName &
PostprocessorInterface::getPostprocessorName(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
// If the Postprocessor is a default value, its name is actually the default value,
// therefore we shouldn't be getting a name associated with it
if (isDefaultPostprocessorValue(param_name, index))
_ppi_moose_object.mooseError(
"While getting the name of the postprocessor from parameter \"",
param_name,
"\" at index ",
index,
":\nCannot get the name because the postprocessor is a defualt value.");
return _ppi_params.isType<PostprocessorName>(param_name)
? _ppi_params.get<PostprocessorName>(param_name)
: _ppi_params.get<std::vector<PostprocessorName>>(param_name)[index];
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueHelper(const std::string & param_name,
unsigned int index,
std::size_t t_index) const
{
// If the Postprocessor is a default value (either set by addParam or set to a constant
// value by the user in input/an action), we covert the name to a value, store said
// value locally, and return it so that it fits in with the rest of the interface
// (needing a reference to a value)
if (isDefaultPostprocessorValue(param_name, index))
{
const auto key = std::make_pair(param_name, index);
const auto value = _ppi_params.getDefaultPostprocessorValue(param_name, index);
return *_default_values.emplace(key, libmesh_make_unique<PostprocessorValue>(value))
.first->second; // first is inserted pair, second is value in pair
}
return getPostprocessorValueByNameHelper(getPostprocessorName(param_name, index), t_index);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueByNameHelper(const PostprocessorName & name,
std::size_t t_index) const
{
mooseAssert(t_index < 3, "Invalid time index");
return _ppi_feproblem.getReporterValue<PostprocessorValue>(
ReporterName(name, "value"), name, REPORTER_MODE_ROOT, t_index);
}
<commit_msg>Check that in the case of non-insertion that values are the same<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PostprocessorInterface.h"
#include "FEProblem.h"
#include "Postprocessor.h"
#include "MooseTypes.h"
#include "MooseObject.h"
#include "UserObject.h"
InputParameters
PostprocessorInterface::validParams()
{
return emptyInputParameters();
}
PostprocessorInterface::PostprocessorInterface(const MooseObject * moose_object)
: _ppi_moose_object(*moose_object),
_ppi_params(_ppi_moose_object.parameters()),
_ppi_feproblem(*_ppi_params.getCheckedPointerParam<FEProblemBase *>("_fe_problem_base"))
{
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValue(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
return getPostprocessorValueHelper(param_name, index, 0);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOld(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
return getPostprocessorValueHelper(param_name, index, 1);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOlder(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
return getPostprocessorValueHelper(param_name, index, 2);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueByName(const PostprocessorName & name) const
{
return getPostprocessorValueByNameHelper(name, 0);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOldByName(const PostprocessorName & name) const
{
return getPostprocessorValueByNameHelper(name, 1);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueOlderByName(const PostprocessorName & name) const
{
return getPostprocessorValueByNameHelper(name, 2);
}
bool
PostprocessorInterface::isDefaultPostprocessorValue(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
checkParam(param_name, index);
return _ppi_params.isDefaultPostprocessorValue(param_name, index);
}
bool
PostprocessorInterface::hasPostprocessor(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
if (!_ppi_feproblem.getMooseApp().actionWarehouse().isTaskComplete("add_postprocessor"))
_ppi_moose_object.mooseError(
"Cannot call hasPostprocessor() until all postprocessors have been constructed.");
// If the parameter is a default value, we don't actually create a Postprocessor object
// for it, therefore this will be false
if (isDefaultPostprocessorValue(param_name, index))
return false;
return hasPostprocessorByName(getPostprocessorName(param_name, index));
}
bool
PostprocessorInterface::hasPostprocessorByName(const PostprocessorName & name) const
{
if (!_ppi_feproblem.getMooseApp().actionWarehouse().isTaskComplete("add_postprocessor"))
_ppi_moose_object.mooseError(
"Cannot call hasPostprocessorByName() until all postprocessors have been constructed.");
return _ppi_feproblem.getReporterData().hasReporterValue<PostprocessorValue>(
ReporterName(name, "value"));
}
bool
PostprocessorInterface::hasPostprocessorObjectByName(const PostprocessorName & name) const
{
if (!_ppi_feproblem.getMooseApp().actionWarehouse().isTaskComplete("add_postprocessor"))
_ppi_moose_object.mooseError("Cannot call hasPostprocessorObjectByName() until all "
"postprocessors have been constructed.");
if (_ppi_feproblem.hasUserObject(name))
return dynamic_cast<const Postprocessor *>(&_ppi_feproblem.getUserObjectBase(name));
return false;
}
std::size_t
PostprocessorInterface::coupledPostprocessors(const std::string & param_name) const
{
checkParam(param_name);
if (_ppi_params.isType<PostprocessorName>(param_name))
return 1;
return _ppi_params.get<std::vector<PostprocessorName>>(param_name).size();
}
void
PostprocessorInterface::checkParam(
const std::string & param_name,
const unsigned int index /* = std::numeric_limits<unsigned int>::max() */) const
{
const bool check_index = index != std::numeric_limits<unsigned int>::max();
if (!_ppi_params.isParamValid(param_name))
_ppi_moose_object.mooseError(
"When getting a Postprocessor, failed to get a parameter with the name \"",
param_name,
"\".",
"\n\nKnown parameters:\n",
_ppi_moose_object.parameters());
if (_ppi_params.isType<PostprocessorName>(param_name))
{
if (check_index && index > 0)
_ppi_moose_object.paramError(param_name,
"A postprocessor was requested with index ",
index,
" but a single postprocessor is coupled.");
}
else if (_ppi_params.isType<std::vector<PostprocessorName>>(param_name))
{
const auto & names = _ppi_params.get<std::vector<PostprocessorName>>(param_name);
if (check_index && names.size() <= index)
_ppi_moose_object.paramError(param_name,
"A postprocessor was requested with index ",
index,
" but only ",
names.size(),
" postprocessors are coupled.");
}
else
{
_ppi_moose_object.mooseError(
"Supplied parameter with name \"",
param_name,
"\" of type \"",
_ppi_params.type(param_name),
"\" is not an expected type for getting a Postprocessor.\n\n",
"Allowed types are \"PostprocessorName\" and \"std::vector<PostprocessorName>\".");
}
}
const PostprocessorName &
PostprocessorInterface::getPostprocessorName(const std::string & param_name,
const unsigned int index /* = 0 */) const
{
// If the Postprocessor is a default value, its name is actually the default value,
// therefore we shouldn't be getting a name associated with it
if (isDefaultPostprocessorValue(param_name, index))
_ppi_moose_object.mooseError(
"While getting the name of the postprocessor from parameter \"",
param_name,
"\" at index ",
index,
":\nCannot get the name because the postprocessor is a defualt value.");
return _ppi_params.isType<PostprocessorName>(param_name)
? _ppi_params.get<PostprocessorName>(param_name)
: _ppi_params.get<std::vector<PostprocessorName>>(param_name)[index];
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueHelper(const std::string & param_name,
unsigned int index,
std::size_t t_index) const
{
// If the Postprocessor is a default value (either set by addParam or set to a constant
// value by the user in input/an action), we covert the name to a value, store said
// value locally, and return it so that it fits in with the rest of the interface
// (needing a reference to a value)
if (isDefaultPostprocessorValue(param_name, index))
{
const auto key = std::make_pair(param_name, index);
const auto value = _ppi_params.getDefaultPostprocessorValue(param_name, index);
const auto & value_ref =
*_default_values.emplace(key, libmesh_make_unique<PostprocessorValue>(value))
.first->second; // first is inserted pair, second is value in pair
mooseAssert(value == value_ref, "Inconsistent default value");
return value_ref;
}
return getPostprocessorValueByNameHelper(getPostprocessorName(param_name, index), t_index);
}
const PostprocessorValue &
PostprocessorInterface::getPostprocessorValueByNameHelper(const PostprocessorName & name,
std::size_t t_index) const
{
mooseAssert(t_index < 3, "Invalid time index");
return _ppi_feproblem.getReporterValue<PostprocessorValue>(
ReporterName(name, "value"), name, REPORTER_MODE_ROOT, t_index);
}
<|endoftext|>
|
<commit_before>//
// $Id$
//
#include "AVGJSScript.h"
#include <iostream>
using namespace std;
AVGJSScript::AVGJSScript(const std::string& code, const std::string& filename,
int lineno, JSContext * pJSContext)
: m_code(code),
m_filename(filename),
m_lineno(lineno),
m_pJSContext(pJSContext),
m_pScript(0)
{
}
AVGJSScript::~AVGJSScript()
{
if (m_pScript) {
JS_DestroyScript(m_pJSContext, m_pScript);
}
}
extern "C" {
// From mozilla/js/jsexn.h
extern JSBool
js_ReportUncaughtException(JSContext *cx);
}
void AVGJSScript::run()
{
// TODO: Actually, compile() should be called in the constructor. However, if I do this,
// any arguments in the script are null when execute is finally called.
compile();
if (m_pScript) {
jsval Result;
JSBool ok = JS_ExecuteScript(m_pJSContext, m_pObject, m_pScript, &Result);
if (!ok) {
js_ReportUncaughtException(m_pJSContext);
}
}
}
void AVGJSScript::compile()
{
m_pObject = JS_GetGlobalObject(m_pJSContext);
m_pScript = JS_CompileScript(m_pJSContext, m_pObject,
m_code.c_str(), m_code.length(), m_filename.c_str(), m_lineno);
if (!m_pScript) {
js_ReportUncaughtException(m_pJSContext);
}
}
<commit_msg>Fixed memory leak<commit_after>//
// $Id$
//
#include "AVGJSScript.h"
#include <iostream>
using namespace std;
AVGJSScript::AVGJSScript(const std::string& code, const std::string& filename,
int lineno, JSContext * pJSContext)
: m_code(code),
m_filename(filename),
m_lineno(lineno),
m_pJSContext(pJSContext),
m_pScript(0)
{
}
AVGJSScript::~AVGJSScript()
{
if (m_pScript) {
JS_DestroyScript(m_pJSContext, m_pScript);
}
}
extern "C" {
// From mozilla/js/jsexn.h
extern JSBool
js_ReportUncaughtException(JSContext *cx);
}
void AVGJSScript::run()
{
// TODO: Actually, compile() should be called in the constructor. However, if I do this,
// any arguments in the script are null when execute is finally called.
compile();
if (m_pScript) {
jsval Result;
JSBool ok = JS_ExecuteScript(m_pJSContext, m_pObject, m_pScript, &Result);
if (!ok) {
js_ReportUncaughtException(m_pJSContext);
}
}
}
void AVGJSScript::compile()
{
if (m_pScript) {
JS_DestroyScript(m_pJSContext, m_pScript);
} m_pObject = JS_GetGlobalObject(m_pJSContext);
m_pScript = JS_CompileScript(m_pJSContext, m_pObject,
m_code.c_str(), m_code.length(), m_filename.c_str(), m_lineno);
if (!m_pScript) {
js_ReportUncaughtException(m_pJSContext);
}
}
<|endoftext|>
|
<commit_before>#ifndef ALPHA_ARRAYVOXMAP_HEADER
#define ALPHA_ARRAYVOXMAP_HEADER
#include "Vector3.hpp"
#include <vector>
namespace nt {
template <class Voxel>
class ArrayVoxmap
{
std::vector<Voxel> _voxmap;
Vector3<int> _size;
public:
ArrayVoxmap() :
_voxmap(),
_size()
{}
ArrayVoxmap(const Vector3<int>& size) :
_voxmap(size.x() * size.y() * size.z()),
_size(size)
{}
const Vector3<int>& size() const;
Voxel get(const int x, const int y, const int z) const;
void set(const int x, const int y, const int z, const Voxel& voxel);
void resize(const Vector3<int>& size);
};
template <class Voxel>
const Vector3<int>& ArrayVoxmap<Voxel>::size() const
{
return _size;
}
template <class Voxel>
void ArrayVoxmap<Voxel>::resize(const Vector3<int>& size)
{
_voxmap.clear();
_size.set(0, 0, 0);
_voxmap.resize(size.x() * size.y() * size.z());
_size = size;
}
template <class Voxel>
Voxel ArrayVoxmap<Voxel>::get(const int x, const int y, const int z) const
{
return _voxmap.at(x + _size.x() * y + z * _size.x() * _size.y());
}
template <class Voxel>
void ArrayVoxmap<Voxel>::set(const int x, const int y, const int z, const Voxel& voxel)
{
_voxmap.at(x + _size.x() * y + z * _size.x() * _size.y()) = voxel;
}
} // namespace nt
#endif // ALPHA_ARRAYVOXMAP_HEADER
<commit_msg>ArrayVoxmap: Split get(x,y,z) into a const and non-const version<commit_after>#ifndef ALPHA_ARRAYVOXMAP_HEADER
#define ALPHA_ARRAYVOXMAP_HEADER
#include "Vector3.hpp"
#include <vector>
namespace nt {
template <class Voxel>
class ArrayVoxmap
{
std::vector<Voxel> _voxmap;
Vector3<int> _size;
public:
ArrayVoxmap() :
_voxmap(),
_size()
{}
ArrayVoxmap(const Vector3<int>& size) :
_voxmap(size.x() * size.y() * size.z()),
_size(size)
{}
const Vector3<int>& size() const;
Voxel& get(const int x, const int y, const int z);
const Voxel& get(const int x, const int y, const int z) const;
void set(const int x, const int y, const int z, const Voxel& voxel);
void resize(const Vector3<int>& size);
};
template <class Voxel>
const Vector3<int>& ArrayVoxmap<Voxel>::size() const
{
return _size;
}
template <class Voxel>
void ArrayVoxmap<Voxel>::resize(const Vector3<int>& size)
{
_voxmap.clear();
_size.set(0, 0, 0);
_voxmap.resize(size.x() * size.y() * size.z());
_size = size;
}
template <class Voxel>
const Voxel& ArrayVoxmap<Voxel>::get(const int x, const int y, const int z) const
{
return _voxmap.at(x + _size.x() * y + z * _size.x() * _size.y());
}
template <class Voxel>
Voxel& ArrayVoxmap<Voxel>::get(const int x, const int y, const int z)
{
return _voxmap.at(x + _size.x() * y + z * _size.x() * _size.y());
}
template <class Voxel>
void ArrayVoxmap<Voxel>::set(const int x, const int y, const int z, const Voxel& voxel)
{
get(x, y, z) = voxel;
}
} // namespace nt
#endif // ALPHA_ARRAYVOXMAP_HEADER
<|endoftext|>
|
<commit_before><commit_msg>If the HTTP response code is -1, don't call OCSPSetResponse because the request failed and there is no response. This fixes the crashes in OCSPTrySendAndReceive.<commit_after><|endoftext|>
|
<commit_before>/*
* RBBallCamera.cpp
* golf
*
* Created by Robert Rose on 9/14/08.
* Copyright 2008 Bork 3D LLC. All rights reserved.
*
*/
#include "RBBallCamera.h"
RBBallCamera::RBBallCamera()
: m_ball(0)
, m_terrain(0)
, m_height(0.0f)
, m_guide(0.0f, 0.0f, 0.0f)
, m_desiredGuide(0.0f, 0.0f, 0.0f)
, m_desiredHeight(0.0f)
, m_yaw(0.0f)
, m_smooth(false)
{
}
void RBBallCamera::SetTrackMode(eTrackMode mode)
{
eTrackMode prevmode = m_mode;
m_mode = mode;
btVector3 ball = m_ball->GetPosition();
m_halffov = (16.0f / 180.0f) * 3.1415926f;
switch(m_mode)
{
case kHitCamera:
{
if(prevmode == kPuttCamera)
m_smooth = true;
else
m_smooth = false;
}
break;
case kPuttCamera:
{
if(prevmode == kHitCamera)
m_smooth = true;
else
m_smooth = false;
}
break;
case kRegardCamera:
{
btVector3 forward = m_desiredGuide - ball;
forward.setY(0);
forward.normalize();
const float kBaseHeight = 25.0f;
const float kBaseDist = 40.0f;
m_pos = ball - ((kBaseDist) * forward) + btVector3(0,kBaseHeight,0);
}
break;
case kPlacementCamera:
m_lookAt = ball;
break;
}
}
void RBBallCamera::NextFrame(float delta)
{
const float kMaxFrameTime = 1.0f / 10.0f;
if(delta > kMaxFrameTime)
delta = kMaxFrameTime;
btVector3 ball = m_ball->GetPosition();
btVector3 ballvel = m_ball->GetLinearVelocity();
switch(m_mode)
{
default:
case kNone:
{
m_pos = btVector3(0,0,-1);
m_lookAt = btVector3(0,0,0);
}
break;
case kHitCamera:
{
float desiredHeight = m_desiredHeight * 50.0f;
m_height += (desiredHeight - m_height) * delta * 3.0f;
m_guide += (m_desiredGuide - m_guide) * delta * 6.0f;
btVector3 forward = m_guide - ball;
forward.setY(0);
forward.normalize();
const float kBaseHeight = 12.0f;
const float kBaseDist = 18.0f;
btVector3 pos = ball - ((m_height + kBaseDist) * forward) + btVector3(0, kBaseHeight + m_height,0);
btVector3 lookAt = ball + ((m_height + kBaseDist * 2.0f) * forward);
if(m_smooth)
{
m_pos += (pos - m_pos) * delta * 3.0f;
m_lookAt += (lookAt - m_lookAt) * delta * 3.0f;
}
else
{
m_pos = pos;
m_lookAt = lookAt;
}
}
break;
case kPuttCamera:
{
float desiredHeight = m_desiredHeight * 10.0f;
m_height += (desiredHeight - m_height) * delta * 3.0f;
btVector3 forward = m_desiredGuide - ball;
forward.setY(0);
forward.normalize();
const float kBaseHeight = 12.0f;
const float kBaseDist = 18.0f;
//btVector3 pos = ball + ((m_height * 1.0f - kBaseDist) * forward) + btVector3(0,kBaseHeight + 4.0f * m_height,0);
//btVector3 lookAt = ball + ((m_height * -6.0f + kBaseDist * 2.0f) * forward);
btVector3 pos = ball - ((m_height + kBaseDist) * forward) + btVector3(0,kBaseHeight + m_height,0);
btVector3 lookAt = ball + ((m_height * -3.0f + kBaseDist * 2.0f) * forward);
if(m_smooth)
{
m_pos += (pos - m_pos) * delta * 3.0f;
m_lookAt += (lookAt - m_lookAt) * delta * 3.0f;
}
else
{
m_pos = pos;
m_lookAt = lookAt;
}
}
break;
case kAimCamera:
{
float height = 75.0f * m_desiredHeight;
m_lookAt += (m_desiredGuide - m_lookAt) * delta * 3.0f;
btVector3 offset(0,height + 5.0f,18 + height);
btMatrix3x3 rot;
rot.setEulerYPR(m_yaw, 0.0f, 0.0f);
offset = rot * offset;
btVector3 newpos = m_desiredGuide + offset;
m_pos += (newpos - m_pos) * delta * 3.0f;
}
break;
case kAfterShotCamera:
{
// slowly lean toward the ball
m_lookAt += (ball - m_lookAt) * delta * 1.0f;
}
break;
case kFollowCamera:
{
m_lookAt = ball;
m_pos = m_lookAt + btVector3(0,20,20);
}
break;
case kPlacementCamera:
{
//ballvel.setY(0.0f);
//btVector3 lookat = ball + ballvel * 0.5f;
const float kSpeedThreshold = 40.0f;
const float kMinFOV = 8.0f;
const float kMaxFOV = 16.0f;
float ballspeed = ballvel.length();
if(ballspeed > kSpeedThreshold)
ballspeed = kSpeedThreshold;
ballspeed /= kSpeedThreshold;
ballspeed = 1.0f - ballspeed;
ballspeed *= (kMaxFOV - kMinFOV);
float halffov = kMaxFOV - ballspeed;
m_halffov += (((halffov / 180.0f) * 3.1415926f) - m_halffov) * delta * 1.0f;
m_lookAt += (ball - m_lookAt) * delta * 3.0f;
m_pos = m_desiredGuide;
}
break;
case kRegardCamera:
{
btVector3 forward = m_desiredGuide - ball;
//float len = forward.length();
forward.normalize();
float halffov = (32.0f / 180.0f) * 3.1415926f;
const float kBaseHeight = 16.0f;
float dist = 20.0f;
forward.setY(0);
forward.normalize();
btVector3 back = forward * -dist;
back.setY(kBaseHeight);
m_pos = ball + back;
//m_pos += (pos - m_pos) * delta * 1.0f;
btVector3 ac = ball - m_pos;
ac.normalize();
btVector3 zaxis = cross(ac, btVector3(0,1,0));
btQuaternion q(zaxis, halffov);
btVector3 angle = q * ac;
m_lookAt = angle + m_pos;
}
break;
}
}
<commit_msg>added motion cutoff to camera movement<commit_after>/*
* RBBallCamera.cpp
* golf
*
* Created by Robert Rose on 9/14/08.
* Copyright 2008 Bork 3D LLC. All rights reserved.
*
*/
#include "RBBallCamera.h"
RBBallCamera::RBBallCamera()
: m_ball(0)
, m_terrain(0)
, m_height(0.0f)
, m_guide(0.0f, 0.0f, 0.0f)
, m_desiredGuide(0.0f, 0.0f, 0.0f)
, m_desiredHeight(0.0f)
, m_yaw(0.0f)
, m_smooth(false)
{
}
void RBBallCamera::SetTrackMode(eTrackMode mode)
{
eTrackMode prevmode = m_mode;
m_mode = mode;
btVector3 ball = m_ball->GetPosition();
m_halffov = (16.0f / 180.0f) * 3.1415926f;
switch(m_mode)
{
case kHitCamera:
{
if(prevmode == kPuttCamera)
m_smooth = true;
else
m_smooth = false;
}
break;
case kPuttCamera:
{
if(prevmode == kHitCamera)
m_smooth = true;
else
m_smooth = false;
}
break;
case kRegardCamera:
{
btVector3 forward = m_desiredGuide - ball;
forward.setY(0);
forward.normalize();
const float kBaseHeight = 25.0f;
const float kBaseDist = 40.0f;
m_pos = ball - ((kBaseDist) * forward) + btVector3(0,kBaseHeight,0);
}
break;
case kPlacementCamera:
m_lookAt = ball;
break;
}
}
void RBBallCamera::NextFrame(float delta)
{
const float kMaxFrameTime = 1.0f / 10.0f;
if(delta > kMaxFrameTime)
delta = kMaxFrameTime;
btVector3 ball = m_ball->GetPosition();
btVector3 ballvel = m_ball->GetLinearVelocity();
switch(m_mode)
{
default:
case kNone:
{
m_pos = btVector3(0,0,-1);
m_lookAt = btVector3(0,0,0);
}
break;
case kHitCamera:
{
float desiredHeight = m_desiredHeight * 50.0f;
if(fabs(desiredHeight - m_height) > 0.01f)
m_height += (desiredHeight - m_height) * delta * 3.0f;
else
m_height = desiredHeight;
if((m_desiredGuide - m_guide).length2() > 0.1f)
m_guide += (m_desiredGuide - m_guide) * delta * 6.0f;
else
m_guide = m_desiredGuide;
btVector3 forward = m_guide - ball;
forward.setY(0);
forward.normalize();
const float kBaseHeight = 12.0f;
const float kBaseDist = 18.0f;
btVector3 pos = ball - ((m_height + kBaseDist) * forward) + btVector3(0, kBaseHeight + m_height,0);
btVector3 lookAt = ball + ((m_height + kBaseDist * 2.0f) * forward);
if(m_smooth)
{
m_pos += (pos - m_pos) * delta * 3.0f;
m_lookAt += (lookAt - m_lookAt) * delta * 3.0f;
}
else
{
m_pos = pos;
m_lookAt = lookAt;
}
}
break;
case kPuttCamera:
{
float desiredHeight = m_desiredHeight * 10.0f;
m_height += (desiredHeight - m_height) * delta * 3.0f;
btVector3 forward = m_desiredGuide - ball;
forward.setY(0);
forward.normalize();
const float kBaseHeight = 12.0f;
const float kBaseDist = 18.0f;
//btVector3 pos = ball + ((m_height * 1.0f - kBaseDist) * forward) + btVector3(0,kBaseHeight + 4.0f * m_height,0);
//btVector3 lookAt = ball + ((m_height * -6.0f + kBaseDist * 2.0f) * forward);
btVector3 pos = ball - ((m_height + kBaseDist) * forward) + btVector3(0,kBaseHeight + m_height,0);
btVector3 lookAt = ball + ((m_height * -3.0f + kBaseDist * 2.0f) * forward);
if(m_smooth)
{
m_pos += (pos - m_pos) * delta * 3.0f;
m_lookAt += (lookAt - m_lookAt) * delta * 3.0f;
}
else
{
m_pos = pos;
m_lookAt = lookAt;
}
}
break;
case kAimCamera:
{
float height = 75.0f * m_desiredHeight;
m_lookAt += (m_desiredGuide - m_lookAt) * delta * 3.0f;
btVector3 offset(0,height + 5.0f,18 + height);
btMatrix3x3 rot;
rot.setEulerYPR(m_yaw, 0.0f, 0.0f);
offset = rot * offset;
btVector3 newpos = m_desiredGuide + offset;
m_pos += (newpos - m_pos) * delta * 3.0f;
}
break;
case kAfterShotCamera:
{
// slowly lean toward the ball
m_lookAt += (ball - m_lookAt) * delta * 1.0f;
}
break;
case kFollowCamera:
{
m_lookAt = ball;
m_pos = m_lookAt + btVector3(0,20,20);
}
break;
case kPlacementCamera:
{
//ballvel.setY(0.0f);
//btVector3 lookat = ball + ballvel * 0.5f;
const float kSpeedThreshold = 40.0f;
const float kMinFOV = 8.0f;
const float kMaxFOV = 16.0f;
float ballspeed = ballvel.length();
if(ballspeed > kSpeedThreshold)
ballspeed = kSpeedThreshold;
ballspeed /= kSpeedThreshold;
ballspeed = 1.0f - ballspeed;
ballspeed *= (kMaxFOV - kMinFOV);
float halffov = kMaxFOV - ballspeed;
m_halffov += (((halffov / 180.0f) * 3.1415926f) - m_halffov) * delta * 1.0f;
m_lookAt += (ball - m_lookAt) * delta * 3.0f;
m_pos = m_desiredGuide;
}
break;
case kRegardCamera:
{
btVector3 forward = m_desiredGuide - ball;
//float len = forward.length();
forward.normalize();
float halffov = (32.0f / 180.0f) * 3.1415926f;
const float kBaseHeight = 16.0f;
float dist = 20.0f;
forward.setY(0);
forward.normalize();
btVector3 back = forward * -dist;
back.setY(kBaseHeight);
m_pos = ball + back;
//m_pos += (pos - m_pos) * delta * 1.0f;
btVector3 ac = ball - m_pos;
ac.normalize();
btVector3 zaxis = cross(ac, btVector3(0,1,0));
btQuaternion q(zaxis, halffov);
btVector3 angle = q * ac;
m_lookAt = angle + m_pos;
}
break;
}
}
<|endoftext|>
|
<commit_before>#include "glcore.hpp"
#include <GL/gl3w.h>
#include <string>
#include <Scene/scene.hpp>
#include <Utilities/exceptions.hpp>
#include <Utilities/log.hpp>
// TODO Find a way to list all available scenes (./Resources/Scenes/[These folders are scenes])
GLCore::GLCore(int width, int height, std::string scene) {
m_display = std::make_unique<const Display>(width, height);
// Log information about current context
Log::getLog() << "\nInformation: \n";
Log::getLog() << "\tGL Version: " << glGetString(GL_VERSION) << '\n';
Log::getLog() << "\tDisplay Address: " << m_display.get() << "\n\n";
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDepthFunc(GL_LESS);
glClearColor(0.0f, 0.1f, 0.0f, 0.0f);
Log::getLog() << Log::OUT_LOG << "GL Context created\n";
Log::getLog() << Log::OUT_LOG_CONS;
initScene(scene);
m_scene->start();
}
GLCore::~GLCore() {
closeScene();
}
void GLCore::displayFunc() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_scene->gameLoop();
m_display->getInputController()->callKeyLambdas();
}
void GLCore::inputFunc(int key, bool state) {
m_display->getInputController()->updateKey(key, state);
}
void GLCore::mouseFunc(double xpos, double ypos) {
m_display->getInputController()->updateMousePosition(xpos, ypos);
}
void GLCore::initScene(std::string scene) {
m_luaState = luaL_newstate();
luaL_openlibs(m_luaState);
m_scene = std::make_unique<Scene>(m_display.get(), m_luaState, scene);
}
void GLCore::closeScene() {
m_scene.reset(nullptr);
lua_close(m_luaState);
}
<commit_msg>changed clear color to black<commit_after>#include "glcore.hpp"
#include <GL/gl3w.h>
#include <string>
#include <Scene/scene.hpp>
#include <Utilities/exceptions.hpp>
#include <Utilities/log.hpp>
// TODO Find a way to list all available scenes (./Resources/Scenes/[These folders are scenes])
GLCore::GLCore(int width, int height, std::string scene) {
m_display = std::make_unique<const Display>(width, height);
// Log information about current context
Log::getLog() << "\nInformation: \n";
Log::getLog() << "\tGL Version: " << glGetString(GL_VERSION) << '\n';
Log::getLog() << "\tDisplay Address: " << m_display.get() << "\n\n";
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDepthFunc(GL_LESS);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
Log::getLog() << Log::OUT_LOG << "GL Context created\n";
Log::getLog() << Log::OUT_LOG_CONS;
initScene(scene);
m_scene->start();
}
GLCore::~GLCore() {
closeScene();
}
void GLCore::displayFunc() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_scene->gameLoop();
m_display->getInputController()->callKeyLambdas();
}
void GLCore::inputFunc(int key, bool state) {
m_display->getInputController()->updateKey(key, state);
}
void GLCore::mouseFunc(double xpos, double ypos) {
m_display->getInputController()->updateMousePosition(xpos, ypos);
}
void GLCore::initScene(std::string scene) {
m_luaState = luaL_newstate();
luaL_openlibs(m_luaState);
m_scene = std::make_unique<Scene>(m_display.get(), m_luaState, scene);
}
void GLCore::closeScene() {
m_scene.reset(nullptr);
lua_close(m_luaState);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkListSampleTest.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
#include "itkArray.h"
#include "itkListSample.h"
int itkListSampleTest(int argc, char *argv[] )
{
std::cout << "ListSample Test \n \n";
if( argc< 2 )
{
std::cerr << "itkListSampleTest LengthOfMeasurementVector" << std::endl;
}
typedef itk::Array< float > MeasurementVectorType ;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;
SampleType::MeasurementVectorSizeType measurementVectorSize = atoi(argv[1]);
std::cerr << "Measurement vector size: " << measurementVectorSize
<< std::endl;
unsigned int sampleSize = 25;
SampleType::Pointer sample = SampleType::New() ;
sample->SetMeasurementVectorSize( measurementVectorSize );
MeasurementVectorType mv( measurementVectorSize ) ;
for ( unsigned int i = 0 ; i < sampleSize ; i++ )
{
for (unsigned int j = 0 ; j < measurementVectorSize ; j++ )
{
mv[j] = rand() / (RAND_MAX+1.0) ;
}
sample->PushBack(mv) ;
}
// tests begin
//
// general interface
//
std::cerr << "General interface..." << std::endl;
if ( sampleSize != sample->Size() )
{
std::cerr << "Size() failed" << std::endl;
return EXIT_FAILURE;
}
if (sample->GetMeasurementVectorSize() != measurementVectorSize)
{
std::cerr << "GetMeasurementVectorSize() failed" << std::endl;
return EXIT_FAILURE;
}
// get and set measurements
mv = sample->GetMeasurementVector(4) ;
if ( mv != sample->GetMeasurementVector(4) )
{
std::cerr << "GetMeasurementVector failed" << std::endl;
return EXIT_FAILURE;
}
float tmp = mv[0];
mv[0] += 1.0;
sample->SetMeasurementVector(4,mv);
if (mv != sample->GetMeasurementVector(4))
{
std::cerr << "SetMeasurementVector failed" << std::endl;
return EXIT_FAILURE;
}
mv[0] = tmp;
sample->SetMeasurement(4,0,tmp);
if (mv != sample->GetMeasurementVector(4))
{
std::cerr << "SetMeasurement failed" << std::endl;
return EXIT_FAILURE;
}
// frequency
if (sample->GetTotalFrequency() != sampleSize)
{
std::cerr << "GetTotalFrequency failed" << std::endl;
return EXIT_FAILURE;
}
//
// iterator tests
//
std::cerr << "Iterators..." << std::endl;
{
// forward iterator
SampleType::Iterator s_iter = sample->Begin() ;
// copy constructor
SampleType::Iterator bs_iter(s_iter);
if (bs_iter != s_iter)
{
std::cerr << "Iterator::Copy Constructor failed" << std::endl;
return EXIT_FAILURE;
}
SampleType::InstanceIdentifier id = 0 ;
while (s_iter != sample->End())
{
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (s_iter.GetFrequency() != 1)
{
std::cerr << "Iterator::GetFrequency (forward) failed" << std::endl;
return EXIT_FAILURE;
}
if (sample->GetFrequency(id) != 1)
{
std::cerr << "GetFrequency (forward) failed" << std::endl;
return EXIT_FAILURE;
}
++id ;
++s_iter ;
}
if (s_iter != sample->End())
{
std::cerr << "Iterator::End (forward) failed" << std::endl;
return EXIT_FAILURE;
}
// backwards iterator
do
{
--s_iter;
--id;
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
} while (!(s_iter == sample->Begin())); // explicitly test ==
if (!(s_iter == sample->Begin()))
{
std::cerr << "Iterator::Begin (backward) failed" << std::endl;
return EXIT_FAILURE;
}
}
// ConstIterator test
std::cerr << "Const Iterators..." << std::endl;
{
// forward iterator
SampleType::ConstIterator s_iter = sample->Begin() ;
// copy constructor
SampleType::ConstIterator bs_iter(s_iter);
if (bs_iter != s_iter)
{
std::cerr << "Iterator::Copy Constructor (from const) failed"
<< std::endl;
return EXIT_FAILURE;
}
// copy from non-const iterator
SampleType::Iterator nonconst_iter = sample->Begin();
SampleType::ConstIterator s2_iter(nonconst_iter);
if (s2_iter != s_iter)
{
std::cerr << "Iterator::Copy Constructor (from non-const) failed"
<< std::endl;
return EXIT_FAILURE;
}
// assignment from non-const iterator
s2_iter = nonconst_iter;
if (s2_iter != s_iter)
{
std::cerr << "Iterator::assignment (from non-const) failed" << std::endl;
return EXIT_FAILURE;
}
SampleType::InstanceIdentifier id = 0 ;
while (s_iter != sample->End())
{
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (s_iter.GetFrequency() != 1)
{
std::cerr << "Iterator::GetFrequency (forward) failed" << std::endl;
return EXIT_FAILURE;
}
++id ;
++s_iter ;
}
if (s_iter != sample->End())
{
std::cerr << "Iterator::End (forward) failed" << std::endl;
return EXIT_FAILURE;
}
// backwards iterator
do
{
--s_iter;
--id;
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
} while (!(s_iter == sample->Begin())); // explicitly test ==
if (!(s_iter == sample->Begin()))
{
std::cerr << "Iterator::Begin (backward) failed" << std::endl;
return EXIT_FAILURE;
}
}
std::cerr << "Search..." << std::endl;
SampleType::SearchResultVectorType searchResult ;
sample->Search(sample->GetMeasurementVector(sampleSize/2), 0.01,
searchResult) ;
//
// resizing
//
sample->Clear();
if (sample->Size() != 0)
{
std::cerr << "Clear() failed" << std::endl;
return EXIT_FAILURE;
}
sample->Resize(sampleSize);
if (sample->Size() != sampleSize)
{
std::cerr << "Resize() failed" << std::endl;
return EXIT_FAILURE;
}
//
// test a list sample of scalars
//
typedef float ScalarMeasurementVectorType;
typedef itk::Statistics::ListSample<ScalarMeasurementVectorType>
ScalarSampleType;
ScalarSampleType::Pointer scalarSample = ScalarSampleType::New();
ScalarMeasurementVectorType correctSum = 0;
for (unsigned int i = 0; i < sampleSize; ++i)
{
scalarSample->PushBack(i);
correctSum += i;
}
ScalarSampleType::ConstIterator scalarSampleIter = scalarSample->Begin();
ScalarMeasurementVectorType sum = 0;
for (; scalarSampleIter != scalarSample->End(); ++scalarSampleIter)
{
sum += scalarSampleIter.GetMeasurementVector();
}
if (sum != correctSum)
{
std::cerr << "Scalar sample failed" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>COMP: removed experimental test code<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkListSampleTest.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
#include "itkArray.h"
#include "itkListSample.h"
int itkListSampleTest(int argc, char *argv[] )
{
std::cout << "ListSample Test \n \n";
if( argc< 2 )
{
std::cerr << "itkListSampleTest LengthOfMeasurementVector" << std::endl;
}
typedef itk::Array< float > MeasurementVectorType ;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;
SampleType::MeasurementVectorSizeType measurementVectorSize = atoi(argv[1]);
std::cerr << "Measurement vector size: " << measurementVectorSize
<< std::endl;
unsigned int sampleSize = 25;
SampleType::Pointer sample = SampleType::New() ;
sample->SetMeasurementVectorSize( measurementVectorSize );
MeasurementVectorType mv( measurementVectorSize ) ;
for ( unsigned int i = 0 ; i < sampleSize ; i++ )
{
for (unsigned int j = 0 ; j < measurementVectorSize ; j++ )
{
mv[j] = rand() / (RAND_MAX+1.0) ;
}
sample->PushBack(mv) ;
}
// tests begin
//
// general interface
//
std::cerr << "General interface..." << std::endl;
if ( sampleSize != sample->Size() )
{
std::cerr << "Size() failed" << std::endl;
return EXIT_FAILURE;
}
if (sample->GetMeasurementVectorSize() != measurementVectorSize)
{
std::cerr << "GetMeasurementVectorSize() failed" << std::endl;
return EXIT_FAILURE;
}
// get and set measurements
mv = sample->GetMeasurementVector(4) ;
if ( mv != sample->GetMeasurementVector(4) )
{
std::cerr << "GetMeasurementVector failed" << std::endl;
return EXIT_FAILURE;
}
float tmp = mv[0];
mv[0] += 1.0;
sample->SetMeasurementVector(4,mv);
if (mv != sample->GetMeasurementVector(4))
{
std::cerr << "SetMeasurementVector failed" << std::endl;
return EXIT_FAILURE;
}
mv[0] = tmp;
sample->SetMeasurement(4,0,tmp);
if (mv != sample->GetMeasurementVector(4))
{
std::cerr << "SetMeasurement failed" << std::endl;
return EXIT_FAILURE;
}
// frequency
if (sample->GetTotalFrequency() != sampleSize)
{
std::cerr << "GetTotalFrequency failed" << std::endl;
return EXIT_FAILURE;
}
//
// iterator tests
//
std::cerr << "Iterators..." << std::endl;
{
// forward iterator
SampleType::Iterator s_iter = sample->Begin() ;
// copy constructor
SampleType::Iterator bs_iter(s_iter);
if (bs_iter != s_iter)
{
std::cerr << "Iterator::Copy Constructor failed" << std::endl;
return EXIT_FAILURE;
}
SampleType::InstanceIdentifier id = 0 ;
while (s_iter != sample->End())
{
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (s_iter.GetFrequency() != 1)
{
std::cerr << "Iterator::GetFrequency (forward) failed" << std::endl;
return EXIT_FAILURE;
}
if (sample->GetFrequency(id) != 1)
{
std::cerr << "GetFrequency (forward) failed" << std::endl;
return EXIT_FAILURE;
}
++id ;
++s_iter ;
}
if (s_iter != sample->End())
{
std::cerr << "Iterator::End (forward) failed" << std::endl;
return EXIT_FAILURE;
}
// backwards iterator
do
{
--s_iter;
--id;
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
} while (!(s_iter == sample->Begin())); // explicitly test ==
if (!(s_iter == sample->Begin()))
{
std::cerr << "Iterator::Begin (backward) failed" << std::endl;
return EXIT_FAILURE;
}
}
// ConstIterator test
std::cerr << "Const Iterators..." << std::endl;
{
// forward iterator
SampleType::ConstIterator s_iter = sample->Begin() ;
// copy constructor
SampleType::ConstIterator bs_iter(s_iter);
if (bs_iter != s_iter)
{
std::cerr << "Iterator::Copy Constructor (from const) failed"
<< std::endl;
return EXIT_FAILURE;
}
// copy from non-const iterator
SampleType::Iterator nonconst_iter = sample->Begin();
SampleType::ConstIterator s2_iter(nonconst_iter);
if (s2_iter != s_iter)
{
std::cerr << "Iterator::Copy Constructor (from non-const) failed"
<< std::endl;
return EXIT_FAILURE;
}
// assignment from non-const iterator
s2_iter = nonconst_iter;
if (s2_iter != s_iter)
{
std::cerr << "Iterator::assignment (from non-const) failed" << std::endl;
return EXIT_FAILURE;
}
SampleType::InstanceIdentifier id = 0 ;
while (s_iter != sample->End())
{
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (forward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (s_iter.GetFrequency() != 1)
{
std::cerr << "Iterator::GetFrequency (forward) failed" << std::endl;
return EXIT_FAILURE;
}
++id ;
++s_iter ;
}
if (s_iter != sample->End())
{
std::cerr << "Iterator::End (forward) failed" << std::endl;
return EXIT_FAILURE;
}
// backwards iterator
do
{
--s_iter;
--id;
if (sample->GetMeasurementVector(id) !=
s_iter.GetMeasurementVector())
{
std::cerr << "Iterator::GetMeasurementVector (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
if (id != s_iter.GetInstanceIdentifier())
{
std::cerr << "Iterator::GetInstanceIdentifier (backward) failed"
<< std::endl;
return EXIT_FAILURE;
}
} while (!(s_iter == sample->Begin())); // explicitly test ==
if (!(s_iter == sample->Begin()))
{
std::cerr << "Iterator::Begin (backward) failed" << std::endl;
return EXIT_FAILURE;
}
}
std::cerr << "Search..." << std::endl;
SampleType::SearchResultVectorType searchResult ;
sample->Search(sample->GetMeasurementVector(sampleSize/2), 0.01,
searchResult) ;
//
// resizing
//
sample->Clear();
if (sample->Size() != 0)
{
std::cerr << "Clear() failed" << std::endl;
return EXIT_FAILURE;
}
sample->Resize(sampleSize);
if (sample->Size() != sampleSize)
{
std::cerr << "Resize() failed" << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|>
|
<commit_before>#ifndef MISC_UI_HPP
#define MISC_UI_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include <map>
#include <utility>
#include "Settings.hpp"
#include "Log.hpp"
/// Macro to build std::wstring that slic3r::log expects using << syntax of wxString
/// Avoids wx pollution of libslic3r
#define LOG_WSTRING(...) ((wxString("") << __VA_ARGS__).ToStdWstring())
/// Common static (that is, free-standing) functions, not part of an object hierarchy.
namespace Slic3r { namespace GUI {
enum class OS { Linux, Mac, Windows } ;
// constants to reduce the proliferation of macros in the rest of the code
#ifdef __WIN32
constexpr OS the_os = OS::Windows;
#elif __APPLE__
constexpr OS the_os = OS::Mac;
#elif __linux__
constexpr OS the_os = OS::Linux;
#ifdef __WXGTK__
constexpr bool wxGTK {true};
#else
constexpr bool wxGTK {false};
#endif
#endif
#ifdef SLIC3R_DEV
constexpr bool isDev = true;
#else
constexpr bool isDev = false;
#endif
// hopefully the compiler is smart enough to figure this out
const std::map<const std::string, const std::string> FILE_WILDCARDS {
std::make_pair("known", "Known files (*.stl, *.obj, *.amf, *.xml, *.3mf)|*.3mf;*.3MF;*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("stl", "STL files (*.stl)|*.stl;*.STL"),
std::make_pair("obj", "OBJ files (*.obj)|*.obj;*.OBJ"),
std::make_pair("amf", "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("tmf", "3MF files (*.3mf)|*.3mf;*.3MF"),
std::make_pair("ini", "INI files *.ini|*.ini;*.INI"),
std::make_pair("gcode", "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC"),
std::make_pair("svg", "SVG files *.svg|*.svg;*.SVG")
};
const std::string MODEL_WILDCARD { FILE_WILDCARDS.at("known") + std::string("|") + FILE_WILDCARDS.at("stl")+ std::string("|") + FILE_WILDCARDS.at("obj") + std::string("|") + FILE_WILDCARDS.at("amf")+ std::string("|") + FILE_WILDCARDS.at("tmf")};
const std::string STL_MODEL_WILDCARD { FILE_WILDCARDS.at("stl") };
const std::string AMF_MODEL_WILDCARD { FILE_WILDCARDS.at("amf") };
const std::string TMF_MODEL_WILDCARD { FILE_WILDCARDS.at("tmf") };
/// Mostly useful for Linux distro maintainers, this will change where Slic3r assumes
/// its ./var directory lives (where its art assets are).
/// Define VAR_ABS and VAR_ABS_PATH
#ifndef VAR_ABS
#define VAR_ABS false
#else
#define VAR_ABS true
#endif
#ifndef VAR_ABS_PATH
#define VAR_ABS_PATH "/usr/share/Slic3r/var"
#endif
#ifndef VAR_REL // Redefine on compile
#define VAR_REL L"/../var"
#endif
/// Performs a check via the Internet for a new version of Slic3r.
/// If this version of Slic3r was compiled with -DSLIC3R_DEV, check the development
/// space instead of release.
void check_version(bool manual = false);
/// Provides a path to Slic3r's var dir.
const wxString var(const wxString& in);
/// Provide a path to where Slic3r exec'd from.
const wxString bin();
/// Always returns path to home directory.
const wxString home(const wxString& in = "Slic3r");
/// Shows an error messagebox
void show_error(wxWindow* parent, const wxString& message);
/// Shows an info messagebox.
void show_info(wxWindow* parent, const wxString& message, const wxString& title);
/// Show an error messagebox and then throw an exception.
void fatal_error(wxWindow* parent, const wxString& message);
template <typename T>
void append_menu_item(wxMenu* menu, const wxString& name,const wxString& help, T lambda, int id = wxID_ANY, const wxString& icon = "", const wxString& accel = "") {
wxMenuItem* tmp = menu->Append(wxID_ANY, name, help);
wxAcceleratorEntry* a = new wxAcceleratorEntry();
if (!accel.IsEmpty()) {
a->FromString(accel);
tmp->SetAccel(a); // set the accelerator if and only if the accelerator is fine
}
tmp->SetHelp(help);
if (!icon.IsEmpty())
tmp->SetBitmap(wxBitmap(var(icon)));
if (typeid(lambda) != typeid(nullptr))
menu->Bind(wxEVT_MENU, lambda, tmp->GetId(), tmp->GetId());
}
/*
sub CallAfter {
my ($self, $cb) = @_;
push @cb, $cb;
}
*/
wxString decode_path(const wxString& in);
wxString encode_path(const wxString& in);
std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top);
}} // namespace Slic3r::GUI
#endif // MISC_UI_HPP
<commit_msg>stubbed in constant for turning on/off threading (mostly to reduce complexity when testing feature code)<commit_after>#ifndef MISC_UI_HPP
#define MISC_UI_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include <map>
#include <utility>
#include "Settings.hpp"
#include "Log.hpp"
/// Macro to build std::wstring that slic3r::log expects using << syntax of wxString
/// Avoids wx pollution of libslic3r
#define LOG_WSTRING(...) ((wxString("") << __VA_ARGS__).ToStdWstring())
/// Common static (that is, free-standing) functions, not part of an object hierarchy.
namespace Slic3r { namespace GUI {
enum class OS { Linux, Mac, Windows } ;
// constants to reduce the proliferation of macros in the rest of the code
#ifdef __WIN32
constexpr OS the_os = OS::Windows;
#elif __APPLE__
constexpr OS the_os = OS::Mac;
#elif __linux__
constexpr OS the_os = OS::Linux;
#ifdef __WXGTK__
constexpr bool wxGTK {true};
#else
constexpr bool wxGTK {false};
#endif
#endif
#ifdef SLIC3R_DEV
constexpr bool isDev = true;
#else
constexpr bool isDev = false;
#endif
constexpr bool threaded = false;
// hopefully the compiler is smart enough to figure this out
const std::map<const std::string, const std::string> FILE_WILDCARDS {
std::make_pair("known", "Known files (*.stl, *.obj, *.amf, *.xml, *.3mf)|*.3mf;*.3MF;*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("stl", "STL files (*.stl)|*.stl;*.STL"),
std::make_pair("obj", "OBJ files (*.obj)|*.obj;*.OBJ"),
std::make_pair("amf", "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("tmf", "3MF files (*.3mf)|*.3mf;*.3MF"),
std::make_pair("ini", "INI files *.ini|*.ini;*.INI"),
std::make_pair("gcode", "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC"),
std::make_pair("svg", "SVG files *.svg|*.svg;*.SVG")
};
const std::string MODEL_WILDCARD { FILE_WILDCARDS.at("known") + std::string("|") + FILE_WILDCARDS.at("stl")+ std::string("|") + FILE_WILDCARDS.at("obj") + std::string("|") + FILE_WILDCARDS.at("amf")+ std::string("|") + FILE_WILDCARDS.at("tmf")};
const std::string STL_MODEL_WILDCARD { FILE_WILDCARDS.at("stl") };
const std::string AMF_MODEL_WILDCARD { FILE_WILDCARDS.at("amf") };
const std::string TMF_MODEL_WILDCARD { FILE_WILDCARDS.at("tmf") };
/// Mostly useful for Linux distro maintainers, this will change where Slic3r assumes
/// its ./var directory lives (where its art assets are).
/// Define VAR_ABS and VAR_ABS_PATH
#ifndef VAR_ABS
#define VAR_ABS false
#else
#define VAR_ABS true
#endif
#ifndef VAR_ABS_PATH
#define VAR_ABS_PATH "/usr/share/Slic3r/var"
#endif
#ifndef VAR_REL // Redefine on compile
#define VAR_REL L"/../var"
#endif
/// Performs a check via the Internet for a new version of Slic3r.
/// If this version of Slic3r was compiled with -DSLIC3R_DEV, check the development
/// space instead of release.
void check_version(bool manual = false);
/// Provides a path to Slic3r's var dir.
const wxString var(const wxString& in);
/// Provide a path to where Slic3r exec'd from.
const wxString bin();
/// Always returns path to home directory.
const wxString home(const wxString& in = "Slic3r");
/// Shows an error messagebox
void show_error(wxWindow* parent, const wxString& message);
/// Shows an info messagebox.
void show_info(wxWindow* parent, const wxString& message, const wxString& title);
/// Show an error messagebox and then throw an exception.
void fatal_error(wxWindow* parent, const wxString& message);
template <typename T>
void append_menu_item(wxMenu* menu, const wxString& name,const wxString& help, T lambda, int id = wxID_ANY, const wxString& icon = "", const wxString& accel = "") {
wxMenuItem* tmp = menu->Append(wxID_ANY, name, help);
wxAcceleratorEntry* a = new wxAcceleratorEntry();
if (!accel.IsEmpty()) {
a->FromString(accel);
tmp->SetAccel(a); // set the accelerator if and only if the accelerator is fine
}
tmp->SetHelp(help);
if (!icon.IsEmpty())
tmp->SetBitmap(wxBitmap(var(icon)));
if (typeid(lambda) != typeid(nullptr))
menu->Bind(wxEVT_MENU, lambda, tmp->GetId(), tmp->GetId());
}
/*
sub CallAfter {
my ($self, $cb) = @_;
push @cb, $cb;
}
*/
wxString decode_path(const wxString& in);
wxString encode_path(const wxString& in);
std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top);
}} // namespace Slic3r::GUI
#endif // MISC_UI_HPP
<|endoftext|>
|
<commit_before>#include <iostream>
#include <time.h>
#include <array>
#include "Brick.h"
#include "GameManager.h"
#include "Log.h"
#include "Menu.h"
#include "Timer.h"
#include "levelLoader.h"
GameManager::GameManager(Window* window):
window(window)
{
currentState = STATE_MENU;
_quit = false;
srand(time(NULL));
music = NULL;
bgTexture = window->loadTexture("bg.bmp");
htpTexture = window->loadTexture("HowToPlay.bmp");
paddle = new Entity(window, "paddle.bmp", 305, 490);
entities.push_back(paddle);
currentLevel = 1;
bricksLeft = 0;
maxBricks = 0;
}
void GameManager::initGame()
{
Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096);
std::string resPath = "res";
std::string filePath = "";
filePath = resPath + PATH_SEP + "backgroundmusic.wav";
music = Mix_LoadMUS(filePath.c_str());
if(!music)
printf("Mix_LoadMUS(\"backgroundmusic.wav\"): %s\n", Mix_GetError());
Mix_PlayMusic(music, -1);
paddle->setMoveRate(8);
paddle->setTexture("paddle.bmp");
paddle->setX(305);
paddle->setY(490);
paddle->stopMoving(MOVE_LEFT);
paddle->stopMoving(MOVE_RIGHT);
ball = new Ball(window, "ball.png", window->getWidth() / 2, window->getHeight() / 2, paddle);
ball->setOnPaddle(true);
//used for random powerup spwaning
randNum = rand() % 4;
mod = new Mods(window, "PowerUP.bmp", 305, 0 );//makes a new power down object
upNum = rand() % 2;
downNum = rand() % 2;
entities = std::vector<Entity*>();
entities.push_back(paddle);
LevelLoader* loader = new LevelLoader(this);
switch (currentLevel)
{
case 1:
loader->openMap("lvl1.txt", maxBricks);
break;
case 2:
loader->openMap("lvl2.txt", maxBricks);
break;
default:
currentState = STATE_WINNER;
break;
}
Log::info("Loaded level " + std::to_string(currentLevel) + " with " + std::to_string(maxBricks) + " blocks.");
bricksLeft = maxBricks;
levelOver = false;
}
void GameManager::runGame()
{
Menu mainMenu(this);
mainMenu.addEntry("Play");
mainMenu.addEntry("How to Play");
mainMenu.addEntry("Credits");
mainMenu.addEntry("Exit");
Timer fpsTimer;
Timer capTimer;
uint32_t frameCount = 0;
fpsTimer.start();
while (!_quit)
{
window->clear();
capTimer.start();
switch (currentState)
{
case STATE_MENU:
{
window->renderTexture(bgTexture, 0, 0);
mainMenu.tick();
break;
}
case STATE_HOWTOPLAY:
{
window->renderTexture(htpTexture, 0, 0);
listenForQuit();
break;
}
case STATE_CREDITS:
{
window->renderTexture(bgTexture, 0, 0);
printCredits();
listenForQuit();
break;
}
case STATE_PLAYING:
gameTick();
break;
case STATE_WINNER:
{
window->renderTexture(bgTexture, 0, 0);
window->renderCenteredText("YOU WON!", 100, { 0, 0, 0 }, 75, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Final Score: " + std::to_string(calcScore()), 180, { 0, 0, 0 }, 75, FONT_RENDER_BLENDED, { 0, 0, 0 });
listenForQuit();
break;
}
default:
Log::warn("Recieved unhandled gamestate: " + std::to_string(currentState));
break;
}
// divide the amount of frames displayed by the runtime in seconds to get the average fps
float avgFps = frameCount / (fpsTimer.getTicks() / 1000.f);
if (avgFps > 2000000)
avgFps = 0;
window->renderText(std::to_string((int)avgFps), window->getWidth()-30, 0, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->render();
frameCount++;
// if our fps it too high, wait here until we're back to ~60fps
if (capTimer.getTicks() < (1000 / window->getMaxFps()))
{
int waitTime = (1000 / window->getMaxFps()) - capTimer.getTicks();
SDL_Delay(waitTime);
}
}
}
void GameManager::gameTick()
{
bool repeatKey = SDL_PollEvent(&event) == 1;
if (levelOver)
{
currentLevel++;
initGame();
levelOver = false;
return;
}
if(ball->getLives() < 1)
{
window->renderCenteredText("GAME OVER", window->getHeight()/4, {0,0,0}, 50, FONT_RENDER_BLENDED, {255,255,255});
window->renderCenteredText("Score: " + std::to_string(calcScore()), window->getHeight()/2, {0,0,0}, 50, FONT_RENDER_BLENDED, {255,255,255});
listenForQuit();
return;
}
switch (event.type)
{
// if user clicks the red X
case SDL_QUIT:
_quit = true;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
paddle->startMoving(MOVE_LEFT);
break;
case SDLK_RIGHT:
paddle->startMoving(MOVE_RIGHT);
break;
case SDLK_SPACE:
if (ball->isOnPaddle())
ball->detach();
isPressed = true;
break;
case SDLK_ESCAPE:
if (repeatKey)
{
setState(STATE_MENU);
return;
}
}
break;
case SDL_KEYUP:
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
paddle->stopMoving(MOVE_LEFT);
break;
case SDLK_RIGHT:
paddle->stopMoving(MOVE_RIGHT);
break;
}
break;
}
bool collidedThisTick = false;
for (Entity* e : entities)
{
// don't think this is that cpu intensive but I guess it could be
if ((ball->collidedWith(e)) && (e->isActive())&&collidedThisTick==false)
{
collidedThisTick = true;
ball->handleCollision(e);
if (e->getTypeId() == TYPEID_BRICK)
{
if (!((Brick*)e)->dealDamage(1))
bricksLeft--;
Log::info(std::to_string(bricksLeft) + " / " + std::to_string(maxBricks) + " bricks remaining");
}
}
e->update();
}
/************** Code segment used for powerup implementation ***************/
if(randNum == 0 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
mod->fastPaddle();
paddle->setMoveRate(7);
mod->remove();
}
}
if(randNum == 1 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
paddle->setTexture("paddle_big.bmp");
mod->largePaddle();
mod->remove();
}
}
if(randNum == 2 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
mod->slowerPaddle();
paddle->setMoveRate(3);
mod->remove();
}
}
if(randNum == 3 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
paddle->setTexture("paddle_small.bmp");
mod->smallPaddle();
mod->remove();
}
}
/***************************************************************************/
ball->update();
window->renderText("Lives: " + std::to_string(ball->getLives()), 0, 0, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
if (bricksLeft == 0)
{
levelOver = true;
}
}
void GameManager::addEntity(Entity* e)
{
entities.push_back(e);
}
void GameManager::setState(int state)
{
Log::info("Set state to " + std::to_string(state));
currentState = state;
}
void GameManager::printCredits()
{
window->renderCenteredText("Henry Gordon", 20, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Anthony Brugal", 50, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Iden Sessani", 80, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Erik Higginbotham", 110, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Aaron Hanuschak", 140, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Kurt Weber", 170, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
}
void GameManager::listenForQuit()
{
SDL_Event currEvent;
bool repeatKey = SDL_PollEvent(&currEvent) == 1;
switch (currEvent.type)
{
// if user clicks the red X
case SDL_QUIT:
_quit = true;
return;
case SDL_KEYDOWN:
if (repeatKey)
{
switch (currEvent.key.keysym.sym)
{
case SDLK_SPACE:
case SDLK_RETURN:
case SDLK_ESCAPE:
setState(STATE_MENU);
}
}
}
}
int GameManager::calcScore()
{
return (ball->getLives() + 1) * (maxBricks - bricksLeft);
}
<commit_msg>Try to fix a bug where the paddle would disappear after stopping and starting the game<commit_after>#include <iostream>
#include <time.h>
#include <array>
#include "Brick.h"
#include "GameManager.h"
#include "Log.h"
#include "Menu.h"
#include "Timer.h"
#include "levelLoader.h"
GameManager::GameManager(Window* window):
window(window)
{
currentState = STATE_MENU;
_quit = false;
srand(time(NULL));
music = NULL;
bgTexture = window->loadTexture("bg.bmp");
htpTexture = window->loadTexture("HowToPlay.bmp");
paddle = new Entity(window, "paddle.bmp", 305, 490);
//entities.push_back(paddle);
currentLevel = 1;
bricksLeft = 0;
maxBricks = 0;
}
void GameManager::initGame()
{
Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096);
std::string resPath = "res";
std::string filePath = "";
filePath = resPath + PATH_SEP + "backgroundmusic.wav";
music = Mix_LoadMUS(filePath.c_str());
if(!music)
printf("Mix_LoadMUS(\"backgroundmusic.wav\"): %s\n", Mix_GetError());
Mix_PlayMusic(music, -1);
paddle->setMoveRate(8);
paddle->setTexture("paddle.bmp");
paddle->setX(305);
paddle->setY(490);
paddle->stopMoving(MOVE_LEFT);
paddle->stopMoving(MOVE_RIGHT);
ball = new Ball(window, "ball.png", window->getWidth() / 2, window->getHeight() / 2, paddle);
ball->setOnPaddle(true);
//used for random powerup spwaning
randNum = rand() % 4;
mod = new Mods(window, "PowerUP.bmp", 305, 0 );//makes a new power down object
upNum = rand() % 2;
downNum = rand() % 2;
entities = std::vector<Entity*>();
LevelLoader* loader = new LevelLoader(this);
switch (currentLevel)
{
case 1:
loader->openMap("lvl1.txt", maxBricks);
break;
case 2:
loader->openMap("lvl2.txt", maxBricks);
break;
default:
currentState = STATE_WINNER;
break;
}
Log::info("Loaded level " + std::to_string(currentLevel) + " with " + std::to_string(maxBricks) + " blocks.");
bricksLeft = maxBricks;
levelOver = false;
}
void GameManager::runGame()
{
Menu mainMenu(this);
mainMenu.addEntry("Play");
mainMenu.addEntry("How to Play");
mainMenu.addEntry("Credits");
mainMenu.addEntry("Exit");
Timer fpsTimer;
Timer capTimer;
uint32_t frameCount = 0;
fpsTimer.start();
while (!_quit)
{
window->clear();
capTimer.start();
switch (currentState)
{
case STATE_MENU:
{
window->renderTexture(bgTexture, 0, 0);
mainMenu.tick();
break;
}
case STATE_HOWTOPLAY:
{
window->renderTexture(htpTexture, 0, 0);
listenForQuit();
break;
}
case STATE_CREDITS:
{
window->renderTexture(bgTexture, 0, 0);
printCredits();
listenForQuit();
break;
}
case STATE_PLAYING:
gameTick();
break;
case STATE_WINNER:
{
window->renderTexture(bgTexture, 0, 0);
window->renderCenteredText("YOU WON!", 100, { 0, 0, 0 }, 75, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Final Score: " + std::to_string(calcScore()), 180, { 0, 0, 0 }, 75, FONT_RENDER_BLENDED, { 0, 0, 0 });
listenForQuit();
break;
}
default:
Log::warn("Recieved unhandled gamestate: " + std::to_string(currentState));
break;
}
// divide the amount of frames displayed by the runtime in seconds to get the average fps
float avgFps = frameCount / (fpsTimer.getTicks() / 1000.f);
if (avgFps > 2000000)
avgFps = 0;
window->renderText(std::to_string((int)avgFps), window->getWidth()-30, 0, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->render();
frameCount++;
// if our fps it too high, wait here until we're back to ~60fps
if (capTimer.getTicks() < (1000 / window->getMaxFps()))
{
int waitTime = (1000 / window->getMaxFps()) - capTimer.getTicks();
SDL_Delay(waitTime);
}
}
}
void GameManager::gameTick()
{
bool repeatKey = SDL_PollEvent(&event) == 1;
if (levelOver)
{
currentLevel++;
initGame();
levelOver = false;
return;
}
if(ball->getLives() < 1)
{
window->renderCenteredText("GAME OVER", window->getHeight()/4, {0,0,0}, 50, FONT_RENDER_BLENDED, {255,255,255});
window->renderCenteredText("Score: " + std::to_string(calcScore()), window->getHeight()/2, {0,0,0}, 50, FONT_RENDER_BLENDED, {255,255,255});
listenForQuit();
return;
}
switch (event.type)
{
// if user clicks the red X
case SDL_QUIT:
_quit = true;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
paddle->startMoving(MOVE_LEFT);
break;
case SDLK_RIGHT:
paddle->startMoving(MOVE_RIGHT);
break;
case SDLK_SPACE:
if (ball->isOnPaddle())
ball->detach();
isPressed = true;
break;
case SDLK_ESCAPE:
if (repeatKey)
{
setState(STATE_MENU);
return;
}
}
break;
case SDL_KEYUP:
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
paddle->stopMoving(MOVE_LEFT);
break;
case SDLK_RIGHT:
paddle->stopMoving(MOVE_RIGHT);
break;
}
break;
}
bool collidedThisTick = false;
for (Entity* e : entities)
{
// don't think this is that cpu intensive but I guess it could be
if ((ball->collidedWith(e)) && (e->isActive()) && !collidedThisTick)
{
collidedThisTick = true;
ball->handleCollision(e);
if (e->getTypeId() == TYPEID_BRICK)
{
if (!((Brick*)e)->dealDamage(1))
bricksLeft--;
Log::info(std::to_string(bricksLeft) + " / " + std::to_string(maxBricks) + " bricks remaining");
}
}
e->update();
}
if (ball->collidedWith(paddle))
ball->handleCollision(paddle);
paddle->update();
/************** Code segment used for powerup implementation ***************/
if(randNum == 0 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
mod->fastPaddle();
paddle->setMoveRate(7);
mod->remove();
}
}
if(randNum == 1 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
paddle->setTexture("paddle_big.bmp");
mod->largePaddle();
mod->remove();
}
}
if(randNum == 2 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
mod->slowerPaddle();
paddle->setMoveRate(3);
mod->remove();
}
}
if(randNum == 3 && isPressed == true)
{
mod->update();
if(mod->collidedWith(paddle))
{
paddle->setTexture("paddle_small.bmp");
mod->smallPaddle();
mod->remove();
}
}
/***************************************************************************/
ball->update();
window->renderText("Lives: " + std::to_string(ball->getLives()), 0, 0, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
if (bricksLeft == 0)
{
levelOver = true;
}
}
void GameManager::addEntity(Entity* e)
{
entities.push_back(e);
}
void GameManager::setState(int state)
{
Log::info("Set state to " + std::to_string(state));
currentState = state;
}
void GameManager::printCredits()
{
window->renderCenteredText("Henry Gordon", 20, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Anthony Brugal", 50, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Iden Sessani", 80, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Erik Higginbotham", 110, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Aaron Hanuschak", 140, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
window->renderCenteredText("Kurt Weber", 170, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });
}
void GameManager::listenForQuit()
{
SDL_Event currEvent;
bool repeatKey = SDL_PollEvent(&currEvent) == 1;
switch (currEvent.type)
{
// if user clicks the red X
case SDL_QUIT:
_quit = true;
return;
case SDL_KEYDOWN:
if (repeatKey)
{
switch (currEvent.key.keysym.sym)
{
case SDLK_SPACE:
case SDLK_RETURN:
case SDLK_ESCAPE:
setState(STATE_MENU);
}
}
}
}
int GameManager::calcScore()
{
return (ball->getLives() + 1) * (maxBricks - bricksLeft);
}
<|endoftext|>
|
<commit_before>
#include "ImageSource.h"
#include "tis_logging.h"
using namespace tis_imaging;
ImageSource::ImageSource ()
: current_status(PIPELINE_UNDEFINED), n_buffers(10)
{}
ImageSource::~ImageSource ()
{
device->release_buffers();
}
bool ImageSource::setStatus (const PIPELINE_STATUS& status)
{
current_status = status;
if (current_status == PIPELINE_PLAYING)
{
device->initialize_buffers(buffers);
device->setSink(shared_from_this());
//tis_log(TIS_LOG_ERROR, "Source changed to state PLAYING");
if ( device->start_stream())
{
tis_log(TIS_LOG_DEBUG, "PLAYING....");
}
else
{
tis_log(TIS_LOG_ERROR, "Unable to start stream from device.");
return false;
}
}
else if (current_status == PIPELINE_STOPPED)
{
tis_log(TIS_LOG_ERROR, "Source changed to state STOPPED");
device->stop_stream();
}
return true;
}
PIPELINE_STATUS ImageSource::getStatus () const
{
return current_status;
}
bool ImageSource::setDevice (std::shared_ptr<DeviceInterface> dev)
{
//tis_log(TIS_LOG_DEBUG, "Received device to use as source.");
if (current_status == PIPELINE_PAUSED || current_status == PIPELINE_PLAYING)
{
return false;
}
device = dev;
this->initialize_buffers();
//tis_log(TIS_LOG_INFO, "Giving %d buffers to initialize in device", buffers.size());
if (buffers.empty())
{
tis_log(TIS_LOG_ERROR, "Have no Buffers to work with");
return false;
}
return true;
}
bool ImageSource::setVideoFormat (const VideoFormat&)
{
}
VideoFormat ImageSource::getVideoFormat () const
{
return device->getActiveVideoFormat();
}
void ImageSource::pushImage (std::shared_ptr<MemoryBuffer> buffer)
{
// tis_log(TIS_LOG_INFO, "received buffer");
pipeline.lock()->pushImage(buffer);
}
void ImageSource::initialize_buffers ()
{
struct video_format format = {};
format.fourcc = V4L2_PIX_FMT_GREY;
format.width = 1920;
format.height = 1080;
format.binning = 0;
format.framerate = 0.1;
// TODO:
int bit_depth = 1;
for (unsigned int i = 0; i < this->n_buffers; ++i)
{
struct image_buffer b = {};
b.pData = NULL;
b.length = format.width * format.height * bit_depth;
b.format = format;
b.pitch = 1;
auto ptr = std::make_shared<MemoryBuffer>(MemoryBuffer(b));
//ptr->isLocked();
this->buffers.push_back(ptr);
}
}
bool ImageSource::setSink (std::shared_ptr<SinkInterface> sink)
{
this->pipeline = sink;
return true;
}
<commit_msg>Corrected pitch calculation<commit_after>
#include "ImageSource.h"
#include "tis_logging.h"
using namespace tis_imaging;
ImageSource::ImageSource ()
: current_status(PIPELINE_UNDEFINED), n_buffers(10)
{}
ImageSource::~ImageSource ()
{
device->release_buffers();
}
bool ImageSource::setStatus (const PIPELINE_STATUS& status)
{
current_status = status;
if (current_status == PIPELINE_PLAYING)
{
device->initialize_buffers(buffers);
device->setSink(shared_from_this());
//tis_log(TIS_LOG_ERROR, "Source changed to state PLAYING");
if ( device->start_stream())
{
tis_log(TIS_LOG_DEBUG, "PLAYING....");
}
else
{
tis_log(TIS_LOG_ERROR, "Unable to start stream from device.");
return false;
}
}
else if (current_status == PIPELINE_STOPPED)
{
tis_log(TIS_LOG_ERROR, "Source changed to state STOPPED");
device->stop_stream();
}
return true;
}
PIPELINE_STATUS ImageSource::getStatus () const
{
return current_status;
}
bool ImageSource::setDevice (std::shared_ptr<DeviceInterface> dev)
{
//tis_log(TIS_LOG_DEBUG, "Received device to use as source.");
if (current_status == PIPELINE_PAUSED || current_status == PIPELINE_PLAYING)
{
return false;
}
device = dev;
this->initialize_buffers();
//tis_log(TIS_LOG_INFO, "Giving %d buffers to initialize in device", buffers.size());
if (buffers.empty())
{
tis_log(TIS_LOG_ERROR, "Have no Buffers to work with");
return false;
}
return true;
}
bool ImageSource::setVideoFormat (const VideoFormat&)
{
}
VideoFormat ImageSource::getVideoFormat () const
{
return device->getActiveVideoFormat();
}
void ImageSource::pushImage (std::shared_ptr<MemoryBuffer> buffer)
{
// tis_log(TIS_LOG_INFO, "received buffer");
pipeline.lock()->pushImage(buffer);
}
void ImageSource::initialize_buffers ()
{
// TODO:
struct video_format format = {};
format.fourcc = V4L2_PIX_FMT_GREY;
format.width = 1920;
format.height = 1080;
format.binning = 0;
format.framerate = 0.1;
int bit_depth = img::getBitsPerPixel(format.fourcc);
for (unsigned int i = 0; i < this->n_buffers; ++i)
{
struct image_buffer b = {};
b.pData = NULL;
b.length = format.width * format.height * bit_depth;
b.format = format;
b.pitch = format.width * bit_depth;
auto ptr = std::make_shared<MemoryBuffer>(MemoryBuffer(b));
this->buffers.push_back(ptr);
}
}
bool ImageSource::setSink (std::shared_ptr<SinkInterface> sink)
{
this->pipeline = sink;
return true;
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <cstdio>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <memory>
using namespace std;
// https://www.hackerrank.com/challenges/merging-communities
using people_vec_t = vector<list<int>*>;
void merge(people_vec_t &people, int ii, int jj) {
if (people[ii] == people[jj]) {
return;
}
if (people[jj]->size() > people[ii]->size()) {
swap(ii, jj);
}
const auto tmp = people[jj];
for (const auto k: *tmp) {
people[k] = people[ii];
}
people[ii]->splice(people[ii]->end(), *tmp);
delete tmp;
}
int main() {
int n{0}, q{0};
cin >> n >> q;
//cout << "N: " << n << " Q: " << q << endl;
people_vec_t people;
for (int i = 0; i < n; ++i) {
people.push_back(new list<int>(1, i));
}
for (int i = 0; i < q; ++i) {
char cmd;
cin >> cmd;
if (cmd == 'M') {
int ii{0}, jj{0};
cin >> ii >> jj;
//cout << "Cmd M: " << ii << " " << jj << endl;
merge(people, ii - 1, jj - 1);
//cout << "Size ii: " << people[ii-1]->size() << " size jj: " << people[jj-1]->size() << endl;
} else if (cmd == 'Q') {
int ii{0};
cin >> ii;
//cout << "Cmd Q: " << ii << endl;
cout << people[ii - 1]->size() << endl;
}
}
return 0;
}
<commit_msg>Added collecting statistics<commit_after>#include <cmath>
#include <cstdio>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <memory>
using namespace std;
// https://www.hackerrank.com/challenges/merging-communities
using people_vec_t = vector<list<int>*>;
int nResets = 0;
int nSplices = 0;
int nQueries = 0;
size_t nMerged = 0;
void dumpStats() {
cerr << "nResets: " << nResets << endl;
cerr << "nSplices: " << nSplices << endl;
cerr << "nQueries: " << nQueries << endl;
cerr << "nMerged: " << nMerged << endl;
cerr << " avg: " << nMerged / nSplices << endl;
}
void merge(people_vec_t &people, int ii, int jj) {
if (people[ii] == people[jj]) {
return;
}
if (people[jj]->size() > people[ii]->size()) {
swap(ii, jj);
}
nMerged += people[jj]->size() + people[ii]->size();
const auto tmp = people[jj];
for (const auto k: *tmp) {
people[k] = people[ii];
++nResets;
}
people[ii]->splice(people[ii]->end(), *tmp);
++nSplices;
delete tmp;
}
int main() {
int n{0}, q{0};
cin >> n >> q;
//cout << "N: " << n << " Q: " << q << endl;
people_vec_t people;
for (int i = 0; i < n; ++i) {
people.push_back(new list<int>(1, i));
}
for (int i = 0; i < q; ++i) {
char cmd;
cin >> cmd;
if (cmd == 'M') {
int ii{0}, jj{0};
cin >> ii >> jj;
//cout << "Cmd M: " << ii << " " << jj << endl;
merge(people, ii - 1, jj - 1);
//cout << "Size ii: " << people[ii-1]->size() << " size jj: " << people[jj-1]->size() << endl;
} else if (cmd == 'Q') {
int ii{0};
cin >> ii;
//cout << "Cmd Q: " << ii << endl;
cout << people[ii - 1]->size() << endl;
++nQueries;
}
}
dumpStats();
return 0;
}
<|endoftext|>
|
<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = path.size() >= 1 && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<commit_msg>Check for UNC paths on Windows<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
// Note that passing null for the first arg isn't strictly POSIX, but is
// supported everywhere we currently build.
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = path.size() >= 1 && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
} else if (path.size() > 2 && path[0] == '\\' && path[1] == '\\') {
// Also allow for UNC-style paths beginning with double-backslash
is_absolute = true;
sep = path[0];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<|endoftext|>
|
<commit_before>
/*
poedit, a wxWindows i18n catalogs editor
---------------
transmemupd.cpp
Translation memory database updater
(c) Vaclav Slavik, 2001
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include <wx/wxprec.h>
#ifdef USE_TRANSMEM
#include <wx/string.h>
#include <wx/tokenzr.h>
#include <wx/log.h>
#include <wx/intl.h>
#include <wx/utils.h>
#include <wx/dir.h>
#include "catalog.h"
#include "transmem.h"
#include "transmemupd.h"
#include "gexecute.h"
#include "progressinfo.h"
/** Does given file contain catalogs in given language?
Handles these cases:
- foo/bar/lang.mo
- foo/lang/bar.mo
- foo/lang/LC_MESSAGES/bar.mo
Futhermore, if \a lang is 2-letter code (e.g. "cs"), handles these:
- foo/bar/lang_??.mo
- foo/lang_??/bar.mo
- foo/lang_??/LC_MESSAGES/bar.mo
and if \a lang is five-letter code (e.g. "cs_CZ"), tries to match its
first two letters (i.e. country-neutral variant of the language).
*/
static inline bool IsForLang(const wxString& filename, const wxString& lang,
bool variants = true)
{
#ifdef __WINDOWS__
#define LC_MESSAGES_STR "/lc_messages"
#else
#define LC_MESSAGES_STR "/LC_MESSAGES"
#endif
wxString base, dir;
wxSplitPath(filename, &dir, &base, NULL);
dir.Replace(wxString(wxFILE_SEP_PATH), _T("/"));
return base.Matches(lang) ||
dir.Matches(_T("*/") + lang) ||
dir.Matches(_T("*/") + lang + LC_MESSAGES_STR) ||
(variants && lang.Len() == 5 && lang[2] == _T('_') &&
IsForLang(filename, lang.Mid(0, 2), false)) ||
(variants && lang.Len() == 2 &&
IsForLang(filename, lang + _T("_??"), false));
#undef LC_MESSAGES_STR
}
class TMUDirTraverser : public wxDirTraverser
{
public:
TMUDirTraverser(wxArrayString *files, const wxString& lang)
: m_files(files), m_lang(lang) {}
virtual ~TMUDirTraverser() {}
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
#ifdef __WINDOWS__
wxString f = filename.Lower();
#else
wxString f = filename;
#endif
if ((f.Matches(_T("*.mo")) && IsForLang(f, m_lang)) ||
(f.Matches(_T("*.po")) && IsForLang(f, m_lang))
#ifdef __UNIX__
|| f.Matches(_T("*.rpm"))
#endif
)
{
m_files->Add(f);
}
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& dirname)
{ return wxDIR_CONTINUE; }
private:
wxArrayString *m_files;
wxString m_lang;
};
TranslationMemoryUpdater::TranslationMemoryUpdater(TranslationMemory *mem,
ProgressInfo *pi)
: m_progress(pi), m_mem(mem)
{
}
bool TranslationMemoryUpdater::Update(const wxArrayString& paths)
{
size_t i;
wxString f;
wxArrayString files;
TMUDirTraverser trav(&files, m_mem->GetLanguage());
m_progress->UpdateMessage(_("Listing files..."));
for (i = 0; i < paths.GetCount(); i++)
{
wxDir dir(paths[i]);
if (!dir.IsOpened() || dir.Traverse(trav) == (size_t)-1)
return false;
}
m_progress->SetGaugeMax(files.GetCount());
m_progress->ResetGauge();
bool res = true;
size_t cnt = files.GetCount();
for (i = 0; i < cnt; i++)
{
f = files[i];
m_progress->UpdateMessage(wxString(_("Scanning file: ")) +
wxFileNameFromPath(f));
if (f.Matches(_T("*.po")))
res = UpdateFromPO(f);
else if (f.Matches(_T("*.mo")))
res = UpdateFromMO(f);
#ifdef __UNIX__
else if (f.Matches(_T("*.rpm")))
res = UpdateFromRPM(f);
#endif
m_progress->UpdateGauge();
wxYield();
if (m_progress->Cancelled()) return false;
}
return res;
}
bool TranslationMemoryUpdater::UpdateFromPO(const wxString& filename)
{
return UpdateFromCatalog(filename);
}
bool TranslationMemoryUpdater::UpdateFromMO(const wxString& filename)
{
wxString tmp;
if (!wxGetTempFileName(_T("poedit"), tmp))
return false;
if (!ExecuteGettext(_T("msgunfmt --force-po -o ") + tmp + _T(" ") + filename))
return false;
bool rt = UpdateFromCatalog(tmp);
wxRemoveFile(tmp);
return rt;
}
#ifdef __UNIX__
bool TranslationMemoryUpdater::UpdateFromRPM(const wxString& filename)
{
#define TMP_DIR _T("/tmp/poedit-rpm-tpm")
if (!wxMkdir(TMP_DIR)) return false;
wxString cmd;
cmd.Printf(_T("sh -c '(cd %s ; rpm2cpio %s | cpio -i -d --quiet \"*.mo\")'"),
TMP_DIR, filename.c_str());
if (wxExecute(cmd, true) != 0)
{
wxLogError(_("Cannot extract catalogs from RPM file."));
wxExecute(_T("rm -rf ") TMP_DIR, true);
return false;
}
bool res = true;
wxArrayString files;
if (wxDir::GetAllFiles(TMP_DIR, &files, _T("*.mo")) != (size_t)-1)
{
size_t cnt = files.GetCount();
for (size_t i = 0; res && i < cnt; i++)
{
if (!IsForLang(files[i], m_mem->GetLanguage())) continue;
if (!UpdateFromMO(files[i]))
res = false;
}
}
wxLog::FlushActive();
wxExecute(_T("rm -rf ") TMP_DIR, true);
return res;
#undef TMP_DIR
}
#endif
bool TranslationMemoryUpdater::UpdateFromCatalog(const wxString& filename)
{
wxLogNull null;
Catalog cat(filename);
if (!cat.IsOk()) return true; // ignore
size_t cnt = cat.GetCount();
for (size_t i = 0; i < cnt; i++)
{
CatalogData &dt = cat[i];
if (!dt.IsTranslated() || dt.IsFuzzy()) continue;
if (!m_mem->Store(dt.GetString(), dt.GetTranslation()))
return false;
}
return true;
}
#endif //USE_TRANSMEM
<commit_msg>supress msgfmt's log messgaes<commit_after>
/*
poedit, a wxWindows i18n catalogs editor
---------------
transmemupd.cpp
Translation memory database updater
(c) Vaclav Slavik, 2001
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include <wx/wxprec.h>
#ifdef USE_TRANSMEM
#include <wx/string.h>
#include <wx/tokenzr.h>
#include <wx/log.h>
#include <wx/intl.h>
#include <wx/utils.h>
#include <wx/dir.h>
#include "catalog.h"
#include "transmem.h"
#include "transmemupd.h"
#include "gexecute.h"
#include "progressinfo.h"
/** Does given file contain catalogs in given language?
Handles these cases:
- foo/bar/lang.mo
- foo/lang/bar.mo
- foo/lang/LC_MESSAGES/bar.mo
Futhermore, if \a lang is 2-letter code (e.g. "cs"), handles these:
- foo/bar/lang_??.mo
- foo/lang_??/bar.mo
- foo/lang_??/LC_MESSAGES/bar.mo
and if \a lang is five-letter code (e.g. "cs_CZ"), tries to match its
first two letters (i.e. country-neutral variant of the language).
*/
static inline bool IsForLang(const wxString& filename, const wxString& lang,
bool variants = true)
{
#ifdef __WINDOWS__
#define LC_MESSAGES_STR "/lc_messages"
#else
#define LC_MESSAGES_STR "/LC_MESSAGES"
#endif
wxString base, dir;
wxSplitPath(filename, &dir, &base, NULL);
dir.Replace(wxString(wxFILE_SEP_PATH), _T("/"));
return base.Matches(lang) ||
dir.Matches(_T("*/") + lang) ||
dir.Matches(_T("*/") + lang + LC_MESSAGES_STR) ||
(variants && lang.Len() == 5 && lang[2] == _T('_') &&
IsForLang(filename, lang.Mid(0, 2), false)) ||
(variants && lang.Len() == 2 &&
IsForLang(filename, lang + _T("_??"), false));
#undef LC_MESSAGES_STR
}
class TMUDirTraverser : public wxDirTraverser
{
public:
TMUDirTraverser(wxArrayString *files, const wxString& lang)
: m_files(files), m_lang(lang) {}
virtual ~TMUDirTraverser() {}
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
#ifdef __WINDOWS__
wxString f = filename.Lower();
#else
wxString f = filename;
#endif
if ((f.Matches(_T("*.mo")) && IsForLang(f, m_lang)) ||
(f.Matches(_T("*.po")) && IsForLang(f, m_lang))
#ifdef __UNIX__
|| f.Matches(_T("*.rpm"))
#endif
)
{
m_files->Add(f);
}
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& dirname)
{ return wxDIR_CONTINUE; }
private:
wxArrayString *m_files;
wxString m_lang;
};
TranslationMemoryUpdater::TranslationMemoryUpdater(TranslationMemory *mem,
ProgressInfo *pi)
: m_progress(pi), m_mem(mem)
{
}
bool TranslationMemoryUpdater::Update(const wxArrayString& paths)
{
size_t i;
wxString f;
wxArrayString files;
TMUDirTraverser trav(&files, m_mem->GetLanguage());
m_progress->UpdateMessage(_("Listing files..."));
for (i = 0; i < paths.GetCount(); i++)
{
wxDir dir(paths[i]);
if (!dir.IsOpened() || dir.Traverse(trav) == (size_t)-1)
return false;
}
m_progress->SetGaugeMax(files.GetCount());
m_progress->ResetGauge();
bool res = true;
size_t cnt = files.GetCount();
for (i = 0; i < cnt; i++)
{
f = files[i];
m_progress->UpdateMessage(wxString(_("Scanning file: ")) +
wxFileNameFromPath(f));
if (f.Matches(_T("*.po")))
res = UpdateFromPO(f);
else if (f.Matches(_T("*.mo")))
res = UpdateFromMO(f);
#ifdef __UNIX__
else if (f.Matches(_T("*.rpm")))
res = UpdateFromRPM(f);
#endif
m_progress->UpdateGauge();
wxYield();
if (m_progress->Cancelled()) return false;
}
return res;
}
bool TranslationMemoryUpdater::UpdateFromPO(const wxString& filename)
{
return UpdateFromCatalog(filename);
}
bool TranslationMemoryUpdater::UpdateFromMO(const wxString& filename)
{
wxString tmp;
wxLogNull null;
if (!wxGetTempFileName(_T("poedit"), tmp))
return false;
if (!ExecuteGettext(_T("msgunfmt --force-po -o ") + tmp + _T(" ") + filename))
return false;
bool rt = UpdateFromCatalog(tmp);
wxRemoveFile(tmp);
return rt;
}
#ifdef __UNIX__
bool TranslationMemoryUpdater::UpdateFromRPM(const wxString& filename)
{
#define TMP_DIR _T("/tmp/poedit-rpm-tpm")
if (!wxMkdir(TMP_DIR)) return false;
wxString cmd;
cmd.Printf(_T("sh -c '(cd %s ; rpm2cpio %s | cpio -i -d --quiet \"*.mo\")'"),
TMP_DIR, filename.c_str());
if (wxExecute(cmd, true) != 0)
{
wxLogError(_("Cannot extract catalogs from RPM file."));
wxExecute(_T("rm -rf ") TMP_DIR, true);
return false;
}
bool res = true;
wxArrayString files;
if (wxDir::GetAllFiles(TMP_DIR, &files, _T("*.mo")) != (size_t)-1)
{
size_t cnt = files.GetCount();
for (size_t i = 0; res && i < cnt; i++)
{
if (!IsForLang(files[i], m_mem->GetLanguage())) continue;
if (!UpdateFromMO(files[i]))
res = false;
}
}
wxLog::FlushActive();
wxExecute(_T("rm -rf ") TMP_DIR, true);
return res;
#undef TMP_DIR
}
#endif
bool TranslationMemoryUpdater::UpdateFromCatalog(const wxString& filename)
{
wxLogNull null;
Catalog cat(filename);
if (!cat.IsOk()) return true; // ignore
size_t cnt = cat.GetCount();
for (size_t i = 0; i < cnt; i++)
{
CatalogData &dt = cat[i];
if (!dt.IsTranslated() || dt.IsFuzzy()) continue;
if (!m_mem->Store(dt.GetString(), dt.GetTranslation()))
return false;
}
return true;
}
#endif //USE_TRANSMEM
<|endoftext|>
|
<commit_before>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <osg/Quat>
#if defined (WIN32) && !defined(__CYGWIN__)
#include <winsock.h>
#endif
#include "receiver.h"
#include "broadcaster.h"
typedef unsigned char * BytePtr;
template <class T>
inline void swapBytes( T &s )
{
if( sizeof( T ) == 1 ) return;
T d = s;
BytePtr sptr = (BytePtr)&s;
BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);
for( unsigned int i = 0; i < sizeof(T); i++ )
*(sptr++) = *(dptr--);
}
class PackedEvent
{
public:
PackedEvent():
_eventType(osgProducer::EventAdapter::NONE),
_key(0),
_button(0),
_Xmin(0),_Xmax(0),
_Ymin(0),_Ymax(0),
_mx(0),
_my(0),
_buttonMask(0),
_modKeyMask(0),
_time(0.0) {}
void set(const osgProducer::EventAdapter& event)
{
_eventType = event._eventType;
_key = event._key;
_button = event._button;
_Xmin = event._Xmin;
_Xmax = event._Xmax;
_Ymin = event._Ymin;
_Ymax = event._Ymax;
_mx = event._mx;
_my = event._my;
_buttonMask = event._buttonMask;
_modKeyMask = event._modKeyMask;
_time = event._time;
}
void get(osgProducer::EventAdapter& event)
{
event._eventType = _eventType;
event._key = _key;
event._button = _button;
event._Xmin = _Xmin;
event._Xmax = _Xmax;
event._Ymin = _Ymin;
event._Ymax = _Ymax;
event._mx = _mx;
event._my = _my;
event._buttonMask = _buttonMask;
event._modKeyMask = _modKeyMask;
event._time = _time;
}
void swapBytes()
{
}
protected:
osgProducer::EventAdapter::EventType _eventType;
int _key;
int _button;
float _Xmin,_Xmax;
float _Ymin,_Ymax;
float _mx;
float _my;
unsigned int _buttonMask;
unsigned int _modKeyMask;
double _time;
};
const unsigned int MAX_NUM_EVENTS = 10;
class CameraPacket {
public:
CameraPacket():_masterKilled(false)
{
_byte_order = 0x12345678;
}
void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
{
_matrix = matrix;
if (frameStamp)
{
_frameStamp = *frameStamp;
}
}
void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
{
matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
}
void readEventQueue(osgProducer::Viewer& viewer);
void writeEventQueue(osgProducer::Viewer& viewer);
void checkByteOrder( void )
{
if( _byte_order == 0x78563412 ) // We're backwards
{
swapBytes( _byte_order );
swapBytes( _masterKilled );
for( int i = 0; i < 16; i++ )
swapBytes( _matrix.ptr()[i] );
// umm.. we should byte swap _frameStamp too...
for(unsigned int ei=0; ei<_numEvents; ++ei)
{
_events[ei].swapBytes();
}
}
}
void setMasterKilled(const bool flag) { _masterKilled = flag; }
const bool getMasterKilled() const { return _masterKilled; }
unsigned int _byte_order;
bool _masterKilled;
osg::Matrix _matrix;
// note don't use a ref_ptr as used elsewhere for FrameStamp
// since we don't want to copy the pointer - but the memory.
// FrameStamp doesn't have a private destructor to allow
// us to do this, even though its a reference counted object.
osg::FrameStamp _frameStamp;
unsigned int _numEvents;
PackedEvent _events[MAX_NUM_EVENTS];
};
void CameraPacket::readEventQueue(osgProducer::Viewer& viewer)
{
osgProducer::KeyboardMouseCallback::EventQueue queue;
viewer.getKeyboardMouseCallback()->copyEventQueue(queue);
_numEvents = 0;
for(osgProducer::KeyboardMouseCallback::EventQueue::iterator itr =queue.begin();
itr != queue.end() && _numEvents<MAX_NUM_EVENTS;
++itr, ++_numEvents)
{
osgProducer::EventAdapter* event = itr->get();
_events[_numEvents].set(*event);
}
osg::notify(osg::INFO)<<"written events = "<<_numEvents<<std::endl;
}
void CameraPacket::writeEventQueue(osgProducer::Viewer& viewer)
{
osg::notify(osg::INFO)<<"recieved events = "<<_numEvents<<std::endl;
// copy the packed events to osgProducer style events.
osgProducer::KeyboardMouseCallback::EventQueue queue;
for(unsigned int ei=0; ei<_numEvents; ++ei)
{
osgProducer::EventAdapter* event = new osgProducer::EventAdapter;
_events[ei].get(*event);
queue.push_back(event);
}
// pass them to the viewer.
viewer.getKeyboardMouseCallback()->appendEventQueue(queue);
}
enum ViewerMode
{
STAND_ALONE,
SLAVE,
MASTER
};
int main( int argc, char **argv )
{
osg::notify(osg::INFO)<<"FrameStamp "<<sizeof(osg::FrameStamp)<<std::endl;
osg::notify(osg::INFO)<<"osg::Matrix "<<sizeof(osg::Matrix)<<std::endl;
osg::notify(osg::INFO)<<"PackedEvent "<<sizeof(PackedEvent)<<std::endl;
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// read up the osgcluster specific arguments.
ViewerMode viewerMode = STAND_ALONE;
while (arguments.read("-m")) viewerMode = MASTER;
while (arguments.read("-s")) viewerMode = SLAVE;
int socketNumber=8100;
while (arguments.read("-n",socketNumber)) ;
float camera_fov=-1.0f;
while (arguments.read("-f",camera_fov))
{
}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) ;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load model.
osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
// set up the lens after realize as the Producer lens is not set up properly before this.... will need to inveestigate this at a later date.
if (camera_fov>0.0f)
{
float aspectRatio = tan( osg::DegreesToRadians(viewer.getLensVerticalFov()*0.5)) / tan(osg::DegreesToRadians(viewer.getLensHorizontalFov()*0.5));
float new_fovy = osg::RadiansToDegrees(atan( aspectRatio * tan( osg::DegreesToRadians(camera_fov*0.5))))*2.0f;
std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
viewer.setLensPerspective(camera_fov,new_fovy,1.0f,1000.0f);
std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
}
CameraPacket *cp = new CameraPacket;
// objects for managing the broadcasting and recieving of camera packets.
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
while( !viewer.done() && !masterKilled )
{
// wait for all cull and draw threads to complete.
viewer.sync();
osg::Timer_t startTick = osg::Timer::instance()->tick();
// special handling for working as a cluster.
switch (viewerMode)
{
case(MASTER):
{
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());
cp->setPacket(modelview,viewer.getFrameStamp());
cp->readEventQueue(viewer);
bc.setBuffer(cp, sizeof( CameraPacket ));
std::cout << "bc.sync()"<<sizeof( CameraPacket )<<std::endl;
bc.sync();
}
break;
case(SLAVE):
{
rc.setBuffer(cp, sizeof( CameraPacket ));
osg::notify(osg::INFO) << "rc.sync()"<<sizeof( CameraPacket )<<std::endl;
rc.sync();
cp->checkByteOrder();
cp->writeEventQueue(viewer);
if (cp->getMasterKilled())
{
std::cout << "Received master killed."<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
break;
default:
// no need to anything here, just a normal interactive viewer.
break;
}
osg::Timer_t endTick = osg::Timer::instance()->tick();
osg::notify(osg::INFO)<<"Time to do cluster sync "<<osg::Timer::instance()->delta_m(startTick,endTick)<<std::endl;
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
if (viewerMode==SLAVE)
{
osg::Matrix modelview;
cp->getModelView(modelview,camera_offset);
viewer.setView(modelview);
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// if we are master clean up by telling all slaves that we're going down.
if (viewerMode==MASTER)
{
// need to broadcast my death.
cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
cp->setMasterKilled(true);
bc.setBuffer(cp, sizeof( CameraPacket ));
bc.sync();
std::cout << "Broadcasting death."<<std::endl;
}
return 0;
}
<commit_msg>Implement a scratch pad for writing and read data to, to solve issue between running a master and slave on a mix of 32bit and 64bit.<commit_after>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <osg/Quat>
#if defined (WIN32) && !defined(__CYGWIN__)
#include <winsock.h>
#endif
#include "receiver.h"
#include "broadcaster.h"
const unsigned int MAX_NUM_EVENTS = 10;
const unsigned int SWAP_BYTES_COMPARE = 0x12345678;
class CameraPacket {
public:
CameraPacket():_masterKilled(false)
{
_byte_order = SWAP_BYTES_COMPARE;
}
void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
{
_matrix = matrix;
if (frameStamp)
{
_frameStamp = *frameStamp;
}
}
void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
{
matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
}
void readEventQueue(osgProducer::Viewer& viewer);
void writeEventQueue(osgProducer::Viewer& viewer);
void setMasterKilled(const bool flag) { _masterKilled = flag; }
const bool getMasterKilled() const { return _masterKilled; }
unsigned int _byte_order;
bool _masterKilled;
osg::Matrix _matrix;
// note don't use a ref_ptr as used elsewhere for FrameStamp
// since we don't want to copy the pointer - but the memory.
// FrameStamp doesn't have a private destructor to allow
// us to do this, even though its a reference counted object.
osg::FrameStamp _frameStamp;
osgProducer::KeyboardMouseCallback::EventQueue _events;
};
class DataConverter
{
public:
DataConverter(unsigned int numBytes):
_startPtr(0),
_endPtr(0),
_swapBytes(false),
_currentPtr(0)
{
_currentPtr = _startPtr = new char[numBytes];
_endPtr = _startPtr+numBytes;
_numBytes = numBytes;
}
char* _startPtr;
char* _endPtr;
unsigned int _numBytes;
bool _swapBytes;
char* _currentPtr;
inline void write1(char* ptr)
{
if (_currentPtr+1>=_endPtr) return;
*(_currentPtr++) = *(ptr);
}
inline void read1(char* ptr)
{
if (_currentPtr+1>=_endPtr) return;
*(ptr) = *(_currentPtr++);
}
inline void write2(char* ptr)
{
if (_currentPtr+2>=_endPtr) return;
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr);
}
inline void read2(char* ptr)
{
if (_currentPtr+2>=_endPtr) return;
if (_swapBytes)
{
*(ptr+1) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
else
{
*(ptr++) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
}
inline void write4(char* ptr)
{
if (_currentPtr+4>=_endPtr) return;
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr);
}
inline void read4(char* ptr)
{
if (_currentPtr+4>=_endPtr) return;
if (_swapBytes)
{
*(ptr+3) = *(_currentPtr++);
*(ptr+2) = *(_currentPtr++);
*(ptr+1) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
else
{
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
}
inline void write8(char* ptr)
{
if (_currentPtr+8>=_endPtr) return;
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr);
}
inline void read8(char* ptr)
{
char* endPtr = _currentPtr+8;
if (endPtr>=_endPtr) return;
if (_swapBytes)
{
*(ptr+7) = *(_currentPtr++);
*(ptr+6) = *(_currentPtr++);
*(ptr+5) = *(_currentPtr++);
*(ptr+4) = *(_currentPtr++);
*(ptr+3) = *(_currentPtr++);
*(ptr+2) = *(_currentPtr++);
*(ptr+1) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
else
{
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
}
inline void writeChar(char c) { write1(&c); }
inline void writeUChar(unsigned char c) { write1((char*)&c); }
inline void writeShort(short c) { write2((char*)&c); }
inline void writeUShort(unsigned short c) { write2((char*)&c); }
inline void writeInt(int c) { write4((char*)&c); }
inline void writeUInt(unsigned int c) { write4((char*)&c); }
inline void writeFloat(float c) { write4((char*)&c); }
inline void writeDouble(double c) { write8((char*)&c); }
inline char readChar() { char c; read1(&c); return c; }
inline unsigned char readUChar() { unsigned char c; read1((char*)&c); return c; }
inline short readShort() { short c; read2((char*)&c); return c; }
inline unsigned short readUShort() { unsigned short c; read2((char*)&c); return c; }
inline int readInt() { int c; read4((char*)&c); return c; }
inline unsigned int readUInt() { unsigned int c; read4((char*)&c); return c; }
inline float readFloat() { float c; read4((char*)&c); return c; }
inline double readDouble() { double c; read8((char*)&c); return c; }
void write(const osg::FrameStamp& fs)
{
writeUInt(fs.getFrameNumber());
return writeDouble(fs.getReferenceTime());
}
void read(osg::FrameStamp& fs)
{
fs.setFrameNumber(readUInt());
fs.setReferenceTime(readDouble());
}
void write(const osg::Matrix& matrix)
{
writeDouble(matrix(0,0));
writeDouble(matrix(0,1));
writeDouble(matrix(0,2));
writeDouble(matrix(0,3));
writeDouble(matrix(1,0));
writeDouble(matrix(1,1));
writeDouble(matrix(1,2));
writeDouble(matrix(1,3));
writeDouble(matrix(2,0));
writeDouble(matrix(2,1));
writeDouble(matrix(2,2));
writeDouble(matrix(2,3));
writeDouble(matrix(3,0));
writeDouble(matrix(3,1));
writeDouble(matrix(3,2));
writeDouble(matrix(3,3));
}
void read(osg::Matrix& matrix)
{
matrix(0,0) = readDouble();
matrix(0,1) = readDouble();
matrix(0,2) = readDouble();
matrix(0,3) = readDouble();
matrix(1,0) = readDouble();
matrix(1,1) = readDouble();
matrix(1,2) = readDouble();
matrix(1,3) = readDouble();
matrix(2,0) = readDouble();
matrix(2,1) = readDouble();
matrix(2,2) = readDouble();
matrix(2,3) = readDouble();
matrix(3,0) = readDouble();
matrix(3,1) = readDouble();
matrix(3,2) = readDouble();
matrix(3,3) = readDouble();
}
void write(const osgProducer::EventAdapter& event)
{
writeUInt(event._eventType);
writeUInt(event._key);
writeUInt(event._button);
writeFloat(event._Xmin);
writeFloat(event._Xmax);
writeFloat(event._Ymin);
writeFloat(event._Ymax);
writeFloat(event._mx);
writeFloat(event._my);
writeUInt(event._buttonMask);
writeUInt(event._modKeyMask);
writeDouble(event._time);
}
void read(osgProducer::EventAdapter& event)
{
event._eventType = (osgGA::GUIEventAdapter::EventType)readUInt();
event._key = readUInt();
event._button = readUInt();
event._Xmin = readFloat();
event._Xmax = readFloat();
event._Ymin = readFloat();
event._Ymax = readFloat();
event._mx = readFloat();
event._my = readFloat();
event._buttonMask = readUInt();
event._modKeyMask = readUInt();
event._time = readDouble();
}
void write(CameraPacket& cameraPacket)
{
writeUInt(cameraPacket._byte_order);
writeUInt(cameraPacket._masterKilled);
write(cameraPacket._matrix);
write(cameraPacket._frameStamp);
writeUInt(cameraPacket._events.size());
for(unsigned int i=0;i<cameraPacket._events.size();++i)
{
write(*(cameraPacket._events[i]));
}
}
void read(CameraPacket& cameraPacket)
{
cameraPacket._byte_order = readUInt();
if (cameraPacket._byte_order != SWAP_BYTES_COMPARE) _swapBytes = !_swapBytes;
cameraPacket._masterKilled = readUInt();
read(cameraPacket._matrix);
read(cameraPacket._frameStamp);
cameraPacket._events.clear();
unsigned int numEvents = readUInt();
for(unsigned int i=0;i<numEvents;++i)
{
osgProducer::EventAdapter* event = new osgProducer::EventAdapter;
read(*(event));
cameraPacket._events.push_back(event);
}
}
};
void CameraPacket::readEventQueue(osgProducer::Viewer& viewer)
{
viewer.getKeyboardMouseCallback()->copyEventQueue(_events);
osg::notify(osg::INFO)<<"written events = "<<_events.size()<<std::endl;
}
void CameraPacket::writeEventQueue(osgProducer::Viewer& viewer)
{
osg::notify(osg::INFO)<<"recieved events = "<<_events.size()<<std::endl;
// copy the events to osgProducer style events.
viewer.getKeyboardMouseCallback()->appendEventQueue(_events);
}
enum ViewerMode
{
STAND_ALONE,
SLAVE,
MASTER
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// read up the osgcluster specific arguments.
ViewerMode viewerMode = STAND_ALONE;
while (arguments.read("-m")) viewerMode = MASTER;
while (arguments.read("-s")) viewerMode = SLAVE;
int socketNumber=8100;
while (arguments.read("-n",socketNumber)) ;
float camera_fov=-1.0f;
while (arguments.read("-f",camera_fov))
{
}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) ;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load model.
osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
// set up the lens after realize as the Producer lens is not set up properly before this.... will need to inveestigate this at a later date.
if (camera_fov>0.0f)
{
float aspectRatio = tan( osg::DegreesToRadians(viewer.getLensVerticalFov()*0.5)) / tan(osg::DegreesToRadians(viewer.getLensHorizontalFov()*0.5));
float new_fovy = osg::RadiansToDegrees(atan( aspectRatio * tan( osg::DegreesToRadians(camera_fov*0.5))))*2.0f;
std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
viewer.setLensPerspective(camera_fov,new_fovy,1.0f,1000.0f);
std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
}
CameraPacket *cp = new CameraPacket;
// objects for managing the broadcasting and recieving of camera packets.
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
DataConverter scratchPad(1024);
while( !viewer.done() && !masterKilled )
{
// wait for all cull and draw threads to complete.
viewer.sync();
osg::Timer_t startTick = osg::Timer::instance()->tick();
// special handling for working as a cluster.
switch (viewerMode)
{
case(MASTER):
{
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());
cp->setPacket(modelview,viewer.getFrameStamp());
cp->readEventQueue(viewer);
scratchPad.write(*cp);
bc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
std::cout << "bc.sync()"<<scratchPad._numBytes<<std::endl;
bc.sync();
}
break;
case(SLAVE):
{
rc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
osg::notify(osg::INFO) << "rc.sync()"<<scratchPad._numBytes<<std::endl;
rc.sync();
scratchPad.read(*cp);
cp->writeEventQueue(viewer);
if (cp->getMasterKilled())
{
std::cout << "Received master killed."<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
break;
default:
// no need to anything here, just a normal interactive viewer.
break;
}
osg::Timer_t endTick = osg::Timer::instance()->tick();
osg::notify(osg::INFO)<<"Time to do cluster sync "<<osg::Timer::instance()->delta_m(startTick,endTick)<<std::endl;
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
if (viewerMode==SLAVE)
{
osg::Matrix modelview;
cp->getModelView(modelview,camera_offset);
viewer.setView(modelview);
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// if we are master clean up by telling all slaves that we're going down.
if (viewerMode==MASTER)
{
// need to broadcast my death.
cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
cp->setMasterKilled(true);
bc.setBuffer(cp, sizeof( CameraPacket ));
bc.sync();
std::cout << "Broadcasting death."<<std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <stdio.h>
#include "fnord-base/stdtypes.h"
#include "fnord-base/exception.h"
#include "fnord-base/test/unittest.h"
#include "fnord-msg/msg.h"
#include "src/schemas.cc"
#include "logjoin/LogJoinTarget.cc"
#include "JoinedSession.pb.h"
using namespace fnord;
using namespace cm;
UNIT_TEST(LogJoinTest);
typedef HashMap<String, HashMap<String, String>> StringMap;
LogJoinTarget mkTestTarget() {
LogJoinTarget trgt(joinedSessionsSchema(), false);
trgt.setNormalize([] (Language l, const String& q) { return q; });
trgt.setGetField([] (const DocID& doc, const String& field) {
return None<String>();
});
return trgt;
}
void printBuf(const Buffer& buf) {
msg::MessageObject msg;
msg::MessageDecoder::decode(buf, joinedSessionsSchema(), &msg);
fnord::iputs("joined session: $0", msg::MessagePrinter::print(msg, joinedSessionsSchema()));
}
// query with click
// multiple queries
// report items in multiple batches (logenplaetze, normal, etc)
// cart // gmv matching
// field expansion // joining
TEST_CASE(LogJoinTest, SimpleQuery, [] () {
auto t = 1432311555 * kMicrosPerSecond;
auto trgt = mkTestTarget();
TrackedSession sess;
sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
{ "is", "p~101~p1,p~102~p2" },
{ "qstr~de", "blah" }
});
auto buf = trgt.trackedSessionToJoinedSession(sess);
auto joined = msg::decode<JoinedSession>(buf);
EXPECT_EQ(joined.num_cart_items(), 0);
EXPECT_EQ(joined.cart_value_eurcents(), 0);
EXPECT_EQ(joined.num_order_items(), 0);
EXPECT_EQ(joined.gmv_eurcents(), 0);
EXPECT_EQ(joined.first_seen_time(), 1432311555);
EXPECT_EQ(joined.search_queries().size(), 1);
EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 0);
EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 0);
EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 0);
EXPECT_EQ(joined.search_queries().Get(0).query_string(), "blah");
EXPECT_EQ(joined.search_queries().Get(0).query_string_normalized(), "blah");
EXPECT_EQ(
ProtoLanguage_Name(joined.search_queries().Get(0).language()),
"LANGUAGE_DE");
//DaWanda Hack
EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 1);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~101");
EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(0).clicked());
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~102");
EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());
});
/*
TEST_CASE(LogJoinTest, Test1, [] () {
auto loglines_txt = FileUtil::read("src/test_loglines.txt");
auto loglines = StringUtil::split(loglines_txt.toString(), "\n");
for (const auto& logline : loglines) {
if (logline.length() == 0) {
continue;
}
URI::ParamList params;
URI::parseQueryString(logline, ¶ms);
String time;
String evtype;
String evid;
for (auto p = params.begin(); p != params.end(); ) {
switch (p->first[0]) {
default:
++p;
continue;
case 't':
time = p->second;
break;
case 'e':
evtype = p->second;
break;
case 'c':
Vector<String> cid = StringUtil::split(p->second, "~");
evid = cid.at(1);
break;
}
p = params.erase(p);
}
tracked_session.insertLogline(
DateTime((uint64_t) std::stoull(time) * 1000000),
evtype,
evid,
params);
}
auto joined_sessions_schema = joinedSessionsSchema();
LogJoinTarget logjoin_target(joined_sessions_schema, false);
StringMap fields;
fields["p~62797695"]["category1"] = "4";
auto getField = [fields] (const DocID& docid, const String& feature) -> Option<String> {
auto it = fields.find(docid.docid);
if (it != fields.end()) {
auto field = it->second;
auto it_ = field.find(feature);
if (it_ != field.end()) {
return Some(String(it_->second));
}
}
return None<String>();
};
auto normalize = [] (Language lang, const String& query) -> String {
return query;
};
logjoin_target.setGetField(getField);
logjoin_target.setNormalize(normalize);
Buffer session = logjoin_target.trackedSessionToJoinedSession(
tracked_session);
JoinedSession joined_session;
joined_session.ParseFromString(session.toString());
});
*/
<commit_msg>LogJoinTest: ItemOrder, gmv, cart item<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <stdio.h>
#include "fnord-base/stdtypes.h"
#include "fnord-base/exception.h"
#include "fnord-base/test/unittest.h"
#include "fnord-msg/msg.h"
#include "src/schemas.cc"
#include "logjoin/LogJoinTarget.cc"
#include "JoinedSession.pb.h"
using namespace fnord;
using namespace cm;
UNIT_TEST(LogJoinTest);
typedef HashMap<String, HashMap<String, String>> StringMap;
LogJoinTarget mkTestTarget() {
LogJoinTarget trgt(joinedSessionsSchema(), false);
trgt.setNormalize([] (Language l, const String& q) { return q; });
trgt.setGetField([] (const DocID& doc, const String& field) {
return None<String>();
});
return trgt;
}
void printBuf(const Buffer& buf) {
msg::MessageObject msg;
msg::MessageDecoder::decode(buf, joinedSessionsSchema(), &msg);
fnord::iputs("joined session: $0", msg::MessagePrinter::print(msg, joinedSessionsSchema()));
}
// query with click
// multiple queries
// report items in multiple batches (logenplaetze, normal, etc)
// cart // gmv matching
// field expansion // joining
TEST_CASE(LogJoinTest, SimpleQuery, [] () {
auto t = 1432311555 * kMicrosPerSecond;
auto trgt = mkTestTarget();
TrackedSession sess;
sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
{ "is", "p~101~p1,p~102~p2" },
{ "qstr~de", "blah" }
});
auto buf = trgt.trackedSessionToJoinedSession(sess);
auto joined = msg::decode<JoinedSession>(buf);
EXPECT_EQ(joined.num_cart_items(), 0);
EXPECT_EQ(joined.cart_value_eurcents(), 0);
EXPECT_EQ(joined.num_order_items(), 0);
EXPECT_EQ(joined.gmv_eurcents(), 0);
EXPECT_EQ(joined.first_seen_time(), 1432311555);
EXPECT_EQ(joined.search_queries().size(), 1);
EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 0);
EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 0);
EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 0);
EXPECT_EQ(joined.search_queries().Get(0).query_string(), "blah");
EXPECT_EQ(joined.search_queries().Get(0).query_string_normalized(), "blah");
EXPECT_EQ(
ProtoLanguage_Name(joined.search_queries().Get(0).language()),
"LANGUAGE_DE");
EXPECT_EQ(
ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
"PAGETYPE_SEARCH_PAGE");
//DaWanda Hack
EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 1);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~101");
EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(0).clicked());
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~102");
EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());
});
TEST_CASE(LogJoinTest, ItemOrder, [] () {
auto t = 1432311555 * kMicrosPerSecond;
auto trgt = mkTestTarget();
TrackedSession sess;
sess.insertLogline(t + 0, "q", "E1", URI::ParamList {
{ "q_cat", "1" },
{ "pg", "1" },
{ "is", "p~105~p5,p~106~p6" }
});
sess.insertLogline(t + 10 * kMicrosPerSecond, "v", "E2", URI::ParamList {
{ "i", "p~105"}
});
sess.insertLogline(t + 60 * kMicrosPerSecond, "c", "E1", URI::ParamList {
{ "s", "1"},
{ "is", "p~105~2~550~eur" },
});
auto buf = trgt.trackedSessionToJoinedSession(sess);
auto joined = msg::decode<JoinedSession>(buf);
EXPECT_EQ(joined.num_cart_items(), 1);
EXPECT_EQ(joined.cart_value_eurcents(), 1100);
EXPECT_EQ(joined.num_order_items(), 1);
EXPECT_EQ(joined.gmv_eurcents(), 1100);
EXPECT_EQ(joined.first_seen_time(), 1432311555);
EXPECT_EQ(joined.first_last_time(), 1432311615);
EXPECT_EQ(joined.cart_items().size(), 1);
EXPECT_EQ(joined.cart_items().Get(0).time(), 1432311615);
EXPECT_EQ(joined.cart_items().Get(0).item_id(), "p~105");
EXPECT_EQ(joined.cart_items().Get(0).quantity(), 2);
EXPECT_EQ(joined.cart_items().Get(0).price_cents(), 550);
EXPECT_EQ(
ProtoCurrency_Name(joined.cart_items().Get(0).currency()),
"CURRENCY_EUR");
EXPECT_EQ(joined.cart_items().Get(0).checkout_step(), 1);
EXPECT_EQ(joined.search_queries().size(), 1);
EXPECT_EQ(joined.search_queries().Get(0).num_result_items(), 2);
EXPECT_EQ(joined.search_queries().Get(0).num_result_items_clicked(), 1);
EXPECT_EQ(joined.search_queries().Get(0).num_ad_clicks(), 0);
EXPECT_EQ(joined.search_queries().Get(0).num_cart_items(), 1);
EXPECT_EQ(joined.search_queries().Get(0).cart_value_eurcents(), 1100);
EXPECT_EQ(joined.search_queries().Get(0).num_order_items(), 1);
EXPECT_EQ(joined.search_queries().Get(0).gmv_eurcents(), 1100);
EXPECT_EQ(joined.search_queries().Get(0).page(), 1);
EXPECT_EQ(
ProtoLanguage_Name(joined.search_queries().Get(0).language()),
"LANGUAGE_UNKNOWN_LANGUAGE");
EXPECT_EQ(
ProtoPageType_Name(joined.search_queries().Get(0).page_type()),
"PAGETYPE_CATALOG_PAGE");
EXPECT_EQ(joined.search_queries().Get(0).num_ad_impressions(), 0);
EXPECT_EQ(joined.search_queries().Get(0).result_items().size(), 2);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).position(), 5);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(0).item_id(), "p~105");
EXPECT_TRUE(joined.search_queries().Get(0).result_items().Get(0).clicked());
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).position(), 6);
EXPECT_EQ(joined.search_queries().Get(0).result_items().Get(1).item_id(), "p~106");
EXPECT_FALSE(joined.search_queries().Get(0).result_items().Get(1).clicked());
EXPECT_EQ(joined.item_visits().size(), 1);
EXPECT_EQ(joined.item_visits().Get(0).time(), 1432311565);
EXPECT_EQ(joined.item_visits().Get(0).item_id(), "p~105");
});
/*
TEST_CASE(LogJoinTest, Test1, [] () {
auto loglines_txt = FileUtil::read("src/test_loglines.txt");
auto loglines = StringUtil::split(loglines_txt.toString(), "\n");
for (const auto& logline : loglines) {
if (logline.length() == 0) {
continue;
}
URI::ParamList params;
URI::parseQueryString(logline, ¶ms);
String time;
String evtype;
String evid;
for (auto p = params.begin(); p != params.end(); ) {
switch (p->first[0]) {
default:
++p;
continue;
case 't':
time = p->second;
break;
case 'e':
evtype = p->second;
break;
case 'c':
Vector<String> cid = StringUtil::split(p->second, "~");
evid = cid.at(1);
break;
}
p = params.erase(p);
}
tracked_session.insertLogline(
DateTime((uint64_t) std::stoull(time) * 1000000),
evtype,
evid,
params);
}
auto joined_sessions_schema = joinedSessionsSchema();
LogJoinTarget logjoin_target(joined_sessions_schema, false);
StringMap fields;
fields["p~62797695"]["category1"] = "4";
auto getField = [fields] (const DocID& docid, const String& feature) -> Option<String> {
auto it = fields.find(docid.docid);
if (it != fields.end()) {
auto field = it->second;
auto it_ = field.find(feature);
if (it_ != field.end()) {
return Some(String(it_->second));
}
}
return None<String>();
};
auto normalize = [] (Language lang, const String& query) -> String {
return query;
};
logjoin_target.setGetField(getField);
logjoin_target.setNormalize(normalize);
Buffer session = logjoin_target.trackedSessionToJoinedSession(
tracked_session);
JoinedSession joined_session;
joined_session.ParseFromString(session.toString());
});
*/
<|endoftext|>
|
<commit_before>#include "Default.h"
#include "../Options.h"
#include "../Variables/Variable.h"
#include "../Value.h"
QcDefault::QcDefault(const Options& iOptions, const Data& iData) : Qc(iOptions, iData) {}
bool QcDefault::checkCore(const Value& iValue) const {
const Variable* var = Variable::get(iValue.getVariable());
float value = iValue.getValue();
if(Global::isValid(var->getMin()) && Global::isValid(var->getMax())) {
if(value < var->getMin() || value > var->getMax()) {
std::stringstream ss;
ss << var->getName() << " value of " << value << " on " << iValue.getDate() << " " << iValue.getOffset() << " assumed missing";
Global::logger->write(ss.str(), Logger::warning);
return false;
}
}
return true;
}
<commit_msg>Fixes bug in QcDefault for variables with one discrete point<commit_after>#include "Default.h"
#include "../Options.h"
#include "../Variables/Variable.h"
#include "../Value.h"
QcDefault::QcDefault(const Options& iOptions, const Data& iData) : Qc(iOptions, iData) {}
bool QcDefault::checkCore(const Value& iValue) const {
const Variable* var = Variable::get(iValue.getVariable());
float value = iValue.getValue();
if((Global::isValid(var->getMin()) && value < var->getMin()) ||
(Global::isValid(var->getMax()) && value > var->getMax())) {
std::stringstream ss;
ss << var->getName() << " value of " << value << " on " << iValue.getDate() << " " << iValue.getOffset() << " assumed missing";
Global::logger->write(ss.str(), Logger::warning);
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>
#include "Program.h"
#include "HeeksCNC.h"
#include "RawMaterial.h"
#include "interface/Property.h"
#include "interface/PropertyChoice.h"
#include "interface/PropertyDouble.h"
#include "interface/HeeksObj.h"
#include "ProgramCanvas.h"
#include <wx/string.h>
#include <sstream>
#include <map>
#include <list>
#include <algorithm>
#include <vector>
static void on_set_raw_material(int value, HeeksObj* object)
{
std::set<wxString> materials = CSpeedReferences::GetMaterials();
std::vector<wxString> copy;
std::copy( materials.begin(), materials.end(), std::inserter(copy,copy.end()));
if (value < int(copy.size()))
{
((CProgram *)object)->m_raw_material.m_material_name = copy[value];
((CProgram *)object)->m_raw_material.m_brinell_hardness = 0.0; // Now that they've selected a material, they need to reset the hardness
} // End if - then
heeksCAD->WasModified(object);
}
static void on_set_brinell_hardness(int value, HeeksObj *object)
{
std::set<double> choices = CSpeedReferences::GetHardnessForMaterial( ((CProgram *)object)->m_raw_material.m_material_name );
std::vector<double> choice_array;
std::copy( choices.begin(), choices.end(), std::inserter( choice_array, choice_array.begin() ) );
if (value < int(choice_array.size()))
{
((CProgram *)object)->m_raw_material.m_brinell_hardness = choice_array[value];
heeksCAD->WasModified(object);
} // End if - then
} // End on_set_brinell_hardness() routine
/**
\class CRawMaterial
\ingroup classes
\brief Defines material hardness of the raw material being machined. This value helps
to determine recommended feed and speed settings.
*/
CRawMaterial::CRawMaterial()
{
m_brinell_hardness = 0.0;
m_material_name = _T("Please select a material to machine");
}
double CRawMaterial::Hardness() const
{
return(m_brinell_hardness);
} // End Hardness() method
void CRawMaterial::GetProperties(CProgram *parent, std::list<Property *> *list)
{
{
std::list< wxString > choices;
int choice = 0;
std::set< wxString > materials = theApp.m_program->m_speed_references->GetMaterials();
std::copy( materials.begin(), materials.end(), std::inserter( choices, choices.begin() ) );
if (std::find( choices.begin(), choices.end(), m_material_name ) != choices.end())
{
choice = int(std::distance( std::find( choices.begin(), choices.end(), m_material_name ), choices.begin() ));
} // End if - then
list->push_back(new PropertyChoice(_("Raw Material"), choices, choice, parent, on_set_raw_material));
}
{
std::set<double> hardness_values = theApp.m_program->m_speed_references->GetHardnessForMaterial(m_material_name);
std::list<wxString> choices;
int choice = 0;
for (std::set<double>::const_iterator l_itChoice = hardness_values.begin(); l_itChoice != hardness_values.end(); l_itChoice++)
{
#ifdef UNICODE
std::wostringstream l_ossChoice;
#else
std::ostringstream l_ossChoice;
#endif
l_ossChoice << *l_itChoice;
if (m_brinell_hardness == *l_itChoice)
{
choice = int(std::distance( hardness_values.begin(), l_itChoice ));
} // End if - then
} // End for
list->push_back(new PropertyChoice(_("Brinell Hardness of raw material"), choices, choice, parent, on_set_brinell_hardness));
}
} // End GetProperties() method
void CRawMaterial::WriteBaseXML(TiXmlElement *element)
{
element->SetDoubleAttribute("brinell_hardness", m_brinell_hardness);
} // End WriteBaseXML() method
void CRawMaterial::ReadBaseXML(TiXmlElement* element)
{
if (element->Attribute("brinell_hardness")) m_brinell_hardness = atof(element->Attribute("brinell_hardness"));
} // End ReadBaseXML() method
/**
This method is called when the CAD operator presses the Python button. This method generates
Python source code whose job will be to generate RS-274 GCode. It's done in two steps so that
the Python code can be configured to generate GCode suitable for various CNC interpreters.
*/
void CRawMaterial::AppendTextToProgram()
{
#ifdef UNICODE
std::wostringstream ss;
#else
std::ostringstream ss;
#endif
ss.imbue(std::locale("C"));
ss << "comment(Feeds and Speeds set for machining " << m_material_name << ")\n";
theApp.m_program_canvas->m_textCtrl->AppendText(ss.str().c_str());
}
<commit_msg>Fixed problem where the generated GCode had a comment() entry without quotes around the comment text.<commit_after>
#include "Program.h"
#include "HeeksCNC.h"
#include "RawMaterial.h"
#include "interface/Property.h"
#include "interface/PropertyChoice.h"
#include "interface/PropertyDouble.h"
#include "interface/HeeksObj.h"
#include "ProgramCanvas.h"
#include <wx/string.h>
#include <sstream>
#include <map>
#include <list>
#include <algorithm>
#include <vector>
static void on_set_raw_material(int value, HeeksObj* object)
{
std::set<wxString> materials = CSpeedReferences::GetMaterials();
std::vector<wxString> copy;
std::copy( materials.begin(), materials.end(), std::inserter(copy,copy.end()));
if (value < int(copy.size()))
{
((CProgram *)object)->m_raw_material.m_material_name = copy[value];
((CProgram *)object)->m_raw_material.m_brinell_hardness = 0.0; // Now that they've selected a material, they need to reset the hardness
} // End if - then
heeksCAD->WasModified(object);
}
static void on_set_brinell_hardness(int value, HeeksObj *object)
{
std::set<double> choices = CSpeedReferences::GetHardnessForMaterial( ((CProgram *)object)->m_raw_material.m_material_name );
std::vector<double> choice_array;
std::copy( choices.begin(), choices.end(), std::inserter( choice_array, choice_array.begin() ) );
if (value < int(choice_array.size()))
{
((CProgram *)object)->m_raw_material.m_brinell_hardness = choice_array[value];
heeksCAD->WasModified(object);
} // End if - then
} // End on_set_brinell_hardness() routine
/**
\class CRawMaterial
\ingroup classes
\brief Defines material hardness of the raw material being machined. This value helps
to determine recommended feed and speed settings.
*/
CRawMaterial::CRawMaterial()
{
m_brinell_hardness = 0.0;
m_material_name = _T("Please select a material to machine");
}
double CRawMaterial::Hardness() const
{
return(m_brinell_hardness);
} // End Hardness() method
void CRawMaterial::GetProperties(CProgram *parent, std::list<Property *> *list)
{
{
std::list< wxString > choices;
int choice = 0;
std::set< wxString > materials = theApp.m_program->m_speed_references->GetMaterials();
std::copy( materials.begin(), materials.end(), std::inserter( choices, choices.begin() ) );
if (std::find( choices.begin(), choices.end(), m_material_name ) != choices.end())
{
choice = int(std::distance( std::find( choices.begin(), choices.end(), m_material_name ), choices.begin() ));
} // End if - then
list->push_back(new PropertyChoice(_("Raw Material"), choices, choice, parent, on_set_raw_material));
}
{
std::set<double> hardness_values = theApp.m_program->m_speed_references->GetHardnessForMaterial(m_material_name);
std::list<wxString> choices;
int choice = 0;
for (std::set<double>::const_iterator l_itChoice = hardness_values.begin(); l_itChoice != hardness_values.end(); l_itChoice++)
{
#ifdef UNICODE
std::wostringstream l_ossChoice;
#else
std::ostringstream l_ossChoice;
#endif
l_ossChoice << *l_itChoice;
if (m_brinell_hardness == *l_itChoice)
{
choice = int(std::distance( hardness_values.begin(), l_itChoice ));
} // End if - then
} // End for
list->push_back(new PropertyChoice(_("Brinell Hardness of raw material"), choices, choice, parent, on_set_brinell_hardness));
}
} // End GetProperties() method
void CRawMaterial::WriteBaseXML(TiXmlElement *element)
{
element->SetDoubleAttribute("brinell_hardness", m_brinell_hardness);
} // End WriteBaseXML() method
void CRawMaterial::ReadBaseXML(TiXmlElement* element)
{
if (element->Attribute("brinell_hardness")) m_brinell_hardness = atof(element->Attribute("brinell_hardness"));
} // End ReadBaseXML() method
/**
This method is called when the CAD operator presses the Python button. This method generates
Python source code whose job will be to generate RS-274 GCode. It's done in two steps so that
the Python code can be configured to generate GCode suitable for various CNC interpreters.
*/
void CRawMaterial::AppendTextToProgram()
{
#ifdef UNICODE
std::wostringstream ss;
#else
std::ostringstream ss;
#endif
ss.imbue(std::locale("C"));
ss << "comment('Feeds and Speeds set for machining " << m_material_name.c_str() << "')\n";
theApp.m_program_canvas->m_textCtrl->AppendText(ss.str().c_str());
}
<|endoftext|>
|
<commit_before>// This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
using namespace arma;
// pn
double pn(mat y, mat mu, mat sigma);
RcppExport SEXP mcif_pn(SEXP ySEXP, SEXP muSEXP, SEXP sigmaSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type mu(muSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
__result = Rcpp::wrap(pn(y, mu, sigma));
return __result;
END_RCPP
}
// loglikfull
vec loglikfull(mat y, mat b, mat u, mat sigma, mat alph, mat dalph, bool cond);
RcppExport SEXP mcif_loglikfull(SEXP ySEXP, SEXP bSEXP, SEXP uSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP condSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type u(uSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< bool >::type cond(condSEXP);
__result = Rcpp::wrap(loglikfull(y, b, u, sigma, alph, dalph, cond));
return __result;
END_RCPP
}
// Dloglikfull
mat Dloglikfull(mat y, mat b, mat u, mat sigma, mat alph, mat dalph, bool cond);
RcppExport SEXP mcif_Dloglikfull(SEXP ySEXP, SEXP bSEXP, SEXP uSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP condSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type u(uSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< bool >::type cond(condSEXP);
__result = Rcpp::wrap(Dloglikfull(y, b, u, sigma, alph, dalph, cond));
return __result;
END_RCPP
}
// D2loglikfull
mat D2loglikfull(mat y, mat b, mat u, mat sigma, mat alph, mat dalph, bool cond);
RcppExport SEXP mcif_D2loglikfull(SEXP ySEXP, SEXP bSEXP, SEXP uSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP condSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type u(uSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< bool >::type cond(condSEXP);
__result = Rcpp::wrap(D2loglikfull(y, b, u, sigma, alph, dalph, cond));
return __result;
END_RCPP
}
// loglik
vec loglik(mat y, mat b, mat sigma, mat alph, mat dalph, int nq, double stepsize, unsigned iter, bool debug);
RcppExport SEXP mcif_loglik(SEXP ySEXP, SEXP bSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP nqSEXP, SEXP stepsizeSEXP, SEXP iterSEXP, SEXP debugSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< int >::type nq(nqSEXP);
Rcpp::traits::input_parameter< double >::type stepsize(stepsizeSEXP);
Rcpp::traits::input_parameter< unsigned >::type iter(iterSEXP);
Rcpp::traits::input_parameter< bool >::type debug(debugSEXP);
__result = Rcpp::wrap(loglik(y, b, sigma, alph, dalph, nq, stepsize, iter, debug));
return __result;
END_RCPP
}
<commit_msg>updated attributes<commit_after>// This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
// pn
double pn(mat y, mat mu, mat sigma);
RcppExport SEXP mcif_pn(SEXP ySEXP, SEXP muSEXP, SEXP sigmaSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type mu(muSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
__result = Rcpp::wrap(pn(y, mu, sigma));
return __result;
END_RCPP
}
// loglikfull
vec loglikfull(mat y, mat b, mat u, mat sigma, mat alph, mat dalph, bool cond);
RcppExport SEXP mcif_loglikfull(SEXP ySEXP, SEXP bSEXP, SEXP uSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP condSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type u(uSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< bool >::type cond(condSEXP);
__result = Rcpp::wrap(loglikfull(y, b, u, sigma, alph, dalph, cond));
return __result;
END_RCPP
}
// Dloglikfull
mat Dloglikfull(mat y, mat b, mat u, mat sigma, mat alph, mat dalph, bool cond);
RcppExport SEXP mcif_Dloglikfull(SEXP ySEXP, SEXP bSEXP, SEXP uSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP condSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type u(uSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< bool >::type cond(condSEXP);
__result = Rcpp::wrap(Dloglikfull(y, b, u, sigma, alph, dalph, cond));
return __result;
END_RCPP
}
// D2loglikfull
mat D2loglikfull(mat y, mat b, mat u, mat sigma, mat alph, mat dalph, bool cond);
RcppExport SEXP mcif_D2loglikfull(SEXP ySEXP, SEXP bSEXP, SEXP uSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP condSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type u(uSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< bool >::type cond(condSEXP);
__result = Rcpp::wrap(D2loglikfull(y, b, u, sigma, alph, dalph, cond));
return __result;
END_RCPP
}
// loglik
vec loglik(mat y, mat b, mat sigma, mat alph, mat dalph, mat eb0, int nq, double stepsize, int useeb0, unsigned iter, bool debug);
RcppExport SEXP mcif_loglik(SEXP ySEXP, SEXP bSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP eb0SEXP, SEXP nqSEXP, SEXP stepsizeSEXP, SEXP useeb0SEXP, SEXP iterSEXP, SEXP debugSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< mat >::type eb0(eb0SEXP);
Rcpp::traits::input_parameter< int >::type nq(nqSEXP);
Rcpp::traits::input_parameter< double >::type stepsize(stepsizeSEXP);
Rcpp::traits::input_parameter< int >::type useeb0(useeb0SEXP);
Rcpp::traits::input_parameter< unsigned >::type iter(iterSEXP);
Rcpp::traits::input_parameter< bool >::type debug(debugSEXP);
__result = Rcpp::wrap(loglik(y, b, sigma, alph, dalph, eb0, nq, stepsize, useeb0, iter, debug));
return __result;
END_RCPP
}
// EB0
mat EB0(mat y, mat b, mat sigma, mat alph, mat dalph, double stepsize, unsigned iter);
RcppExport SEXP mcif_EB0(SEXP ySEXP, SEXP bSEXP, SEXP sigmaSEXP, SEXP alphSEXP, SEXP dalphSEXP, SEXP stepsizeSEXP, SEXP iterSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< mat >::type y(ySEXP);
Rcpp::traits::input_parameter< mat >::type b(bSEXP);
Rcpp::traits::input_parameter< mat >::type sigma(sigmaSEXP);
Rcpp::traits::input_parameter< mat >::type alph(alphSEXP);
Rcpp::traits::input_parameter< mat >::type dalph(dalphSEXP);
Rcpp::traits::input_parameter< double >::type stepsize(stepsizeSEXP);
Rcpp::traits::input_parameter< unsigned >::type iter(iterSEXP);
__result = Rcpp::wrap(EB0(y, b, sigma, alph, dalph, stepsize, iter));
return __result;
END_RCPP
}
<|endoftext|>
|
<commit_before>#include "instruction_list.h"
#include "instruction_structs.h"
#include <istream>
#include <sstream>
#include <memory>
#include <algorithm>
#include <iterator>
#include <bitset>
using namespace std;
InstructionList::InstructionList(const InstructionManager & im) {
build_assembly_table(im);
build_execution_tables(im);
}
Instruction InstructionList::assemble(string & str) const {
trim(str);
transform(begin(str), end(str), begin(str),
[](auto i) { return toupper(i); });
istringstream to_tokenize(str);
vector<string> tokens((istream_iterator<string>(to_tokenize)),
istream_iterator<string>());
auto i = assembly_table.find(tokens.front());
if (i == assembly_table.end()) {
throw runtime_error("no such instruction");
}
return i->second->assemble(tokens);
}
shared_ptr<InstructionDescriptor> InstructionList::descriptor_for_instruction(
Instruction instr) const {
auto type = get_op_type(instr.r.op);
switch (type) {
case OpType::R: {
auto i = execution_r_table.find(instr.r.funct);
if (i == execution_r_table.end()) {
stringstream ss;
ss << "no such function code: " << instr.r.funct << endl;
ss << "full instruction: " << instr.raw << " ("
<< bitset<32>(instr.raw) << ")" << endl;
throw runtime_error(ss.str());
}
return i->second;
}
case OpType::I: {
auto i = execution_i_table.find(instr.i.op);
if (i == execution_i_table.end()) {
stringstream ss;
ss << "no such op code: " << instr.i.op << endl;
ss << "full instruction: " << instr.raw << " ("
<< bitset<32>(instr.raw) << ")" << endl;
throw runtime_error(ss.str());
}
return i->second;
}
case OpType::J: {
auto i = execution_j_table.find(instr.j.op);
if (i == execution_j_table.end()) {
stringstream ss;
ss << "no such op code: " << instr.j.op;
ss << "full instruction: " << instr.raw << " ("
<< bitset<32>(instr.raw) << ")" << endl;
throw runtime_error(ss.str());
}
return i->second;
}
}
}
string InstructionList::disassemble(Instruction instr) const {
return descriptor_for_instruction(instr)->disassemble(instr);
}
string InstructionList::tooltip(Instruction instr) const {
return descriptor_for_instruction(instr)->get_tooltip();
}
void InstructionList::execute(Core & core, vector<Instruction> & memory) const {
auto instr = memory[core.ip];
descriptor_for_instruction(instr)->execute(core, memory, instr);
if (get_op_type(instr.r.op) != OpType::J)
core.ip += 1;
}
void InstructionList::build_assembly_table(const InstructionManager & im) {
for (auto i : im.r_instructions)
assembly_table[i->get_string()] = i;
for (auto i : im.i_instructions)
assembly_table[i->get_string()] = i;
for (auto i : im.j_instructions)
assembly_table[i->get_string()] = i;
}
void InstructionList::build_execution_tables(const InstructionManager & im) {
for (auto i : im.r_instructions)
execution_r_table[i->get_id_code()] = i;
for (auto i : im.i_instructions)
execution_i_table[i->get_id_code()] = i;
for (auto i : im.j_instructions)
execution_j_table[i->get_id_code()] = i;
}
<commit_msg>added reminder comment<commit_after>#include "instruction_list.h"
#include "instruction_structs.h"
#include <istream>
#include <sstream>
#include <memory>
#include <algorithm>
#include <iterator>
#include <bitset>
using namespace std;
InstructionList::InstructionList(const InstructionManager & im) {
build_assembly_table(im);
build_execution_tables(im);
}
Instruction InstructionList::assemble(string & str) const {
trim(str);
transform(begin(str), end(str), begin(str),
[](auto i) { return toupper(i); });
istringstream to_tokenize(str);
vector<string> tokens((istream_iterator<string>(to_tokenize)),
istream_iterator<string>());
auto i = assembly_table.find(tokens.front());
if (i == assembly_table.end()) {
throw runtime_error("no such instruction");
}
return i->second->assemble(tokens);
}
shared_ptr<InstructionDescriptor> InstructionList::descriptor_for_instruction(
Instruction instr) const {
auto type = get_op_type(instr.r.op);
// TODO could replace with nested maps
switch (type) {
case OpType::R: {
auto i = execution_r_table.find(instr.r.funct);
if (i == execution_r_table.end()) {
stringstream ss;
ss << "no such function code: " << instr.r.funct << endl;
ss << "full instruction: " << instr.raw << " ("
<< bitset<32>(instr.raw) << ")" << endl;
throw runtime_error(ss.str());
}
return i->second;
}
case OpType::I: {
auto i = execution_i_table.find(instr.i.op);
if (i == execution_i_table.end()) {
stringstream ss;
ss << "no such op code: " << instr.i.op << endl;
ss << "full instruction: " << instr.raw << " ("
<< bitset<32>(instr.raw) << ")" << endl;
throw runtime_error(ss.str());
}
return i->second;
}
case OpType::J: {
auto i = execution_j_table.find(instr.j.op);
if (i == execution_j_table.end()) {
stringstream ss;
ss << "no such op code: " << instr.j.op;
ss << "full instruction: " << instr.raw << " ("
<< bitset<32>(instr.raw) << ")" << endl;
throw runtime_error(ss.str());
}
return i->second;
}
}
}
string InstructionList::disassemble(Instruction instr) const {
return descriptor_for_instruction(instr)->disassemble(instr);
}
string InstructionList::tooltip(Instruction instr) const {
return descriptor_for_instruction(instr)->get_tooltip();
}
void InstructionList::execute(Core & core, vector<Instruction> & memory) const {
auto instr = memory[core.ip];
descriptor_for_instruction(instr)->execute(core, memory, instr);
if (get_op_type(instr.r.op) != OpType::J)
core.ip += 1;
}
void InstructionList::build_assembly_table(const InstructionManager & im) {
for (auto i : im.r_instructions)
assembly_table[i->get_string()] = i;
for (auto i : im.i_instructions)
assembly_table[i->get_string()] = i;
for (auto i : im.j_instructions)
assembly_table[i->get_string()] = i;
}
void InstructionList::build_execution_tables(const InstructionManager & im) {
for (auto i : im.r_instructions)
execution_r_table[i->get_id_code()] = i;
for (auto i : im.i_instructions)
execution_i_table[i->get_id_code()] = i;
for (auto i : im.j_instructions)
execution_j_table[i->get_id_code()] = i;
}
<|endoftext|>
|
<commit_before>/*
* The Biomechanical ToolKit
* Copyright (c) 2009-2011, Arnaud Barré
* 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "btkVTKGRFsFramesSource.h"
#include "btkVTKDataObjectAdapter.h"
#include <vtkstd/vector>
#include <vtkPolyData.h>
#include <vtkLineSource.h>
#include <vtkAppendPolyData.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkStreamingDemandDrivenPipeline.h>
namespace btk
{
/**
* @class VTKGRFsComponents btkVTKGRFsFramesSource.h
* @brief Store ground reaction forces vector as vector of vtkPolyData
*/
class VTKGRFsComponents : public vtkstd::vector<vtkPolyData*>
{};
/**
* @class VTKGRFsFramesSource
* @brief Display ground reaction forces (GRF).
*
* This filter compute all GRFs when a new input is set or modified (@see VTKGRFsFramesSource::RequestInformation).
* The display of GRFs for each frame use the vtk TIME mechanism by setting the required frame
* to a vtkStreamingDemandDrivenPipeline object and call the vtkRenderer::Renderer() method.
* For example:
* @code
* // BTK
* btk::AcquisitionFileReader::Pointer reader = btk::AcquisitionFileReader::New();
* reader->SetDisableFilenameExceptionState(true);
* btk::ForcePlatformsExtractor::Pointer forcePlatformsExtractor = btk::ForcePlatformsExtractor::New();
* forcePlatformsExtractor->SetInput(reader->GetOutput());
* btk::GroundReactionWrenchFilter::Pointer GRWsFilter = btk::GroundReactionWrenchFilter::New();
* GRWsFilter->SetThresholdValue(5.0); // PWA are not computed from vertical forces lower than 5 newtons.
* GRWsFilter->SetThresholdState(true);
* GRWsFilter->SetInput(forcePlatformsExtractor->GetOutput());
* // VTK
* vtkRenderer* renderer = vtkRenderer::New()
* btk::VTKGRFsFramesSource* GRFs = btk::VTKGRFsFramesSource::New();
* GRFs->SetInput(GRWsFilter->GetOutput());
* vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
* mapper->SetInputConnection(GRFs->GetOutputPort());
* vtkActor* actor = vtkActor::New();
* actor->SetMapper(mapper);
* renderer->AddActor(actor);
* // ...
* int numberOfFrames = reader->GetAnalogFrameNumber();
* vtkStreamingDemandDrivenPipeline* exec = vtkStreamingDemandDrivenPipeline::SafeDownCast(GRFs->GetExecutive());
* for (int i = 1 ; i < numberOfFrames ; ++i)
* {
* exec->SetUpdateTimeStep(0, i);
* mapper->Modified();
* renderer->Render();
* }
* // Code cleanup
* // ...
* @endcode
*
* @ingroup BTKVTK
*/
/**
* @fn static VTKGRFsFramesSource* VTKGRFsFramesSource::New();
* Creates a VTKGRFsFramesSource object and return it as a pointer.
*/
vtkStandardNewMacro(VTKGRFsFramesSource);
vtkCxxRevisionMacro(VTKGRFsFramesSource, "$Revision: 0.1 $");
/**
* Prints only the Superclass information.
*/
void VTKGRFsFramesSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
/**
* Set filter's input.
*/
void VTKGRFsFramesSource::SetInput(WrenchCollection::Pointer input)
{
VTKDataObjectAdapter* inObject = VTKDataObjectAdapter::New();
inObject->SetBTKDataObject(input);
this->vtkPolyDataAlgorithm::SetInput(inObject);
inObject->Delete();
};
/**
* @fn double VTKGRFsFramesSource::GetScaleUnit()
* Returns the scale factor used to set GRFs' positions (i.e. the point of wrench application (PWA)).
*
* Usefull when visualized acquistion date are set in meter, millimeter, inch, etc.
*/
/**
* @fn void VTKGRFsFramesSource::SetScaleUnit(double s)
* Sets the scale factor used to set GRFs' positions.
*
* Usefull when visualized acquistion date are set in meter, millimeter, inch, etc.
*/
/**
* Constructor.
*
* Filter with one input and output.
*/
VTKGRFsFramesSource::VTKGRFsFramesSource()
: vtkPolyDataAlgorithm()
{
this->mp_GRFsComponents = new VTKGRFsComponents();
this->mp_Scale = 1.0;
};
/**
* Destructor.
*/
VTKGRFsFramesSource::~VTKGRFsFramesSource()
{
for (size_t i = 0 ; i < this->mp_GRFsComponents->size() ; ++i)
this->mp_GRFsComponents->operator[](i)->Delete();
delete this->mp_GRFsComponents;
};
/**
* Generate GRFs' vectors
*/
int VTKGRFsFramesSource::RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
btkNotUsed(request)
// Convert a btk::PointCollection into a collection of polydata containing only vertices.
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
VTKDataObjectAdapter* inObject = VTKDataObjectAdapter::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
if (!inObject)
return 0;
WrenchCollection::Pointer input = static_pointer_cast<WrenchCollection>(inObject->GetBTKDataObject());
// Raz
for (size_t i = 0 ; i < this->mp_GRFsComponents->size() ; ++i)
this->mp_GRFsComponents->operator[](i)->Delete();
this->mp_GRFsComponents->clear();
int frameNumber = 0;
int wrenchNumber = input->GetItemNumber();
if (wrenchNumber != 0)
{
frameNumber = input->GetItem(0)->GetPosition()->GetFrameNumber();
this->mp_GRFsComponents->resize(frameNumber);
vtkAppendPolyData* append = vtkAppendPolyData::New();
append->UserManagedInputsOn();
append->SetNumberOfInputs(wrenchNumber);
vtkLineSource* lineGenerator = vtkLineSource::New();
for (int i = 0 ; i < frameNumber ; ++i)
{
int wrenchIdx = 0;
WrenchCollection::ConstIterator it = input->Begin();
while (it != input->End())
{
if ((*it)->GetPosition()->GetResiduals().coeff(i) != -1.0)
{
double* positions = (*it)->GetPosition()->GetValues().data();
double* forces = (*it)->GetForce()->GetValues().data();
lineGenerator->SetPoint1(positions[i] * this->mp_Scale,
positions[i + frameNumber] * this->mp_Scale,
positions[i + 2 * frameNumber] * this->mp_Scale);
lineGenerator->SetPoint2(positions[i] * this->mp_Scale + forces[i],
positions[i + frameNumber] * this->mp_Scale + forces[i + frameNumber],
positions[i + 2 * frameNumber] * this->mp_Scale + forces[i + 2 * frameNumber]);
lineGenerator->Update();
vtkPolyData* GRF = vtkPolyData::New();
GRF->DeepCopy(lineGenerator->GetOutput());
append->SetInputByNumber(wrenchIdx, GRF);
GRF->Delete();
}
else
append->SetInputByNumber(wrenchIdx, 0);
++it; ++wrenchIdx;
}
append->Update();
vtkPolyData* GRFs = vtkPolyData::New();
GRFs->DeepCopy(append->GetOutput());
this->mp_GRFsComponents->operator[](i) = GRFs;
}
lineGenerator->Delete();
append->Delete();
}
// Update output informations
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// TIME_STEPS
double *outTimes = new double [frameNumber];
int i;
for (i = 0; i < frameNumber; ++i)
outTimes[i] = i;
outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), outTimes, frameNumber);
delete [] outTimes;
// TIME_RANGE
double outRange[2];
outRange[0] = 0;
outRange[1] = frameNumber - 1;
outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), outRange, 2);
return 1;
};
/**
* Extract GRFs frame required by a vtkStreamingDemandDrivenPipeline object.
*/
int VTKGRFsFramesSource::RequestData(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
btkNotUsed(request);
btkNotUsed(inputVector);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (this->mp_GRFsComponents->size() != 0)
{
double t = 0;
if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS()))
t = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS())[0];
outInfo->Set(vtkDataObject::DATA_TIME_STEPS(), &t, 1);
vtkPolyData* poly = vtkPolyData::SafeDownCast(this->mp_GRFsComponents->operator[](static_cast<int>(t)));
output->ShallowCopy(poly);
}
else
output->Initialize();
return 1;
};
/*
int VTKGRFsFramesSource::RequestUpdateExtent(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector)
{
btkNotUsed(request);
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()));
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()));
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()));
inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1);
return 1;
}
*/
/**
* Sets the type of object required for the input.
*/
int VTKGRFsFramesSource::FillInputPortInformation(int port,
vtkInformation* info)
{
btkNotUsed(port);
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "VTKDataObjectAdapter");
return 1;
}
};
<commit_msg>[FIX] btk::VTKGRFsFramesSource is called two times inside Mokka each time you load an acquisition (MTimes problem?).<commit_after>/*
* The Biomechanical ToolKit
* Copyright (c) 2009-2011, Arnaud Barré
* 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "btkVTKGRFsFramesSource.h"
#include "btkVTKDataObjectAdapter.h"
#include <vtkstd/vector>
#include <vtkPolyData.h>
#include <vtkLineSource.h>
#include <vtkAppendPolyData.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkStreamingDemandDrivenPipeline.h>
namespace btk
{
/**
* @class VTKGRFsComponents btkVTKGRFsFramesSource.h
* @brief Store ground reaction forces vector as vector of vtkPolyData
*/
class VTKGRFsComponents : public vtkstd::vector<vtkPolyData*>
{};
/**
* @class VTKGRFsFramesSource
* @brief Display ground reaction forces (GRF).
*
* This filter compute all GRFs when a new input is set or modified (@see VTKGRFsFramesSource::RequestInformation).
* The display of GRFs for each frame use the vtk TIME mechanism by setting the required frame
* to a vtkStreamingDemandDrivenPipeline object and call the vtkRenderer::Renderer() method.
* For example:
* @code
* // BTK
* btk::AcquisitionFileReader::Pointer reader = btk::AcquisitionFileReader::New();
* reader->SetDisableFilenameExceptionState(true);
* btk::ForcePlatformsExtractor::Pointer forcePlatformsExtractor = btk::ForcePlatformsExtractor::New();
* forcePlatformsExtractor->SetInput(reader->GetOutput());
* btk::GroundReactionWrenchFilter::Pointer GRWsFilter = btk::GroundReactionWrenchFilter::New();
* GRWsFilter->SetThresholdValue(5.0); // PWA are not computed from vertical forces lower than 5 newtons.
* GRWsFilter->SetThresholdState(true);
* GRWsFilter->SetInput(forcePlatformsExtractor->GetOutput());
* // VTK
* vtkRenderer* renderer = vtkRenderer::New()
* btk::VTKGRFsFramesSource* GRFs = btk::VTKGRFsFramesSource::New();
* GRFs->SetInput(GRWsFilter->GetOutput());
* vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
* mapper->SetInputConnection(GRFs->GetOutputPort());
* vtkActor* actor = vtkActor::New();
* actor->SetMapper(mapper);
* renderer->AddActor(actor);
* // ...
* int numberOfFrames = reader->GetAnalogFrameNumber();
* vtkStreamingDemandDrivenPipeline* exec = vtkStreamingDemandDrivenPipeline::SafeDownCast(GRFs->GetExecutive());
* for (int i = 1 ; i < numberOfFrames ; ++i)
* {
* exec->SetUpdateTimeStep(0, i);
* mapper->Modified();
* renderer->Render();
* }
* // Code cleanup
* // ...
* @endcode
*
* @ingroup BTKVTK
*/
/**
* @fn static VTKGRFsFramesSource* VTKGRFsFramesSource::New();
* Creates a VTKGRFsFramesSource object and return it as a pointer.
*/
vtkStandardNewMacro(VTKGRFsFramesSource);
vtkCxxRevisionMacro(VTKGRFsFramesSource, "$Revision: 0.1 $");
/**
* Prints only the Superclass information.
*/
void VTKGRFsFramesSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
/**
* Set filter's input.
*/
void VTKGRFsFramesSource::SetInput(WrenchCollection::Pointer input)
{
VTKDataObjectAdapter* inObject = VTKDataObjectAdapter::New();
inObject->SetBTKDataObject(input);
this->vtkPolyDataAlgorithm::SetInput(inObject);
inObject->Delete();
};
/**
* @fn double VTKGRFsFramesSource::GetScaleUnit()
* Returns the scale factor used to set GRFs' positions (i.e. the point of wrench application (PWA)).
*
* Usefull when visualized acquistion date are set in meter, millimeter, inch, etc.
*/
/**
* @fn void VTKGRFsFramesSource::SetScaleUnit(double s)
* Sets the scale factor used to set GRFs' positions.
*
* Usefull when visualized acquistion date are set in meter, millimeter, inch, etc.
*/
/**
* Constructor.
*
* Filter with one input and output.
*/
VTKGRFsFramesSource::VTKGRFsFramesSource()
: vtkPolyDataAlgorithm()
{
this->mp_GRFsComponents = new VTKGRFsComponents();
this->mp_Scale = 1.0;
};
/**
* Destructor.
*/
VTKGRFsFramesSource::~VTKGRFsFramesSource()
{
for (size_t i = 0 ; i < this->mp_GRFsComponents->size() ; ++i)
this->mp_GRFsComponents->operator[](i)->Delete();
delete this->mp_GRFsComponents;
};
/**
* Generate GRFs' vectors
*/
int VTKGRFsFramesSource::RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
btkNotUsed(request)
// Convert a btk::PointCollection into a collection of polydata containing only vertices.
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
VTKDataObjectAdapter* inObject = VTKDataObjectAdapter::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
if (!inObject)
return 0;
if (inObject->GetMTime() < this->GetMTime())
return 0;
WrenchCollection::Pointer input = static_pointer_cast<WrenchCollection>(inObject->GetBTKDataObject());
// Raz
for (size_t i = 0 ; i < this->mp_GRFsComponents->size() ; ++i)
this->mp_GRFsComponents->operator[](i)->Delete();
this->mp_GRFsComponents->clear();
int frameNumber = 0;
int wrenchNumber = input->GetItemNumber();
if (wrenchNumber != 0)
{
frameNumber = input->GetItem(0)->GetPosition()->GetFrameNumber();
this->mp_GRFsComponents->resize(frameNumber);
vtkAppendPolyData* append = vtkAppendPolyData::New();
append->UserManagedInputsOn();
append->SetNumberOfInputs(wrenchNumber);
vtkLineSource* lineGenerator = vtkLineSource::New();
for (int i = 0 ; i < frameNumber ; ++i)
{
int wrenchIdx = 0;
WrenchCollection::ConstIterator it = input->Begin();
while (it != input->End())
{
if ((*it)->GetPosition()->GetResiduals().coeff(i) != -1.0)
{
double* positions = (*it)->GetPosition()->GetValues().data();
double* forces = (*it)->GetForce()->GetValues().data();
lineGenerator->SetPoint1(positions[i] * this->mp_Scale,
positions[i + frameNumber] * this->mp_Scale,
positions[i + 2 * frameNumber] * this->mp_Scale);
lineGenerator->SetPoint2(positions[i] * this->mp_Scale + forces[i],
positions[i + frameNumber] * this->mp_Scale + forces[i + frameNumber],
positions[i + 2 * frameNumber] * this->mp_Scale + forces[i + 2 * frameNumber]);
lineGenerator->Update();
vtkPolyData* GRF = vtkPolyData::New();
GRF->DeepCopy(lineGenerator->GetOutput());
append->SetInputByNumber(wrenchIdx, GRF);
GRF->Delete();
}
else
append->SetInputByNumber(wrenchIdx, 0);
++it; ++wrenchIdx;
}
append->Update();
vtkPolyData* GRFs = vtkPolyData::New();
GRFs->DeepCopy(append->GetOutput());
this->mp_GRFsComponents->operator[](i) = GRFs;
}
lineGenerator->Delete();
append->Delete();
}
// Update output informations
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// TIME_STEPS
double *outTimes = new double [frameNumber];
int i;
for (i = 0; i < frameNumber; ++i)
outTimes[i] = i;
outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), outTimes, frameNumber);
delete [] outTimes;
// TIME_RANGE
double outRange[2];
outRange[0] = 0;
outRange[1] = frameNumber - 1;
outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), outRange, 2);
return 1;
};
/**
* Extract GRFs frame required by a vtkStreamingDemandDrivenPipeline object.
*/
int VTKGRFsFramesSource::RequestData(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
btkNotUsed(request);
btkNotUsed(inputVector);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (this->mp_GRFsComponents->size() != 0)
{
double t = 0;
if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS()))
t = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS())[0];
outInfo->Set(vtkDataObject::DATA_TIME_STEPS(), &t, 1);
vtkPolyData* poly = vtkPolyData::SafeDownCast(this->mp_GRFsComponents->operator[](static_cast<int>(t)));
output->ShallowCopy(poly);
}
else
output->Initialize();
return 1;
};
/*
int VTKGRFsFramesSource::RequestUpdateExtent(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector)
{
btkNotUsed(request);
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()));
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()));
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()));
inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1);
return 1;
}
*/
/**
* Sets the type of object required for the input.
*/
int VTKGRFsFramesSource::FillInputPortInformation(int port,
vtkInformation* info)
{
btkNotUsed(port);
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "VTKDataObjectAdapter");
return 1;
}
};
<|endoftext|>
|
<commit_before>#pragma once
#ifdef __APPLE__
namespace cgc1
{
/**
* \brief Scoped variable for locking lock.
**/
template <typename T>
using lock_guard_t = ::std::lock_guard<T>;
/**
* \brief Lockable that is a pthread mutex.
**/
class pthread_mutex_t
{
public:
/**
* \brief Constructor.
*
* Aborts on error.
**/
pthread_mutex_t() noexcept
{
if (pthread_mutex_init(&m_mutex, 0))
::abort();
}
pthread_mutex_t(const pthread_mutex_t &) = delete;
pthread_mutex_t(pthread_mutex_t &&) = default;
/**
* \brief Destructor.
*
* Aborts on error.
**/
~pthread_mutex_t()
{
if (::pthread_mutex_destroy(&m_mutex))
::abort();
}
/**
* \brief Locks lock.
*
* Aborts on error.
**/
void lock() noexcept
{
if (::pthread_mutex_lock(&m_mutex))
::abort();
}
/**
* \brief Unlocks lock.
*
* Aborts on error.
**/
void unlock() noexcept
{
if (::pthread_mutex_unlock(&m_mutex))
::abort();
}
/**
* \brief Try to acquire locks.
*
* Does not block.
* @return True if acquired lock, false otherwise.
**/
bool try_lock() noexcept
{
auto result = ::pthread_mutex_trylock(&m_mutex);
if (result == 0)
return true;
return false;
}
/**
* \brief Type of native handle.
**/
using native_handle_type = ::pthread_mutex_t *;
/**
* \brief Return native handle.
**/
native_handle_type native_handle() noexcept
{
return &m_mutex;
}
private:
/**
* \brief Underlying pthread mutex.
**/
::pthread_mutex_t m_mutex;
};
/**
* \brief Conditional variable using pthreads.
**/
class pthread_condition_variable_any_t
{
public:
/**
* \brief Constructor.
*
* Aborts on error.
**/
pthread_condition_variable_any_t() noexcept
{
if (::pthread_cond_init(&m_cond, 0))
::abort();
}
pthread_condition_variable_any_t(const pthread_condition_variable_any_t &) = delete;
pthread_condition_variable_any_t(pthread_condition_variable_any_t &&) = default;
/**
* \brief Destructor.
*
* Aborts on error.
**/
~pthread_condition_variable_any_t()
{
if (::pthread_cond_destroy(&m_cond))
::abort();
}
/**
* \brief Wait until signaled and pred is true.
*
* Aborts on error.
* @param lock Lock to unlock while waiting and reacquire afterwards.
* @param pred Predicate to test.
**/
template <typename Lock, typename Pred>
void wait(Lock &lock, const Pred &pred)
{
while (!pred())
wait(lock);
}
/**
* \brief Wait until signaled.
*
* Aborts on error.
* @param lock Lock to unlock while waiting and reacquire afterwards.
**/
template <typename Lock>
void wait(Lock &lock)
{
m_mutex.lock();
lock.unlock();
if (::pthread_cond_wait(&m_cond, m_mutex.native_handle()))
::abort();
m_mutex.unlock();
lock.lock();
}
/**
* \brief Notify all variables waiting.
*
* Aborts on error.
**/
void notify_all() noexcept
{
lock_guard_t<decltype(m_mutex)> lg(m_mutex);
if (::pthread_cond_broadcast(&m_cond))
::abort();
}
private:
/**
* \brief Underlying pthread conditional variable.
**/
::pthread_cond_t m_cond;
/**
* \brief Internal mutex needed for protection since pthread requires a pthread mutex.
**/
::pthread_mutex_t m_mutex;
};
/**
* \brief Lockable that is an operating system mutex.
**/
using mutex_t = pthread_mutex_t;
/**
* \brief The class unique_lock_t is a general-purpose mutex ownership wrapper.
**/
template <typename T>
using unique_lock_t = ::std::unique_lock<T>;
}
#endif
<commit_msg>Fix OSX compile error<commit_after>#pragma once
#ifdef __APPLE__
namespace cgc1
{
/**
* \brief Scoped variable for locking lock.
**/
template <typename T>
using lock_guard_t = ::std::lock_guard<T>;
/**
* \brief Lockable that is a pthread mutex.
**/
class pthread_mutex_t
{
public:
/**
* \brief Constructor.
*
* Aborts on error.
**/
pthread_mutex_t() noexcept
{
if (pthread_mutex_init(&m_mutex, 0))
::abort();
}
pthread_mutex_t(const pthread_mutex_t &) = delete;
pthread_mutex_t(pthread_mutex_t &&) = default;
/**
* \brief Destructor.
*
* Aborts on error.
**/
~pthread_mutex_t()
{
if (::pthread_mutex_destroy(&m_mutex))
::abort();
}
/**
* \brief Locks lock.
*
* Aborts on error.
**/
void lock() noexcept
{
if (::pthread_mutex_lock(&m_mutex))
::abort();
}
/**
* \brief Unlocks lock.
*
* Aborts on error.
**/
void unlock() noexcept
{
if (::pthread_mutex_unlock(&m_mutex))
::abort();
}
/**
* \brief Try to acquire locks.
*
* Does not block.
* @return True if acquired lock, false otherwise.
**/
bool try_lock() noexcept
{
auto result = ::pthread_mutex_trylock(&m_mutex);
if (result == 0)
return true;
return false;
}
/**
* \brief Type of native handle.
**/
using native_handle_type = ::pthread_mutex_t *;
/**
* \brief Return native handle.
**/
native_handle_type native_handle() noexcept
{
return &m_mutex;
}
private:
/**
* \brief Underlying pthread mutex.
**/
::pthread_mutex_t m_mutex;
};
/**
* \brief Conditional variable using pthreads.
**/
class pthread_condition_variable_any_t
{
public:
/**
* \brief Constructor.
*
* Aborts on error.
**/
pthread_condition_variable_any_t() noexcept
{
if (::pthread_cond_init(&m_cond, 0))
::abort();
}
pthread_condition_variable_any_t(const pthread_condition_variable_any_t &) = delete;
pthread_condition_variable_any_t(pthread_condition_variable_any_t &&) = default;
/**
* \brief Destructor.
*
* Aborts on error.
**/
~pthread_condition_variable_any_t()
{
if (::pthread_cond_destroy(&m_cond))
::abort();
}
/**
* \brief Wait until signaled and pred is true.
*
* Aborts on error.
* @param lock Lock to unlock while waiting and reacquire afterwards.
* @param pred Predicate to test.
**/
template <typename Lock, typename Pred>
void wait(Lock &lock, const Pred &pred)
{
while (!pred())
wait(lock);
}
/**
* \brief Wait until signaled.
*
* Aborts on error.
* @param lock Lock to unlock while waiting and reacquire afterwards.
**/
template <typename Lock>
void wait(Lock &lock)
{
m_mutex.lock();
lock.unlock();
if (::pthread_cond_wait(&m_cond, m_mutex.native_handle()))
::abort();
m_mutex.unlock();
lock.lock();
}
/**
* \brief Notify all variables waiting.
*
* Aborts on error.
**/
void notify_all() noexcept
{
lock_guard_t<decltype(m_mutex)> lg(m_mutex);
if (::pthread_cond_broadcast(&m_cond))
::abort();
}
private:
/**
* \brief Underlying pthread conditional variable.
**/
::pthread_cond_t m_cond;
/**
* \brief Internal mutex needed for protection since pthread requires a pthread mutex.
**/
pthread_mutex_t m_mutex;
};
/**
* \brief Lockable that is an operating system mutex.
**/
using mutex_t = pthread_mutex_t;
/**
* \brief The class unique_lock_t is a general-purpose mutex ownership wrapper.
**/
template <typename T>
using unique_lock_t = ::std::unique_lock<T>;
}
#endif
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2016 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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 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 "CCodeReviewComment.h"
#include "../nodes/CommentedNode.h"
#include "../nodes/ReviewComment.h"
#include "ModelBase/src/model/TreeManager.h"
#include "ModelBase/src/model/AllTreeManagers.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "../CodeReviewManager.h"
#include "../overlays/CodeReviewCommentOverlay.h"
using namespace Visualization;
namespace CodeReview {
CCodeReviewComment::CCodeReviewComment() : Command{"comment"} {}
bool CCodeReviewComment::canInterpret(Visualization::Item*, Visualization::Item*,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
if (commandTokens.size() > 0)
return name() == commandTokens.first();
return false;
}
Interaction::CommandResult* CCodeReviewComment::execute(Visualization::Item* source, Visualization::Item*,
const QStringList&, const std::unique_ptr<Visualization::Cursor>&)
{
auto ancestorWithNodeItem = source->findAncestorWithNode();
for (auto manager : Model::AllTreeManagers::instance().loadedManagers())
{
auto id = manager->nodeIdMap().idIfExists(ancestorWithNodeItem->node());
if (!id.isNull())
{
auto commentedNode = CodeReviewManager::instance().commentedNode(id.toString(),
ancestorWithNodeItem->mapFromScene(source->scenePos()).toPoint());
commentedNode->reviewComments()->append(new ReviewComment{});
auto overlay = new CodeReviewCommentOverlay{ancestorWithNodeItem, commentedNode};
ancestorWithNodeItem->addOverlay(overlay, "CodeReviewComment");
break;
}
}
return new Interaction::CommandResult{};
}
QList<Interaction::CommandSuggestion*> CCodeReviewComment::suggest(Visualization::Item*, Visualization::Item*,
const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
if (name().startsWith(textSoFar))
return {new Interaction::CommandSuggestion{name()}};
return {};
}
}
<commit_msg>Add begin-/endModification<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2016 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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 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 "CCodeReviewComment.h"
#include "../nodes/CommentedNode.h"
#include "../nodes/ReviewComment.h"
#include "ModelBase/src/model/TreeManager.h"
#include "ModelBase/src/model/AllTreeManagers.h"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/views/MainView.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "../CodeReviewManager.h"
#include "../overlays/CodeReviewCommentOverlay.h"
using namespace Visualization;
namespace CodeReview {
CCodeReviewComment::CCodeReviewComment() : Command{"comment"} {}
bool CCodeReviewComment::canInterpret(Visualization::Item*, Visualization::Item*,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
if (commandTokens.size() > 0)
return name() == commandTokens.first();
return false;
}
Interaction::CommandResult* CCodeReviewComment::execute(Visualization::Item* source, Visualization::Item*,
const QStringList&, const std::unique_ptr<Visualization::Cursor>&)
{
auto ancestorWithNodeItem = source->findAncestorWithNode();
for (auto manager : Model::AllTreeManagers::instance().loadedManagers())
{
auto id = manager->nodeIdMap().idIfExists(ancestorWithNodeItem->node());
if (!id.isNull())
{
auto commentedNode = CodeReviewManager::instance().commentedNode(id.toString(),
ancestorWithNodeItem->mapFromScene(source->scenePos()).toPoint());
commentedNode->beginModification();
commentedNode->reviewComments()->append(new ReviewComment{});
commentedNode->endModification();
auto overlay = new CodeReviewCommentOverlay{ancestorWithNodeItem, commentedNode};
ancestorWithNodeItem->addOverlay(overlay, "CodeReviewComment");
break;
}
}
return new Interaction::CommandResult{};
}
QList<Interaction::CommandSuggestion*> CCodeReviewComment::suggest(Visualization::Item*, Visualization::Item*,
const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
if (name().startsWith(textSoFar))
return {new Interaction::CommandSuggestion{name()}};
return {};
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/window_snapshot/window_snapshot.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/size.h"
#include "ui/gfx/test/gfx_test_utils.h"
#if defined(VIEWS_COMPOSITOR)
#include "ui/gfx/compositor/compositor.h"
#endif
namespace {
// Command line flag for overriding the default location for putting generated
// test images that do not match references.
const char kGeneratedDir[] = "generated-dir";
// Reads and decodes a PNG image to a bitmap. Returns true on success. The PNG
// should have been encoded using |gfx::PNGCodec::Encode|.
bool ReadPNGFile(const FilePath& file_path, SkBitmap* bitmap) {
DCHECK(bitmap);
std::string png_data;
return file_util::ReadFileToString(file_path, &png_data) &&
gfx::PNGCodec::Decode(reinterpret_cast<unsigned char*>(&png_data[0]),
png_data.length(),
bitmap);
}
// Encodes a bitmap into a PNG and write to disk. Returns true on success. The
// parent directory does not have to exist.
bool WritePNGFile(const SkBitmap& bitmap, const FilePath& file_path) {
std::vector<unsigned char> png_data;
if (gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, true, &png_data) &&
file_util::CreateDirectory(file_path.DirName())) {
int bytes_written = file_util::WriteFile(
file_path, reinterpret_cast<char*>(&png_data[0]), png_data.size());
if (bytes_written == static_cast<int>(png_data.size()))
return true;
}
return false;
}
// Resizes the browser window so that the tab's contents are at a given size.
void ResizeTabContainer(Browser* browser, const gfx::Size& desired_size) {
gfx::Rect container_rect;
browser->GetSelectedTabContents()->GetContainerBounds(&container_rect);
// Size cannot be negative, so use a point.
gfx::Point correction(desired_size.width() - container_rect.size().width(),
desired_size.height() - container_rect.size().height());
gfx::Rect window_rect = browser->window()->GetRestoredBounds();
gfx::Size new_size = window_rect.size();
new_size.Enlarge(correction.x(), correction.y());
window_rect.set_size(new_size);
browser->window()->SetBounds(window_rect);
}
} // namespace
// Test fixture for GPU image comparison tests.
// TODO(kkania): Document how to add to/modify these tests.
class GpuPixelBrowserTest : public InProcessBrowserTest {
public:
GpuPixelBrowserTest() : ref_img_revision_no_older_than_(0) {}
virtual void SetUpCommandLine(CommandLine* command_line) {
InProcessBrowserTest::SetUpCommandLine(command_line);
// This enables DOM automation for tab contents.
EnableDOMAutomation();
}
virtual void SetUpInProcessBrowserTestFixture() {
InProcessBrowserTest::SetUpInProcessBrowserTestFixture();
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
test_data_dir_ = test_data_dir_.AppendASCII("gpu");
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kGeneratedDir))
generated_img_dir_ = command_line->GetSwitchValuePath(kGeneratedDir);
else
generated_img_dir_ = test_data_dir_.AppendASCII("generated");
test_name_ = testing::UnitTest::GetInstance()->current_test_info()->name();
const char* test_status_prefixes[] = {"DISABLED_", "FLAKY_", "FAILS_"};
for (size_t i = 0; i < arraysize(test_status_prefixes); ++i) {
ReplaceFirstSubstringAfterOffset(
&test_name_, 0, test_status_prefixes[i], "");
}
#if defined(VIEWS_COMPOSITOR)
ui::Compositor::set_compositor_factory_for_testing(NULL);
#endif
}
// Compares the generated bitmap with the appropriate reference image on disk.
// Returns true iff the images were the same.
//
// If no valid reference image exists, save the generated bitmap to the disk.
// The image format is:
// <test_name>_<revision>.png
// E.g.,
// WebGLTeapot_19762.png
//
// On failure, the image and diff image will be written to disk.
// The formats are:
// FAIL_<test_name>.png, DIFF_<test_name>.png
// E.g.,
// FAIL_WebGLTeapot.png, DIFF_WebGLTeapot.png
bool CompareImages(const SkBitmap& gen_bmp) {
SkBitmap ref_bmp;
if (ref_img_path_.empty() ||
!ReadPNGFile(ref_img_path_, &ref_bmp)) {
chrome::VersionInfo chrome_version_info;
FilePath img_revision_path = generated_img_dir_.AppendASCII(
test_name_ + "_" + chrome_version_info.LastChange() + ".png");
if (!WritePNGFile(gen_bmp, img_revision_path)) {
LOG(ERROR) << "Can't save generated image to: "
<< img_revision_path.value()
<< " as future reference.";
return false;
}
if (!ref_img_path_.empty()) {
LOG(ERROR) << "Can't read the local ref image: "
<< ref_img_path_.value()
<< ", reset it.";
file_util::Delete(ref_img_path_, false);
return false;
}
return true;
}
bool rt = true;
bool save_diff = false;
SkBitmap diff_bmp;
if (ref_bmp.width() != gen_bmp.width() ||
ref_bmp.height() != gen_bmp.height()) {
LOG(ERROR)
<< "Dimensions do not match (Expected) vs (Actual):"
<< "(" << ref_bmp.width() << "x" << ref_bmp.height()
<< ") vs. "
<< "(" << gen_bmp.width() << "x" << gen_bmp.height() << ")";
rt = false;
} else {
// Compare pixels and create a simple diff image.
int diff_pixels_count = 0;
diff_bmp.setConfig(SkBitmap::kARGB_8888_Config,
gen_bmp.width(), gen_bmp.height());
diff_bmp.allocPixels();
diff_bmp.eraseColor(SK_ColorWHITE);
SkAutoLockPixels lock_bmp(gen_bmp);
SkAutoLockPixels lock_ref_bmp(ref_bmp);
SkAutoLockPixels lock_diff_bmp(diff_bmp);
// The reference images were saved with no alpha channel. Use the mask to
// set alpha to 0.
uint32_t kAlphaMask = 0x00FFFFFF;
for (int x = 0; x < gen_bmp.width(); ++x) {
for (int y = 0; y < gen_bmp.height(); ++y) {
if ((*gen_bmp.getAddr32(x, y) & kAlphaMask) !=
(*ref_bmp.getAddr32(x, y) & kAlphaMask)) {
++diff_pixels_count;
*diff_bmp.getAddr32(x, y) = 192 << 16; // red
}
}
}
if (diff_pixels_count > 0) {
LOG(ERROR) << diff_pixels_count
<< " pixels do not match.";
rt = false;
save_diff = true;
}
}
if (!rt) {
FilePath img_fail_path = generated_img_dir_.AppendASCII(
"FAIL_" + test_name_ + ".png");
if (!WritePNGFile(gen_bmp, img_fail_path)) {
LOG(ERROR) << "Can't save generated image to: "
<< img_fail_path.value();
}
if (save_diff) {
FilePath img_diff_path = generated_img_dir_.AppendASCII(
"DIFF_" + test_name_ + ".png");
if (!WritePNGFile(diff_bmp, img_diff_path)) {
LOG(ERROR) << "Can't save generated diff image to: "
<< img_diff_path.value();
}
}
}
return rt;
}
// This has to be called by every pixel test. If no specific revision is
// required, just call it with 0.
void SetRefImageRevisionNoOlderThan(int64 revision) {
ref_img_revision_no_older_than_ = revision;
ObtainLocalRefImageFilePath();
}
protected:
FilePath test_data_dir_;
private:
FilePath generated_img_dir_;
FilePath ref_img_path_;
// The name of the test, with any special prefixes dropped.
std::string test_name_;
// Any local ref image generated from older revision is ignored.
int64 ref_img_revision_no_older_than_;
// If no valid local ref image is located, the ref_img_path_ remains
// empty.
void ObtainLocalRefImageFilePath() {
FilePath filter;
filter = filter.AppendASCII(test_name_ + "_*.png");
file_util::FileEnumerator locator(generated_img_dir_,
false, // non recursive
file_util::FileEnumerator::FILES,
filter.value());
int64 max_revision = 0;
std::vector<FilePath> outdated_ref_imgs;
for (FilePath full_path = locator.Next();
!full_path.empty();
full_path = locator.Next()) {
std::string filename =
full_path.BaseName().RemoveExtension().MaybeAsASCII();
std::string revision_string =
filename.substr(test_name_.length() + 1);
int64 revision = 0;
bool converted = base::StringToInt64(revision_string, &revision);
CHECK(converted);
if (revision < ref_img_revision_no_older_than_ ||
revision < max_revision) {
outdated_ref_imgs.push_back(full_path);
continue;
}
ref_img_path_ = full_path;
max_revision = revision;
}
for (size_t i = 0; i < outdated_ref_imgs.size(); ++i)
file_util::Delete(outdated_ref_imgs[i], false);
}
DISALLOW_COPY_AND_ASSIGN(GpuPixelBrowserTest);
};
// Enable initially only on Windows and progressively enable on more
// platforms.
// Bug tracking test failure on Windows/Mac: http://crbug.com/95214
// Bug tracking test failure on Linux: http://crbug.com/95214
#if defined(OS_WIN)
#define MAYBE_WebGLTeapot WebGLTeapot
#else
#define MAYBE_WebGLTeapot DISABLED_WebGLTeapot
#endif
IN_PROC_BROWSER_TEST_F(GpuPixelBrowserTest, MAYBE_WebGLTeapot) {
// If test baseline needs to be updated after a given revision, update the
// revision number in SetRefImageNoOlderThan(#revision).
SetRefImageRevisionNoOlderThan(0);
ui_test_utils::DOMMessageQueue message_queue;
ui_test_utils::NavigateToURL(
browser(),
net::FilePathToFileURL(test_data_dir_.AppendASCII("webgl_teapot").
AppendASCII("teapot.html")));
gfx::Size container_size(500, 500);
ResizeTabContainer(browser(), container_size);
// Wait for message from teapot page indicating the GL calls have been issued.
ASSERT_TRUE(message_queue.WaitForMessage(NULL));
std::vector<unsigned char> screenshot_png;
gfx::Rect root_bounds = browser()->window()->GetBounds();
gfx::Rect tab_contents_bounds;
browser()->GetSelectedTabContents()->GetContainerBounds(&tab_contents_bounds);
gfx::Rect snapshot_bounds(tab_contents_bounds.x() - root_bounds.x(),
tab_contents_bounds.y() - root_bounds.y(),
tab_contents_bounds.width(),
tab_contents_bounds.height());
gfx::NativeWindow native_window = browser()->window()->GetNativeHandle();
bool success = browser::GrabWindowSnapshot(native_window, &screenshot_png,
snapshot_bounds);
ASSERT_TRUE(success);
SkBitmap bitmap;
success = gfx::PNGCodec::Decode(
reinterpret_cast<unsigned char*>(&*screenshot_png.begin()),
screenshot_png.size(),
&bitmap);
ASSERT_TRUE(success);
ASSERT_TRUE(CompareImages(bitmap));
}
<commit_msg>Seperate reference images location and the generated results location.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/window_snapshot/window_snapshot.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/size.h"
#include "ui/gfx/test/gfx_test_utils.h"
#if defined(VIEWS_COMPOSITOR)
#include "ui/gfx/compositor/compositor.h"
#endif
namespace {
// Command line flag for overriding the default location for putting generated
// test images that do not match references.
const char kGeneratedDir[] = "generated-dir";
// Command line flag for overriding the default location for reference images.
const char kReferenceDir[] = "reference-dir";
// Reads and decodes a PNG image to a bitmap. Returns true on success. The PNG
// should have been encoded using |gfx::PNGCodec::Encode|.
bool ReadPNGFile(const FilePath& file_path, SkBitmap* bitmap) {
DCHECK(bitmap);
std::string png_data;
return file_util::ReadFileToString(file_path, &png_data) &&
gfx::PNGCodec::Decode(reinterpret_cast<unsigned char*>(&png_data[0]),
png_data.length(),
bitmap);
}
// Encodes a bitmap into a PNG and write to disk. Returns true on success. The
// parent directory does not have to exist.
bool WritePNGFile(const SkBitmap& bitmap, const FilePath& file_path) {
std::vector<unsigned char> png_data;
if (gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, true, &png_data) &&
file_util::CreateDirectory(file_path.DirName())) {
int bytes_written = file_util::WriteFile(
file_path, reinterpret_cast<char*>(&png_data[0]), png_data.size());
if (bytes_written == static_cast<int>(png_data.size()))
return true;
}
return false;
}
// Resizes the browser window so that the tab's contents are at a given size.
void ResizeTabContainer(Browser* browser, const gfx::Size& desired_size) {
gfx::Rect container_rect;
browser->GetSelectedTabContents()->GetContainerBounds(&container_rect);
// Size cannot be negative, so use a point.
gfx::Point correction(desired_size.width() - container_rect.size().width(),
desired_size.height() - container_rect.size().height());
gfx::Rect window_rect = browser->window()->GetRestoredBounds();
gfx::Size new_size = window_rect.size();
new_size.Enlarge(correction.x(), correction.y());
window_rect.set_size(new_size);
browser->window()->SetBounds(window_rect);
}
} // namespace
// Test fixture for GPU image comparison tests.
// TODO(kkania): Document how to add to/modify these tests.
class GpuPixelBrowserTest : public InProcessBrowserTest {
public:
GpuPixelBrowserTest() : ref_img_revision_no_older_than_(0) {}
virtual void SetUpCommandLine(CommandLine* command_line) {
InProcessBrowserTest::SetUpCommandLine(command_line);
// This enables DOM automation for tab contents.
EnableDOMAutomation();
}
virtual void SetUpInProcessBrowserTestFixture() {
InProcessBrowserTest::SetUpInProcessBrowserTestFixture();
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
test_data_dir_ = test_data_dir_.AppendASCII("gpu");
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kGeneratedDir))
generated_img_dir_ = command_line->GetSwitchValuePath(kGeneratedDir);
else
generated_img_dir_ = test_data_dir_.AppendASCII("generated");
if (command_line->HasSwitch(kReferenceDir))
ref_img_dir_ = command_line->GetSwitchValuePath(kReferenceDir);
else
ref_img_dir_ = test_data_dir_.AppendASCII("gpu_reference");
test_name_ = testing::UnitTest::GetInstance()->current_test_info()->name();
const char* test_status_prefixes[] = {"DISABLED_", "FLAKY_", "FAILS_"};
for (size_t i = 0; i < arraysize(test_status_prefixes); ++i) {
ReplaceFirstSubstringAfterOffset(
&test_name_, 0, test_status_prefixes[i], "");
}
#if defined(VIEWS_COMPOSITOR)
ui::Compositor::set_compositor_factory_for_testing(NULL);
#endif
}
// Compares the generated bitmap with the appropriate reference image on disk.
// Returns true iff the images were the same.
//
// If no valid reference image exists, save the generated bitmap to the disk.
// The image format is:
// <test_name>_<revision>.png
// E.g.,
// WebGLTeapot_19762.png
// The number is the chromium revision that generated the image.
//
// On failure or on ref image generation, the image and diff image will be
// written to disk. The formats are:
// FAIL_<ref_image_name>, DIFF_<ref_image_name>
// E.g.,
// FAIL_WebGLTeapot_19762.png, DIFF_WebGLTeapot_19762.png
bool CompareImages(const SkBitmap& gen_bmp) {
SkBitmap ref_bmp_on_disk;
const SkBitmap* ref_bmp;
bool save_gen = false;
bool save_diff = false;
bool rt = true;
if (ref_img_path_.empty() ||
!ReadPNGFile(ref_img_path_, &ref_bmp_on_disk)) {
chrome::VersionInfo chrome_version_info;
FilePath img_revision_path = ref_img_dir_.AppendASCII(
test_name_ + "_" + chrome_version_info.LastChange() + ".png");
if (!WritePNGFile(gen_bmp, img_revision_path)) {
LOG(ERROR) << "Can't save generated image to: "
<< img_revision_path.value()
<< " as future reference.";
rt = false;
}
if (!ref_img_path_.empty()) {
LOG(ERROR) << "Can't read the local ref image: "
<< ref_img_path_.value()
<< ", reset it.";
file_util::Delete(ref_img_path_, false);
rt = false;
}
ref_img_path_ = img_revision_path;
// If we re-generate the ref image, we save the gen and diff images so
// the ref image can be uploaded to the server and be viewed later.
save_gen = true;
save_diff = true;
ref_bmp = &gen_bmp;
} else {
ref_bmp = &ref_bmp_on_disk;
}
SkBitmap diff_bmp;
if (ref_bmp->width() != gen_bmp.width() ||
ref_bmp->height() != gen_bmp.height()) {
LOG(ERROR)
<< "Dimensions do not match (Expected) vs (Actual):"
<< "(" << ref_bmp->width() << "x" << ref_bmp->height()
<< ") vs. "
<< "(" << gen_bmp.width() << "x" << gen_bmp.height() << ")";
save_gen = true;
rt = false;
} else {
// Compare pixels and create a simple diff image.
int diff_pixels_count = 0;
diff_bmp.setConfig(SkBitmap::kARGB_8888_Config,
gen_bmp.width(), gen_bmp.height());
diff_bmp.allocPixels();
diff_bmp.eraseColor(SK_ColorWHITE);
SkAutoLockPixels lock_bmp(gen_bmp);
SkAutoLockPixels lock_ref_bmp(*ref_bmp);
SkAutoLockPixels lock_diff_bmp(diff_bmp);
// The reference images were saved with no alpha channel. Use the mask to
// set alpha to 0.
uint32_t kAlphaMask = 0x00FFFFFF;
for (int x = 0; x < gen_bmp.width(); ++x) {
for (int y = 0; y < gen_bmp.height(); ++y) {
if ((*gen_bmp.getAddr32(x, y) & kAlphaMask) !=
(*ref_bmp->getAddr32(x, y) & kAlphaMask)) {
++diff_pixels_count;
*diff_bmp.getAddr32(x, y) = 192 << 16; // red
}
}
}
if (diff_pixels_count > 0) {
LOG(ERROR) << diff_pixels_count
<< " pixels do not match.";
save_gen = true;
save_diff = true;
rt = false;
}
}
std::string ref_img_filename = ref_img_path_.BaseName().MaybeAsASCII();
if (save_gen) {
FilePath img_fail_path = generated_img_dir_.AppendASCII(
"FAIL_" + ref_img_filename);
if (!WritePNGFile(gen_bmp, img_fail_path)) {
LOG(ERROR) << "Can't save generated image to: "
<< img_fail_path.value();
}
}
if (save_diff) {
FilePath img_diff_path = generated_img_dir_.AppendASCII(
"DIFF_" + ref_img_filename);
if (!WritePNGFile(diff_bmp, img_diff_path)) {
LOG(ERROR) << "Can't save generated diff image to: "
<< img_diff_path.value();
}
}
return rt;
}
// This has to be called by every pixel test. If no specific revision is
// required, just call it with 0.
void SetRefImageRevisionNoOlderThan(int64 revision) {
ref_img_revision_no_older_than_ = revision;
ObtainLocalRefImageFilePath();
}
protected:
FilePath test_data_dir_;
private:
FilePath generated_img_dir_;
FilePath ref_img_dir_;
FilePath ref_img_path_;
// The name of the test, with any special prefixes dropped.
std::string test_name_;
// Any local ref image generated from older revision is ignored.
int64 ref_img_revision_no_older_than_;
// If no valid local ref image is located, the ref_img_path_ remains
// empty.
void ObtainLocalRefImageFilePath() {
FilePath filter;
filter = filter.AppendASCII(test_name_ + "_*.png");
file_util::FileEnumerator locator(ref_img_dir_,
false, // non recursive
file_util::FileEnumerator::FILES,
filter.value());
int64 max_revision = 0;
std::vector<FilePath> outdated_ref_imgs;
for (FilePath full_path = locator.Next();
!full_path.empty();
full_path = locator.Next()) {
std::string filename =
full_path.BaseName().RemoveExtension().MaybeAsASCII();
std::string revision_string =
filename.substr(test_name_.length() + 1);
int64 revision = 0;
bool converted = base::StringToInt64(revision_string, &revision);
CHECK(converted);
if (revision < ref_img_revision_no_older_than_ ||
revision < max_revision) {
outdated_ref_imgs.push_back(full_path);
continue;
}
ref_img_path_ = full_path;
max_revision = revision;
}
for (size_t i = 0; i < outdated_ref_imgs.size(); ++i)
file_util::Delete(outdated_ref_imgs[i], false);
}
DISALLOW_COPY_AND_ASSIGN(GpuPixelBrowserTest);
};
// Enable initially only on Windows and progressively enable on more
// platforms.
// Bug tracking test failure on Windows/Mac: http://crbug.com/95214
// Bug tracking test failure on Linux: http://crbug.com/95214
#if defined(OS_WIN)
#define MAYBE_WebGLTeapot WebGLTeapot
#else
#define MAYBE_WebGLTeapot DISABLED_WebGLTeapot
#endif
IN_PROC_BROWSER_TEST_F(GpuPixelBrowserTest, MAYBE_WebGLTeapot) {
// If test baseline needs to be updated after a given revision, update the
// revision number in SetRefImageNoOlderThan(#revision).
SetRefImageRevisionNoOlderThan(0);
ui_test_utils::DOMMessageQueue message_queue;
ui_test_utils::NavigateToURL(
browser(),
net::FilePathToFileURL(test_data_dir_.AppendASCII("webgl_teapot").
AppendASCII("teapot.html")));
gfx::Size container_size(500, 500);
ResizeTabContainer(browser(), container_size);
// Wait for message from teapot page indicating the GL calls have been issued.
ASSERT_TRUE(message_queue.WaitForMessage(NULL));
std::vector<unsigned char> screenshot_png;
gfx::Rect root_bounds = browser()->window()->GetBounds();
gfx::Rect tab_contents_bounds;
browser()->GetSelectedTabContents()->GetContainerBounds(&tab_contents_bounds);
gfx::Rect snapshot_bounds(tab_contents_bounds.x() - root_bounds.x(),
tab_contents_bounds.y() - root_bounds.y(),
tab_contents_bounds.width(),
tab_contents_bounds.height());
gfx::NativeWindow native_window = browser()->window()->GetNativeHandle();
bool success = browser::GrabWindowSnapshot(native_window, &screenshot_png,
snapshot_bounds);
ASSERT_TRUE(success);
SkBitmap bitmap;
success = gfx::PNGCodec::Decode(
reinterpret_cast<unsigned char*>(&*screenshot_png.begin()),
screenshot_png.size(),
&bitmap);
ASSERT_TRUE(success);
ASSERT_TRUE(CompareImages(bitmap));
}
<|endoftext|>
|
<commit_before>#include "native/UriTemplate.hpp"
#include "native/UriTemplateFormat.hpp"
#include "native/UriTemplateValue.hpp"
#include "native/helper/trace.hpp"
#if NNATIVE_USE_RE2 == 1
#include <re2/re2.h>
#elif NNATIVE_USE_STDREGEX == 1
#include <regex>
#else
#endif // elif NNATIVE_USE_STDREGEX == 1
#include <set>
#include <memory>
using namespace native;
namespace {
#if NNATIVE_USE_RE2 == 1
bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) {
// regex is compiled only at the first call
static const re2::RE2 reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName}
re2::StringPiece text(&(*iBegin), std::distance(iBegin, iEnd));
re2::StringPiece results[3];
if(!reParam.Match(text, 0, text.size(), re2::RE2::UNANCHORED, results, 3)) {
return false;
}
iText.assign(text.data(), results[0].begin() - text.begin());
Name.assign(results[1].data(), results[1].size());
iFormat.assign(results[2].data(), results[2].size());
iBegin += results[0].end() - text.begin();
return true;
}
/**
* Recursive save extracted data by regex into values
* @param ioParsedValues parsed values container to be populated
* @param ioPosition current smatch position
* @iParams parameters name vector to be added as key values
* @iFormatNames format name vector to parse child values, if exists
*/
void saveValues(
UriTemplateValue &ioParsedValues,
int &ioPosition,
const re2::StringPiece* iMatchResults,
const int iMatchResultsSize,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames) {
NNATIVE_ASSERT(iParams.size() == iFormatNames.size());
NNATIVE_ASSERT(iMatchResultsSize - ioPosition >= static_cast<int>(iParams.size()));
for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i)
{
const std::string value = iMatchResults[ioPosition++].as_string();
const std::string &name = iParams[i];
const std::string &formatName = iFormatNames[i];
UriTemplateValue &childValue = ioParsedValues.addChild(name, value);
const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName);
if(format.isRegExOnly())
{
continue;
}
// Parse subvalues of format name
const UriTemplate &uriTemplate = format.getTemplate();
NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\"");
saveValues(childValue, ioPosition, iMatchResults, iMatchResultsSize, uriTemplate.getParams(), uriTemplate.getFormatNames());
}
}
bool extractAndSaveValues(UriTemplateValue &oValues,
const std::string &iUri,
const std::string &iExtractPattern,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames,
const bool iAnchorEnd = true) {
const re2::RE2 rePattern(iExtractPattern);
const int matchResultsSize = 1+rePattern.NumberOfCapturingGroups();
std::unique_ptr<re2::StringPiece[]> matchResults(new re2::StringPiece[matchResultsSize]);
re2::StringPiece uriPiece(iUri);
if(!rePattern.Match(uriPiece, 0, uriPiece.size(), (iAnchorEnd ? re2::RE2::ANCHOR_BOTH : re2::RE2::ANCHOR_START), matchResults.get(), matchResultsSize)) {
NNATIVE_DEBUG("No match found");
return false;
}
int position = 0;
// No name to the first parsed value
oValues.clear();
oValues.getString() = matchResults[position++].as_string();
// save child values
saveValues(oValues, position, matchResults.get(), matchResultsSize, iParams, iFormatNames);
return true;
}
bool containCapturingGroup(const std::string &iPattern) {
const re2::RE2 reCapturingGroup(iPattern);
return reCapturingGroup.NumberOfCapturingGroups() > 0;
}
#elif NNATIVE_USE_STDREGEX == 1
#include <regex>
bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) {
// regex is compiled only at the first call
static const std::regex reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName}
std::smatch results;
if(!std::regex_search(iBegin, iEnd, results, reParam)) {
return false;
}
iText.assign(iBegin, iBegin + results.position());
Name = results.str(1);
iFormat = results.str(2);
iBegin += results.position() + results.length();
return true;
}
/**
* Recursive save extracted data by regex into values
* @param ioParsedValues parsed values container to be populated
* @param ioPosition current smatch position
* @iParams parameters name vector to be added as key values
* @iFormatNames format name vector to parse child values, if exists
*/
void saveValues(
UriTemplateValue &ioParsedValues,
int &ioPosition,
const std::smatch &iMatchResults,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames) {
NNATIVE_ASSERT(iParams.size() == iFormatNames.size());
NNATIVE_ASSERT(iMatchResults.size() - ioPosition >= iParams.size());
for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i)
{
const std::string value = iMatchResults.str(ioPosition++);
const std::string &name = iParams[i];
const std::string &formatName = iFormatNames[i];
UriTemplateValue &childValue = ioParsedValues.addChild(name, value);
const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName);
if(format.isRegExOnly())
{
continue;
}
// Parse subvalues of format name
const UriTemplate &uriTemplate = format.getTemplate();
NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\"");
saveValues(childValue, ioPosition, iMatchResults, uriTemplate.getParams(), uriTemplate.getFormatNames());
}
}
bool extractAndSaveValues(UriTemplateValue &oValues,
const std::string &iUri,
const std::string &iExtractPattern,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames,
const bool iAnchorEnd = true) {
std::smatch matchResults;
const std::regex rePattern(iExtractPattern);
if(iAnchorEnd) {
if(!std::regex_match(iUri, matchResults, rePattern)) {
NNATIVE_DEBUG("No match found");
return false;
}
} else {
if(!std::regex_search(iUri, matchResults, rePattern, std::regex_constants::match_continuous)) {
NNATIVE_DEBUG("No match found");
return false;
}
}
int position = 0;
// No name to the first parsed value
oValues.clear();
oValues.getString() = matchResults.str(position++);
// save child values
saveValues(oValues, position, matchResults, iParams, iFormatNames);
return true;
}
bool containCapturingGroup(const std::string &iPattern) {
// regex is compiled only at the first call
static const std::regex reCapturingGroup("\\([^?\\)]+\\)"); // true for "(test|other)", but false for non capturing groups (?:test|other)
std::smatch dummyResults;
return std::regex_search(iPattern, dummyResults, reCapturingGroup);
}
#endif // elif NNATIVE_USE_STDREGEX == 1
} /* namespace */
UriTemplate::UriTemplate(const std::string &iTemplate) : _template(iTemplate) {
parse();
}
UriTemplate::UriTemplate(const UriTemplate &iBaseUriTemplate, const std::string &iTemplateSuffix) :
_template(iBaseUriTemplate.getTemplate() + iTemplateSuffix) {
parse();
}
UriTemplate::UriTemplate(const UriTemplate &iOther) :
_template(iOther._template),
_matchPattern(iOther._matchPattern),
_extractPattern(iOther._extractPattern),
_params(iOther._params),
_formatNames(iOther._formatNames) {
// Avoid parsing because template string is already parsed
}
void UriTemplate::parse() {
NNATIVE_DEBUG("New URI Template \"" << _template << "\", size:" << _template.size());
// should not contain capturing groups. e.g. "/path/(caputeText)/{param1:format1}"
NNATIVE_ASSERT_MSG(!ContainCapturingGroup(_template), "URI template \"" << _template << "\" contain capturing groups");
_matchPattern = "";
_extractPattern = "";
std::set<std::string> uniqParams;
_params.clear();
_formatNames.clear();
// extract format names
std::string::const_iterator begin = _template.begin();
std::string::const_iterator end = _template.end();
std::string textStr;
std::string paramName;
std::string formatName;
while (getNextParameter(begin, end, textStr, paramName, formatName)) {
NNATIVE_DEBUG("paramName:"<<paramName<<", formatName:"<<formatName);
const UriTemplateFormat& globalFormat = UriTemplateFormat::GetGlobalFormat(formatName);
// Check if parameter name duplicate. e.g: "/path{sameParamName:anyFormatName}/other/{sameParamName:anyFormatName}"
if(!uniqParams.insert(paramName).second) {
NNATIVE_DEBUG("Duplicate parameter name found " << paramName);
NNATIVE_ASSERT(0);
}
_params.push_back(paramName);
_formatNames.push_back(formatName);
_matchPattern += textStr + globalFormat.getPattern();
_extractPattern += textStr + globalFormat.getPattern(true);
}
// add the remaing string
std::string textRemained(begin, end);
_matchPattern += textRemained;
// extract pattern may be part of a format name, do net add end of string ("$")
_extractPattern += textRemained;
NNATIVE_DEBUG("Pattern for match: \"" << _matchPattern << "\"");
NNATIVE_DEBUG("Pattern for extraction: \"" << _extractPattern << "\"");
}
bool UriTemplate::extract(UriTemplateValue &oValues, const std::string &iUri, const bool iAnchorEnd) const {
NNATIVE_DEBUG("Extract values from \"" << iUri << "\" by using URI template \"" << _template << "\", pattern: \"" << _extractPattern << "\")");
return extractAndSaveValues(oValues, iUri, _extractPattern, getParams(), getFormatNames(), iAnchorEnd);
}
bool UriTemplate::ContainCapturingGroup(const std::string &iPattern) {
return ::containCapturingGroup(iPattern);
}
<commit_msg>uriTemplate: optimized stdregex 's containCapturingGroup by using std::regex::mark_count()<commit_after>#include "native/UriTemplate.hpp"
#include "native/UriTemplateFormat.hpp"
#include "native/UriTemplateValue.hpp"
#include "native/helper/trace.hpp"
#if NNATIVE_USE_RE2 == 1
#include <re2/re2.h>
#elif NNATIVE_USE_STDREGEX == 1
#include <regex>
#else
#endif // elif NNATIVE_USE_STDREGEX == 1
#include <set>
#include <memory>
using namespace native;
namespace {
#if NNATIVE_USE_RE2 == 1
bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) {
// regex is compiled only at the first call
static const re2::RE2 reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName}
re2::StringPiece text(&(*iBegin), std::distance(iBegin, iEnd));
re2::StringPiece results[3];
if(!reParam.Match(text, 0, text.size(), re2::RE2::UNANCHORED, results, 3)) {
return false;
}
iText.assign(text.data(), results[0].begin() - text.begin());
Name.assign(results[1].data(), results[1].size());
iFormat.assign(results[2].data(), results[2].size());
iBegin += results[0].end() - text.begin();
return true;
}
/**
* Recursive save extracted data by regex into values
* @param ioParsedValues parsed values container to be populated
* @param ioPosition current smatch position
* @iParams parameters name vector to be added as key values
* @iFormatNames format name vector to parse child values, if exists
*/
void saveValues(
UriTemplateValue &ioParsedValues,
int &ioPosition,
const re2::StringPiece* iMatchResults,
const int iMatchResultsSize,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames) {
NNATIVE_ASSERT(iParams.size() == iFormatNames.size());
NNATIVE_ASSERT(iMatchResultsSize - ioPosition >= static_cast<int>(iParams.size()));
for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i)
{
const std::string value = iMatchResults[ioPosition++].as_string();
const std::string &name = iParams[i];
const std::string &formatName = iFormatNames[i];
UriTemplateValue &childValue = ioParsedValues.addChild(name, value);
const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName);
if(format.isRegExOnly())
{
continue;
}
// Parse subvalues of format name
const UriTemplate &uriTemplate = format.getTemplate();
NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\"");
saveValues(childValue, ioPosition, iMatchResults, iMatchResultsSize, uriTemplate.getParams(), uriTemplate.getFormatNames());
}
}
bool extractAndSaveValues(UriTemplateValue &oValues,
const std::string &iUri,
const std::string &iExtractPattern,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames,
const bool iAnchorEnd = true) {
const re2::RE2 rePattern(iExtractPattern);
const int matchResultsSize = 1+rePattern.NumberOfCapturingGroups();
std::unique_ptr<re2::StringPiece[]> matchResults(new re2::StringPiece[matchResultsSize]);
re2::StringPiece uriPiece(iUri);
if(!rePattern.Match(uriPiece, 0, uriPiece.size(), (iAnchorEnd ? re2::RE2::ANCHOR_BOTH : re2::RE2::ANCHOR_START), matchResults.get(), matchResultsSize)) {
NNATIVE_DEBUG("No match found");
return false;
}
int position = 0;
// No name to the first parsed value
oValues.clear();
oValues.getString() = matchResults[position++].as_string();
// save child values
saveValues(oValues, position, matchResults.get(), matchResultsSize, iParams, iFormatNames);
return true;
}
bool containCapturingGroup(const std::string &iPattern) {
const re2::RE2 reCapturingGroup(iPattern); // true for "(test|other)", but false for non capturing groups (?:test|other)
return reCapturingGroup.NumberOfCapturingGroups() > 0;
}
#elif NNATIVE_USE_STDREGEX == 1
#include <regex>
bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) {
// regex is compiled only at the first call
static const std::regex reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName}
std::smatch results;
if(!std::regex_search(iBegin, iEnd, results, reParam)) {
return false;
}
iText.assign(iBegin, iBegin + results.position());
Name = results.str(1);
iFormat = results.str(2);
iBegin += results.position() + results.length();
return true;
}
/**
* Recursive save extracted data by regex into values
* @param ioParsedValues parsed values container to be populated
* @param ioPosition current smatch position
* @iParams parameters name vector to be added as key values
* @iFormatNames format name vector to parse child values, if exists
*/
void saveValues(
UriTemplateValue &ioParsedValues,
int &ioPosition,
const std::smatch &iMatchResults,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames) {
NNATIVE_ASSERT(iParams.size() == iFormatNames.size());
NNATIVE_ASSERT(iMatchResults.size() - ioPosition >= iParams.size());
for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i)
{
const std::string value = iMatchResults.str(ioPosition++);
const std::string &name = iParams[i];
const std::string &formatName = iFormatNames[i];
UriTemplateValue &childValue = ioParsedValues.addChild(name, value);
const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName);
if(format.isRegExOnly())
{
continue;
}
// Parse subvalues of format name
const UriTemplate &uriTemplate = format.getTemplate();
NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\"");
saveValues(childValue, ioPosition, iMatchResults, uriTemplate.getParams(), uriTemplate.getFormatNames());
}
}
bool extractAndSaveValues(UriTemplateValue &oValues,
const std::string &iUri,
const std::string &iExtractPattern,
const std::vector<std::string> &iParams,
const std::vector<std::string> &iFormatNames,
const bool iAnchorEnd = true) {
std::smatch matchResults;
const std::regex rePattern(iExtractPattern);
if(iAnchorEnd) {
if(!std::regex_match(iUri, matchResults, rePattern)) {
NNATIVE_DEBUG("No match found");
return false;
}
} else {
if(!std::regex_search(iUri, matchResults, rePattern, std::regex_constants::match_continuous)) {
NNATIVE_DEBUG("No match found");
return false;
}
}
int position = 0;
// No name to the first parsed value
oValues.clear();
oValues.getString() = matchResults.str(position++);
// save child values
saveValues(oValues, position, matchResults, iParams, iFormatNames);
return true;
}
bool containCapturingGroup(const std::string &iPattern) {
// regex is compiled only at the first call
const std::regex reCapturingGroup(iPattern); // true for "(test|other)", but false for non capturing groups (?:test|other)
return reCapturingGroup.mark_count() > 0;
}
#endif // elif NNATIVE_USE_STDREGEX == 1
} /* namespace */
UriTemplate::UriTemplate(const std::string &iTemplate) : _template(iTemplate) {
parse();
}
UriTemplate::UriTemplate(const UriTemplate &iBaseUriTemplate, const std::string &iTemplateSuffix) :
_template(iBaseUriTemplate.getTemplate() + iTemplateSuffix) {
parse();
}
UriTemplate::UriTemplate(const UriTemplate &iOther) :
_template(iOther._template),
_matchPattern(iOther._matchPattern),
_extractPattern(iOther._extractPattern),
_params(iOther._params),
_formatNames(iOther._formatNames) {
// Avoid parsing because template string is already parsed
}
void UriTemplate::parse() {
NNATIVE_DEBUG("New URI Template \"" << _template << "\", size:" << _template.size());
// should not contain capturing groups. e.g. "/path/(caputeText)/{param1:format1}"
NNATIVE_ASSERT_MSG(!ContainCapturingGroup(_template), "URI template \"" << _template << "\" contain capturing groups");
_matchPattern = "";
_extractPattern = "";
std::set<std::string> uniqParams;
_params.clear();
_formatNames.clear();
// extract format names
std::string::const_iterator begin = _template.begin();
std::string::const_iterator end = _template.end();
std::string textStr;
std::string paramName;
std::string formatName;
while (getNextParameter(begin, end, textStr, paramName, formatName)) {
NNATIVE_DEBUG("paramName:"<<paramName<<", formatName:"<<formatName);
const UriTemplateFormat& globalFormat = UriTemplateFormat::GetGlobalFormat(formatName);
// Check if parameter name duplicate. e.g: "/path{sameParamName:anyFormatName}/other/{sameParamName:anyFormatName}"
if(!uniqParams.insert(paramName).second) {
NNATIVE_DEBUG("Duplicate parameter name found " << paramName);
NNATIVE_ASSERT(0);
}
_params.push_back(paramName);
_formatNames.push_back(formatName);
_matchPattern += textStr + globalFormat.getPattern();
_extractPattern += textStr + globalFormat.getPattern(true);
}
// add the remaing string
std::string textRemained(begin, end);
_matchPattern += textRemained;
// extract pattern may be part of a format name, do net add end of string ("$")
_extractPattern += textRemained;
NNATIVE_DEBUG("Pattern for match: \"" << _matchPattern << "\"");
NNATIVE_DEBUG("Pattern for extraction: \"" << _extractPattern << "\"");
}
bool UriTemplate::extract(UriTemplateValue &oValues, const std::string &iUri, const bool iAnchorEnd) const {
NNATIVE_DEBUG("Extract values from \"" << iUri << "\" by using URI template \"" << _template << "\", pattern: \"" << _extractPattern << "\")");
return extractAndSaveValues(oValues, iUri, _extractPattern, getParams(), getFormatNames(), iAnchorEnd);
}
bool UriTemplate::ContainCapturingGroup(const std::string &iPattern) {
return ::containCapturingGroup(iPattern);
}
<|endoftext|>
|
<commit_before>#include "costs.hpp"
#include "typo.hpp"
#include <iostream>
// auto reduce_typos(const std::vector<Typo> &t) -> int {
// auto result = 0;
// for (const auto &v : t) {
// result += v.cost;
// }
// return result;
// }
// auto do_stuff(const std::string &correct, const std::string &typo)
// -> std::vector<Typo> {
// if (correct.size() == 1 && typo.size() == 2) {
// return std::vector<Typo>();
// }
// if (correct.size() == 1) {
// auto result = do_stuff(correct, typo.substr(0, typo.size() - 1));
// result.emplace_back(TypoClass::Insert,
// compute_insert_cost(typo[typo.size() - 3],
// typo[typo.size() - 2],
// typo.back()),
// typo.size() - 3, typo);
// return result;
// }
// if (typo.size() == 2) {
// auto result = std::vector<Typo>(correct.size() - 1);
// for (auto &v : result) {
// v.kind = TypoClass::Delete;
// v.cost = 6;
// v.idx = -1;
// v.typo = typo;
// }
// return result;
// }
// auto options = std::vector<std::vector<Typo>>();
// auto corr = correct.back();
// auto left = typo[typo.size() - 3];
// auto curr = typo[typo.size() - 2];
// auto right = typo.back();
// if (corr == curr) {
// return do_stuff(correct.substr(0, correct.size() - 1),
// typo.substr(0, typo.size() - 1));
// }
// auto substitute = do_stuff(correct.substr(0, correct.size() - 1),
// typo.substr(0, typo.size() - 1));
// substitute.emplace_back(TypoClass::Substitute,
// compute_substitute_cost(corr, curr), typo.size() -
// 3,
// typo);
// options.push_back(substitute);
// auto insert = do_stuff(correct, typo.substr(0, typo.size() - 1));
// insert.emplace_back(TypoClass::Insert, compute_insert_cost(left, curr,
// right),
// typo.size() - 2, typo);
// options.push_back(insert);
// auto del = do_stuff(correct.substr(0, correct.size() - 1), typo);
// del.emplace_back(TypoClass::Delete, compute_delete_cost(curr, corr),
// typo.size() - 1, typo);
// options.push_back(del);
// if (corr == left) {
// auto traveller = curr;
// auto idx =
// auto transpose =
// do_stuff(correct.substr(0, correct.size() - 1), new_string);
// transpose.emplace_back(TypoClass::Transpose,
// compute_transpose_cost(left, curr), typo.size() -
// 3,
// typo);
// options.push_back(transpose);
// }
// auto mini = 0;
// auto minv = reduce_typos(options[0]);
// for (auto i = 1; i < options.size(); i++) {
// const auto cost = reduce_typos(options[i]);
// if (cost < minv) {
// mini = i;
// minv = cost;
// }
// }
// return options[mini];
// }
// auto prep_stuff(const std::string &correct, const std::string &actual)
// -> std::vector<Typo> {
// return do_stuff("\0" + correct, "\0" + actual + '\0');
// }
#include "temp.hpp"
auto main(const int argc, const char **argv) -> int {
std::cout << "Still just a stub!\n";
std::cout << "But now I compile!\n";
const std::string correct = "The rain in spain ";
const std::string actual = "Teh driafna i pasin ";
TransposeList result{};
find_tranpose(result, correct, actual);
for (const auto &pairs : result) {
auto i = pairs.first / actual.size();
auto j = pairs.first % actual.size();
std::cout << i << "," << j << " (" << correct[i] << "," << actual[j]
<< "): ";
for (const auto &value : pairs.second) {
std::cout << value << " ";
}
std::cout << std::endl;
}
}
<commit_msg>Removed include of removed temp<commit_after>#include "costs.hpp"
#include "typo.hpp"
#include <iostream>
// auto reduce_typos(const std::vector<Typo> &t) -> int {
// auto result = 0;
// for (const auto &v : t) {
// result += v.cost;
// }
// return result;
// }
// auto do_stuff(const std::string &correct, const std::string &typo)
// -> std::vector<Typo> {
// if (correct.size() == 1 && typo.size() == 2) {
// return std::vector<Typo>();
// }
// if (correct.size() == 1) {
// auto result = do_stuff(correct, typo.substr(0, typo.size() - 1));
// result.emplace_back(TypoClass::Insert,
// compute_insert_cost(typo[typo.size() - 3],
// typo[typo.size() - 2],
// typo.back()),
// typo.size() - 3, typo);
// return result;
// }
// if (typo.size() == 2) {
// auto result = std::vector<Typo>(correct.size() - 1);
// for (auto &v : result) {
// v.kind = TypoClass::Delete;
// v.cost = 6;
// v.idx = -1;
// v.typo = typo;
// }
// return result;
// }
// auto options = std::vector<std::vector<Typo>>();
// auto corr = correct.back();
// auto left = typo[typo.size() - 3];
// auto curr = typo[typo.size() - 2];
// auto right = typo.back();
// if (corr == curr) {
// return do_stuff(correct.substr(0, correct.size() - 1),
// typo.substr(0, typo.size() - 1));
// }
// auto substitute = do_stuff(correct.substr(0, correct.size() - 1),
// typo.substr(0, typo.size() - 1));
// substitute.emplace_back(TypoClass::Substitute,
// compute_substitute_cost(corr, curr), typo.size() -
// 3,
// typo);
// options.push_back(substitute);
// auto insert = do_stuff(correct, typo.substr(0, typo.size() - 1));
// insert.emplace_back(TypoClass::Insert, compute_insert_cost(left, curr,
// right),
// typo.size() - 2, typo);
// options.push_back(insert);
// auto del = do_stuff(correct.substr(0, correct.size() - 1), typo);
// del.emplace_back(TypoClass::Delete, compute_delete_cost(curr, corr),
// typo.size() - 1, typo);
// options.push_back(del);
// if (corr == left) {
// auto traveller = curr;
// auto idx =
// auto transpose =
// do_stuff(correct.substr(0, correct.size() - 1), new_string);
// transpose.emplace_back(TypoClass::Transpose,
// compute_transpose_cost(left, curr), typo.size() -
// 3,
// typo);
// options.push_back(transpose);
// }
// auto mini = 0;
// auto minv = reduce_typos(options[0]);
// for (auto i = 1; i < options.size(); i++) {
// const auto cost = reduce_typos(options[i]);
// if (cost < minv) {
// mini = i;
// minv = cost;
// }
// }
// return options[mini];
// }
// auto prep_stuff(const std::string &correct, const std::string &actual)
// -> std::vector<Typo> {
// return do_stuff("\0" + correct, "\0" + actual + '\0');
// }
auto main(const int argc, const char **argv) -> int {
std::cout << "Still just a stub!\n";
std::cout << "But now I compile!\n";
const std::string correct = "The rain in spain ";
const std::string actual = "Teh driafna i pasin ";
TransposeList result{};
find_tranpose(result, correct, actual);
for (const auto &pairs : result) {
auto i = pairs.first / actual.size();
auto j = pairs.first % actual.size();
std::cout << i << "," << j << " (" << correct[i] << "," << actual[j]
<< "): ";
for (const auto &value : pairs.second) {
std::cout << value << " ";
}
std::cout << std::endl;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Coverity was complaining about the result of getenv not being null checked, but when I look at the code and confer with mal it looks like the offending code can just be removed (and some de-linting applied).<commit_after><|endoftext|>
|
<commit_before><?hh
/**
* Labrys
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @copyright 2015-2016 Appertly
* @license Apache-2.0
*/
namespace Labrys\View;
use Axe\Page;
use Caridea\Container\EmptyContainer;
/**
* Creates Views and broadcasts the render event.
*/
class Service implements \Caridea\Container\ContainerAware
{
use \Caridea\Container\ContainerSetter;
/**
* The page
*/
private ?Page $page;
/**
* List of statuses
*/
private static ImmVector<string> $statuses = ImmVector{'msg-warning', 'msg-info', 'msg-error'};
/**
* Creates a new ViewService.
*
* @param $container - The dependency injection container
*/
public function __construct(?\Caridea\Container\Container $container)
{
$this->container = $container ?? new EmptyContainer();
}
/**
* Gets the Page for this request (created lazily).
*
* @param $title - The page title
* @return - A Page
*/
public function getPage(\Stringish $title): Page
{
if ($this->page === null) {
$page = (new Page())->setTitle($this->getPageTitle($title));
\HH\Asio\join($this->callPageVisitors($page));
$this->page = $page;
}
return $this->page;
}
/**
* Calls the page visitors.
*
* @param $page - The page to visit
*/
protected async function callPageVisitors(Page $page): Awaitable<Vector<mixed>>
{
return await \HH\Asio\v(
array_map(
(PageVisitor $v) ==> $v->visit($page),
/* HH_IGNORE_ERROR[4064]: This is never null */
$this->container->getByType(PageVisitor::class)
)
);
}
/**
* Generates a page title.
*
* @param $title - The page title
* @return - The formatted page title
*/
protected function getPageTitle(?\Stringish $title): string
{
return sprintf(
/* HH_FIXME[4110]: HHVM is weird with this method */
/* HH_FIXME[4027]: HHVM is weird with this method */
/* HH_IGNORE_ERROR[4064]: This is never null */
$this->container->get('web.ui.title.template'),
$title,
/* HH_IGNORE_ERROR[4064]: This is never null */
$this->container->get('system.name')
);
}
/**
* Sets a Flash Message.
*
* @param $name - The status
* @param $value - The message
* @param $current - Whether to add message to the current request
*/
public function setFlashMessage(string $name, string $value, bool $current = false): void
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$session = $this->container->getFirst(\Caridea\Session\Session::class);
if ($session === null) {
throw new \UnexpectedValueException("No Session Manager found");
}
$session->resume() || $session->start();
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$flash->set($name, $value, $current);
}
/**
* Clears Flash Messages.
*
* @param $name - The status
* @param $value - The message
* @param $current - Whether to add message to the current request
*/
public function clearFlashMessages(bool $current = false): void
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$session = $this->container->getFirst(\Caridea\Session\Session::class);
if ($session === null) {
throw new \UnexpectedValueException("No Session Manager found");
}
$session->resume() || $session->start();
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$flash->clear($current);
}
/**
* Keeps all current flash messages for the next request.
*/
public function keepFlashMessages(): void
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$session = $this->container->getFirst(\Caridea\Session\Session::class);
if ($session === null) {
throw new \UnexpectedValueException("No Session Manager found");
}
$session->resume() || $session->start();
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$flash->keep();
}
/**
* Gets any flash messages in the session keyed by status.
*
* @return - ImmMap of flash messages
*/
public function getFlashMessages(): \ConstMap<string,ImmVector<string>>
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$plugin = $flash;
$map = Map{};
foreach (self::$statuses as $status) {
$messages = $plugin->getCurrent($status);
if (!$messages) {
continue;
}
$vector = Vector{};
if ($messages instanceof Traversable) {
foreach ($messages as $message) {
$vector->add((string) $message);
}
} else {
$vector->add((string) $messages);
}
$map->set($status, $vector->toImmVector());
}
return $map->toImmMap();
}
/**
* Gets the last request that the Dispatcher sent to a controller.
*
* @return - The last dispatched request, or `null`
* @since 0.6.3
*/
public function getDispatchedRequest(): ?\Psr\Http\Message\ServerRequestInterface
{
$c = $this->container ?? new EmptyContainer();
$d = Vector::fromItems($c->getByType(\Labrys\Route\Dispatcher::class))->firstValue();
return $d?->getLastDispatchedRequest();
}
/**
* Gets all blocks registered for a given region
*
* @param $region - The region to search
* @return - The found blocks in that region, or an empty array.
*/
public function getBlocks(string $region): \ConstVector<Block>
{
$c = $this->container ?? new EmptyContainer();
$blocks = new Vector($c->getByType(Block::class));
$blocks = $blocks->filter((Block $b) ==> $region === $b->getRegion());
return $blocks->toImmVector();
}
/**
* Gets any `Labrys\Db\DbRefResolver` objects in the container.
*
* @return - The DbRefResolver objects found.
* @since 0.5.0
*/
public function getDbRefResolvers(): \ConstVector<\Labrys\Db\DbRefResolver>
{
/* HH_IGNORE_ERROR[4064]: This is never null */
return new ImmVector($this->container->getByType(\Labrys\Db\DbRefResolver::class));
}
/**
* Gets any `Labrys\View\EntityLinker` objects in the container.
*
* @return - The EntityLinker objects found.
* @since 0.5.0
*/
public function getEntityLinkers(): \ConstVector<EntityLinker>
{
/* HH_IGNORE_ERROR[4064]: This is never null */
return new ImmVector($this->container->getByType(EntityLinker::class));
}
/**
* Gets the CSRF token.
*
* @return - The CSRF token or `null`
* @throws \UnexpectedValueException if the plugin wasn't in the container
* @since 0.6.5
*/
public function getCsrfToken(): ?string
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$plugin = $this->container->getFirst(\Caridea\Session\CsrfPlugin::class);
if ($plugin === null) {
throw new \UnexpectedValueException("No CSRF Plugin found");
}
return $plugin->getValue();
}
/**
* Checks to see if the provided token matches the session CSRF token.
*
* @return - whether the provided token matches
* @throws \UnexpectedValueException if the plugin wasn't in the container
* @since 0.6.5
*/
public function isCsrfValid(string $token): bool
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$plugin = $this->container->getFirst(\Caridea\Session\CsrfPlugin::class);
if ($plugin === null) {
throw new \UnexpectedValueException("No CSRF Plugin found");
}
return $plugin->isValid($token);
}
}
<commit_msg>Blocks now ordered properly<commit_after><?hh
/**
* Labrys
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @copyright 2015-2016 Appertly
* @license Apache-2.0
*/
namespace Labrys\View;
use Axe\Page;
use Caridea\Container\EmptyContainer;
/**
* Creates Views and broadcasts the render event.
*/
class Service implements \Caridea\Container\ContainerAware
{
use \Caridea\Container\ContainerSetter;
/**
* The page
*/
private ?Page $page;
/**
* List of statuses
*/
private static ImmVector<string> $statuses = ImmVector{'msg-warning', 'msg-info', 'msg-error'};
/**
* Creates a new ViewService.
*
* @param $container - The dependency injection container
*/
public function __construct(?\Caridea\Container\Container $container)
{
$this->container = $container ?? new EmptyContainer();
}
/**
* Gets the Page for this request (created lazily).
*
* @param $title - The page title
* @return - A Page
*/
public function getPage(\Stringish $title): Page
{
if ($this->page === null) {
$page = (new Page())->setTitle($this->getPageTitle($title));
\HH\Asio\join($this->callPageVisitors($page));
$this->page = $page;
}
return $this->page;
}
/**
* Calls the page visitors.
*
* @param $page - The page to visit
*/
protected async function callPageVisitors(Page $page): Awaitable<Vector<mixed>>
{
return await \HH\Asio\v(
array_map(
(PageVisitor $v) ==> $v->visit($page),
/* HH_IGNORE_ERROR[4064]: This is never null */
$this->container->getByType(PageVisitor::class)
)
);
}
/**
* Generates a page title.
*
* @param $title - The page title
* @return - The formatted page title
*/
protected function getPageTitle(?\Stringish $title): string
{
return sprintf(
/* HH_FIXME[4110]: HHVM is weird with this method */
/* HH_FIXME[4027]: HHVM is weird with this method */
/* HH_IGNORE_ERROR[4064]: This is never null */
$this->container->get('web.ui.title.template'),
$title,
/* HH_IGNORE_ERROR[4064]: This is never null */
$this->container->get('system.name')
);
}
/**
* Sets a Flash Message.
*
* @param $name - The status
* @param $value - The message
* @param $current - Whether to add message to the current request
*/
public function setFlashMessage(string $name, string $value, bool $current = false): void
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$session = $this->container->getFirst(\Caridea\Session\Session::class);
if ($session === null) {
throw new \UnexpectedValueException("No Session Manager found");
}
$session->resume() || $session->start();
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$flash->set($name, $value, $current);
}
/**
* Clears Flash Messages.
*
* @param $name - The status
* @param $value - The message
* @param $current - Whether to add message to the current request
*/
public function clearFlashMessages(bool $current = false): void
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$session = $this->container->getFirst(\Caridea\Session\Session::class);
if ($session === null) {
throw new \UnexpectedValueException("No Session Manager found");
}
$session->resume() || $session->start();
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$flash->clear($current);
}
/**
* Keeps all current flash messages for the next request.
*/
public function keepFlashMessages(): void
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$session = $this->container->getFirst(\Caridea\Session\Session::class);
if ($session === null) {
throw new \UnexpectedValueException("No Session Manager found");
}
$session->resume() || $session->start();
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$flash->keep();
}
/**
* Gets any flash messages in the session keyed by status.
*
* @return - ImmMap of flash messages
*/
public function getFlashMessages(): \ConstMap<string,ImmVector<string>>
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$flash = $this->container->getFirst(\Caridea\Session\FlashPlugin::class);
if ($flash === null) {
throw new \UnexpectedValueException("No Flash Plugin found");
}
$plugin = $flash;
$map = Map{};
foreach (self::$statuses as $status) {
$messages = $plugin->getCurrent($status);
if (!$messages) {
continue;
}
$vector = Vector{};
if ($messages instanceof Traversable) {
foreach ($messages as $message) {
$vector->add((string) $message);
}
} else {
$vector->add((string) $messages);
}
$map->set($status, $vector->toImmVector());
}
return $map->toImmMap();
}
/**
* Gets the last request that the Dispatcher sent to a controller.
*
* @return - The last dispatched request, or `null`
* @since 0.6.3
*/
public function getDispatchedRequest(): ?\Psr\Http\Message\ServerRequestInterface
{
$c = $this->container ?? new EmptyContainer();
$d = Vector::fromItems($c->getByType(\Labrys\Route\Dispatcher::class))->firstValue();
return $d?->getLastDispatchedRequest();
}
/**
* Gets all blocks registered for a given region
*
* @param $region - The region to search
* @return - The found blocks in that region, or an empty array.
*/
public function getBlocks(string $region): \ConstVector<Block>
{
$c = $this->container ?? new EmptyContainer();
$blocks = new Vector($c->getByType(Block::class));
$blocks = $blocks->filter((Block $b) ==> $region === $b->getRegion());
usort($blocks, function ($a, $b) {
/* HH_IGNORE_ERROR[1002]: Hack hates the spaceship operator */
return $a->getOrder() <=> $b->getOrder();
});
return $blocks->toImmVector();
}
/**
* Gets any `Labrys\Db\DbRefResolver` objects in the container.
*
* @return - The DbRefResolver objects found.
* @since 0.5.0
*/
public function getDbRefResolvers(): \ConstVector<\Labrys\Db\DbRefResolver>
{
/* HH_IGNORE_ERROR[4064]: This is never null */
return new ImmVector($this->container->getByType(\Labrys\Db\DbRefResolver::class));
}
/**
* Gets any `Labrys\View\EntityLinker` objects in the container.
*
* @return - The EntityLinker objects found.
* @since 0.5.0
*/
public function getEntityLinkers(): \ConstVector<EntityLinker>
{
/* HH_IGNORE_ERROR[4064]: This is never null */
return new ImmVector($this->container->getByType(EntityLinker::class));
}
/**
* Gets the CSRF token.
*
* @return - The CSRF token or `null`
* @throws \UnexpectedValueException if the plugin wasn't in the container
* @since 0.6.5
*/
public function getCsrfToken(): ?string
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$plugin = $this->container->getFirst(\Caridea\Session\CsrfPlugin::class);
if ($plugin === null) {
throw new \UnexpectedValueException("No CSRF Plugin found");
}
return $plugin->getValue();
}
/**
* Checks to see if the provided token matches the session CSRF token.
*
* @return - whether the provided token matches
* @throws \UnexpectedValueException if the plugin wasn't in the container
* @since 0.6.5
*/
public function isCsrfValid(string $token): bool
{
/* HH_IGNORE_ERROR[4064]: This is never null */
$plugin = $this->container->getFirst(\Caridea\Session\CsrfPlugin::class);
if ($plugin === null) {
throw new \UnexpectedValueException("No CSRF Plugin found");
}
return $plugin->isValid($token);
}
}
<|endoftext|>
|
<commit_before><commit_msg>Fix linker error on Linux & Mac by stubbing out a function. Review URL: http://codereview.chromium.org/20100<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkMath.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTArray.h"
#include "PictureRenderer.h"
#include "picture_utils.h"
static void usage(const char* argv0) {
SkDebugf("SkPicture rendering tool\n");
SkDebugf("\n"
"Usage: \n"
" %s <input>... <outputDir> \n"
" [--mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]]\n"
" [--device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
"]"
, argv0);
SkDebugf("\n\n");
SkDebugf(
" input: A list of directories and files to use as input. Files are\n"
" expected to have the .skp extension.\n\n");
SkDebugf(
" outputDir: directory to write the rendered images.\n\n");
SkDebugf(
" --mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]: Run in the corresponding mode.\n"
" Default is simple.\n");
SkDebugf(
" pipe, Render using a SkGPipe.\n");
SkDebugf(
" pow2tile minWidth height[%], Creates tiles with widths\n"
" that are all a power of two\n"
" such that they minimize the\n"
" amount of wasted tile space.\n"
" minWidth is the minimum width\n"
" of these tiles and must be a\n"
" power of two. A simple render\n"
" is done with these tiles.\n");
SkDebugf(
" simple, Render using the default rendering method.\n");
SkDebugf(
" tile width[%] height[%], Do a simple render using tiles\n"
" with the given dimensions.\n");
SkDebugf("\n");
SkDebugf(
" --device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
": Use the corresponding device. Default is bitmap.\n");
SkDebugf(
" bitmap, Render to a bitmap.\n");
#if SK_SUPPORT_GPU
SkDebugf(
" gpu, Render to the GPU.\n");
#endif
}
static void make_output_filepath(SkString* path, const SkString& dir,
const SkString& name) {
sk_tools::make_filepath(path, dir, name);
path->remove(path->size() - 3, 3);
path->append("png");
}
static void write_output(const SkString& outputDir, const SkString& inputFilename,
const sk_tools::PictureRenderer& renderer) {
SkString outputPath;
make_output_filepath(&outputPath, outputDir, inputFilename);
bool isWritten = renderer.write(outputPath);
if (!isWritten) {
SkDebugf("Could not write to file %s\n", outputPath.c_str());
}
}
static void render_picture(const SkString& inputPath, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkString inputFilename;
sk_tools::get_basename(&inputFilename, inputPath);
SkFILEStream inputStream;
inputStream.setPath(inputPath.c_str());
if (!inputStream.isValid()) {
SkDebugf("Could not open file %s\n", inputPath.c_str());
return;
}
SkPicture picture(&inputStream);
renderer.init(&picture);
renderer.render(true);
renderer.resetState();
write_output(outputDir, inputFilename, renderer);
renderer.end();
}
static void process_input(const SkString& input, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkOSFile::Iter iter(input.c_str(), "skp");
SkString inputFilename;
if (iter.next(&inputFilename)) {
do {
SkString inputPath;
sk_tools::make_filepath(&inputPath, input, inputFilename);
render_picture(inputPath, outputDir, renderer);
} while(iter.next(&inputFilename));
} else {
SkString inputPath(input);
render_picture(inputPath, outputDir, renderer);
}
}
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
sk_tools::PictureRenderer*& renderer){
const char* argv0 = argv[0];
char* const* stop = argv + argc;
sk_tools::PictureRenderer::SkDeviceTypes deviceType =
sk_tools::PictureRenderer::kBitmap_DeviceType;
for (++argv; argv < stop; ++argv) {
if (0 == strcmp(*argv, "--mode")) {
SkDELETE(renderer);
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --mode\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "pipe")) {
renderer = SkNEW(sk_tools::PipePictureRenderer);
} else if (0 == strcmp(*argv, "simple")) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
} else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
char* mode = *argv;
bool isPowerOf2Mode = false;
if (0 == strcmp(*argv, "pow2tile")) {
isPowerOf2Mode = true;
}
sk_tools::TiledPictureRenderer* tileRenderer =
SkNEW(sk_tools::TiledPictureRenderer);
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing width for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (isPowerOf2Mode) {
int minWidth = atoi(*argv);
if (!SkIsPow2(minWidth) || minWidth <= 0) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width"
" value that is a power of two\n", mode);
exit(-1);
}
tileRenderer->setTileMinPowerOf2Width(minWidth);
} else if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileWidthPercentage(atof(*argv));
if (!(tileRenderer->getTileWidthPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileWidth(atoi(*argv));
if (!(tileRenderer->getTileWidth() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width > 0\n", mode);
exit(-1);
}
}
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing height for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileHeightPercentage(atof(*argv));
if (!(tileRenderer->getTileHeightPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf(
"--mode %s must be given a height percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileHeight(atoi(*argv));
if (!(tileRenderer->getTileHeight() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a height > 0\n", mode);
exit(-1);
}
}
renderer = tileRenderer;
} else {
SkDebugf("%s is not a valid mode for --mode\n", *argv);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--device")) {
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --deivce\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "bitmap")) {
deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
}
#if SK_SUPPORT_GPU
else if (0 == strcmp(*argv, "gpu")) {
deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
}
#endif
else {
SkDebugf("%s is not a valid mode for --device\n", *argv);
usage(argv0);
exit(-1);
}
} else if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
} else {
inputs->push_back(SkString(*argv));
}
}
if (inputs->count() < 2) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
}
if (NULL == renderer) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
}
renderer->setDeviceType(deviceType);
}
int main(int argc, char* const argv[]) {
SkTArray<SkString> inputs;
sk_tools::PictureRenderer* renderer = NULL;
parse_commandline(argc, argv, &inputs, renderer);
SkString outputDir = inputs[inputs.count() - 1];
SkASSERT(renderer);
for (int i = 0; i < inputs.count() - 1; i ++) {
process_input(inputs[i], outputDir, *renderer);
}
SkDELETE(renderer);
}
<commit_msg>Fix render_pictures for skia_static_initializers=0 Review URL: https://codereview.appspot.com/6500097<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGraphics.h"
#include "SkMath.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTArray.h"
#include "PictureRenderer.h"
#include "picture_utils.h"
static void usage(const char* argv0) {
SkDebugf("SkPicture rendering tool\n");
SkDebugf("\n"
"Usage: \n"
" %s <input>... <outputDir> \n"
" [--mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]]\n"
" [--device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
"]"
, argv0);
SkDebugf("\n\n");
SkDebugf(
" input: A list of directories and files to use as input. Files are\n"
" expected to have the .skp extension.\n\n");
SkDebugf(
" outputDir: directory to write the rendered images.\n\n");
SkDebugf(
" --mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]: Run in the corresponding mode.\n"
" Default is simple.\n");
SkDebugf(
" pipe, Render using a SkGPipe.\n");
SkDebugf(
" pow2tile minWidth height[%], Creates tiles with widths\n"
" that are all a power of two\n"
" such that they minimize the\n"
" amount of wasted tile space.\n"
" minWidth is the minimum width\n"
" of these tiles and must be a\n"
" power of two. A simple render\n"
" is done with these tiles.\n");
SkDebugf(
" simple, Render using the default rendering method.\n");
SkDebugf(
" tile width[%] height[%], Do a simple render using tiles\n"
" with the given dimensions.\n");
SkDebugf("\n");
SkDebugf(
" --device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
": Use the corresponding device. Default is bitmap.\n");
SkDebugf(
" bitmap, Render to a bitmap.\n");
#if SK_SUPPORT_GPU
SkDebugf(
" gpu, Render to the GPU.\n");
#endif
}
static void make_output_filepath(SkString* path, const SkString& dir,
const SkString& name) {
sk_tools::make_filepath(path, dir, name);
path->remove(path->size() - 3, 3);
path->append("png");
}
static void write_output(const SkString& outputDir, const SkString& inputFilename,
const sk_tools::PictureRenderer& renderer) {
SkString outputPath;
make_output_filepath(&outputPath, outputDir, inputFilename);
bool isWritten = renderer.write(outputPath);
if (!isWritten) {
SkDebugf("Could not write to file %s\n", outputPath.c_str());
}
}
static void render_picture(const SkString& inputPath, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkString inputFilename;
sk_tools::get_basename(&inputFilename, inputPath);
SkFILEStream inputStream;
inputStream.setPath(inputPath.c_str());
if (!inputStream.isValid()) {
SkDebugf("Could not open file %s\n", inputPath.c_str());
return;
}
SkPicture picture(&inputStream);
renderer.init(&picture);
renderer.render(true);
renderer.resetState();
write_output(outputDir, inputFilename, renderer);
renderer.end();
}
static void process_input(const SkString& input, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkOSFile::Iter iter(input.c_str(), "skp");
SkString inputFilename;
if (iter.next(&inputFilename)) {
do {
SkString inputPath;
sk_tools::make_filepath(&inputPath, input, inputFilename);
render_picture(inputPath, outputDir, renderer);
} while(iter.next(&inputFilename));
} else {
SkString inputPath(input);
render_picture(inputPath, outputDir, renderer);
}
}
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
sk_tools::PictureRenderer*& renderer){
const char* argv0 = argv[0];
char* const* stop = argv + argc;
sk_tools::PictureRenderer::SkDeviceTypes deviceType =
sk_tools::PictureRenderer::kBitmap_DeviceType;
for (++argv; argv < stop; ++argv) {
if (0 == strcmp(*argv, "--mode")) {
SkDELETE(renderer);
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --mode\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "pipe")) {
renderer = SkNEW(sk_tools::PipePictureRenderer);
} else if (0 == strcmp(*argv, "simple")) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
} else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
char* mode = *argv;
bool isPowerOf2Mode = false;
if (0 == strcmp(*argv, "pow2tile")) {
isPowerOf2Mode = true;
}
sk_tools::TiledPictureRenderer* tileRenderer =
SkNEW(sk_tools::TiledPictureRenderer);
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing width for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (isPowerOf2Mode) {
int minWidth = atoi(*argv);
if (!SkIsPow2(minWidth) || minWidth <= 0) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width"
" value that is a power of two\n", mode);
exit(-1);
}
tileRenderer->setTileMinPowerOf2Width(minWidth);
} else if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileWidthPercentage(atof(*argv));
if (!(tileRenderer->getTileWidthPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileWidth(atoi(*argv));
if (!(tileRenderer->getTileWidth() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width > 0\n", mode);
exit(-1);
}
}
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing height for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileHeightPercentage(atof(*argv));
if (!(tileRenderer->getTileHeightPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf(
"--mode %s must be given a height percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileHeight(atoi(*argv));
if (!(tileRenderer->getTileHeight() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a height > 0\n", mode);
exit(-1);
}
}
renderer = tileRenderer;
} else {
SkDebugf("%s is not a valid mode for --mode\n", *argv);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--device")) {
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --deivce\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "bitmap")) {
deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
}
#if SK_SUPPORT_GPU
else if (0 == strcmp(*argv, "gpu")) {
deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
}
#endif
else {
SkDebugf("%s is not a valid mode for --device\n", *argv);
usage(argv0);
exit(-1);
}
} else if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
} else {
inputs->push_back(SkString(*argv));
}
}
if (inputs->count() < 2) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
}
if (NULL == renderer) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
}
renderer->setDeviceType(deviceType);
}
int main(int argc, char* const argv[]) {
SkGraphics::Init();
SkTArray<SkString> inputs;
sk_tools::PictureRenderer* renderer = NULL;
parse_commandline(argc, argv, &inputs, renderer);
SkString outputDir = inputs[inputs.count() - 1];
SkASSERT(renderer);
for (int i = 0; i < inputs.count() - 1; i ++) {
process_input(inputs[i], outputDir, *renderer);
}
SkDELETE(renderer);
SkGraphics::Term();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
// Internal Headers
#include "magnetometersensorsym.h"
#include <sensrvgeneralproperties.h>
/**
* set the id of the magnetometer sensor
*/
char const * const CMagnetometerSensorSym::id("sym.magnetometer");
/**
* Factory function, this is used to create the magnetometer sensor object
* @return CMagnetometerSensorSym if successful, leaves on failure
*/
CMagnetometerSensorSym* CMagnetometerSensorSym::NewL(QSensor *sensor)
{
CMagnetometerSensorSym* self = new (ELeave) CMagnetometerSensorSym(sensor);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop();
return self;
}
/**
* Destructor
* Closes the backend resources
*/
CMagnetometerSensorSym::~CMagnetometerSensorSym()
{
//Closes the backend resources
Close();
}
/**
* Default constructor
*/
CMagnetometerSensorSym::CMagnetometerSensorSym(QSensor *sensor):CSensorBackendSym(sensor),
iCalibrationLevel(0.0),
iScaleRange(0)
{
if(sensor)
{
setReading<QMagnetometerReading>(&iReading);
}
iBackendData.iSensorType = KSensrvChannelTypeIdMagnetometerXYZAxisData;
//Enable Property listening, required to get Calibration level
SetListening(ETrue, ETrue);
}
/**
* start is overridden to allow retrieving initial calibration property before
* and to set the required value type flags
*/
void CMagnetometerSensorSym::start()
{
if(sensor())
{
// Initialize the values
iReading.setX(0);
iReading.setY(0);
iReading.setZ(0);
// Set the required type of values
QVariant v = sensor()->property("returnGeoValues");
iReturnGeoValues = (v.isValid() && v.toBool()); // if the property isn't set it's false
}
TInt err;
// get current property value for calibration and set it to reading
TSensrvProperty calibration;
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropCalibrationLevel, ESensrvSingleProperty, calibration));
// If error in getting the calibration level, continue to start the sensor
// as it is not a fatal error
if ( err == KErrNone )
{
TInt calibrationVal;
calibration.GetValue(calibrationVal);
iCalibrationLevel = calibrationVal * (1.0/3.0);
}
// Call backend start
CSensorBackendSym::start();
TSensrvProperty dataFormatProperty;
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropIdChannelDataFormat, ESensrvSingleProperty, dataFormatProperty));
if(err == KErrNone)
{
TInt dataFormat;
dataFormatProperty.GetValue(dataFormat);
if(dataFormat == ESensrvChannelDataFormatScaled)
{
TSensrvProperty scaleRangeProperty;
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropIdScaledRange, KSensrvItemIndexNone, scaleRangeProperty));
if(err == KErrNone)
{
if(scaleRangeProperty.GetArrayIndex() == ESensrvSingleProperty)
{
if(scaleRangeProperty.PropertyType() == ESensrvIntProperty)
{
scaleRangeProperty.GetMaxValue(iScaleRange);
}
else if(scaleRangeProperty.PropertyType() == ESensrvRealProperty)
{
TReal realScale;
scaleRangeProperty.GetMaxValue(realScale);
iScaleRange = realScale;
}
}
else if(scaleRangeProperty.GetArrayIndex() == ESensrvArrayPropertyInfo)
{
TInt index;
if(scaleRangeProperty.PropertyType() == ESensrvIntProperty)
{
scaleRangeProperty.GetValue(index);
}
else if(scaleRangeProperty.PropertyType() == ESensrvRealProperty)
{
TReal realIndex;
scaleRangeProperty.GetValue(realIndex);
index = realIndex;
}
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropIdScaledRange, KSensrvItemIndexNone, index, scaleRangeProperty));
if(err == KErrNone)
{
if(scaleRangeProperty.PropertyType() == ESensrvIntProperty)
{
scaleRangeProperty.GetMaxValue(iScaleRange);
}
else if(scaleRangeProperty.PropertyType() == ESensrvRealProperty)
{
TReal realScaleRange;
scaleRangeProperty.GetMaxValue(realScaleRange);
iScaleRange = realScaleRange;
}
}
}
}
}
}
}
/*
* DataReceived is used to retrieve the sensor reading from sensor server
* It is implemented here to handle magnetometer sensor specific
* reading data and provides conversion and utility code
*/
void CMagnetometerSensorSym::DataReceived(CSensrvChannel &aChannel, TInt aCount, TInt /*aDataLost*/)
{
ProcessData(aChannel, aCount, iData);
}
void CMagnetometerSensorSym::ProcessReading()
{
TReal x, y, z;
// If Geo values are requested set it
if(iReturnGeoValues)
{
x = iData.iAxisXCalibrated;
y = iData.iAxisYCalibrated;
z = iData.iAxisZCalibrated;
}
// If Raw values are requested set it
else
{
x = iData.iAxisXRaw;
y = iData.iAxisYRaw;
z = iData.iAxisZRaw;
}
// Scale adjustments
if(iScaleRange)
{
qoutputrangelist rangeList = sensor()->outputRanges();
int outputRange = sensor()->outputRange();
if (outputRange == -1)
outputRange = 0;
TReal maxValue = rangeList[outputRange].maximum;
x = (x/iScaleRange) * maxValue;
y = (y/iScaleRange) * maxValue;
z = (z/iScaleRange) * maxValue;
}
// Get a lock on the reading data
iBackendData.iReadingLock.Wait();
iReading.setX(x);
iReading.setY(y);
iReading.setZ(z);
// Set the timestamp
iReading.setTimestamp(iData.iTimeStamp.Int64());
// Set the calibration level
iReading.setCalibrationLevel(iCalibrationLevel);
// Release the lock
iBackendData.iReadingLock.Signal();
// Notify that a reading is available
newReadingAvailable();
}
/**
* HandlePropertyChange is called from backend, to indicate a change in property
*/
void CMagnetometerSensorSym::HandlePropertyChange(CSensrvChannel &/*aChannel*/, const TSensrvProperty &aChangedProperty)
{
if(aChangedProperty.GetPropertyId() != KSensrvPropCalibrationLevel)
{
// Do nothing, if calibration property has not changed
return;
}
TInt calibrationlevel;
aChangedProperty.GetValue(calibrationlevel);
// As Qt requires calibration level in qreal but symbian provides in enum
// It has been agreed with DS Team that the following mechanism will be
// used till discussions with qt mobility are complete
iCalibrationLevel = (1.0/3.0) * calibrationlevel;
}
/*
* Used to retrieve the current calibration level
* iCalibrationLevel is automatically updated whenever there is a change
* in calibration level
*/
qreal CMagnetometerSensorSym::GetCalibrationLevel()
{
return iCalibrationLevel;
}
/**
* Second phase constructor
* Initialize the backend resources
*/
void CMagnetometerSensorSym::ConstructL()
{
InitializeL();
}
<commit_msg>Don't crash when using Compass/Magnetometer<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
// Internal Headers
#include "magnetometersensorsym.h"
#include <sensrvgeneralproperties.h>
/**
* set the id of the magnetometer sensor
*/
char const * const CMagnetometerSensorSym::id("sym.magnetometer");
/**
* Factory function, this is used to create the magnetometer sensor object
* @return CMagnetometerSensorSym if successful, leaves on failure
*/
CMagnetometerSensorSym* CMagnetometerSensorSym::NewL(QSensor *sensor)
{
CMagnetometerSensorSym* self = new (ELeave) CMagnetometerSensorSym(sensor);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop();
return self;
}
/**
* Destructor
* Closes the backend resources
*/
CMagnetometerSensorSym::~CMagnetometerSensorSym()
{
//Closes the backend resources
Close();
}
/**
* Default constructor
*/
CMagnetometerSensorSym::CMagnetometerSensorSym(QSensor *sensor):CSensorBackendSym(sensor),
iCalibrationLevel(0.0),
iScaleRange(0)
{
if(sensor)
{
setReading<QMagnetometerReading>(&iReading);
}
iBackendData.iSensorType = KSensrvChannelTypeIdMagnetometerXYZAxisData;
//Enable Property listening, required to get Calibration level
SetListening(ETrue, ETrue);
}
/**
* start is overridden to allow retrieving initial calibration property before
* and to set the required value type flags
*/
void CMagnetometerSensorSym::start()
{
if(sensor())
{
// Initialize the values
iReading.setX(0);
iReading.setY(0);
iReading.setZ(0);
// Set the required type of values
QVariant v = sensor()->property("returnGeoValues");
iReturnGeoValues = (v.isValid() && v.toBool()); // if the property isn't set it's false
}
TInt err;
// get current property value for calibration and set it to reading
TSensrvProperty calibration;
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropCalibrationLevel, ESensrvSingleProperty, calibration));
// If error in getting the calibration level, continue to start the sensor
// as it is not a fatal error
if ( err == KErrNone )
{
TInt calibrationVal;
calibration.GetValue(calibrationVal);
iCalibrationLevel = calibrationVal * (1.0/3.0);
}
// Call backend start
CSensorBackendSym::start();
TSensrvProperty dataFormatProperty;
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropIdChannelDataFormat, ESensrvSingleProperty, dataFormatProperty));
if(err == KErrNone)
{
TInt dataFormat;
dataFormatProperty.GetValue(dataFormat);
if(dataFormat == ESensrvChannelDataFormatScaled)
{
TSensrvProperty scaleRangeProperty;
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropIdScaledRange, KSensrvItemIndexNone, scaleRangeProperty));
if(err == KErrNone)
{
if(scaleRangeProperty.GetArrayIndex() == ESensrvSingleProperty)
{
if(scaleRangeProperty.PropertyType() == ESensrvIntProperty)
{
scaleRangeProperty.GetMaxValue(iScaleRange);
}
else if(scaleRangeProperty.PropertyType() == ESensrvRealProperty)
{
TReal realScale;
scaleRangeProperty.GetMaxValue(realScale);
iScaleRange = realScale;
}
}
else if(scaleRangeProperty.GetArrayIndex() == ESensrvArrayPropertyInfo)
{
TInt index;
if(scaleRangeProperty.PropertyType() == ESensrvIntProperty)
{
scaleRangeProperty.GetValue(index);
}
else if(scaleRangeProperty.PropertyType() == ESensrvRealProperty)
{
TReal realIndex;
scaleRangeProperty.GetValue(realIndex);
index = realIndex;
}
TRAP(err, iBackendData.iSensorChannel->GetPropertyL(KSensrvPropIdScaledRange, KSensrvItemIndexNone, index, scaleRangeProperty));
if(err == KErrNone)
{
if(scaleRangeProperty.PropertyType() == ESensrvIntProperty)
{
scaleRangeProperty.GetMaxValue(iScaleRange);
}
else if(scaleRangeProperty.PropertyType() == ESensrvRealProperty)
{
TReal realScaleRange;
scaleRangeProperty.GetMaxValue(realScaleRange);
iScaleRange = realScaleRange;
}
}
}
}
}
}
}
/*
* DataReceived is used to retrieve the sensor reading from sensor server
* It is implemented here to handle magnetometer sensor specific
* reading data and provides conversion and utility code
*/
void CMagnetometerSensorSym::DataReceived(CSensrvChannel &aChannel, TInt aCount, TInt /*aDataLost*/)
{
ProcessData(aChannel, aCount, iData);
}
void CMagnetometerSensorSym::ProcessReading()
{
TReal x, y, z;
// If Geo values are requested set it
if(iReturnGeoValues)
{
x = iData.iAxisXCalibrated;
y = iData.iAxisYCalibrated;
z = iData.iAxisZCalibrated;
}
// If Raw values are requested set it
else
{
x = iData.iAxisXRaw;
y = iData.iAxisYRaw;
z = iData.iAxisZRaw;
}
// Scale adjustments
if(iScaleRange && sensor()->outputRanges().count())
{
qoutputrangelist rangeList = sensor()->outputRanges();
int outputRange = sensor()->outputRange();
if (outputRange == -1)
outputRange = 0;
TReal maxValue = rangeList[outputRange].maximum;
x = (x/iScaleRange) * maxValue;
y = (y/iScaleRange) * maxValue;
z = (z/iScaleRange) * maxValue;
}
// Get a lock on the reading data
iBackendData.iReadingLock.Wait();
iReading.setX(x);
iReading.setY(y);
iReading.setZ(z);
// Set the timestamp
iReading.setTimestamp(iData.iTimeStamp.Int64());
// Set the calibration level
iReading.setCalibrationLevel(iCalibrationLevel);
// Release the lock
iBackendData.iReadingLock.Signal();
// Notify that a reading is available
newReadingAvailable();
}
/**
* HandlePropertyChange is called from backend, to indicate a change in property
*/
void CMagnetometerSensorSym::HandlePropertyChange(CSensrvChannel &/*aChannel*/, const TSensrvProperty &aChangedProperty)
{
if(aChangedProperty.GetPropertyId() != KSensrvPropCalibrationLevel)
{
// Do nothing, if calibration property has not changed
return;
}
TInt calibrationlevel;
aChangedProperty.GetValue(calibrationlevel);
// As Qt requires calibration level in qreal but symbian provides in enum
// It has been agreed with DS Team that the following mechanism will be
// used till discussions with qt mobility are complete
iCalibrationLevel = (1.0/3.0) * calibrationlevel;
}
/*
* Used to retrieve the current calibration level
* iCalibrationLevel is automatically updated whenever there is a change
* in calibration level
*/
qreal CMagnetometerSensorSym::GetCalibrationLevel()
{
return iCalibrationLevel;
}
/**
* Second phase constructor
* Initialize the backend resources
*/
void CMagnetometerSensorSym::ConstructL()
{
InitializeL();
}
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE trace_data_extraction
#include <boost/test/included/unit_test.hpp>
#include <eosio/chain/trace.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/block.hpp>
#include <eosio/chain/block_state.hpp>
#include <eosio/trace_api_plugin/test_common.hpp>
#include <eosio/trace_api_plugin/chain_extraction.hpp>
#include <fc/bitutil.hpp>
using namespace eosio;
using namespace eosio::trace_api_plugin;
using namespace eosio::trace_api_plugin::test_common;
using eosio::chain::name;
using eosio::chain::digest_type;
namespace {
chain::transaction_trace_ptr make_transaction_trace( const chain::transaction_id_type& id, uint32_t block_number,
uint32_t slot, chain::transaction_receipt_header::status_enum status, std::vector<chain::action_trace>&& actions ) {
return std::make_shared<chain::transaction_trace>(chain::transaction_trace{
id,
block_number,
chain::block_timestamp_type(slot),
{},
chain::transaction_receipt_header{status},
fc::microseconds(0),
0,
false,
std::move(actions),
{},
{},
{},
{},
{}
});
}
chain::bytes make_transfer_data( chain::name from, chain::name to, chain::asset quantity, std::string&& memo ) {
fc::datastream<size_t> ps;
fc::raw::pack(ps, from, to, quantity, memo);
chain::bytes result(ps.tellp());
if( result.size() ) {
fc::datastream<char*> ds( result.data(), size_t(result.size()) );
fc::raw::pack(ds, from, to, quantity, memo);
}
return result;
}
auto get_private_key( name keyname, std::string role = "owner" ) {
auto secret = fc::sha256::hash( keyname.to_string() + role );
return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret );
}
auto get_public_key( name keyname, std::string role = "owner" ) {
return get_private_key( keyname, role ).get_public_key();
}
auto make_transfer_action( chain::name from, chain::name to, chain::asset quantity, std::string memo ) {
return chain::action( std::vector<chain::permission_level> {{from, chain::config::active_name}},
"eosio.token"_n, "transfer"_n, make_transfer_data( from, to, quantity, std::move(memo) ) );
}
auto make_packed_trx( std::vector<chain::action> actions ) {
chain::signed_transaction trx;
trx.actions = std::move( actions );
return packed_transaction( trx );
}
chain::action_trace make_action_trace( uint64_t global_sequence, chain::action act, chain::name receiver ) {
chain::action_trace result;
// don't think we need any information other than receiver and global sequence
result.receipt.emplace(chain::action_receipt{
receiver,
digest_type::hash(act),
global_sequence,
0,
{},
0,
0
});
result.receiver = receiver;
result.act = std::move(act);
return result;
}
auto make_block_state( chain::block_id_type previous, uint32_t height, uint32_t slot, chain::name producer,
std::vector<chain::packed_transaction> trxs ) {
chain::signed_block_ptr block = std::make_shared<chain::signed_block>();
for( auto& trx : trxs ) {
block->transactions.emplace_back( trx );
}
block->producer = producer;
block->timestamp = chain::block_timestamp_type(slot);
// make sure previous contains correct block # so block_header::block_num() returns correct value
if( previous == chain::block_id_type() ) {
previous._hash[0] &= 0xffffffff00000000;
previous._hash[0] += fc::endian_reverse_u32(height - 1);
}
block->previous = previous;
auto priv_key = get_private_key( block->producer, "active" );
auto pub_key = get_public_key( block->producer, "active" );
auto prev = std::make_shared<chain::block_state>();
auto header_bmroot = digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root()));
auto sig_digest = digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash ));
block->producer_signature = priv_key.sign( sig_digest );
std::vector<chain::private_key_type> signing_keys;
signing_keys.emplace_back( std::move( priv_key ));
auto signer = [&]( digest_type d ) {
std::vector<chain::signature_type> result;
result.reserve( signing_keys.size());
for( const auto& k: signing_keys )
result.emplace_back( k.sign( d ));
return result;
};
chain::pending_block_header_state pbhs;
pbhs.producer = block->producer;
pbhs.timestamp = block->timestamp;
chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer,
chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}};
pbhs.active_schedule = schedule;
pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}};
auto bsp = std::make_shared<chain::block_state>(
std::move( pbhs ),
std::move( block ),
std::vector<chain::transaction_metadata_ptr>(),
chain::protocol_feature_set(),
[]( chain::block_timestamp_type timestamp,
const fc::flat_set<digest_type>& cur_features,
const std::vector<digest_type>& new_features ) {},
signer
);
bsp->block_num = height;
return bsp;
}
}
struct extraction_test_fixture {
/**
* MOCK implementation of the logfile input API
*/
struct mock_logfile_provider_type {
mock_logfile_provider_type(extraction_test_fixture& fixture)
:fixture(fixture)
{}
/**
* append an entry to the end of the data log
*
* @param entry : the entry to append
* @return the offset in the log where that entry is written
*/
uint64_t append_data_log( const data_log_entry& entry ) {
fixture.data_log.emplace_back(entry);
return fixture.data_log.size() - 1;
}
/**
* Append an entry to the metadata log
*
* @param entry
* @return
*/
uint64_t append_metadata_log( const metadata_log_entry& entry ) {
if (entry.contains<block_entry_v0>()) {
const auto& b = entry.get<block_entry_v0>();
fixture.block_entry_for_height[b.number] = b;
} else if (entry.contains<lib_entry_v0>()) {
const auto& lib = entry.get<lib_entry_v0>();
fixture.max_lib = std::max(fixture.max_lib, lib.lib);
} else {
BOOST_FAIL("Unknown metadata log entry emitted");
}
return fixture.metadata_offset++;
}
extraction_test_fixture& fixture;
};
extraction_test_fixture()
: extraction_impl(mock_logfile_provider_type(*this), [](std::exception_ptr eptr) {})
{
}
void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {
extraction_impl.signal_applied_transaction(trace, strx);
}
void signal_accepted_block( const chain::block_state_ptr& bsp ) {
extraction_impl.signal_accepted_block(bsp);
}
// fixture data and methods
std::map<uint64_t, block_entry_v0> block_entry_for_height = {};
uint64_t metadata_offset = 0;
uint64_t max_lib = 0;
std::vector<data_log_entry> data_log = {};
chain_extraction_impl_type<mock_logfile_provider_type> extraction_impl;
};
BOOST_AUTO_TEST_SUITE(block_extraction)
BOOST_FIXTURE_TEST_CASE(basic_single_transaction_block, extraction_test_fixture)
{
auto act1 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act2 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act3 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto actt1 = make_action_trace( 0, act1, "eosio.token"_n );
auto actt2 = make_action_trace( 1, act1, "alice"_n );
auto actt3 = make_action_trace( 2, act1, "bob"_n );
auto ptrx1 = make_packed_trx( { act1, act2, act3 } );
// apply a basic transfer
//
signal_applied_transaction(
make_transaction_trace(
ptrx1.id(),
1,
1,
chain::transaction_receipt_header::executed,
{ actt1, actt2, actt3 }
),
{
// I don't think we will need any data from here?
}
);
// accept the block with one transaction
auto bsp1 = make_block_state(
chain::block_id_type(),
1,
1,
"bp.one"_n,
{ chain::packed_transaction(ptrx1) } );
signal_accepted_block( bsp1 );
// Verify that the blockheight and LIB are correct
//
const uint64_t expected_lib = 0;
const block_entry_v0 expected_entry {
bsp1->id,
1,
0
};
const block_trace_v0 expected_trace {
bsp1->id,
1,
bsp1->prev(),
chain::block_timestamp_type(1),
"bp.one"_n,
{
{
ptrx1.id(),
chain::transaction_receipt_header::executed,
{
{
0,
"eosio.token"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
1,
"alice"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
2,
"bob"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
}
}
}
}
};
BOOST_REQUIRE_EQUAL(max_lib, 0);
BOOST_REQUIRE(block_entry_for_height.count(1) > 0);
BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);
BOOST_REQUIRE(data_log.size() >= expected_entry.offset);
BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());
BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add multi trx test and clean up single trx test<commit_after>#define BOOST_TEST_MODULE trace_data_extraction
#include <boost/test/included/unit_test.hpp>
#include <eosio/chain/trace.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/block.hpp>
#include <eosio/chain/block_state.hpp>
#include <eosio/trace_api_plugin/test_common.hpp>
#include <eosio/trace_api_plugin/chain_extraction.hpp>
#include <fc/bitutil.hpp>
using namespace eosio;
using namespace eosio::trace_api_plugin;
using namespace eosio::trace_api_plugin::test_common;
using eosio::chain::name;
using eosio::chain::digest_type;
namespace {
chain::transaction_trace_ptr make_transaction_trace( const chain::transaction_id_type& id, uint32_t block_number,
uint32_t slot, chain::transaction_receipt_header::status_enum status, std::vector<chain::action_trace>&& actions ) {
return std::make_shared<chain::transaction_trace>(chain::transaction_trace{
id,
block_number,
chain::block_timestamp_type(slot),
{},
chain::transaction_receipt_header{status},
fc::microseconds(0),
0,
false,
std::move(actions),
{},
{},
{},
{},
{}
});
}
chain::bytes make_transfer_data( chain::name from, chain::name to, chain::asset quantity, std::string&& memo ) {
fc::datastream<size_t> ps;
fc::raw::pack(ps, from, to, quantity, memo);
chain::bytes result(ps.tellp());
if( result.size() ) {
fc::datastream<char*> ds( result.data(), size_t(result.size()) );
fc::raw::pack(ds, from, to, quantity, memo);
}
return result;
}
auto get_private_key( name keyname, std::string role = "owner" ) {
auto secret = fc::sha256::hash( keyname.to_string() + role );
return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret );
}
auto get_public_key( name keyname, std::string role = "owner" ) {
return get_private_key( keyname, role ).get_public_key();
}
auto make_transfer_action( chain::name from, chain::name to, chain::asset quantity, std::string memo ) {
return chain::action( std::vector<chain::permission_level> {{from, chain::config::active_name}},
"eosio.token"_n, "transfer"_n, make_transfer_data( from, to, quantity, std::move(memo) ) );
}
auto make_packed_trx( std::vector<chain::action> actions ) {
chain::signed_transaction trx;
trx.actions = std::move( actions );
return packed_transaction( trx );
}
chain::action_trace make_action_trace( uint64_t global_sequence, chain::action act, chain::name receiver ) {
chain::action_trace result;
// don't think we need any information other than receiver and global sequence
result.receipt.emplace(chain::action_receipt{
receiver,
digest_type::hash(act),
global_sequence,
0,
{},
0,
0
});
result.receiver = receiver;
result.act = std::move(act);
return result;
}
auto make_block_state( chain::block_id_type previous, uint32_t height, uint32_t slot, chain::name producer,
std::vector<chain::packed_transaction> trxs ) {
chain::signed_block_ptr block = std::make_shared<chain::signed_block>();
for( auto& trx : trxs ) {
block->transactions.emplace_back( trx );
}
block->producer = producer;
block->timestamp = chain::block_timestamp_type(slot);
// make sure previous contains correct block # so block_header::block_num() returns correct value
if( previous == chain::block_id_type() ) {
previous._hash[0] &= 0xffffffff00000000;
previous._hash[0] += fc::endian_reverse_u32(height - 1);
}
block->previous = previous;
auto priv_key = get_private_key( block->producer, "active" );
auto pub_key = get_public_key( block->producer, "active" );
auto prev = std::make_shared<chain::block_state>();
auto header_bmroot = digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root()));
auto sig_digest = digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash ));
block->producer_signature = priv_key.sign( sig_digest );
std::vector<chain::private_key_type> signing_keys;
signing_keys.emplace_back( std::move( priv_key ));
auto signer = [&]( digest_type d ) {
std::vector<chain::signature_type> result;
result.reserve( signing_keys.size());
for( const auto& k: signing_keys )
result.emplace_back( k.sign( d ));
return result;
};
chain::pending_block_header_state pbhs;
pbhs.producer = block->producer;
pbhs.timestamp = block->timestamp;
chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer,
chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}};
pbhs.active_schedule = schedule;
pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}};
auto bsp = std::make_shared<chain::block_state>(
std::move( pbhs ),
std::move( block ),
std::vector<chain::transaction_metadata_ptr>(),
chain::protocol_feature_set(),
[]( chain::block_timestamp_type timestamp,
const fc::flat_set<digest_type>& cur_features,
const std::vector<digest_type>& new_features ) {},
signer
);
bsp->block_num = height;
return bsp;
}
}
struct extraction_test_fixture {
/**
* MOCK implementation of the logfile input API
*/
struct mock_logfile_provider_type {
mock_logfile_provider_type(extraction_test_fixture& fixture)
:fixture(fixture)
{}
/**
* append an entry to the end of the data log
*
* @param entry : the entry to append
* @return the offset in the log where that entry is written
*/
uint64_t append_data_log( const data_log_entry& entry ) {
fixture.data_log.emplace_back(entry);
return fixture.data_log.size() - 1;
}
/**
* Append an entry to the metadata log
*
* @param entry
* @return
*/
uint64_t append_metadata_log( const metadata_log_entry& entry ) {
if (entry.contains<block_entry_v0>()) {
const auto& b = entry.get<block_entry_v0>();
fixture.block_entry_for_height[b.number] = b;
} else if (entry.contains<lib_entry_v0>()) {
const auto& lib = entry.get<lib_entry_v0>();
fixture.max_lib = std::max(fixture.max_lib, lib.lib);
} else {
BOOST_FAIL("Unknown metadata log entry emitted");
}
return fixture.metadata_offset++;
}
extraction_test_fixture& fixture;
};
extraction_test_fixture()
: extraction_impl(mock_logfile_provider_type(*this), [](std::exception_ptr eptr) {})
{
}
void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {
extraction_impl.signal_applied_transaction(trace, strx);
}
void signal_accepted_block( const chain::block_state_ptr& bsp ) {
extraction_impl.signal_accepted_block(bsp);
}
// fixture data and methods
std::map<uint64_t, block_entry_v0> block_entry_for_height = {};
uint64_t metadata_offset = 0;
uint64_t max_lib = 0;
std::vector<data_log_entry> data_log = {};
chain_extraction_impl_type<mock_logfile_provider_type> extraction_impl;
};
BOOST_AUTO_TEST_SUITE(block_extraction)
BOOST_FIXTURE_TEST_CASE(basic_single_transaction_block, extraction_test_fixture)
{
auto act1 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act2 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act3 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto actt1 = make_action_trace( 0, act1, "eosio.token"_n );
auto actt2 = make_action_trace( 1, act2, "alice"_n );
auto actt3 = make_action_trace( 2, act3, "bob"_n );
auto ptrx1 = make_packed_trx( { act1, act2, act3 } );
// apply a basic transfer
signal_applied_transaction(
make_transaction_trace( ptrx1.id(), 1, 1, chain::transaction_receipt_header::executed,
{ actt1, actt2, actt3 } ),
ptrx1.get_signed_transaction() );
// accept the block with one transaction
auto bsp1 = make_block_state( chain::block_id_type(), 1, 1, "bp.one"_n,
{ chain::packed_transaction(ptrx1) } );
signal_accepted_block( bsp1 );
// Verify that the blockheight and LIB are correct
const uint64_t expected_lib = 0;
const block_entry_v0 expected_entry { bsp1->id, 1, 0 };
const block_trace_v0 expected_trace { bsp1->id, 1, bsp1->prev(), chain::block_timestamp_type(1), "bp.one"_n,
{
{
ptrx1.id(),
chain::transaction_receipt_header::executed,
{
{
0,
"eosio.token"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
1,
"alice"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
2,
"bob"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
}
}
}
}
};
BOOST_REQUIRE_EQUAL(max_lib, 0);
BOOST_REQUIRE(block_entry_for_height.count(1) > 0);
BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);
BOOST_REQUIRE(data_log.size() >= expected_entry.offset);
BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());
BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);
}
BOOST_FIXTURE_TEST_CASE(basic_multi_transaction_block, extraction_test_fixture) {
auto act1 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act2 = make_transfer_action( "bob"_n, "alice"_n, "0.0001 SYS"_t, "Memo!" );
auto act3 = make_transfer_action( "fred"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto actt1 = make_action_trace( 0, act1, "eosio.token"_n );
auto actt2 = make_action_trace( 1, act2, "bob"_n );
auto actt3 = make_action_trace( 2, act3, "fred"_n );
auto ptrx1 = make_packed_trx( { act1 } );
auto ptrx2 = make_packed_trx( { act2 } );
auto ptrx3 = make_packed_trx( { act3 } );
signal_applied_transaction(
make_transaction_trace( ptrx1.id(), 1, 1, chain::transaction_receipt_header::executed,
{ actt1 } ),
ptrx1.get_signed_transaction() );
signal_applied_transaction(
make_transaction_trace( ptrx2.id(), 1, 1, chain::transaction_receipt_header::executed,
{ actt2 } ),
ptrx2.get_signed_transaction() );
signal_applied_transaction(
make_transaction_trace( ptrx3.id(), 1, 1, chain::transaction_receipt_header::executed,
{ actt3 } ),
ptrx3.get_signed_transaction() );
// accept the block with three transaction
auto bsp1 = make_block_state( chain::block_id_type(), 1, 1, "bp.one"_n,
{ chain::packed_transaction(ptrx1), chain::packed_transaction(ptrx2), chain::packed_transaction(ptrx3) } );
signal_accepted_block( bsp1 );
// Verify that the blockheight and LIB are correct
const uint64_t expected_lib = 0;
const block_entry_v0 expected_entry { bsp1->id, 1, 0 };
const block_trace_v0 expected_trace { bsp1->id, 1, bsp1->prev(), chain::block_timestamp_type(1), "bp.one"_n,
{
{
ptrx1.id(),
chain::transaction_receipt_header::executed,
{
{
0,
"eosio.token"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
}
}
},
{
ptrx2.id(),
chain::transaction_receipt_header::executed,
{
{
1,
"bob"_n, "eosio.token"_n, "transfer"_n,
{{ "bob"_n, "active"_n }},
make_transfer_data( "bob"_n, "alice"_n, "0.0001 SYS"_t, "Memo!" )
}
}
},
{
ptrx3.id(),
chain::transaction_receipt_header::executed,
{
{
2,
"fred"_n, "eosio.token"_n, "transfer"_n,
{{ "fred"_n, "active"_n }},
make_transfer_data( "fred"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
}
}
}
}
};
BOOST_REQUIRE_EQUAL(max_lib, 0);
BOOST_REQUIRE(block_entry_for_height.count(1) > 0);
BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);
BOOST_REQUIRE(data_log.size() >= expected_entry.offset);
BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());
BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.