commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
948ba7e8f22b20fc9bd6af96d4f019c98ebc42b6
|
hash.cpp
|
hash.cpp
|
/******************************************************************************
Copyright 2016 Allied Telesis Labs Ltd. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE 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 <buildsys.h>
#include <openssl/evp.h>
void buildsys::hash_setup()
{
OpenSSL_add_all_digests();
}
void buildsys::hash_shutdown()
{
EVP_cleanup();
}
std::string buildsys::hash_file(const std::string & fname)
{
EVP_MD_CTX *mdctx;
const EVP_MD *md;
int BUFLEN = 4096;
char buff[BUFLEN];
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
md = EVP_get_digestbyname("sha256");
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
FILE *f = fopen(fname.c_str(), "rb");
if(!f) {
fprintf(stderr, "Failed opening: %s\n", fname.c_str());
return NULL;
}
while(!feof(f)) {
size_t red = fread(buff, 1, BUFLEN, f);
EVP_DigestUpdate(mdctx, buff, red);
}
fclose(f);
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
char *str_res = (char *) calloc(1, (md_len * 2) + 1);
for(unsigned int i = 0; i < md_len; i++) {
sprintf(&str_res[i * 2], "%02x", md_value[i]);
}
std::string res = std::string(str_res);
free(str_res);
return res;
}
|
/******************************************************************************
Copyright 2016 Allied Telesis Labs Ltd. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE 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 <buildsys.h>
#include <openssl/evp.h>
void buildsys::hash_setup()
{
OpenSSL_add_all_digests();
}
void buildsys::hash_shutdown()
{
EVP_cleanup();
}
std::string buildsys::hash_file(const std::string & fname)
{
EVP_MD_CTX *mdctx;
const EVP_MD *md;
int BUFLEN = 4096;
char buff[BUFLEN];
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
md = EVP_get_digestbyname("sha256");
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
FILE *f = fopen(fname.c_str(), "rb");
if(!f) {
fprintf(stderr, "Failed opening: %s\n", fname.c_str());
return std::string("");
}
while(!feof(f)) {
size_t red = fread(buff, 1, BUFLEN, f);
EVP_DigestUpdate(mdctx, buff, red);
}
fclose(f);
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
char *str_res = (char *) calloc(1, (md_len * 2) + 1);
for(unsigned int i = 0; i < md_len; i++) {
sprintf(&str_res[i * 2], "%02x", md_value[i]);
}
std::string res = std::string(str_res);
free(str_res);
return res;
}
|
Fix return value for hash_file function
|
hash: Fix return value for hash_file function
Returning NULL causes a crash (as there is no valid conversion to a
string). Simply return an empty string instead. The rest of the code
is already comparing against an empty string.
Change-Id: I916cf8ac96dd514b8fd59b49c2292afc28b0393b
Reviewed-by: Scott Parlane <[email protected]>
Reviewed-by: Ridge Kennedy <[email protected]>
Signed-off-by: Matt Bennett <[email protected]>
|
C++
|
bsd-2-clause
|
ATL-NZ/buildsyspp,alliedtelesis/buildsyspp
|
2dd9577ab35819a8e3fc4c2bb7565aa5bc00c2e7
|
example/TableModel.cpp
|
example/TableModel.cpp
|
#include "TableModel.h"
static const char *header[] = {"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"};
typedef struct {
QString date;
QString author;
int isbn;
float price;
} Row;
static Row rows[] = {
{"1985/01/21","Douglas Adams",345391802,5.95f},
{"1990/01/12","Douglas Hofstadter",465026567,9.95f},
{"1998/07/15","Timothy ""The Parser"" Campbell",968411304,18.99f},
{"1999/12/03","Richard Friedman",60630353,5.95f},
{"2001/09/19","Karen Armstrong",345384563,9.95f},
{"2002/06/23","David Jones",198504691,9.95f},
{"2002/06/23","Julian Jaynes",618057072,12.50f},
{"2003/09/30","Scott Adams",740721909,4.95f},
{"2004/10/04","Benjamin Radcliff",804818088,4.95f},
{"2004/10/04","Randel Helms",879755725,4.50f}};
TableModel::TableModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
int TableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 10;
}
int TableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 4;
}
QVariant TableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= 10 || index.row() < 0)
return QVariant();
if (role == Qt::DisplayRole) {
switch(index.column()) {
case 0: return rows[index.row()].date;
case 1: return rows[index.row()].author;
case 2: return rows[index.row()].isbn;
case 3: return rows[index.row()].price;
}
}
return QVariant();
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
return header[section];
}
return QVariant();
}
void TableModel::swapRows(int r1, int r2)
{
qSwap(rows[r1].date, rows[r2].date);
qSwap(rows[r1].author, rows[r2].author);
qSwap(rows[r1].isbn, rows[r2].isbn);
qSwap(rows[r1].price, rows[r2].price);
}
bool TableModel::lessThan(int column, int r1, int r2)
{
switch(column) {
case 0: return rows[r1].date <= rows[r2].date;
case 1: return rows[r1].author <= rows[r2].author;
case 2: return rows[r1].isbn <= rows[r2].isbn;
case 3: return rows[r1].price <= rows[r2].price;
}
return false;
}
void TableModel::sort(int column, Qt::SortOrder order)
{
emit layoutAboutToBeChanged();
// gnomesort
for ( int i = 1; i < rowCount(); ) {
if ( order == Qt::AscendingOrder ? lessThan(column, i-1, i) : lessThan(column, i, i-1)) {
++i;
} else {
swapRows(i-1, i);
--i;
if ( i == 0 ) {
i = 1;
}
}
}
emit layoutChanged();
}
|
#include "TableModel.h"
static const char *header[] = {"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"};
typedef struct {
QString date;
QString author;
int isbn;
float price;
} Row;
static Row rows[] = {
{"1985/01/21","Douglas Adams",345391802,5.95f},
{"1990/01/12","Douglas Hofstadter",465026567,9.95f},
{"1998/07/15","Timothy ""The Parser"" Campbell",968411304,18.99f},
{"1999/12/03","Richard Friedman",60630353,5.95f},
{"2001/09/19","Karen Armstrong",345384563,9.95f},
{"2002/06/23","David Jones",198504691,9.95f},
{"2002/06/23","Julian Jaynes",618057072,12.50f},
{"2003/09/30","Scott Adams",740721909,4.95f},
{"2004/10/04","Benjamin Radcliff",804818088,4.95f},
{"2004/10/04","Randel Helms",879755725,4.50f}};
TableModel::TableModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
int TableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 10;
}
int TableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 4;
}
QVariant TableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= 10 || index.row() < 0)
return QVariant();
if (role == Qt::DisplayRole) {
switch(index.column()) {
case 0: return rows[index.row()].date;
case 1: return rows[index.row()].author;
case 2: return rows[index.row()].isbn;
case 3: return rows[index.row()].price;
}
}
return QVariant();
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
return header[section];
} else {
return section+1;
}
return QVariant();
}
void TableModel::swapRows(int r1, int r2)
{
qSwap(rows[r1].date, rows[r2].date);
qSwap(rows[r1].author, rows[r2].author);
qSwap(rows[r1].isbn, rows[r2].isbn);
qSwap(rows[r1].price, rows[r2].price);
}
bool TableModel::lessThan(int column, int r1, int r2)
{
switch(column) {
case 0: return rows[r1].date <= rows[r2].date;
case 1: return rows[r1].author <= rows[r2].author;
case 2: return rows[r1].isbn <= rows[r2].isbn;
case 3: return rows[r1].price <= rows[r2].price;
}
return false;
}
void TableModel::sort(int column, Qt::SortOrder order)
{
emit layoutAboutToBeChanged();
// gnomesort
for ( int i = 1; i < rowCount(); ) {
if ( order == Qt::AscendingOrder ? lessThan(column, i-1, i) : lessThan(column, i, i-1)) {
++i;
} else {
swapRows(i-1, i);
--i;
if ( i == 0 ) {
i = 1;
}
}
}
emit layoutChanged();
}
|
add row numbers
|
example: add row numbers
|
C++
|
mit
|
mojocorp/QSpreadsheetHeaderView
|
c85b2de13dfcd70b4335fac42d1f078b0968ed8b
|
libsrc/grabber/dispmanx/DispmanxWrapper.cpp
|
libsrc/grabber/dispmanx/DispmanxWrapper.cpp
|
// QT includes
#include <QDateTime>
// Hyperion includes
#include <hyperion/Hyperion.h>
#include <hyperion/ImageProcessorFactory.h>
#include <hyperion/ImageProcessor.h>
// Dispmanx grabber includes
#include <grabber/DispmanxWrapper.h>
#include <grabber/DispmanxFrameGrabber.h>
DispmanxWrapper::DispmanxWrapper(const unsigned grabWidth, const unsigned grabHeight, const unsigned updateRate_Hz, const int priority)
: GrabberWrapper("Dispmanx", priority)
, _updateInterval_ms(1000/updateRate_Hz)
, _timeout_ms(2 * _updateInterval_ms)
, _image(grabWidth, grabHeight)
, _grabber(new DispmanxFrameGrabber(grabWidth, grabHeight))
, _ledColors(Hyperion::getInstance()->getLedCount(), ColorRgb{0,0,0})
{
// Configure the timer to generate events every n milliseconds
_timer.setInterval(_updateInterval_ms);
_processor->setSize(grabWidth, grabHeight);
}
DispmanxWrapper::~DispmanxWrapper()
{
delete _grabber;
}
void DispmanxWrapper::action()
{
// Grab frame into the allocated image
_grabber->grabFrame(_image);
Image<ColorRgb> image_rgb;
_image.toRgb(image_rgb);
emit emitImage(_priority, image_rgb, _timeout_ms);
_processor->process(_image, _ledColors);
setColors(_ledColors, _timeout_ms);
}
void DispmanxWrapper::kodiPlay()
{
_grabber->setFlags(DISPMANX_SNAPSHOT_NO_RGB|DISPMANX_SNAPSHOT_FILL);
GrabberWrapper::kodiPlay();
}
void DispmanxWrapper::kodiPause()
{
_grabber->setFlags(0);
GrabberWrapper::kodiPause();
}
void DispmanxWrapper::setVideoMode(const VideoMode mode)
{
_grabber->setVideoMode(mode);
}
void DispmanxWrapper::setCropping(const unsigned cropLeft, const unsigned cropRight,
const unsigned cropTop, const unsigned cropBottom)
{
_grabber->setCropping(cropLeft, cropRight, cropTop, cropBottom);
}
|
// QT includes
#include <QDateTime>
// Hyperion includes
#include <hyperion/Hyperion.h>
#include <hyperion/ImageProcessorFactory.h>
#include <hyperion/ImageProcessor.h>
// Dispmanx grabber includes
#include <grabber/DispmanxWrapper.h>
#include <grabber/DispmanxFrameGrabber.h>
DispmanxWrapper::DispmanxWrapper(const unsigned grabWidth, const unsigned grabHeight, const unsigned updateRate_Hz, const int priority)
: GrabberWrapper("Dispmanx", priority)
, _updateInterval_ms(1000/updateRate_Hz)
, _timeout_ms(2 * _updateInterval_ms)
, _image(grabWidth, grabHeight)
, _grabber(new DispmanxFrameGrabber(grabWidth, grabHeight))
, _ledColors(Hyperion::getInstance()->getLedCount(), ColorRgb{0,0,0})
{
// Configure the timer to generate events every n milliseconds
_timer.setInterval(_updateInterval_ms);
_processor->setSize(grabWidth, grabHeight);
}
DispmanxWrapper::~DispmanxWrapper()
{
delete _grabber;
}
void DispmanxWrapper::action()
{
// Grab frame into the allocated image
_grabber->grabFrame(_image);
Image<ColorRgb> image_rgb;
_image.toRgb(image_rgb);
emit emitImage(_priority, image_rgb, _timeout_ms);
_processor->process(_image, _ledColors);
setColors(_ledColors, _timeout_ms);
}
void DispmanxWrapper::kodiPlay()
{
_grabber->setFlags(0);
GrabberWrapper::kodiPlay();
}
void DispmanxWrapper::kodiPause()
{
_grabber->setFlags(0);
GrabberWrapper::kodiPause();
}
void DispmanxWrapper::setVideoMode(const VideoMode mode)
{
_grabber->setVideoMode(mode);
}
void DispmanxWrapper::setCropping(const unsigned cropLeft, const unsigned cropRight,
const unsigned cropTop, const unsigned cropBottom)
{
_grabber->setCropping(cropLeft, cropRight, cropTop, cropBottom);
}
|
Update DispmanxWrapper.cpp
|
Update DispmanxWrapper.cpp
|
C++
|
mit
|
redPanther/hyperion.ng,penfold42/hyperion.ng,hyperion-project/hyperion.ng,redPanther/hyperion.ng,hyperion-project/hyperion.ng,redPanther/hyperion.ng,redPanther/hyperion.ng,penfold42/hyperion.ng,hyperion-project/hyperion.ng,redPanther/hyperion.ng,penfold42/hyperion.ng,hyperion-project/hyperion.ng,penfold42/hyperion.ng,penfold42/hyperion.ng,penfold42/hyperion.ng,hyperion-project/hyperion.ng,hyperion-project/hyperion.ng,redPanther/hyperion.ng
|
7aa363951edd852c67bf7fb89492aefe14a5003e
|
src/sdp2blocks/main.cxx
|
src/sdp2blocks/main.cxx
|
#include "Boost_Float.hxx"
#include "Positive_Matrix_With_Prefactor.hxx"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
void read_input(const boost::filesystem::path &input_file,
std::vector<El::BigFloat> &objectives,
std::vector<El::BigFloat> &normalization,
std::vector<Positive_Matrix_With_Prefactor> &matrices);
void write_output_files(
const boost::filesystem::path &outdir,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const std::vector<Positive_Matrix_With_Prefactor> &matrices);
int main(int argc, char **argv)
{
El::Environment env(argc, argv);
if(El::mpi::Size(El::mpi::COMM_WORLD) != 1)
{
if(El::mpi::Rank() == 0)
{
std::cerr
<< "sdp2blocks can only be run with a single MPI task, but "
"was invoked with "
<< El::mpi::Size(El::mpi::COMM_WORLD) << " tasks.\n"
<< std::flush;
}
El::Finalize();
exit(-1);
}
try
{
int precision;
boost::filesystem::path input_file, output_dir;
po::options_description options("Basic options");
options.add_options()("help,h", "Show this helpful message.");
options.add_options()(
"input,i", po::value<boost::filesystem::path>(&input_file)->required(),
"XML file with SDP definition");
options.add_options()(
"output,o",
po::value<boost::filesystem::path>(&output_dir)->required(),
"Directory to place output");
options.add_options()(
"precision", po::value<int>(&precision)->required(),
"The precision, in the number of bits, for numbers in the "
"computation. ");
po::positional_options_description positional;
positional.add("precision", 1);
positional.add("input", 1);
positional.add("output", 1);
po::variables_map variables_map;
po::store(po::parse_command_line(argc, argv, options), variables_map);
if(variables_map.count("help") != 0)
{
std::cout << options << '\n';
return 0;
}
po::notify(variables_map);
if(!boost::filesystem::exists(input_file))
{
throw std::runtime_error("Input file '" + input_file.string()
+ "' does not exist");
}
if(boost::filesystem::is_directory(input_file))
{
throw std::runtime_error("Input file '" + input_file.string()
+ "' is a directory, not a file");
}
if(boost::filesystem::exists(output_dir)
&& !boost::filesystem::is_directory(output_dir))
{
throw std::runtime_error("Output directory '" + output_dir.string()
+ "' exists and is not a directory");
}
El::gmp::SetPrecision(precision);
// FIXME: This should be in base 10, not base 2.
Boost_Float::default_precision(El::gmp::Precision());
std::vector<El::BigFloat> objectives, normalization;
std::vector<Positive_Matrix_With_Prefactor> matrices;
read_input(input_file, objectives, normalization, matrices);
write_output_files(output_dir, objectives, normalization, matrices);
}
catch(std::exception &e)
{
std::cerr << "Error: " << e.what() << "\n" << std::flush;
El::mpi::Abort(El::mpi::COMM_WORLD, 1);
}
catch(...)
{
std::cerr << "Unknown Error\n" << std::flush;
El::mpi::Abort(El::mpi::COMM_WORLD, 1);
}
}
|
#include "Boost_Float.hxx"
#include "Positive_Matrix_With_Prefactor.hxx"
#include "../Timers.hxx"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
void read_input(const boost::filesystem::path &input_file,
std::vector<El::BigFloat> &objectives,
std::vector<El::BigFloat> &normalization,
std::vector<Positive_Matrix_With_Prefactor> &matrices);
void write_output_files(
const boost::filesystem::path &outdir,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const std::vector<Positive_Matrix_With_Prefactor> &matrices);
int main(int argc, char **argv)
{
El::Environment env(argc, argv);
if(El::mpi::Size(El::mpi::COMM_WORLD) != 1)
{
if(El::mpi::Rank() == 0)
{
std::cerr
<< "sdp2blocks can only be run with a single MPI task, but "
"was invoked with "
<< El::mpi::Size(El::mpi::COMM_WORLD) << " tasks.\n"
<< std::flush;
}
El::Finalize();
exit(-1);
}
try
{
int precision;
boost::filesystem::path input_file, output_dir;
bool debug(false);
po::options_description options("Basic options");
options.add_options()("help,h", "Show this helpful message.");
options.add_options()(
"input,i", po::value<boost::filesystem::path>(&input_file)->required(),
"XML file with SDP definition");
options.add_options()(
"output,o",
po::value<boost::filesystem::path>(&output_dir)->required(),
"Directory to place output");
options.add_options()(
"precision", po::value<int>(&precision)->required(),
"The precision, in the number of bits, for numbers in the "
"computation. ");
options.add_options()(
"debug", po::value<bool>(&debug)->default_value(false),
"Write out debugging output.");
po::positional_options_description positional;
positional.add("precision", 1);
positional.add("input", 1);
positional.add("output", 1);
po::variables_map variables_map;
po::store(po::parse_command_line(argc, argv, options), variables_map);
if(variables_map.count("help") != 0)
{
std::cout << options << '\n';
return 0;
}
po::notify(variables_map);
if(!boost::filesystem::exists(input_file))
{
throw std::runtime_error("Input file '" + input_file.string()
+ "' does not exist");
}
if(boost::filesystem::is_directory(input_file))
{
throw std::runtime_error("Input file '" + input_file.string()
+ "' is a directory, not a file");
}
if(boost::filesystem::exists(output_dir)
&& !boost::filesystem::is_directory(output_dir))
{
throw std::runtime_error("Output directory '" + output_dir.string()
+ "' exists and is not a directory");
}
El::gmp::SetPrecision(precision);
// FIXME: This should be in base 10, not base 2.
Boost_Float::default_precision(El::gmp::Precision());
std::vector<El::BigFloat> objectives, normalization;
std::vector<Positive_Matrix_With_Prefactor> matrices;
Timers timers(debug);
auto &read_input_timer(timers.add_and_start("read_input"));
read_input(input_file, objectives, normalization, matrices);
read_input_timer.stop();
auto &write_output_timer(timers.add_and_start("write_output"));
write_output_files(output_dir, objectives, normalization, matrices);
write_output_timer.stop();
if(debug)
{
timers.write_profile(output_dir.string() + "/profile");
}
}
catch(std::exception &e)
{
std::cerr << "Error: " << e.what() << "\n" << std::flush;
El::mpi::Abort(El::mpi::COMM_WORLD, 1);
}
catch(...)
{
std::cerr << "Unknown Error\n" << std::flush;
El::mpi::Abort(El::mpi::COMM_WORLD, 1);
}
}
|
Add timers to sdp2blocks
|
Add timers to sdp2blocks
|
C++
|
mit
|
davidsd/sdpb,davidsd/sdpb,davidsd/sdpb
|
f5c4d0a08857e59912c7a12fc082bbf2e3aeaaf6
|
test/fs/TestFileFS.hpp
|
test/fs/TestFileFS.hpp
|
//
// Created by jan on 11/29/15.
//
#ifndef NIX_TESTFILEFS_HPP
#define NIX_TESTFILEFS_HPP
#include "BaseTestFile.hpp"
#include <boost/filesystem.hpp>
namespace bfs = boost::filesystem;
class TestFileFS: public BaseTestFile {
CPPUNIT_TEST_SUITE(TestFileFS);
CPPUNIT_TEST(testOpen);
CPPUNIT_TEST(testValidate);
CPPUNIT_TEST(testFormat);
CPPUNIT_TEST(testLocation);
CPPUNIT_TEST(testVersion);
CPPUNIT_TEST(testCreatedAt);
CPPUNIT_TEST(testUpdatedAt);
CPPUNIT_TEST(testBlockAccess);
CPPUNIT_TEST(testSectionAccess);
CPPUNIT_TEST(testOperators);
CPPUNIT_TEST(testReopen);
CPPUNIT_TEST(testCheckHeader);
CPPUNIT_TEST_SUITE_END ();
public:
void setUp() {
startup_time = time(NULL);
file_open = nix::File::open("test_file", nix::FileMode::Overwrite, "file");
file_other = nix::File::open("test_file_other", nix::FileMode::Overwrite, "file");
file_null = nix::none;
}
void tearDown() {
file_open.close();
file_other.close();
}
void testLocation() {
bfs::path p = boost::filesystem::current_path();
bfs::path p_file("test_file");
bfs::path p_other("test_file_other");
CPPUNIT_ASSERT(file_open.location() == (p / p_file).string());
CPPUNIT_ASSERT(file_other.location() == (p / p_other).string());
}
void testCheckHeader() {
nix::file::AttributesFS attr(file_open.location(), file_open.fileMode());
std::string frmt("xin");
attr.set("format", frmt);
CPPUNIT_ASSERT_THROW(nix::File::open("test_file", nix::FileMode::ReadWrite, "file"), std::runtime_error);
attr.set("format", "nix");
std::vector<int> version{2, 0, 0};
attr.set("version", version);
CPPUNIT_ASSERT_THROW(nix::File::open("test_file", nix::FileMode::ReadWrite, "file"), std::runtime_error);
}
};
#endif //NIX_TESTFILEFS_HPP
|
//
// Created by jan on 11/29/15.
//
#ifndef NIX_TESTFILEFS_HPP
#define NIX_TESTFILEFS_HPP
#include "BaseTestFile.hpp"
#include <boost/filesystem.hpp>
namespace bfs = boost::filesystem;
class TestFileFS: public BaseTestFile {
CPPUNIT_TEST_SUITE(TestFileFS);
CPPUNIT_TEST(testOpen);
CPPUNIT_TEST(testValidate);
CPPUNIT_TEST(testFormat);
CPPUNIT_TEST(testLocation);
CPPUNIT_TEST(testVersion);
CPPUNIT_TEST(testCreatedAt);
CPPUNIT_TEST(testUpdatedAt);
CPPUNIT_TEST(testBlockAccess);
CPPUNIT_TEST(testSectionAccess);
CPPUNIT_TEST(testOperators);
CPPUNIT_TEST(testReopen);
CPPUNIT_TEST(testCheckHeader);
CPPUNIT_TEST(testNonNix);
CPPUNIT_TEST_SUITE_END ();
public:
void setUp() {
startup_time = time(NULL);
file_open = nix::File::open("test_file", nix::FileMode::Overwrite, "file");
file_other = nix::File::open("test_file_other", nix::FileMode::Overwrite, "file");
file_null = nix::none;
}
void tearDown() {
file_open.close();
file_other.close();
}
void testLocation() {
bfs::path p = boost::filesystem::current_path();
bfs::path p_file("test_file");
bfs::path p_other("test_file_other");
CPPUNIT_ASSERT(file_open.location() == (p / p_file).string());
CPPUNIT_ASSERT(file_other.location() == (p / p_other).string());
}
void testCheckHeader() {
nix::file::AttributesFS attr(file_open.location(), file_open.fileMode());
std::string frmt("xin");
attr.set("format", frmt);
CPPUNIT_ASSERT_THROW(nix::File::open("test_file", nix::FileMode::ReadWrite, "file"), std::runtime_error);
attr.set("format", "nix");
std::vector<int> version{2, 0, 0};
attr.set("version", version);
CPPUNIT_ASSERT_THROW(nix::File::open("test_file", nix::FileMode::ReadWrite, "file"), std::runtime_error);
}
void testNonNix() {
bfs::path p("non-nix");
bfs::path pa("non-nix_with_wrong_attributes");
bfs::create_directory(p);
bfs::create_directory(pa);
std::ofstream ofs;
ofs.open("non-nix_with_wrong_attributes/attributes", std::ofstream::out | std::ofstream::app);
ofs.close();
CPPUNIT_ASSERT_THROW(nix::File::open(p.string(), nix::FileMode::ReadOnly, "file"), nix::InvalidFile);
CPPUNIT_ASSERT_THROW(nix::File::open(pa.string(), nix::FileMode::ReadOnly, "file"), nix::InvalidFile);
bfs::remove_all(p);
bfs::remove_all(pa);
}
};
#endif //NIX_TESTFILEFS_HPP
|
add test for checking of non-nix folders
|
add test for checking of non-nix folders
|
C++
|
bsd-3-clause
|
stoewer/nix
|
ab7d6a5a75a64736653d535cb04f90ffedc422c9
|
tensorflow/core/kernels/data_format_ops.cc
|
tensorflow/core/kernels/data_format_ops.cc
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/nn_ops.cc.
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/data_format_ops.h"
#include <map>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/errors.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
// Ensure that `src` and `dst` define a valid permutation.
// Ops defined in this file assume that user specifies a permutation via two
// string attributes. This check validates that these attributes properly define
// it to prevent security vulnerabilities.
static bool IsValidPermutation(const std::string& src, const std::string& dst) {
if (src.size() != dst.size()) {
return false;
}
std::map<char, bool> characters;
// Every character in `src` must be present only once
for (const auto c : src) {
if (characters[c]) {
return false;
}
characters[c] = true;
}
// Every character in `dst` must show up in `src` exactly once
for (const auto c : dst) {
if (!characters[c]) {
return false;
}
characters[c] = false;
}
// At this point, characters[] has been switched to true and false exactly
// once for all character in `src` (and `dst`) so we have a valid permutation
return true;
}
template <typename Device, typename T>
class DataFormatDimMapOp : public OpKernel {
public:
explicit DataFormatDimMapOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(
"Source format must be of length 4 or 5, received "
"src_format = ",
src_format));
OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument("Destination format must be of length "
"4 or 5, received dst_format = ",
dst_format));
OP_REQUIRES(
context, IsValidPermutation(src_format, dst_format),
errors::InvalidArgument(
"Destination and source format must determine a permutation, got ",
src_format, " and ", dst_format));
dst_idx_ = Tensor(DT_INT32, {static_cast<int64>(src_format.size())});
for (int i = 0; i < src_format.size(); ++i) {
for (int j = 0; j < dst_format.size(); ++j) {
if (dst_format[j] == src_format[i]) {
dst_idx_.vec<int>()(i) = j;
break;
}
}
}
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
Tensor* output;
OP_REQUIRES_OK(context,
context->allocate_output(0, input.shape(), &output));
functor::DataFormatDimMap<Device, T>()(context->eigen_device<Device>(),
input.flat<T>(), output->flat<T>(),
dst_idx_.vec<int>());
}
Tensor dst_idx_;
};
template <typename Device, typename T>
class DataFormatVecPermuteOp : public OpKernel {
public:
explicit DataFormatVecPermuteOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(
"Source format must be of length 4 or 5, received "
"src_format = ",
src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument("Destination format must be of length "
"4 or 5, received dst_format = ",
dst_format));
OP_REQUIRES(
context, IsValidPermutation(src_format, dst_format),
errors::InvalidArgument(
"Destination and source format must determine a permutation, got ",
src_format, " and ", dst_format));
src_format_ = src_format;
dst_format_ = dst_format;
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
OP_REQUIRES(context, input.dims() == 1 || input.dims() == 2,
errors::InvalidArgument(
"input must be a vector or 2D tensor, but got shape ",
input.shape().DebugString()));
const int full_dim_count = src_format_.size();
const int spatial_dim_count = full_dim_count - 2;
if (input.dims() == 1) {
OP_REQUIRES(context,
input.NumElements() == spatial_dim_count ||
input.NumElements() == full_dim_count,
errors::InvalidArgument("1D input must be of size ",
spatial_dim_count, " or ",
full_dim_count, ", but got shape ",
input.shape().DebugString()));
} else if (input.dims() == 2) {
OP_REQUIRES(context,
input.dim_size(0) == spatial_dim_count ||
input.dim_size(0) == full_dim_count,
errors::InvalidArgument("First dimension of 2D input must be "
"of size ",
spatial_dim_count, " or ",
full_dim_count, ", but got shape ",
input.shape().DebugString()));
OP_REQUIRES(
context, input.dim_size(1) == 2,
errors::InvalidArgument(
"Second dimension of 2D input must be of size 2, but got shape ",
input.shape().DebugString()));
}
Tensor* output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, input.shape(), &output));
// Support 1D and 2D cases.
Eigen::DSizes<Eigen::DenseIndex, 10> dst_idx;
string src_format_str = src_format_;
string dst_format_str = dst_format_;
if (input.dim_size(0) == spatial_dim_count) {
// If the input is a vector of size spatial_dim_count, treat the elements
// as spatial dimensions.
auto keep_only_spatial_dimensions =
[spatial_dim_count](string* format_str) -> void {
auto new_end =
std::remove_if(format_str->begin(), format_str->end(),
[spatial_dim_count](const char dim) {
return dim != 'H' && dim != 'W' &&
(spatial_dim_count == 2 || dim != 'D');
});
format_str->erase(new_end, format_str->end());
};
keep_only_spatial_dimensions(&src_format_str);
keep_only_spatial_dimensions(&dst_format_str);
if (spatial_dim_count == 3) {
OP_REQUIRES(
context, src_format_str.size() == 3 && dst_format_str.size() == 3,
errors::InvalidArgument(
"Format specifier must contain D, H and W for 2D case"));
} else {
DCHECK(spatial_dim_count == 2);
OP_REQUIRES(context,
src_format_str.size() == 2 && dst_format_str.size() == 2,
errors::InvalidArgument(
"Format specifier must contain H and W for 2D case"));
}
}
ComputeDstIndex(src_format_str, dst_format_str, input.dims(), &dst_idx);
functor::DataFormatVecPermute<Device, T>()(context->eigen_device<Device>(),
input.flat<T>(),
output->flat<T>(), dst_idx);
}
private:
// Finds out the destination index. Support 1D and 2D cases.
// Example: HWNC --> NHWC
// 1D: dst = [1, 2, 0, 3],
// 2D: dst = [2, 3, 4, 5, 0, 1, 6, 7]
static void ComputeDstIndex(const string& src_format_str,
const string& dst_format_str, int num_dim,
Eigen::DSizes<Eigen::DenseIndex, 10>* dst) {
for (int i = 0; i < src_format_str.size(); ++i) {
for (int j = 0; j < dst_format_str.size(); ++j) {
if (dst_format_str[j] != src_format_str[i]) continue;
// Found the dst index. Set output based on the number of dims.
for (int k = 0; k < num_dim; ++k) {
(*dst)[i * num_dim + k] = j * num_dim + k;
}
}
}
}
string src_format_;
string dst_format_;
};
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatDimMap").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
DataFormatDimMapOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatVecPermute").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER(Name("DataFormatDimMap") \
.Device(DEVICE_CPU) \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatDimMapOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER(Name("DataFormatVecPermute") \
.Device(DEVICE_CPU) \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void DataFormatDimMap<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::ConstFlat x, \
typename TTypes<T>::Flat y, const TTypes<int>::Vec dst); \
extern template struct DataFormatDimMap<GPUDevice, T>;
#define DECLARE_GPU_SPECS(T) DECLARE_GPU_SPEC(T);
TF_CALL_int32(DECLARE_GPU_SPECS);
TF_CALL_int64(DECLARE_GPU_SPECS);
#undef DECLARE_GPU_SPEC
#define DECLARE_GPU_SPEC(T) \
template <> \
void DataFormatVecPermute<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::ConstFlat x, \
typename TTypes<T>::Vec y, \
const Eigen::DSizes<Eigen::DenseIndex, 10>& dst_idx); \
extern template struct DataFormatVecPermute<GPUDevice, T>;
#define DECLARE_GPU_SPECS(T) DECLARE_GPU_SPEC(T);
TF_CALL_int32(DECLARE_GPU_SPECS);
TF_CALL_int64(DECLARE_GPU_SPECS);
#undef DECLARE_GPU_SPEC
} // namespace functor
// Registration of the GPU implementations.
#define REGISTER_GPU_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatDimMap").Device(DEVICE_GPU).TypeConstraint<T>("T"), \
DataFormatDimMapOp<GPUDevice, T>); \
REGISTER_KERNEL_BUILDER(Name("DataFormatDimMap") \
.Device(DEVICE_GPU) \
.HostMemory("x") \
.HostMemory("y") \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatDimMapOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_GPU_KERNEL);
TF_CALL_int64(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
#define REGISTER_GPU_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatVecPermute").Device(DEVICE_GPU).TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<GPUDevice, T>); \
REGISTER_KERNEL_BUILDER(Name("DataFormatVecPermute") \
.Device(DEVICE_GPU) \
.HostMemory("x") \
.HostMemory("y") \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_GPU_KERNEL);
TF_CALL_int64(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/nn_ops.cc.
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/data_format_ops.h"
#include <map>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/errors.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
// Ensure that `src` and `dst` define a valid permutation.
// Ops defined in this file assume that user specifies a permutation via two
// string attributes. This check validates that these attributes properly define
// it to prevent security vulnerabilities.
static bool IsValidPermutation(const std::string& src, const std::string& dst) {
if (src.size() != dst.size()) {
return false;
}
std::map<char, bool> characters;
// Every character in `src` must be present only once
for (const auto c : src) {
if (characters[c]) {
return false;
}
characters[c] = true;
}
// Every character in `dst` must show up in `src` exactly once
for (const auto c : dst) {
if (!characters[c]) {
return false;
}
characters[c] = false;
}
// At this point, characters[] has been switched to true and false exactly
// once for all character in `src` (and `dst`) so we have a valid permutation
return true;
}
template <typename Device, typename T>
class DataFormatDimMapOp : public OpKernel {
public:
explicit DataFormatDimMapOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(
"Source format must be of length 4 or 5, received "
"src_format = ",
src_format));
OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument("Destination format must be of length "
"4 or 5, received dst_format = ",
dst_format));
OP_REQUIRES(
context, IsValidPermutation(src_format, dst_format),
errors::InvalidArgument(
"Destination and source format must determine a permutation, got ",
src_format, " and ", dst_format));
dst_idx_ = Tensor(DT_INT32, {static_cast<int64>(src_format.size())});
for (int i = 0; i < src_format.size(); ++i) {
for (int j = 0; j < dst_format.size(); ++j) {
if (dst_format[j] == src_format[i]) {
dst_idx_.vec<int>()(i) = j;
break;
}
}
}
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
Tensor* output;
OP_REQUIRES_OK(context,
context->allocate_output(0, input.shape(), &output));
functor::DataFormatDimMap<Device, T>()(context->eigen_device<Device>(),
input.flat<T>(), output->flat<T>(),
dst_idx_.vec<int>());
}
Tensor dst_idx_;
};
template <typename Device, typename T>
class DataFormatVecPermuteOp : public OpKernel {
public:
explicit DataFormatVecPermuteOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(
"Source format must be of length 4 or 5, received "
"src_format = ",
src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument("Destination format must be of length "
"4 or 5, received dst_format = ",
dst_format));
OP_REQUIRES(
context, IsValidPermutation(src_format, dst_format),
errors::InvalidArgument(
"Destination and source format must determine a permutation, got ",
src_format, " and ", dst_format));
src_format_ = src_format;
dst_format_ = dst_format;
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
OP_REQUIRES(context, input.dims() == 1 || input.dims() == 2,
errors::InvalidArgument(
"input must be a vector or 2D tensor, but got shape ",
input.shape().DebugString()));
const int full_dim_count = src_format_.size();
const int spatial_dim_count = full_dim_count - 2;
if (input.dims() == 1) {
OP_REQUIRES(context,
input.NumElements() == spatial_dim_count ||
input.NumElements() == full_dim_count,
errors::InvalidArgument("1D input must be of size ",
spatial_dim_count, " or ",
full_dim_count, ", but got shape ",
input.shape().DebugString()));
} else if (input.dims() == 2) {
OP_REQUIRES(context,
input.dim_size(0) == spatial_dim_count ||
input.dim_size(0) == full_dim_count,
errors::InvalidArgument("First dimension of 2D input must be "
"of size ",
spatial_dim_count, " or ",
full_dim_count, ", but got shape ",
input.shape().DebugString()));
OP_REQUIRES(
context, input.dim_size(1) == 2,
errors::InvalidArgument(
"Second dimension of 2D input must be of size 2, but got shape ",
input.shape().DebugString()));
}
Tensor* output = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, input.shape(), &output));
// Support 1D and 2D cases.
Eigen::DSizes<Eigen::DenseIndex, 10> dst_idx;
string src_format_str = src_format_;
string dst_format_str = dst_format_;
if (input.dim_size(0) == spatial_dim_count) {
// If the input is a vector of size spatial_dim_count, treat the elements
// as spatial dimensions.
auto keep_only_spatial_dimensions =
[spatial_dim_count](string* format_str) -> void {
auto new_end =
std::remove_if(format_str->begin(), format_str->end(),
[spatial_dim_count](const char dim) {
return dim != 'H' && dim != 'W' &&
(spatial_dim_count == 2 || dim != 'D');
});
format_str->erase(new_end, format_str->end());
};
keep_only_spatial_dimensions(&src_format_str);
keep_only_spatial_dimensions(&dst_format_str);
if (spatial_dim_count == 3) {
OP_REQUIRES(
context, src_format_str.size() == 3 && dst_format_str.size() == 3,
errors::InvalidArgument(
"Format specifier must contain D, H and W for 2D case"));
} else {
DCHECK(spatial_dim_count == 2);
OP_REQUIRES(context,
src_format_str.size() == 2 && dst_format_str.size() == 2,
errors::InvalidArgument(
"Format specifier must contain H and W for 2D case"));
}
}
ComputeDstIndex(src_format_str, dst_format_str, input.dims(), &dst_idx);
functor::DataFormatVecPermute<Device, T>()(context->eigen_device<Device>(),
input.flat<T>(),
output->flat<T>(), dst_idx);
}
private:
// Finds out the destination index. Support 1D and 2D cases.
// Example: HWNC --> NHWC
// 1D: dst = [1, 2, 0, 3],
// 2D: dst = [2, 3, 4, 5, 0, 1, 6, 7]
static void ComputeDstIndex(const string& src_format_str,
const string& dst_format_str, int num_dim,
Eigen::DSizes<Eigen::DenseIndex, 10>* dst) {
for (int i = 0; i < src_format_str.size(); ++i) {
for (int j = 0; j < dst_format_str.size(); ++j) {
if (dst_format_str[j] != src_format_str[i]) continue;
// Found the dst index. Set output based on the number of dims.
for (int k = 0; k < num_dim; ++k) {
(*dst)[i * num_dim + k] = j * num_dim + k;
}
}
}
}
string src_format_;
string dst_format_;
};
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatDimMap").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
DataFormatDimMapOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatVecPermute").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER(Name("DataFormatDimMap") \
.Device(DEVICE_CPU) \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatDimMapOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(T) \
REGISTER_KERNEL_BUILDER(Name("DataFormatVecPermute") \
.Device(DEVICE_CPU) \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_KERNEL);
TF_CALL_int64(REGISTER_KERNEL);
#undef REGISTER_KERNEL
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void DataFormatDimMap<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::ConstFlat x, \
typename TTypes<T>::Flat y, const TTypes<int>::Vec dst); \
extern template struct DataFormatDimMap<GPUDevice, T>;
#define DECLARE_GPU_SPECS(T) DECLARE_GPU_SPEC(T);
TF_CALL_int32(DECLARE_GPU_SPECS);
TF_CALL_int64(DECLARE_GPU_SPECS);
#undef DECLARE_GPU_SPEC
#define DECLARE_GPU_SPEC(T) \
template <> \
void DataFormatVecPermute<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::ConstFlat x, \
typename TTypes<T>::Vec y, \
const Eigen::DSizes<Eigen::DenseIndex, 10>& dst_idx); \
extern template struct DataFormatVecPermute<GPUDevice, T>;
#define DECLARE_GPU_SPECS(T) DECLARE_GPU_SPEC(T);
TF_CALL_int32(DECLARE_GPU_SPECS);
TF_CALL_int64(DECLARE_GPU_SPECS);
#undef DECLARE_GPU_SPEC
} // namespace functor
// Registration of the GPU implementations.
#define REGISTER_GPU_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatDimMap").Device(DEVICE_GPU).TypeConstraint<T>("T"), \
DataFormatDimMapOp<GPUDevice, T>); \
REGISTER_KERNEL_BUILDER(Name("DataFormatDimMap") \
.Device(DEVICE_GPU) \
.HostMemory("x") \
.HostMemory("y") \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatDimMapOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_GPU_KERNEL);
TF_CALL_int64(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
#define REGISTER_GPU_KERNEL(T) \
REGISTER_KERNEL_BUILDER( \
Name("DataFormatVecPermute").Device(DEVICE_GPU).TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<GPUDevice, T>); \
REGISTER_KERNEL_BUILDER(Name("DataFormatVecPermute") \
.Device(DEVICE_GPU) \
.HostMemory("x") \
.HostMemory("y") \
.Label("host") \
.TypeConstraint<T>("T"), \
DataFormatVecPermuteOp<CPUDevice, T>);
TF_CALL_int32(REGISTER_GPU_KERNEL);
TF_CALL_int64(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
|
Revert change to the includes order
|
Revert change to the includes order
|
C++
|
apache-2.0
|
Intel-tensorflow/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,yongtang/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,Intel-Corporation/tensorflow
|
540266762787503b9fd166c1a5db6be00c2a0e1d
|
tools/gn/command_gen.cc
|
tools/gn/command_gen.cc
|
// Copyright (c) 2013 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/atomicops.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "base/timer/elapsed_timer.h"
#include "tools/gn/build_settings.h"
#include "tools/gn/commands.h"
#include "tools/gn/ninja_target_writer.h"
#include "tools/gn/ninja_writer.h"
#include "tools/gn/scheduler.h"
#include "tools/gn/setup.h"
#include "tools/gn/standard_out.h"
namespace commands {
namespace {
// Suppress output on success.
const char kSwitchQuiet[] = "q";
const char kSwitchCheck[] = "check";
void BackgroundDoWrite(const Target* target,
const Toolchain* toolchain,
const std::vector<const Item*>& deps_for_visibility) {
// Validate visibility.
Err err;
for (size_t i = 0; i < deps_for_visibility.size(); i++) {
if (!Visibility::CheckItemVisibility(target, deps_for_visibility[i],
&err)) {
g_scheduler->FailWithError(err);
break; // Don't return early since we need DecrementWorkCount below.
}
}
if (!err.has_error())
NinjaTargetWriter::RunAndWriteFile(target, toolchain);
g_scheduler->DecrementWorkCount();
}
// Called on the main thread.
void ItemResolvedCallback(base::subtle::Atomic32* write_counter,
scoped_refptr<Builder> builder,
const BuilderRecord* record) {
base::subtle::NoBarrier_AtomicIncrement(write_counter, 1);
const Item* item = record->item();
const Target* target = item->AsTarget();
if (target) {
const Toolchain* toolchain =
builder->GetToolchain(target->settings()->toolchain_label());
DCHECK(toolchain);
// Collect all dependencies.
std::vector<const Item*> deps;
for (BuilderRecord::BuilderRecordSet::const_iterator iter =
record->all_deps().begin();
iter != record->all_deps().end();
++iter)
deps.push_back((*iter)->item());
g_scheduler->IncrementWorkCount();
g_scheduler->ScheduleWork(
base::Bind(&BackgroundDoWrite, target, toolchain, deps));
}
}
} // namespace
const char kGen[] = "gen";
const char kGen_HelpShort[] =
"gen: Generate ninja files.";
const char kGen_Help[] =
"gn gen: Generate ninja files.\n"
"\n"
" gn gen <output_directory>\n"
"\n"
" Generates ninja files from the current tree and puts them in the given\n"
" output directory.\n"
"\n"
" The output directory can be a source-repo-absolute path name such as:\n"
" //out/foo\n"
" Or it can be a directory relative to the current directory such as:\n"
" out/foo\n"
"\n"
" See \"gn help\" for the common command-line switches.\n";
// Note: partially duplicated in command_gyp.cc.
int RunGen(const std::vector<std::string>& args) {
base::ElapsedTimer timer;
if (args.size() != 1) {
Err(Location(), "Need exactly one build directory to generate.",
"I expected something more like \"gn gen out/foo\"\n"
"You can also see \"gn help gen\".").PrintToStdout();
return 1;
}
// Deliberately leaked to avoid expensive process teardown.
Setup* setup = new Setup();
if (!setup->DoSetup(args[0]))
return 1;
if (CommandLine::ForCurrentProcess()->HasSwitch(kSwitchCheck))
setup->set_check_public_headers(true);
// Cause the load to also generate the ninja files for each target. We wrap
// the writing to maintain a counter.
base::subtle::Atomic32 write_counter = 0;
setup->builder()->set_resolved_callback(
base::Bind(&ItemResolvedCallback, &write_counter,
scoped_refptr<Builder>(setup->builder())));
// Do the actual load. This will also write out the target ninja files.
if (!setup->Run())
return 1;
// Write the root ninja files.
if (!NinjaWriter::RunAndWriteFiles(&setup->build_settings(),
setup->builder()))
return 1;
base::TimeDelta elapsed_time = timer.Elapsed();
if (!CommandLine::ForCurrentProcess()->HasSwitch(kSwitchQuiet)) {
OutputString("Done. ", DECORATION_GREEN);
std::string stats = "Wrote " +
base::IntToString(static_cast<int>(write_counter)) +
" targets from " +
base::IntToString(
setup->scheduler().input_file_manager()->GetInputFileCount()) +
" files in " +
base::IntToString(elapsed_time.InMilliseconds()) + "ms\n";
OutputString(stats);
}
return 0;
}
} // namespace commands
|
// Copyright (c) 2013 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/atomicops.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "base/timer/elapsed_timer.h"
#include "tools/gn/build_settings.h"
#include "tools/gn/commands.h"
#include "tools/gn/ninja_target_writer.h"
#include "tools/gn/ninja_writer.h"
#include "tools/gn/scheduler.h"
#include "tools/gn/setup.h"
#include "tools/gn/standard_out.h"
namespace commands {
namespace {
// Suppress output on success.
const char kSwitchQuiet[] = "q";
const char kSwitchCheck[] = "check";
void BackgroundDoWrite(const Target* target,
const Toolchain* toolchain,
const std::vector<const Item*>& deps_for_visibility) {
// Validate visibility.
Err err;
for (size_t i = 0; i < deps_for_visibility.size(); i++) {
if (!Visibility::CheckItemVisibility(target, deps_for_visibility[i],
&err)) {
g_scheduler->FailWithError(err);
break; // Don't return early since we need DecrementWorkCount below.
}
}
if (!err.has_error())
NinjaTargetWriter::RunAndWriteFile(target, toolchain);
g_scheduler->DecrementWorkCount();
}
// Called on the main thread.
void ItemResolvedCallback(base::subtle::Atomic32* write_counter,
scoped_refptr<Builder> builder,
const BuilderRecord* record) {
base::subtle::NoBarrier_AtomicIncrement(write_counter, 1);
const Item* item = record->item();
const Target* target = item->AsTarget();
if (target) {
const Toolchain* toolchain =
builder->GetToolchain(target->settings()->toolchain_label());
DCHECK(toolchain);
// Collect all dependencies.
std::vector<const Item*> deps;
for (BuilderRecord::BuilderRecordSet::const_iterator iter =
record->all_deps().begin();
iter != record->all_deps().end();
++iter)
deps.push_back((*iter)->item());
g_scheduler->IncrementWorkCount();
g_scheduler->ScheduleWork(
base::Bind(&BackgroundDoWrite, target, toolchain, deps));
}
}
} // namespace
const char kGen[] = "gen";
const char kGen_HelpShort[] =
"gen: Generate ninja files.";
const char kGen_Help[] =
"gn gen: Generate ninja files.\n"
"\n"
" gn gen <output_directory>\n"
"\n"
" Generates ninja files from the current tree and puts them in the given\n"
" output directory.\n"
"\n"
" The output directory can be a source-repo-absolute path name such as:\n"
" //out/foo\n"
" Or it can be a directory relative to the current directory such as:\n"
" out/foo\n"
"\n"
" See \"gn help\" for the common command-line switches.\n";
int RunGen(const std::vector<std::string>& args) {
base::ElapsedTimer timer;
if (args.size() != 1) {
Err(Location(), "Need exactly one build directory to generate.",
"I expected something more like \"gn gen out/foo\"\n"
"You can also see \"gn help gen\".").PrintToStdout();
return 1;
}
// Deliberately leaked to avoid expensive process teardown.
Setup* setup = new Setup();
if (!setup->DoSetup(args[0]))
return 1;
if (CommandLine::ForCurrentProcess()->HasSwitch(kSwitchCheck))
setup->set_check_public_headers(true);
// Cause the load to also generate the ninja files for each target. We wrap
// the writing to maintain a counter.
base::subtle::Atomic32 write_counter = 0;
setup->builder()->set_resolved_callback(
base::Bind(&ItemResolvedCallback, &write_counter,
scoped_refptr<Builder>(setup->builder())));
// Do the actual load. This will also write out the target ninja files.
if (!setup->Run())
return 1;
// Write the root ninja files.
if (!NinjaWriter::RunAndWriteFiles(&setup->build_settings(),
setup->builder()))
return 1;
base::TimeDelta elapsed_time = timer.Elapsed();
if (!CommandLine::ForCurrentProcess()->HasSwitch(kSwitchQuiet)) {
OutputString("Done. ", DECORATION_GREEN);
std::string stats = "Wrote " +
base::IntToString(static_cast<int>(write_counter)) +
" targets from " +
base::IntToString(
setup->scheduler().input_file_manager()->GetInputFileCount()) +
" files in " +
base::IntToString(elapsed_time.InMilliseconds()) + "ms\n";
OutputString(stats);
}
return 0;
}
} // namespace commands
|
Remove obsolete comment about gyp command.
|
gn: Remove obsolete comment about gyp command.
BUG=None
TEST=None
[email protected]
Review URL: https://codereview.chromium.org/296153002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@271968 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Just-D/chromium-1,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Just-D/chromium-1,M4sse/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,jaruba/chromium.src,ltilve/chromium,M4sse/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,jaruba/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,Chilledheart/chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Just-D/chromium-1,littlstar/chromium.src,Just-D/chromium-1,Just-D/chromium-1,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,Chilledheart/chromium,jaruba/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Jonekee/chromium.src,dednal/chromium.src
|
17259f777593b547329f181e3dd02078c00e96c9
|
tests/tickets/ticket4/main.cpp
|
tests/tickets/ticket4/main.cpp
|
#include <Step/SPFFunctions.h>
#include <Step/String.h>
#include <Step/SimpleTypes.h>
#include "../../tests.h"
#include <sstream>
/// tests for ticket4
/**
All references to atof are now using the program's locale.
So for french the decimal separator is a , (comma) not a
point leading to wrong string to real conversions.
*/
#define REAL_VALUE -0.000000000000009991
#define REAL_STRING "-0.000000000000009991"
int main (int /*n*/, char ** /*p*/)
{
std::string real_string(REAL_STRING);
Step::Real real_value =
Step::spfToReal(real_string);
TEST_ASSERT(real_value == REAL_VALUE)
std::cout << std::endl << "Failure : " << failure_results << " Success : " << success_results << std::endl;
return failure_results;
}
|
#include <Step/SPFFunctions.h>
#include <Step/String.h>
#include <Step/SimpleTypes.h>
#include "../../tests.h"
#include <sstream>
/// tests for ticket4
/**
All references to atof are now using the program's locale.
So for french the decimal separator is a , (comma) not a
point leading to wrong string to real conversions.
*/
#define REAL_VALUE -0.000000000000009991
#define REAL_STRING "-0.000000000000009991"
int main (int /*n*/, char ** /*p*/)
{
std::string real_string(REAL_STRING);
Step::Real real_value =
Step::spfToReal(real_string);
Step::Real diff = real_value - REAL_VALUE;
TEST_ASSERT( -0.000000000000000001 < diff);
TEST_ASSERT( diff < 0.000000000000000001 );
std::cout << std::endl << "Failure : " << failure_results << " Success : " << success_results << std::endl;
return failure_results;
}
|
make test compare precision instead of equality
|
make test compare precision instead of equality
|
C++
|
lgpl-2.1
|
cstb/ifc2x3-SDK,cstb/ifc2x3-SDK
|
7757bbc2f683d669c8beb52b1449ba2b76ad2e3d
|
tests/time-parameterization.cc
|
tests/time-parameterization.cc
|
// Copyright (c) 2017, Joseph Mirabel
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#define BOOST_TEST_MODULE time_parameterization
#include <boost/test/included/unit_test.hpp>
#include <hpp/core/time-parameterization/polynomial.hh>
#include <hpp/pinocchio/simple-device.hh>
using namespace hpp::core;
using namespace hpp::pinocchio;
DevicePtr_t createRobot ()
{
DevicePtr_t robot = unittest::makeDevice(unittest::ManipulatorArm2);
return robot;
}
BOOST_AUTO_TEST_SUITE (polynomial)
BOOST_AUTO_TEST_CASE (linear)
{
vector_t a (vector_t::Ones(2));
timeParameterization::Polynomial P (a);
BOOST_CHECK_EQUAL(P.value(-1), 0);
BOOST_CHECK_EQUAL(P.value( 0), 1);
BOOST_CHECK_EQUAL(P.value( 1), 2);
BOOST_CHECK_EQUAL(P.derivative(-1, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 1, 1), 1);
BOOST_CHECK_EQUAL(P.derivativeBound( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivativeBound(-1, 1), 1);
BOOST_CHECK_EQUAL(P.derivativeBound(-5, 5), 1);
}
BOOST_AUTO_TEST_CASE (cubic1)
{
vector_t a (vector_t::Ones(4));
timeParameterization::Polynomial P (a);
BOOST_CHECK_EQUAL(P.value(-1), 0);
BOOST_CHECK_EQUAL(P.value( 0), 1);
BOOST_CHECK_EQUAL(P.value( 1), 4);
BOOST_CHECK_EQUAL(P.derivative(-2, 1), 9);
BOOST_CHECK_EQUAL(P.derivative(-1, 1), 2);
BOOST_CHECK_EQUAL(P.derivative( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 1, 1), 6);
// x_m = - 1 / 3, P'(x_m) = 2/3
BOOST_CHECK_EQUAL(P.derivativeBound( 0, 1), 6);
BOOST_CHECK_EQUAL(P.derivativeBound(-1, 0), 2);
BOOST_CHECK_EQUAL(P.derivativeBound(-2,-1), 9);
}
BOOST_AUTO_TEST_CASE (cubic2)
{
vector_t a (vector_t::Ones(4));
a[3] = -1;
timeParameterization::Polynomial P (a);
BOOST_CHECK_EQUAL(P.value(-1), 2);
BOOST_CHECK_EQUAL(P.value( 0), 1);
BOOST_CHECK_EQUAL(P.value( 1), 2);
BOOST_CHECK_EQUAL(P.derivative(-1, 1),-4);
BOOST_CHECK_EQUAL(P.derivative( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 1, 1), 0);
// x_m = 1 / 3, P'(x_m) = 4 / 3
BOOST_CHECK_EQUAL(P.derivativeBound( 0, 1), 4./3);
BOOST_CHECK_EQUAL(P.derivativeBound(-1, 0), 4);
BOOST_CHECK_EQUAL(P.derivativeBound(1./3,1), 4./3);
}
BOOST_AUTO_TEST_SUITE_END ()
|
// Copyright (c) 2017, Joseph Mirabel
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#define BOOST_TEST_MODULE time_parameterization
#include <boost/test/included/unit_test.hpp>
#include <hpp/core/time-parameterization/polynomial.hh>
#include <hpp/pinocchio/simple-device.hh>
using namespace hpp::core;
using namespace hpp::pinocchio;
DevicePtr_t createRobot ()
{
DevicePtr_t robot = unittest::makeDevice(unittest::ManipulatorArm2);
return robot;
}
BOOST_AUTO_TEST_SUITE (polynomial)
BOOST_AUTO_TEST_CASE (linear)
{
vector_t a (vector_t::Ones(2));
timeParameterization::Polynomial P (a);
BOOST_CHECK_EQUAL(P.value(-1), 0);
BOOST_CHECK_EQUAL(P.value( 0), 1);
BOOST_CHECK_EQUAL(P.value( 1), 2);
BOOST_CHECK_EQUAL(P.derivative(-1, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 1, 1), 1);
BOOST_CHECK_EQUAL(P.derivativeBound( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivativeBound(-1, 1), 1);
BOOST_CHECK_EQUAL(P.derivativeBound(-5, 5), 1);
}
BOOST_AUTO_TEST_CASE (cubic1)
{
vector_t a (vector_t::Ones(4));
timeParameterization::Polynomial P (a);
BOOST_CHECK_EQUAL(P.value(-1), 0);
BOOST_CHECK_EQUAL(P.value( 0), 1);
BOOST_CHECK_EQUAL(P.value( 1), 4);
BOOST_CHECK_EQUAL(P.derivative(-2, 1), 9);
BOOST_CHECK_EQUAL(P.derivative(-1, 1), 2);
BOOST_CHECK_EQUAL(P.derivative( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 1, 1), 6);
// x_m = - 1 / 3, P'(x_m) = 2/3
BOOST_CHECK_EQUAL(P.derivativeBound( 0, 1), 6);
BOOST_CHECK_EQUAL(P.derivativeBound(-1, 0), 2);
BOOST_CHECK_EQUAL(P.derivativeBound(-2,-1), 9);
}
BOOST_AUTO_TEST_CASE (cubic2)
{
vector_t a (vector_t::Ones(4));
a[3] = -1;
timeParameterization::Polynomial P (a);
BOOST_CHECK_EQUAL(P.value(-1), 2);
BOOST_CHECK_EQUAL(P.value( 0), 1);
BOOST_CHECK_EQUAL(P.value( 1), 2);
BOOST_CHECK_EQUAL(P.derivative(-1, 1),-4);
BOOST_CHECK_EQUAL(P.derivative( 0, 1), 1);
BOOST_CHECK_EQUAL(P.derivative( 1, 1), 0);
// x_m = 1 / 3, P'(x_m) = 4 / 3
BOOST_CHECK_EQUAL(P.derivativeBound( 0, 1), 4./3);
BOOST_CHECK_EQUAL(P.derivativeBound(-1, 0), 4);
BOOST_CHECK_EQUAL(P.derivativeBound(1./3,1), 4./3);
}
value_type integrate (const timeParameterization::Polynomial& P,
const value_type& L)
{
int N = 10000;
value_type dt = L / N;
value_type integral = 0;
for (int i = 0; i < N; ++i)
{
integral += P.derivative (i*dt, 1) * dt;
}
return integral;
}
BOOST_AUTO_TEST_CASE (degree5integration)
{
value_type prec = 0.01; // %
vector_t a (6);
{
a << 0, 0, 0, 2.10515, -3.83792, 1.86585;
timeParameterization::Polynomial P (a);
value_type integral = integrate (P, 0.822769);
BOOST_CHECK_CLOSE (integral, 0.117251, prec);
}
{
a << 0, 0, 0, 1.13097, -1.10773, 0.289323;
timeParameterization::Polynomial P (a);
value_type integral = integrate (P, 1.53147);
BOOST_CHECK_CLOSE (integral, 0.406237, prec);
}
}
BOOST_AUTO_TEST_SUITE_END ()
|
Add unit test for time-parameterization
|
Add unit test for time-parameterization
|
C++
|
bsd-2-clause
|
humanoid-path-planner/hpp-core
|
ff4496a1c4f11f40a21c4875328399c186e4b406
|
src/allocator/allocator.cpp
|
src/allocator/allocator.cpp
|
#include "ros/ros.h"
#include "lagrange_allocator.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "allocator");
ROS_INFO("Launching node allocator.\n");
LagrangeAllocator allocator;
allocator.setWeights(Eigen::MatrixXd::Identity(6,6));
ros::spin();
return 0;
}
|
#include "ros/ros.h"
#include "lagrange_allocator.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "allocator");
ROS_INFO("Launching node allocator.");
LagrangeAllocator allocator;
allocator.setWeights(Eigen::MatrixXd::Identity(6,6));
ros::spin();
return 0;
}
|
Remove newline
|
Remove newline
|
C++
|
mit
|
vortexntnu/rov-control,vortexntnu/rov-control,vortexntnu/rov-control
|
098dcf28858f244bae53d63f9d58f1d00d100808
|
tests/unit_tests/mnemonics.cpp
|
tests/unit_tests/mnemonics.cpp
|
// Copyright (c) 2014-2016, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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 "gtest/gtest.h"
#include "mnemonics/electrum-words.h"
#include "crypto/crypto.h"
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include "mnemonics/english.h"
#include "mnemonics/spanish.h"
#include "mnemonics/portuguese.h"
#include "mnemonics/japanese.h"
#include "mnemonics/old_english.h"
#include "mnemonics/language_base.h"
#include "mnemonics/singleton.h"
namespace
{
/*!
* \brief Returns random index from 0 to max-1
* \param max Range maximum
* \return required random index
*/
uint32_t get_random_index(int max)
{
return rand() % max;
}
/*!
* \brief Compares vectors for equality
* \param expected expected vector
* \param present current vector
*/
void compare_vectors(const std::vector<std::string> &expected, const std::vector<std::string> &present)
{
std::vector<std::string>::const_iterator it1, it2;
for (it1 = expected.begin(), it2 = present.begin(); it1 != expected.end() && it2 != present.end();
it1++, it2++)
{
ASSERT_STREQ(it1->c_str(), it2->c_str());
}
}
/*!
* \brief Tests the given language mnemonics.
* \param language A Language instance to test
*/
void test_language(const Language::Base &language)
{
const std::vector<std::string> &word_list = language.get_word_list();
std::string seed = "", return_seed = "";
// Generate a random seed without checksum
for (int ii = 0; ii < crypto::ElectrumWords::seed_length; ii++)
{
seed += (word_list[get_random_index(word_list.size())] + ' ');
}
seed.pop_back();
std::cout << "Test seed without checksum:\n";
std::cout << seed << std::endl;
crypto::secret_key key;
std::string language_name;
bool res;
std::vector<std::string> seed_vector, return_seed_vector;
std::string checksum_word;
// Convert it to secret key
res = crypto::ElectrumWords::words_to_bytes(seed, key, language_name);
ASSERT_EQ(true, res);
std::cout << "Detected language: " << language_name << std::endl;
ASSERT_STREQ(language.get_language_name().c_str(), language_name.c_str());
// Convert the secret key back to seed
crypto::ElectrumWords::bytes_to_words(key, return_seed, language.get_language_name());
ASSERT_EQ(true, res);
std::cout << "Returned seed:\n";
std::cout << return_seed << std::endl;
boost::split(seed_vector, seed, boost::is_any_of(" "));
boost::split(return_seed_vector, return_seed, boost::is_any_of(" "));
// Extract the checksum word
checksum_word = return_seed_vector.back();
return_seed_vector.pop_back();
ASSERT_EQ(seed_vector.size(), return_seed_vector.size());
// Ensure that the rest of it is same
compare_vectors(seed_vector, return_seed_vector);
// Append the checksum word to repeat the entire process with a seed with checksum
seed += (" " + checksum_word);
std::cout << "Test seed with checksum:\n";
std::cout << seed << std::endl;
res = crypto::ElectrumWords::words_to_bytes(seed, key, language_name);
ASSERT_EQ(true, res);
std::cout << "Detected language: " << language_name << std::endl;
ASSERT_STREQ(language.get_language_name().c_str(), language_name.c_str());
return_seed = "";
crypto::ElectrumWords::bytes_to_words(key, return_seed, language.get_language_name());
ASSERT_EQ(true, res);
std::cout << "Returned seed:\n";
std::cout << return_seed << std::endl;
seed_vector.clear();
return_seed_vector.clear();
boost::split(seed_vector, seed, boost::is_any_of(" "));
boost::split(return_seed_vector, return_seed, boost::is_any_of(" "));
ASSERT_EQ(seed_vector.size(), return_seed_vector.size());
compare_vectors(seed_vector, return_seed_vector);
}
}
TEST(mnemonics, all_languages)
{
srand(time(NULL));
std::vector<Language::Base*> languages({
Language::Singleton<Language::English>::instance(),
Language::Singleton<Language::Spanish>::instance(),
Language::Singleton<Language::Portuguese>::instance(),
Language::Singleton<Language::Japanese>::instance(),
});
for (std::vector<Language::Base*>::iterator it = languages.begin(); it != languages.end(); it++)
{
test_language(*(*it));
}
}
|
// Copyright (c) 2014-2016, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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 "gtest/gtest.h"
#include "mnemonics/electrum-words.h"
#include "crypto/crypto.h"
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include "mnemonics/english.h"
#include "mnemonics/spanish.h"
#include "mnemonics/portuguese.h"
#include "mnemonics/japanese.h"
#include "mnemonics/old_english.h"
#include "mnemonics/language_base.h"
#include "mnemonics/singleton.h"
namespace
{
/*!
* \brief Compares vectors for equality
* \param expected expected vector
* \param present current vector
*/
void compare_vectors(const std::vector<std::string> &expected, const std::vector<std::string> &present)
{
std::vector<std::string>::const_iterator it1, it2;
for (it1 = expected.begin(), it2 = present.begin(); it1 != expected.end() && it2 != present.end();
it1++, it2++)
{
ASSERT_STREQ(it1->c_str(), it2->c_str());
}
}
/*!
* \brief Tests the given language mnemonics.
* \param language A Language instance to test
*/
void test_language(const Language::Base &language)
{
const std::vector<std::string> &word_list = language.get_word_list();
std::string seed = "", return_seed = "";
// Generate a random seed without checksum
crypto::secret_key randkey;
for (size_t ii = 0; ii < sizeof(randkey); ++ii)
{
randkey.data[ii] = rand();
}
crypto::ElectrumWords::bytes_to_words(randkey, seed, language.get_language_name());
// remove the checksum word
const char *space = strrchr(seed.c_str(), ' ');
ASSERT_TRUE(space != NULL);
seed = std::string(seed.c_str(), space-seed.c_str());
std::cout << "Test seed without checksum:\n";
std::cout << seed << std::endl;
crypto::secret_key key;
std::string language_name;
bool res;
std::vector<std::string> seed_vector, return_seed_vector;
std::string checksum_word;
// Convert it to secret key
res = crypto::ElectrumWords::words_to_bytes(seed, key, language_name);
ASSERT_EQ(true, res);
std::cout << "Detected language: " << language_name << std::endl;
ASSERT_STREQ(language.get_language_name().c_str(), language_name.c_str());
// Convert the secret key back to seed
crypto::ElectrumWords::bytes_to_words(key, return_seed, language.get_language_name());
ASSERT_EQ(true, res);
std::cout << "Returned seed:\n";
std::cout << return_seed << std::endl;
boost::split(seed_vector, seed, boost::is_any_of(" "));
boost::split(return_seed_vector, return_seed, boost::is_any_of(" "));
// Extract the checksum word
checksum_word = return_seed_vector.back();
return_seed_vector.pop_back();
ASSERT_EQ(seed_vector.size(), return_seed_vector.size());
// Ensure that the rest of it is same
compare_vectors(seed_vector, return_seed_vector);
// Append the checksum word to repeat the entire process with a seed with checksum
seed += (" " + checksum_word);
std::cout << "Test seed with checksum:\n";
std::cout << seed << std::endl;
res = crypto::ElectrumWords::words_to_bytes(seed, key, language_name);
ASSERT_EQ(true, res);
std::cout << "Detected language: " << language_name << std::endl;
ASSERT_STREQ(language.get_language_name().c_str(), language_name.c_str());
return_seed = "";
crypto::ElectrumWords::bytes_to_words(key, return_seed, language.get_language_name());
ASSERT_EQ(true, res);
std::cout << "Returned seed:\n";
std::cout << return_seed << std::endl;
seed_vector.clear();
return_seed_vector.clear();
boost::split(seed_vector, seed, boost::is_any_of(" "));
boost::split(return_seed_vector, return_seed, boost::is_any_of(" "));
ASSERT_EQ(seed_vector.size(), return_seed_vector.size());
compare_vectors(seed_vector, return_seed_vector);
}
}
TEST(mnemonics, all_languages)
{
srand(time(NULL));
std::vector<Language::Base*> languages({
Language::Singleton<Language::English>::instance(),
Language::Singleton<Language::Spanish>::instance(),
Language::Singleton<Language::Portuguese>::instance(),
Language::Singleton<Language::Japanese>::instance(),
});
for (std::vector<Language::Base*>::iterator it = languages.begin(); it != languages.end(); it++)
{
test_language(*(*it));
}
}
|
fix mnemonics unit test testing invalid seeds
|
unit_tests: fix mnemonics unit test testing invalid seeds
Some word triplets, such as "mugged names nail", are not valid
results from any 32 bit value. If used to decode a 32 bit value,
the result will therefore encode to a different word triplet.
Fix this by using random words converted from an actual random
bitstring, ensuring we always get valid triplets.
|
C++
|
bsd-3-clause
|
eiabea/bitmonero,eiabea/bitmonero,ranok/bitmonero,ranok/bitmonero,eiabea/bitmonero,eiabea/bitmonero,eiabea/bitmonero,ranok/bitmonero,eiabea/bitmonero,ranok/bitmonero,ranok/bitmonero,ranok/bitmonero
|
887c80ec10c0f64df9769ac09201889125cde18d
|
test/libcxx/modules/clocale_exports.sh.cpp
|
test/libcxx/modules/clocale_exports.sh.cpp
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// REQUIRES: modules-support
// RUN: %build_module
#include <clocale>
#define TEST(...) do { using T = decltype( __VA_ARGS__ ); } while(false)
int main() {
std::lconv l; ((void)l);
TEST(std::setlocale(0, ""));
TEST(std::localeconv());
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// REQUIRES: modules-support
// UNSUPPORTED: c++98, c++03
// RUN: %build_module
#include <clocale>
#define TEST(...) do { using T = decltype( __VA_ARGS__ ); } while(false)
int main() {
std::lconv l; ((void)l);
TEST(std::setlocale(0, ""));
TEST(std::localeconv());
}
|
Mark test as unsupported in C++03
|
Mark test as unsupported in C++03
git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@287417 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
|
dcc85e38eab286f5167dbea44fde59bc89ea74c1
|
src/athena/MemoryReader.cpp
|
src/athena/MemoryReader.cpp
|
#include "athena/MemoryReader.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
#ifdef HW_RVL
#include <malloc.h>
#endif // HW_RVL
namespace athena::io {
MemoryReader::MemoryReader(const void* data, atUint64 length, bool takeOwnership, bool globalErr)
: m_data(data), m_length(length), m_position(0), m_owns(takeOwnership), m_globalErr(globalErr) {
if (!data) {
if (m_globalErr)
atError(fmt("data cannot be NULL"));
setError();
return;
}
}
MemoryReader::~MemoryReader() {
if (m_owns)
delete[] reinterpret_cast<const atUint8*>(m_data);
}
MemoryCopyReader::MemoryCopyReader(const void* data, atUint64 length) : MemoryReader(data, length, false) {
if (!data) {
if (m_globalErr)
atError(fmt("data cannot be NULL"));
setError();
return;
}
m_dataCopy.reset(new atUint8[m_length]);
m_data = m_dataCopy.get();
memmove(m_dataCopy.get(), data, m_length);
}
void MemoryReader::seek(atInt64 position, SeekOrigin origin) {
switch (origin) {
case SeekOrigin::Begin:
if ((position < 0 || atInt64(position) > atInt64(m_length))) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), position);
m_position = m_length;
setError();
return;
}
m_position = atUint64(position);
break;
case SeekOrigin::Current:
if (((atInt64(m_position) + position) < 0 || (m_position + atUint64(position)) > m_length)) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), position);
m_position = (position < 0 ? 0 ? m_length;
setError();
return;
}
m_position += position;
break;
case SeekOrigin::End:
if ((((atInt64)m_length - position < 0) || (m_length - position) > m_length)) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), position);
m_position = m_length;
setError();
return;
}
m_position = m_length - position;
break;
}
}
void MemoryReader::setData(const atUint8* data, atUint64 length, bool takeOwnership) {
if (m_owns)
delete[] static_cast<const atUint8*>(m_data);
m_data = (atUint8*)data;
m_length = length;
m_position = 0;
m_owns = takeOwnership;
}
void MemoryCopyReader::setData(const atUint8* data, atUint64 length) {
m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get();
memmove(m_dataCopy.get(), data, length);
m_length = length;
m_position = 0;
}
atUint8* MemoryReader::data() const {
atUint8* ret = new atUint8[m_length];
memset(ret, 0, m_length);
memmove(ret, m_data, m_length);
return ret;
}
atUint64 MemoryReader::readUBytesToBuf(void* buf, atUint64 length) {
if (m_position >= m_length) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), m_position);
m_position = m_length;
setError();
return 0;
}
length = std::min(length, m_length - m_position);
memmove(buf, reinterpret_cast<const atUint8*>(m_data) + m_position, length);
m_position += length;
return length;
}
void MemoryCopyReader::loadData() {
FILE* in;
atUint64 length;
in = fopen(m_filepath.c_str(), "rb");
if (!in) {
if (m_globalErr)
atError(fmt("Unable to open file '%s'"), m_filepath);
setError();
return;
}
rewind(in);
length = utility::fileSize(m_filepath);
m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get();
atUint64 done = 0;
atUint64 blocksize = BLOCKSZ;
do {
if (blocksize > length - done)
blocksize = length - done;
atInt64 ret = fread(m_dataCopy.get() + done, 1, blocksize, in);
if (ret < 0) {
if (m_globalErr)
atError(fmt("Error reading data from disk"));
setError();
return;
} else if (ret == 0)
break;
done += ret;
} while (done < length);
fclose(in);
m_length = length;
m_position = 0;
}
} // namespace athena::io
|
#include "athena/MemoryReader.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
#ifdef HW_RVL
#include <malloc.h>
#endif // HW_RVL
namespace athena::io {
MemoryReader::MemoryReader(const void* data, atUint64 length, bool takeOwnership, bool globalErr)
: m_data(data), m_length(length), m_position(0), m_owns(takeOwnership), m_globalErr(globalErr) {
if (!data) {
if (m_globalErr)
atError(fmt("data cannot be NULL"));
setError();
return;
}
}
MemoryReader::~MemoryReader() {
if (m_owns)
delete[] reinterpret_cast<const atUint8*>(m_data);
}
MemoryCopyReader::MemoryCopyReader(const void* data, atUint64 length) : MemoryReader(data, length, false) {
if (!data) {
if (m_globalErr)
atError(fmt("data cannot be NULL"));
setError();
return;
}
m_dataCopy.reset(new atUint8[m_length]);
m_data = m_dataCopy.get();
memmove(m_dataCopy.get(), data, m_length);
}
void MemoryReader::seek(atInt64 position, SeekOrigin origin) {
switch (origin) {
case SeekOrigin::Begin:
if ((position < 0 || atInt64(position) > atInt64(m_length))) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), position);
m_position = m_length;
setError();
return;
}
m_position = atUint64(position);
break;
case SeekOrigin::Current:
if (((atInt64(m_position) + position) < 0 || (m_position + atUint64(position)) > m_length)) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), position);
m_position = (position < 0 ? 0 : m_length);
setError();
return;
}
m_position += position;
break;
case SeekOrigin::End:
if ((((atInt64)m_length - position < 0) || (m_length - position) > m_length)) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), position);
m_position = m_length;
setError();
return;
}
m_position = m_length - position;
break;
}
}
void MemoryReader::setData(const atUint8* data, atUint64 length, bool takeOwnership) {
if (m_owns)
delete[] static_cast<const atUint8*>(m_data);
m_data = (atUint8*)data;
m_length = length;
m_position = 0;
m_owns = takeOwnership;
}
void MemoryCopyReader::setData(const atUint8* data, atUint64 length) {
m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get();
memmove(m_dataCopy.get(), data, length);
m_length = length;
m_position = 0;
}
atUint8* MemoryReader::data() const {
atUint8* ret = new atUint8[m_length];
memset(ret, 0, m_length);
memmove(ret, m_data, m_length);
return ret;
}
atUint64 MemoryReader::readUBytesToBuf(void* buf, atUint64 length) {
if (m_position >= m_length) {
if (m_globalErr)
atFatal(fmt("Position {:08X} outside stream bounds "), m_position);
m_position = m_length;
setError();
return 0;
}
length = std::min(length, m_length - m_position);
memmove(buf, reinterpret_cast<const atUint8*>(m_data) + m_position, length);
m_position += length;
return length;
}
void MemoryCopyReader::loadData() {
FILE* in;
atUint64 length;
in = fopen(m_filepath.c_str(), "rb");
if (!in) {
if (m_globalErr)
atError(fmt("Unable to open file '%s'"), m_filepath);
setError();
return;
}
rewind(in);
length = utility::fileSize(m_filepath);
m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get();
atUint64 done = 0;
atUint64 blocksize = BLOCKSZ;
do {
if (blocksize > length - done)
blocksize = length - done;
atInt64 ret = fread(m_dataCopy.get() + done, 1, blocksize, in);
if (ret < 0) {
if (m_globalErr)
atError(fmt("Error reading data from disk"));
setError();
return;
} else if (ret == 0)
break;
done += ret;
} while (done < length);
fclose(in);
m_length = length;
m_position = 0;
}
} // namespace athena::io
|
Fix build error in MemoryReader.cpp
|
Fix build error in MemoryReader.cpp
|
C++
|
mit
|
libAthena/Athena,libAthena/Athena
|
72a53cd945756a6d193426eee8c56208cd166a9b
|
utils.cpp
|
utils.cpp
|
#include "mpdas.h"
#define RED "\x1b[31;01m"
#define RESET "\x1b[0m"
#define GREEN "\x1b[32;01m"
#define YELLOW "\x1b[33;01m"
std::string
md5sum(const char* fmt, ...)
{
va_list ap;
char* abuf;
md5_state_t state;
unsigned char md5buf[16];
va_start(ap, fmt);
vasprintf(&abuf, fmt, ap);
va_end(ap);
std::string buf(abuf);
free(abuf);
md5_init(&state);
md5_append(&state, (const md5_byte_t*)buf.c_str(), buf.length());
md5_finish(&state, md5buf);
std::ostringstream ret;
for(unsigned int i = 0; i < 16; i++)
ret << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)md5buf[i];
return ret.str();
}
std::string
timestr()
{
std::stringstream buf;
time_t rawtime = time(NULL);
struct tm* t = localtime(&rawtime);
if(t->tm_hour < 10)
buf << 0;
buf << t->tm_hour << ":";
if(t->tm_min < 10)
buf << "0";
buf << t->tm_min << ":";
if(t->tm_sec < 10)
buf << "0";
buf << t->tm_sec;
return buf.str();
}
void
eprintf(const char* fmt, ...)
{
char* abuf;
va_list ap;
va_start(ap, fmt);
vasprintf(&abuf, fmt, ap);
va_end(ap);
std::string buf(abuf);
free(abuf);
std::cerr << "(" << timestr() << ") [" << RED << "ERROR" << RESET << "] " << buf << std::endl;
}
void
iprintf(const char* fmt, ...)
{
time_t rawtime = time(NULL);
struct tm* t = localtime(&rawtime);
char* abuf;
va_list ap;
va_start(ap, fmt);
vasprintf(&abuf, fmt, ap);
va_end(ap);
std::string buf(abuf);
free(abuf);
std::cerr << "(" << timestr() << ") [" << YELLOW << "INFO" << RESET << "] " << buf << std::endl;
}
|
#include "mpdas.h"
#define RED "\x1b[31;01m"
#define RESET "\x1b[0m"
#define GREEN "\x1b[32;01m"
#define YELLOW "\x1b[33;01m"
bool
fileexists(const char* file)
{
if (access(file, F_OK) == 0)
return true;
else
return false;
}
std::string
md5sum(const char* fmt, ...)
{
va_list ap;
char* abuf;
md5_state_t state;
unsigned char md5buf[16];
va_start(ap, fmt);
vasprintf(&abuf, fmt, ap);
va_end(ap);
std::string buf(abuf);
free(abuf);
md5_init(&state);
md5_append(&state, (const md5_byte_t*)buf.c_str(), buf.length());
md5_finish(&state, md5buf);
std::ostringstream ret;
for(unsigned int i = 0; i < 16; i++)
ret << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)md5buf[i];
return ret.str();
}
std::string
timestr()
{
std::stringstream buf;
time_t rawtime = time(NULL);
struct tm* t = localtime(&rawtime);
if(t->tm_hour < 10)
buf << 0;
buf << t->tm_hour << ":";
if(t->tm_min < 10)
buf << "0";
buf << t->tm_min << ":";
if(t->tm_sec < 10)
buf << "0";
buf << t->tm_sec;
return buf.str();
}
void
eprintf(const char* fmt, ...)
{
char* abuf;
va_list ap;
va_start(ap, fmt);
vasprintf(&abuf, fmt, ap);
va_end(ap);
std::string buf(abuf);
free(abuf);
std::cerr << "(" << timestr() << ") [" << RED << "ERROR" << RESET << "] " << buf << std::endl;
}
void
iprintf(const char* fmt, ...)
{
time_t rawtime = time(NULL);
struct tm* t = localtime(&rawtime);
char* abuf;
va_list ap;
va_start(ap, fmt);
vasprintf(&abuf, fmt, ap);
va_end(ap);
std::string buf(abuf);
free(abuf);
std::cerr << "(" << timestr() << ") [" << YELLOW << "INFO" << RESET << "] " << buf << std::endl;
}
|
add fileexists() util function
|
add fileexists() util function
|
C++
|
bsd-3-clause
|
chrisf1337/mpdas,chrisf1337/mpdas,riggs-/mpdas,riggs-/mpdas
|
3271ee423bcc428b523603216ee1b155d004789d
|
tokenize_command_line_gtest.cc
|
tokenize_command_line_gtest.cc
|
/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*-
* vi: set shiftwidth=4 tabstop=8:
* :indentSize=4:tabSize=8:
*/
#include "gtest/gtest.h"
#include "tokenize_command_line.h"
#if defined(_WIN32)
void setenv(const char *key, const char* val, int);
#endif
TEST(tokenize_command_line, handles_empty_string)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("", argc, argv));
ASSERT_EQ(0, argc);
ASSERT_TRUE(argv != nullptr);
ASSERT_TRUE(*argv == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_one_parameter)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("a", argc, argv));
ASSERT_EQ(1, argc);
ASSERT_TRUE(argv != nullptr);
ASSERT_STREQ("a", argv[0]);
ASSERT_TRUE(argv[1] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_two_parameters)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("a b", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_tab_as_whitespace)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("a\tb", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_single_quotes)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("'a' 'b c d'", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b c d", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_double_quotes)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("\"a\" \"b c d\"", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b c d", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, variable_substitution1)
{
setenv("SECOND", "second", 1);
#if defined(_WIN32)
const char *command_line = "first %SECOND% third";
#else
const char *command_line = "first $SECOND third";
#endif
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line(command_line, argc, argv));
ASSERT_EQ(3, argc);
ASSERT_STREQ("first", argv[0]);
ASSERT_STREQ("second", argv[1]);
ASSERT_STREQ("third", argv[2]);
ASSERT_TRUE(argv[3] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, variable_substitution2)
{
setenv("SECOND", "2", 1);
#if defined(_WIN32)
const char *command_line = "eins%SECOND%drei";
#else
const char *command_line = "eins${SECOND}drei";
#endif
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line(command_line, argc, argv));
ASSERT_EQ(1, argc);
ASSERT_STREQ("eins2drei", argv[0]);
ASSERT_TRUE(argv[1] == nullptr);
tokenize_command_line_free(argv);
}
|
/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*-
* vi: set shiftwidth=4 tabstop=8:
* :indentSize=4:tabSize=8:
*/
#include "gtest/gtest.h"
#include "tokenize_command_line.h"
#if defined(_WIN32)
void setenv(const char *key, const char* val, int);
#endif
TEST(tokenize_command_line, handles_empty_string)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("", argc, argv));
ASSERT_EQ(0, argc);
ASSERT_TRUE(argv != nullptr);
ASSERT_TRUE(*argv == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_one_parameter)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("a", argc, argv));
ASSERT_EQ(1, argc);
ASSERT_TRUE(argv != nullptr);
ASSERT_STREQ("a", argv[0]);
ASSERT_TRUE(argv[1] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_two_parameters)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("a b", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_tab_as_whitespace)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("a\tb", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_single_quotes)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("'a' 'b c d'", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b c d", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, handles_double_quotes)
{
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line("\"a\" \"b c d\"", argc, argv));
ASSERT_EQ(2, argc);
ASSERT_STREQ("a", argv[0]);
ASSERT_STREQ("b c d", argv[1]);
ASSERT_TRUE(argv[2] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, variable_substitution1)
{
setenv("SECOND", "second", 1);
#if defined(_WIN32)
const char *command_line = "first %SECOND% third";
#else
const char *command_line = "first $SECOND third";
#endif
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line(command_line, argc, argv));
ASSERT_EQ(3, argc);
ASSERT_STREQ("first", argv[0]);
ASSERT_STREQ("second", argv[1]);
ASSERT_STREQ("third", argv[2]);
ASSERT_TRUE(argv[3] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, variable_substitution2)
{
setenv("SECOND", "2", 1);
#if defined(_WIN32)
const char *command_line = "eins%SECOND%drei";
#else
const char *command_line = "eins${SECOND}drei";
#endif
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line(command_line, argc, argv));
ASSERT_EQ(1, argc);
ASSERT_STREQ("eins2drei", argv[0]);
ASSERT_TRUE(argv[1] == nullptr);
tokenize_command_line_free(argv);
}
TEST(tokenize_command_line, recursive_variable_substitution)
{
setenv("d1", "d1", 1);
#if defined(_WIN32)
setenv("d2", "%d1%", 1);
const char *command_line = "%d2%";
#else
setenv("d2", "$d1", 1);
const char *command_line = "$d2";
#endif
int argc;
char **argv;
ASSERT_TRUE(tokenize_command_line(command_line, argc, argv));
ASSERT_EQ(1, argc);
#if defined(_WIN32)
ASSERT_STREQ("%d1%", argv[0]);
#else
ASSERT_STREQ("$d1", argv[0]);
#endif
ASSERT_TRUE(argv[1] == nullptr);
tokenize_command_line_free(argv);
}
|
add recursive variable test
|
add recursive variable test
|
C++
|
mit
|
doj/few,doj/few
|
6baa3884086d0024ddd304464709f70746b29361
|
test/src/CSVParser.cpp
|
test/src/CSVParser.cpp
|
#include "CSVParser.hpp"
#include <bandit/bandit.h>
using namespace bandit;
go_bandit([]() {
describe("CSVParser Test", []() {
CSVParser<1> csv(R"(column1 ,column2\ncell1,cell2\n)");
it("should trim white spaces from column and header", [&]() {
AssertThat(3, Equals(3));
});
});
});
|
#include "CSVParser.hpp"
#include <bandit/bandit.h>
using namespace bandit;
go_bandit([]() {
describe("CSVParser Test", []() {
it("should trim tab character from header column", [&]() {
CSVParser<2> csv("column1\t,column2\t\n");
csv.readHeader("column1", "column2");
});
it("should trim tab character from row cell", [&]() {
CSVParser<2> csv("column1,column2\ncell1\t,cell2\t\n");
csv.readHeader("column1", "column2");
std::string cell1, cell2;
csv.readRow(cell1, cell2);
AssertThat(cell1, Equals("cell1"));
AssertThat(cell2, Equals("cell2"));
});
});
});
|
Add CSVParser tests.
|
Add CSVParser tests.
|
C++
|
mit
|
cristian-szabo/bt-code-test
|
23d31c4fea61962e156f992889c6b041ad757d12
|
tools/mac/run_with_crashpad.cc
|
tools/mac/run_with_crashpad.cc
|
// Copyright 2014 The Crashpad 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 <errno.h>
#include <getopt.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <map>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/logging.h"
#include "client/crashpad_client.h"
#include "tools/tool_support.h"
#include "util/stdlib/map_insert.h"
#include "util/string/split_string.h"
namespace crashpad {
namespace {
void Usage(const std::string& me) {
fprintf(stderr,
"Usage: %s [OPTION]... COMMAND [ARG]...\n"
"Start a Crashpad handler and have it handle crashes from COMMAND.\n"
"\n"
" -h, --handler=HANDLER invoke HANDLER instead of crashpad_handler\n"
" --annotation=KEY=VALUE passed to the handler as an --annotation argument\n"
" --database=PATH passed to the handler as its --database argument\n"
" --url=URL passed to the handler as its --url argument\n"
" -a, --argument=ARGUMENT invoke the handler with ARGUMENT\n"
" --help display this help and exit\n"
" --version output version information and exit\n",
me.c_str());
ToolSupport::UsageTail(me);
}
int RunWithCrashpadMain(int argc, char* argv[]) {
const std::string me(basename(argv[0]));
enum ExitCode {
kExitSuccess = EXIT_SUCCESS,
// To differentiate this tool’s errors from errors in the programs it execs,
// use a high exit code for ordinary failures instead of EXIT_FAILURE. This
// is the same rationale for using the distinct exit codes for exec
// failures.
kExitFailure = 125,
// Like env, use exit code 126 if the program was found but could not be
// invoked, and 127 if it could not be found.
// http://pubs.opengroup.org/onlinepubs/9699919799/utilities/env.html
kExitExecFailure = 126,
kExitExecENOENT = 127,
};
enum OptionFlags {
// “Short” (single-character) options.
kOptionHandler = 'h',
kOptionArgument = 'a',
// Long options without short equivalents.
kOptionLastChar = 255,
kOptionAnnotation,
kOptionDatabase,
kOptionURL,
// Standard options.
kOptionHelp = -2,
kOptionVersion = -3,
};
const option long_options[] = {
{"handler", required_argument, nullptr, kOptionHandler},
{"annotation", required_argument, nullptr, kOptionAnnotation},
{"database", required_argument, nullptr, kOptionDatabase},
{"url", required_argument, nullptr, kOptionURL},
{"argument", required_argument, nullptr, kOptionArgument},
{"help", no_argument, nullptr, kOptionHelp},
{"version", no_argument, nullptr, kOptionVersion},
{nullptr, 0, nullptr, 0},
};
struct {
std::string handler;
std::map<std::string, std::string> annotations;
std::string database;
std::string url;
std::vector<std::string> arguments;
} options = {};
options.handler = "crashpad_handler";
int opt;
while ((opt = getopt_long(argc, argv, "+a:h:", long_options, nullptr)) !=
-1) {
switch (opt) {
case kOptionHandler: {
options.handler = optarg;
break;
}
case kOptionAnnotation: {
std::string key;
std::string value;
if (!SplitString(optarg, '=', &key, &value)) {
ToolSupport::UsageHint(me, "--annotation requires KEY=VALUE");
return EXIT_FAILURE;
}
std::string old_value;
if (!MapInsertOrReplace(&options.annotations, key, value, &old_value)) {
LOG(WARNING) << "duplicate key " << key << ", discarding value "
<< old_value;
}
break;
}
case kOptionDatabase: {
options.database = optarg;
break;
}
case kOptionURL: {
options.url = optarg;
break;
}
case kOptionArgument: {
options.arguments.push_back(optarg);
break;
}
case kOptionHelp: {
Usage(me);
return kExitSuccess;
}
case kOptionVersion: {
ToolSupport::Version(me);
return kExitSuccess;
}
default: {
ToolSupport::UsageHint(me, nullptr);
return kExitFailure;
}
}
}
argc -= optind;
argv += optind;
if (!argc) {
ToolSupport::UsageHint(me, "COMMAND is required");
return kExitFailure;
}
// Start the handler process and direct exceptions to it.
CrashpadClient crashpad_client;
if (!crashpad_client.StartHandler(base::FilePath(options.handler),
base::FilePath(options.database),
options.url,
options.annotations,
options.arguments,
false)) {
return kExitFailure;
}
if (!crashpad_client.UseHandler()) {
return kExitFailure;
}
// Using the remaining arguments, start a new program with the new exception
// port in effect.
execvp(argv[0], argv);
PLOG(ERROR) << "execvp " << argv[0];
return errno == ENOENT ? kExitExecENOENT : kExitExecFailure;
}
} // namespace
} // namespace crashpad
int main(int argc, char* argv[]) {
return crashpad::RunWithCrashpadMain(argc, argv);
}
|
// Copyright 2014 The Crashpad 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 <errno.h>
#include <getopt.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <map>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/logging.h"
#include "client/crashpad_client.h"
#include "tools/tool_support.h"
#include "util/stdlib/map_insert.h"
#include "util/string/split_string.h"
namespace crashpad {
namespace {
void Usage(const std::string& me) {
fprintf(stderr,
"Usage: %s [OPTION]... COMMAND [ARG]...\n"
"Start a Crashpad handler and have it handle crashes from COMMAND.\n"
"\n"
" -h, --handler=HANDLER invoke HANDLER instead of crashpad_handler\n"
" --annotation=KEY=VALUE passed to the handler as an --annotation argument\n"
" --database=PATH passed to the handler as its --database argument\n"
" --url=URL passed to the handler as its --url argument\n"
" -a, --argument=ARGUMENT invoke the handler with ARGUMENT\n"
" --help display this help and exit\n"
" --version output version information and exit\n",
me.c_str());
ToolSupport::UsageTail(me);
}
int RunWithCrashpadMain(int argc, char* argv[]) {
const std::string me(basename(argv[0]));
enum ExitCode {
kExitSuccess = EXIT_SUCCESS,
// To differentiate this tool’s errors from errors in the programs it execs,
// use a high exit code for ordinary failures instead of EXIT_FAILURE. This
// is the same rationale for using the distinct exit codes for exec
// failures.
kExitFailure = 125,
// Like env, use exit code 126 if the program was found but could not be
// invoked, and 127 if it could not be found.
// http://pubs.opengroup.org/onlinepubs/9699919799/utilities/env.html
kExitExecFailure = 126,
kExitExecENOENT = 127,
};
enum OptionFlags {
// “Short” (single-character) options.
kOptionHandler = 'h',
kOptionArgument = 'a',
// Long options without short equivalents.
kOptionLastChar = 255,
kOptionAnnotation,
kOptionDatabase,
kOptionURL,
// Standard options.
kOptionHelp = -2,
kOptionVersion = -3,
};
const option long_options[] = {
{"handler", required_argument, nullptr, kOptionHandler},
{"annotation", required_argument, nullptr, kOptionAnnotation},
{"database", required_argument, nullptr, kOptionDatabase},
{"url", required_argument, nullptr, kOptionURL},
{"argument", required_argument, nullptr, kOptionArgument},
{"help", no_argument, nullptr, kOptionHelp},
{"version", no_argument, nullptr, kOptionVersion},
{nullptr, 0, nullptr, 0},
};
struct {
std::string handler;
std::map<std::string, std::string> annotations;
std::string database;
std::string url;
std::vector<std::string> arguments;
} options = {};
options.handler = "crashpad_handler";
int opt;
while ((opt = getopt_long(argc, argv, "+a:h:", long_options, nullptr)) !=
-1) {
switch (opt) {
case kOptionHandler: {
options.handler = optarg;
break;
}
case kOptionAnnotation: {
std::string key;
std::string value;
if (!SplitString(optarg, '=', &key, &value)) {
ToolSupport::UsageHint(me, "--annotation requires KEY=VALUE");
return EXIT_FAILURE;
}
std::string old_value;
if (!MapInsertOrReplace(&options.annotations, key, value, &old_value)) {
LOG(WARNING) << "duplicate key " << key << ", discarding value "
<< old_value;
}
break;
}
case kOptionDatabase: {
options.database = optarg;
break;
}
case kOptionURL: {
options.url = optarg;
break;
}
case kOptionArgument: {
options.arguments.push_back(optarg);
break;
}
case kOptionHelp: {
Usage(me);
return kExitSuccess;
}
case kOptionVersion: {
ToolSupport::Version(me);
return kExitSuccess;
}
default: {
ToolSupport::UsageHint(me, nullptr);
return kExitFailure;
}
}
}
argc -= optind;
argv += optind;
if (!argc) {
ToolSupport::UsageHint(me, "COMMAND is required");
return kExitFailure;
}
// Start the handler process and direct exceptions to it.
CrashpadClient crashpad_client;
if (!crashpad_client.StartHandler(base::FilePath(options.handler),
base::FilePath(options.database),
base::FilePath(),
options.url,
options.annotations,
options.arguments,
false)) {
return kExitFailure;
}
if (!crashpad_client.UseHandler()) {
return kExitFailure;
}
// Using the remaining arguments, start a new program with the new exception
// port in effect.
execvp(argv[0], argv);
PLOG(ERROR) << "execvp " << argv[0];
return errno == ENOENT ? kExitExecENOENT : kExitExecFailure;
}
} // namespace
} // namespace crashpad
int main(int argc, char* argv[]) {
return crashpad::RunWithCrashpadMain(argc, argv);
}
|
Fix Mac build after 27aeb2c9
|
Fix Mac build after 27aeb2c9
Oh yeah, that other platform.
[email protected]
BUG=crashpad:100
Change-Id: Iaacd9a2a4a9754a26af9dd78f5b12cb1523ea19b
Reviewed-on: https://chromium-review.googlesource.com/386785
Reviewed-by: Mark Mentovai <[email protected]>
|
C++
|
apache-2.0
|
chromium/crashpad,atom/crashpad,chromium/crashpad,atom/crashpad,chromium/crashpad,atom/crashpad
|
1be44a1b8e3c0e49b81c1ae386555dc5516e931d
|
examples/hello_spider/hello_spider.cpp
|
examples/hello_spider/hello_spider.cpp
|
/*
Copyright (c) 2014 Mutantspider authors, see AUTHORS file.
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 "mutantspider.h"
#include "math.h" // for sqrt
/*
Beginner's note:
The first thing called is CreateModule at the bottom of this file.
Then HelloSpiderModule::CreateInstance is the next thing called
(second to bottom of the file). That creates the HelloSpiderInstance
(immediately below this comment)
*/
/*
An instance of HelloSpiderInstance is created by the initialization logic
(pp::CreateModule()->CreateInstance()). This instance is then associated
with the component on the web page that initiated this code. Virtual methods
like DidChangeView and HandleInputEvent are called in response to event
processing in the browser.
This HelloSpiderInstance contains a small bit of boilerplate logic, but
primarily implements some logic that paints a black dot where the mouse
currently is.
*/
class HelloSpiderInstance : public MS_AppInstance
{
public:
explicit HelloSpiderInstance(MS_Instance instance)
: MS_AppInstance(instance),
callback_factory_(this),
blitting_(false),
mouse_down_(false),
mouse_loc_x_(0),
mouse_loc_y_(0)
{}
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[])
{
// even though HelloSpiderInstance doesn't exercise any file system code,
// we still need to call this to complete the initialization logic.
mutantspider::init_fs(this);
return true;
}
// called when the DOM element that this is associated with changes sizes
virtual void DidChangeView(const mutantspider::View& view)
{
if (!CreateContext(view.GetRect().size()))
return;
Paint();
}
// called when an "input" event of some kind is directed at our DOM element
// in this example we are only tracking mouse and touch events
virtual bool HandleInputEvent(const mutantspider::InputEvent& event)
{
if (event.GetType() == MS_INPUTEVENT_TYPE_MOUSEDOWN || event.GetType() == MS_INPUTEVENT_TYPE_TOUCHSTART)
mouse_down_ = true;
else if(event.GetType() == MS_INPUTEVENT_TYPE_MOUSEUP || event.GetType() == MS_INPUTEVENT_TYPE_TOUCHEND)
mouse_down_ = false;
if (mouse_down_)
{
switch(event.GetType())
{
case MS_INPUTEVENT_TYPE_MOUSEDOWN:
case MS_INPUTEVENT_TYPE_MOUSEUP:
case MS_INPUTEVENT_TYPE_MOUSEMOVE:
case MS_INPUTEVENT_TYPE_MOUSEENTER:
case MS_INPUTEVENT_TYPE_MOUSELEAVE:
{
mutantspider::MouseInputEvent mouse_event(event);
mouse_loc_x_ = mouse_event.GetPosition().x();
mouse_loc_y_ = mouse_event.GetPosition().y();
if (!blitting_)
Paint();
} return true;
case MS_INPUTEVENT_TYPE_TOUCHSTART:
case MS_INPUTEVENT_TYPE_TOUCHMOVE:
{
mutantspider::TouchInputEvent touch_event(event);
if (touch_event.GetTouchCount(MS_TOUCHLIST_TYPE_TOUCHES) == 1)
{
mouse_loc_x_ = (int)touch_event.GetTouchByIndex(MS_TOUCHLIST_TYPE_TOUCHES, 0).position().x();
mouse_loc_y_ = (int)touch_event.GetTouchByIndex(MS_TOUCHLIST_TYPE_TOUCHES, 0).position().y();
if (!blitting_)
Paint();
}
} return true;
default:
break;
}
}
return false;
}
// function to create our "context" object (the graphic object we
// use to display our bitmap on the web page)
bool CreateContext(const mutantspider::Size& new_size)
{
const bool kIsAlwaysOpaque = true;
context_ = mutantspider::Graphics2D(this, new_size, kIsAlwaysOpaque);
if (!BindGraphics(context_))
{
fprintf(stderr, "Unable to bind 2d context!\n");
context_ = mutantspider::Graphics2D();
return false;
}
size_ = new_size;
return true;
}
// called to construct the "black-dot" bitmap and show it on the web page
void Paint()
{
// get the rgb vs. bgr layout that is optimal for this system
MS_ImageDataFormat format = mutantspider::ImageData::GetNativeImageDataFormat();
// allocate an image buffer in the optimal format, that is the size of our DOM element
mutantspider::ImageData image_data(this, format, size_, false/*don't bother to init to zero*/);
// get a pointer to its pixels
uint32_t* data = static_cast<uint32_t*>(image_data.data());
// 'g' and 'a' are in the same position for rgb vs. bgr, but
// 'r' and 'b' reverse positions
int ri, gi = 1, bi, ai = 3;
if (format == MS_IMAGEDATAFORMAT_RGBA_PREMUL)
{
ri = 0;
bi = 2;
}
else
{
bi = 0;
ri = 2;
}
// paint the red field with a black circle around the current mouse position
size_t offset = 0;
for (int y=0;y<size_.height();y++)
{
for (int x=0;x<size_.width();x++)
{
int xdist = x - mouse_loc_x_;
int ydist = y - mouse_loc_y_;
int dist = (int)(sqrt(xdist*xdist + ydist*ydist));
if (dist > 255)
dist = 255;
// construct one pixel
uint8_t px[4];
px[ri] = dist;
px[gi] = px[bi] = 0;
px[ai] = 255;
// set it into our bitmap
data[offset] = *(uint32_t*)&px[0];
++offset;
}
}
// display our bitmap
context_.ReplaceContents(&image_data);
blitting_ = true;
context_.Flush(callback_factory_.NewCallback(&HelloSpiderInstance::BlitDone));
}
// called when a previous call to context_.Flush has completed. In a multi-threaded
// build like nacl, we don't want to try building and displaying a new bitmap until
// the previous one completed its display to the screen. If a new mouse event comes
// in between the time we requested that it be displayed (our call to context_.Flush)
// and the time it completes its display (when this BlitDone is called), then we just
// skip trying to update and display the bitmap. See blitting_ testing in HandleInputEvent
void BlitDone(uint32_t)
{
blitting_ = false;
}
private:
mutantspider::CompletionCallbackFactory<HelloSpiderInstance> callback_factory_;
mutantspider::Graphics2D context_;
mutantspider::Size size_;
bool blitting_;
bool mouse_down_;
int mouse_loc_x_;
int mouse_loc_y_;
};
/*
standard Module, whose CreateInstance is called during startup
to create the Instance object which the browser interacts with.
Mutantspider follows the Pepper design here of a two-stage
initialization sequence. pp::CreateModule is the first stage,
that Module's (this HellowSpiderModule's) CreateInstance is the
second stage.
*/
class HelloSpiderModule : public MS_Module
{
public:
virtual MS_AppInstancePtr CreateInstance(MS_Instance instance)
{
return new HelloSpiderInstance(instance);
}
};
/*
a bit of crappy, almost boilerplace code.
This is the one place in mutantspider where it leaves the Pepper
"pp" namespace in tact, and just follows the pepper model for how
the basic initialization works. To be a functioning mutantspider
component, you have to implement pp::CreateModule. It will be called
as the first thing during initialization of your component. It is
required to return an allocated instance of a Module. The (virtual)
CreateInstance method of that Module is then called to create an
Instance. That Instance's virtual methods are then called to
interact with the web page.
*/
namespace pp {
MS_Module* CreateModule() { return new HelloSpiderModule(); }
}
|
/*
Copyright (c) 2014 Mutantspider authors, see AUTHORS file.
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 "mutantspider.h"
#include "math.h" // for sqrt
/*
Beginner's note:
The first thing called is pp::CreateModule at the bottom of this file.
Then HelloSpiderModule::CreateInstance is the next thing called
(second to bottom of the file). That creates the HelloSpiderInstance
(immediately below this comment)
*/
/*
An instance of HelloSpiderInstance is created by the initialization logic
(pp::CreateModule()->CreateInstance()). This instance is then associated
with the component on the web page that initiated this code. Virtual methods
like DidChangeView and HandleInputEvent are called in response to event
processing in the browser.
This HelloSpiderInstance contains a small bit of boilerplate logic, but
primarily implements the code that paints a black dot where the mouse
currently is.
*/
class HelloSpiderInstance : public MS_AppInstance
{
public:
explicit HelloSpiderInstance(MS_Instance instance)
: MS_AppInstance(instance),
callback_factory_(this),
blitting_(false),
mouse_down_(false),
mouse_loc_x_(0),
mouse_loc_y_(0)
{}
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[])
{
// even though HelloSpiderInstance doesn't exercise any file system code,
// we still need to call this to complete the initialization logic.
mutantspider::init_fs(this);
return true;
}
// called when the DOM element that this is associated with changes sizes
virtual void DidChangeView(const mutantspider::View& view)
{
if (!CreateContext(view.GetRect().size()))
return;
Paint();
}
// called when an "input" event of some kind is directed at our DOM element
// in this example we are only tracking mouse and touch events
virtual bool HandleInputEvent(const mutantspider::InputEvent& event)
{
if (event.GetType() == MS_INPUTEVENT_TYPE_MOUSEDOWN || event.GetType() == MS_INPUTEVENT_TYPE_TOUCHSTART)
mouse_down_ = true;
else if(event.GetType() == MS_INPUTEVENT_TYPE_MOUSEUP || event.GetType() == MS_INPUTEVENT_TYPE_TOUCHEND)
mouse_down_ = false;
if (mouse_down_)
{
switch(event.GetType())
{
case MS_INPUTEVENT_TYPE_MOUSEDOWN:
case MS_INPUTEVENT_TYPE_MOUSEUP:
case MS_INPUTEVENT_TYPE_MOUSEMOVE:
case MS_INPUTEVENT_TYPE_MOUSEENTER:
case MS_INPUTEVENT_TYPE_MOUSELEAVE:
{
mutantspider::MouseInputEvent mouse_event(event);
mouse_loc_x_ = mouse_event.GetPosition().x();
mouse_loc_y_ = mouse_event.GetPosition().y();
if (!blitting_)
Paint();
} return true;
case MS_INPUTEVENT_TYPE_TOUCHSTART:
case MS_INPUTEVENT_TYPE_TOUCHMOVE:
{
mutantspider::TouchInputEvent touch_event(event);
if (touch_event.GetTouchCount(MS_TOUCHLIST_TYPE_TOUCHES) == 1)
{
mouse_loc_x_ = (int)touch_event.GetTouchByIndex(MS_TOUCHLIST_TYPE_TOUCHES, 0).position().x();
mouse_loc_y_ = (int)touch_event.GetTouchByIndex(MS_TOUCHLIST_TYPE_TOUCHES, 0).position().y();
if (!blitting_)
Paint();
}
} return true;
default:
break;
}
}
return false;
}
// function to create our "context" object (the graphic object we
// use to display our bitmap on the web page)
bool CreateContext(const mutantspider::Size& new_size)
{
const bool kIsAlwaysOpaque = true;
context_ = mutantspider::Graphics2D(this, new_size, kIsAlwaysOpaque);
if (!BindGraphics(context_))
{
fprintf(stderr, "Unable to bind 2d context!\n");
context_ = mutantspider::Graphics2D();
return false;
}
size_ = new_size;
return true;
}
// called to construct the "black-dot" bitmap and show it on the web page
void Paint()
{
// get the rgb vs. bgr layout that is optimal for this system
MS_ImageDataFormat format = mutantspider::ImageData::GetNativeImageDataFormat();
// allocate an image buffer in the optimal format, that is the size of our DOM element
mutantspider::ImageData image_data(this, format, size_, false/*don't bother to init to zero*/);
// get a pointer to its pixels
uint32_t* data = static_cast<uint32_t*>(image_data.data());
// 'g' and 'a' are in the same position for rgb vs. bgr, but
// 'r' and 'b' reverse positions
int ri, gi = 1, bi, ai = 3;
if (format == MS_IMAGEDATAFORMAT_RGBA_PREMUL)
{
ri = 0;
bi = 2;
}
else
{
bi = 0;
ri = 2;
}
// paint the red field with a black circle around the current mouse position
size_t offset = 0;
for (int y=0;y<size_.height();y++)
{
for (int x=0;x<size_.width();x++)
{
int xdist = x - mouse_loc_x_;
int ydist = y - mouse_loc_y_;
int dist = (int)(sqrt(xdist*xdist + ydist*ydist));
if (dist > 255)
dist = 255;
// construct one pixel
uint8_t px[4];
px[ri] = dist;
px[gi] = px[bi] = 0;
px[ai] = 255;
// set it into our bitmap
data[offset] = *(uint32_t*)&px[0];
++offset;
}
}
// display our bitmap
context_.ReplaceContents(&image_data);
blitting_ = true;
context_.Flush(callback_factory_.NewCallback(&HelloSpiderInstance::BlitDone));
}
// called when a previous call to context_.Flush has completed. In a multi-threaded
// build like nacl, we don't want to try building and displaying a new bitmap until
// the previous one completed its display to the screen. If a new mouse event comes
// in between the time we requested that it be displayed (our call to context_.Flush)
// and the time it completes its display (when this BlitDone is called), then we just
// skip trying to update and display the bitmap. See blitting_ testing in HandleInputEvent
void BlitDone(uint32_t)
{
blitting_ = false;
}
private:
mutantspider::CompletionCallbackFactory<HelloSpiderInstance> callback_factory_;
mutantspider::Graphics2D context_;
mutantspider::Size size_;
bool blitting_;
bool mouse_down_;
int mouse_loc_x_;
int mouse_loc_y_;
};
/*
standard MS_Module, whose CreateInstance is called during startup
to create the Instance object which the browser interacts with.
Mutantspider follows the Pepper design here of a two-stage
initialization sequence. pp::CreateModule is the first stage,
that MS_Module's (this HellowSpiderModule's) CreateInstance is the
second stage.
*/
class HelloSpiderModule : public MS_Module
{
public:
virtual MS_AppInstancePtr CreateInstance(MS_Instance instance)
{
return new HelloSpiderInstance(instance);
}
};
/*
a bit of crappy, almost boilerplate code.
This is the one place in mutantspider where it leaves the Pepper
"pp" namespace intact, and just follows the pepper model for how
the basic initialization works. To be a functioning mutantspider
component, you have to implement pp::CreateModule. It will be called
as the first thing during initialization of your component. It is
required to return an allocated instance of an MS_Module. The (virtual)
CreateInstance method of that MS_Module is then called to create an
Instance. That Instance's virtual methods are then called to
interact with the web page.
*/
namespace pp {
MS_Module* CreateModule() { return new HelloSpiderModule(); }
}
|
comment editing
|
comment editing
|
C++
|
mit
|
pkholland/mutantspider,pkholland/mutantspider
|
0932e38ad73d8e7214adda5103ced38c7b2754d0
|
testing/rtkfdktest.cxx
|
testing/rtkfdktest.cxx
|
#include <itkImageRegionConstIterator.h>
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#ifdef USE_CUDA
# include "rtkCudaFDKConeBeamReconstructionFilter.h"
#elif USE_OPENCL
# include "rtkOpenCLFDKConeBeamReconstructionFilter.h"
#else
# include "rtkFDKConeBeamReconstructionFilter.h"
#endif
template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
ImageIteratorType itRef( ref, ref->GetBufferedRegion() );
typedef double ErrorType;
ErrorType TestError = 0.;
ErrorType EnerError = 0.;
itTest.GoToBegin();
itRef.GoToBegin();
while( !itRef.IsAtEnd() )
{
typename TImage::PixelType TestVal = itTest.Get();
typename TImage::PixelType RefVal = itRef.Get();
TestError += vcl_abs(RefVal - TestVal);
EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
++itTest;
++itRef;
}
// Error per Pixel
ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
// MSE
ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "MSE = " << MSE << std::endl;
// PSNR
ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
std::cout << "PSNR = " << PSNR << "dB" << std::endl;
// QI
ErrorType QI = (2.0-ErrorPerPixel)/2.0;
std::cout << "QI = " << QI << std::endl;
// Checking results
if (ErrorPerPixel > 0.03)
{
std::cerr << "Test Failed, Error per pixel not valid! "
<< ErrorPerPixel << " instead of 0.03." << std::endl;
exit( EXIT_FAILURE);
}
if (PSNR < 26.)
{
std::cerr << "Test Failed, PSNR not valid! "
<< PSNR << " instead of 26" << std::endl;
exit( EXIT_FAILURE);
}
}
int main(int, char** )
{
const unsigned int Dimension = 3;
typedef float OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
const unsigned int NumberOfProjectionImages = 180;
// Constant image sources
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::PointType origin;
ConstantImageSourceType::SizeType size;
ConstantImageSourceType::SpacingType spacing;
ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();
origin[0] = -127.;
origin[1] = -127.;
origin[2] = -127.;
size[0] = 128;
size[1] = 128;
size[2] = 128;
spacing[0] = 2.;
spacing[1] = 2.;
spacing[2] = 2.;
tomographySource->SetOrigin( origin );
tomographySource->SetSpacing( spacing );
tomographySource->SetSize( size );
tomographySource->SetConstant( 0. );
ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
origin[0] = -254.;
origin[1] = -254.;
origin[2] = -254.;
size[0] = 128;
size[1] = 128;
size[2] = NumberOfProjectionImages;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
projectionsSource->SetOrigin( origin );
projectionsSource->SetSpacing( spacing );
projectionsSource->SetSize( size );
projectionsSource->SetConstant( 0. );
// Geometry object
typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
GeometryType::Pointer geometry = GeometryType::New();
for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Shepp Logan projections filter
typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType;
SLPType::Pointer slp=SLPType::New();
slp->SetInput( projectionsSource->GetOutput() );
slp->SetGeometry(geometry);
TRY_AND_EXIT_ON_ITK_EXCEPTION( slp->Update() );
// Create a reference object (in this case a 3D phantom reference).
typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType;
DSLType::Pointer dsl = DSLType::New();
dsl->SetInput( tomographySource->GetOutput() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )
// FDK reconstruction filtering
#ifdef USE_CUDA
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKType;
#elif USE_OPENCL
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKType;
#else
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
FDKType::Pointer feldkamp = FDKType::New();
feldkamp->SetInput( 0, tomographySource->GetOutput() );
feldkamp->SetInput( 1, slp->GetOutput() );
feldkamp->SetGeometry( geometry );
TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() );
// FOV
typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
FOVFilterType::Pointer fov=FOVFilterType::New();
fov->SetInput(0, feldkamp->GetOutput());
fov->SetProjectionsStack(slp->GetOutput());
fov->SetGeometry( geometry );
fov->Update();
CheckImageQuality<OutputImageType>(fov->GetOutput(), dsl->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
return EXIT_SUCCESS;
}
|
#include <itkImageRegionConstIterator.h>
#include <itkStreamingImageFilter.h>
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#ifdef USE_CUDA
# include "rtkCudaFDKConeBeamReconstructionFilter.h"
#elif USE_OPENCL
# include "rtkOpenCLFDKConeBeamReconstructionFilter.h"
#else
# include "rtkFDKConeBeamReconstructionFilter.h"
#endif
template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
ImageIteratorType itRef( ref, ref->GetBufferedRegion() );
typedef double ErrorType;
ErrorType TestError = 0.;
ErrorType EnerError = 0.;
itTest.GoToBegin();
itRef.GoToBegin();
while( !itRef.IsAtEnd() )
{
typename TImage::PixelType TestVal = itTest.Get();
typename TImage::PixelType RefVal = itRef.Get();
TestError += vcl_abs(RefVal - TestVal);
EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
++itTest;
++itRef;
}
// Error per Pixel
ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
// MSE
ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "MSE = " << MSE << std::endl;
// PSNR
ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
std::cout << "PSNR = " << PSNR << "dB" << std::endl;
// QI
ErrorType QI = (2.0-ErrorPerPixel)/2.0;
std::cout << "QI = " << QI << std::endl;
// Checking results
if (ErrorPerPixel > 0.03)
{
std::cerr << "Test Failed, Error per pixel not valid! "
<< ErrorPerPixel << " instead of 0.03." << std::endl;
exit( EXIT_FAILURE);
}
if (PSNR < 26.)
{
std::cerr << "Test Failed, PSNR not valid! "
<< PSNR << " instead of 26" << std::endl;
exit( EXIT_FAILURE);
}
}
int main(int, char** )
{
const unsigned int Dimension = 3;
typedef float OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
const unsigned int NumberOfProjectionImages = 180;
// Constant image sources
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::PointType origin;
ConstantImageSourceType::SizeType size;
ConstantImageSourceType::SpacingType spacing;
ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();
origin[0] = -127.;
origin[1] = -127.;
origin[2] = -127.;
size[0] = 128;
size[1] = 128;
size[2] = 128;
spacing[0] = 2.;
spacing[1] = 2.;
spacing[2] = 2.;
tomographySource->SetOrigin( origin );
tomographySource->SetSpacing( spacing );
tomographySource->SetSize( size );
tomographySource->SetConstant( 0. );
ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
origin[0] = -254.;
origin[1] = -254.;
origin[2] = -254.;
size[0] = 128;
size[1] = 128;
size[2] = NumberOfProjectionImages;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
projectionsSource->SetOrigin( origin );
projectionsSource->SetSpacing( spacing );
projectionsSource->SetSize( size );
projectionsSource->SetConstant( 0. );
std::cout << "\n\n****** Case 1: No streaming ******" << std::endl;
// Geometry object
typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
GeometryType::Pointer geometry = GeometryType::New();
for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Shepp Logan projections filter
typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType;
SLPType::Pointer slp=SLPType::New();
slp->SetInput( projectionsSource->GetOutput() );
slp->SetGeometry(geometry);
TRY_AND_EXIT_ON_ITK_EXCEPTION( slp->Update() );
// Create a reference object (in this case a 3D phantom reference).
typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType;
DSLType::Pointer dsl = DSLType::New();
dsl->SetInput( tomographySource->GetOutput() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )
// FDK reconstruction filtering
#ifdef USE_CUDA
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKType;
#elif USE_OPENCL
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKType;
#else
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
FDKType::Pointer feldkamp = FDKType::New();
feldkamp->SetInput( 0, tomographySource->GetOutput() );
feldkamp->SetInput( 1, slp->GetOutput() );
feldkamp->SetGeometry( geometry );
TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() );
// FOV
typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
FOVFilterType::Pointer fov=FOVFilterType::New();
fov->SetInput(0, feldkamp->GetOutput());
fov->SetProjectionsStack(slp->GetOutput());
fov->SetGeometry( geometry );
fov->Update();
CheckImageQuality<OutputImageType>(fov->GetOutput(), dsl->GetOutput());
std::cout << "Test PASSED! " << std::endl;
std::cout << "\n\n****** Case 2: streaming ******" << std::endl;
// Make sure that the data will be recomputed by releasing them
fov->GetOutput()->ReleaseData();
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamingType;
StreamingType::Pointer streamer = StreamingType::New();
streamer->SetInput(0, fov->GetOutput());
streamer->SetNumberOfStreamDivisions(8);
streamer->Update();
CheckImageQuality<OutputImageType>(streamer->GetOutput(), dsl->GetOutput());
std::cout << "Test PASSED! " << std::endl;
return EXIT_SUCCESS;
}
|
Include streaming test
|
Include streaming test
|
C++
|
apache-2.0
|
ldqcarbon/RTK,dsarrut/RTK,fabienmomey/RTK,ldqcarbon/RTK,SimonRit/RTK,fabienmomey/RTK,ldqcarbon/RTK,dsarrut/RTK,fabienmomey/RTK,dsarrut/RTK,ipsusila/RTK,ipsusila/RTK,ldqcarbon/RTK,ipsusila/RTK,ipsusila/RTK,ipsusila/RTK,ipsusila/RTK,dsarrut/RTK,SimonRit/RTK,ldqcarbon/RTK,dsarrut/RTK,SimonRit/RTK,fabienmomey/RTK,ldqcarbon/RTK,SimonRit/RTK,dsarrut/RTK,fabienmomey/RTK,ipsusila/RTK,dsarrut/RTK,fabienmomey/RTK,fabienmomey/RTK,ldqcarbon/RTK
|
b8de8ec3f5eb987cf37ef13026e4c4c5c8b961c5
|
tests/LEQuad/tasks.cpp
|
tests/LEQuad/tasks.cpp
|
/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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.
******************************************************************************/
/*******************************************************************************
* \file tasks.c
*
* \author MAV'RIC Team
*
* \brief Definition of the tasks executed on the autopilot
*
******************************************************************************/
#include "tasks.hpp"
#include "central_data.hpp"
#include "data_logging.hpp"
extern "C"
{
#include "led.h"
#include "pwm_servos.h"
}
void tasks_run_imu_update(Central_data* central_data)
{
central_data->imu.update();
qfilter_update(¢ral_data->attitude_filter);
position_estimation_update(¢ral_data->position_estimation);
}
bool tasks_run_stabilisation(Central_data* central_data)
{
tasks_run_imu_update(central_data);
mav_mode_t mode = central_data->state.mav_mode;
if( mode.ARMED == ARMED_ON )
{
if ( mode.AUTO == AUTO_ON )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
// if no waypoints are set, we do position hold therefore the yaw mode is absolute
if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)&&(!central_data->navigation.stop_nav)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
//if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mode.GUIDED == GUIDED_ON )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
if ((central_data->state.mav_state == MAV_STATE_CRITICAL) && (central_data->navigation.critical_behavior == FLY_TO_HOME_WP))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mode.STABILISE == STABILISE_ON )
{
manual_control_get_velocity_vector(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
central_data->controls.yaw_mode = YAW_RELATIVE;
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mode.MANUAL == MANUAL_ON )
{
manual_control_get_control_command(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = ATTITUDE_COMMAND_MODE;
central_data->controls.yaw_mode=YAW_RELATIVE;
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
return true;
}
bool tasks_run_gps_update(Central_data* central_data)
{
central_data->gps.update();
return true;
}
bool tasks_run_barometer_update(Central_data* central_data)
{
central_data->barometer.update();
return true;
}
bool tasks_run_sonar_update(Central_data* central_data)
{
central_data->sonar.update();
return true;
}
bool tasks_create_tasks(Central_data* central_data)
{
bool init_success = true;
scheduler_t* scheduler = ¢ral_data->scheduler;
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGHEST, (task_function_t)&tasks_run_stabilisation , (task_argument_t)central_data , 0);
init_success &= scheduler_add_task(scheduler, 15000, RUN_REGULAR, PERIODIC_RELATIVE, PRIORITY_HIGH , (task_function_t)&tasks_run_barometer_update , (task_argument_t)central_data , 2);
init_success &= scheduler_add_task(scheduler, 100000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&tasks_run_gps_update , (task_argument_t)central_data , 3);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&navigation_update , (task_argument_t)¢ral_data->navigation , 4);
init_success &= scheduler_add_task(scheduler, 200000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&state_machine_update , (task_argument_t)¢ral_data->state_machine , 5);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&mavlink_communication_update , (task_argument_t)¢ral_data->mavlink_communication , 6);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&waypoint_handler_control_time_out_waypoint_msg , (task_argument_t)¢ral_data->waypoint_handler , 8);
init_success &= scheduler_add_task(scheduler, 20000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&remote_update , (task_argument_t)¢ral_data->manual_control.remote , 12);
init_success &= scheduler_add_task(scheduler, 500000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&tasks_run_sonar_update , (task_argument_t)central_data , 13);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&data_logging_update , (task_argument_t)¢ral_data->data_logging , 12);
scheduler_sort_tasks(scheduler);
return init_success;
}
|
/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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.
******************************************************************************/
/*******************************************************************************
* \file tasks.c
*
* \author MAV'RIC Team
*
* \brief Definition of the tasks executed on the autopilot
*
******************************************************************************/
#include "tasks.hpp"
#include "central_data.hpp"
#include "data_logging.hpp"
extern "C"
{
#include "led.h"
#include "pwm_servos.h"
}
void tasks_run_imu_update(Central_data* central_data)
{
central_data->imu.update();
qfilter_update(¢ral_data->attitude_filter);
position_estimation_update(¢ral_data->position_estimation);
}
bool tasks_run_stabilisation(Central_data* central_data)
{
tasks_run_imu_update(central_data);
mav_mode_t mode = central_data->state.mav_mode;
if( mode.ARMED == ARMED_ON )
{
if ( mode.AUTO == AUTO_ON )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
// if no waypoints are set, we do position hold therefore the yaw mode is absolute
if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)&&(!central_data->navigation.stop_nav)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
//if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mode.GUIDED == GUIDED_ON )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
if ((central_data->state.mav_state == MAV_STATE_CRITICAL) && (central_data->navigation.critical_behavior == FLY_TO_HOME_WP))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mode.STABILISE == STABILISE_ON )
{
manual_control_get_velocity_vector(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
central_data->controls.yaw_mode = YAW_RELATIVE;
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mode.MANUAL == MANUAL_ON )
{
manual_control_get_control_command(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = ATTITUDE_COMMAND_MODE;
central_data->controls.yaw_mode=YAW_RELATIVE;
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
return true;
}
bool tasks_run_gps_update(Central_data* central_data)
{
central_data->gps.update();
return true;
}
bool tasks_run_barometer_update(Central_data* central_data)
{
central_data->barometer.update();
return true;
}
bool tasks_run_sonar_update(Central_data* central_data)
{
central_data->sonar.update();
return true;
}
bool tasks_create_tasks(Central_data* central_data)
{
bool init_success = true;
scheduler_t* scheduler = ¢ral_data->scheduler;
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGHEST, (task_function_t)&tasks_run_stabilisation , (task_argument_t)central_data , 0);
init_success &= scheduler_add_task(scheduler, 15000, RUN_REGULAR, PERIODIC_RELATIVE, PRIORITY_HIGH , (task_function_t)&tasks_run_barometer_update , (task_argument_t)central_data , 2);
init_success &= scheduler_add_task(scheduler, 100000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&tasks_run_gps_update , (task_argument_t)central_data , 3);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&navigation_update , (task_argument_t)¢ral_data->navigation , 4);
init_success &= scheduler_add_task(scheduler, 200000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&state_machine_update , (task_argument_t)¢ral_data->state_machine , 5);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&mavlink_communication_update , (task_argument_t)¢ral_data->mavlink_communication , 6);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&waypoint_handler_control_time_out_waypoint_msg , (task_argument_t)¢ral_data->waypoint_handler , 8);
init_success &= scheduler_add_task(scheduler, 20000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&remote_update , (task_argument_t)¢ral_data->manual_control.remote , 12);
init_success &= scheduler_add_task(scheduler, 500000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&tasks_run_sonar_update , (task_argument_t)central_data , 13);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&data_logging_update , (task_argument_t)¢ral_data->data_logging , 11);
scheduler_sort_tasks(scheduler);
return init_success;
}
|
Change ID of data_logging task
|
Change ID of data_logging task
|
C++
|
bsd-3-clause
|
lis-epfl/MAVRIC_Library,lis-epfl/MAVRIC_Library,lis-epfl/MAVRIC_Library
|
ac4737e4d959e7a2bc71a2e9b3db0fd23e780361
|
tests/TestTimeSpan.cpp
|
tests/TestTimeSpan.cpp
|
//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Dennis Nienhüser <[email protected]>
//
#include <QtCore/QObject>
#include <QtTest/QtTest>
#include <GeoDataParser.h>
#include <GeoDataDocument.h>
#include <GeoDataPlacemark.h>
#include <GeoDataTimeSpan.h>
#include <GeoDataCamera.h>
#include <MarbleDebug.h>
#include <GeoDataFolder.h>
#include "TestUtils.h"
using namespace Marble;
class TestTimeStamp : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void simpleParseTest();
};
void TestTimeStamp::initTestCase()
{
MarbleDebug::enable = true;
}
void TestTimeStamp::simpleParseTest()
{
QString const centerContent (
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<kml xmlns=\"http://www.opengis.net/kml/2.2\""
" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">"
"<Document>"
"<Placemark><TimeSpan><begin>1988</begin><end>1999</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1989-04</begin><end>1999-05</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1990-02-03</begin><end>1999-04-08</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1997-07-16T07:30:15Z</begin><end>1997-08-17T02:35:12Z</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1997-07-16T10:30:15+03:00</begin><end>1998-07-16T10:30:15+03:00</end></TimeSpan></Placemark>"
"</Document>"
"</kml>" );
GeoDataDocument* dataDocument = parseKml( centerContent );
QCOMPARE( dataDocument->placemarkList().size(), 5 );
GeoDataPlacemark* placemark1 = dataDocument->placemarkList().at( 0 );
QCOMPARE( placemark1->timeSpan().begin().date().year(), 1988 );
QCOMPARE( placemark1->timeSpan().end().date().year(), 1999 );
GeoDataPlacemark* placemark2 = dataDocument->placemarkList().at( 1 );
QCOMPARE( placemark2->timeSpan().begin().date().year(), 1989 );
QCOMPARE( placemark2->timeSpan().begin().date().month(), 4 );
QCOMPARE( placemark2->timeSpan().end().date().year(), 1999 );
QCOMPARE( placemark2->timeSpan().end().date().month(), 5 );
GeoDataPlacemark* placemark3 = dataDocument->placemarkList().at( 2 );
QCOMPARE( placemark3->timeSpan().begin().date().year(), 1990 );
QCOMPARE( placemark3->timeSpan().begin().date().month(), 2 );
QCOMPARE( placemark3->timeSpan().begin().date().day(), 3 );
QCOMPARE( placemark3->timeSpan().end().date().year(), 1999 );
QCOMPARE( placemark3->timeSpan().end().date().month(), 4 );
QCOMPARE( placemark3->timeSpan().end().date().day(), 8 );
GeoDataPlacemark* placemark4 = dataDocument->placemarkList().at( 3 );
QCOMPARE( placemark4->timeSpan().begin(), QDateTime::fromString( "1997-07-16T07:30:15Z", Qt::ISODate ) );
QCOMPARE( placemark4->timeSpan().end(), QDateTime::fromString( "1997-08-17T02:35:12Z", Qt::ISODate ) );
GeoDataPlacemark* placemark5 = dataDocument->placemarkList().at( 4 );
QCOMPARE( placemark5->timeSpan().begin(), QDateTime::fromString( "1997-07-16T10:30:15+03:00", Qt::ISODate ) );
QCOMPARE( placemark5->timeSpan().end(), QDateTime::fromString( "1998-07-16T10:30:15+03:00", Qt::ISODate ) );
delete dataDocument;
}
QTEST_MAIN( TestTimeStamp )
#include "TestTimeStamp.moc"
|
//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Dennis Nienhüser <[email protected]>
//
#include <QtCore/QObject>
#include <QtTest/QtTest>
#include <GeoDataParser.h>
#include <GeoDataDocument.h>
#include <GeoDataPlacemark.h>
#include <GeoDataTimeSpan.h>
#include <GeoDataCamera.h>
#include <MarbleDebug.h>
#include <GeoDataFolder.h>
#include "TestUtils.h"
using namespace Marble;
class TestTimeStamp : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void simpleParseTest();
};
void TestTimeStamp::initTestCase()
{
MarbleDebug::enable = true;
}
void TestTimeStamp::simpleParseTest()
{
QString const centerContent (
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<kml xmlns=\"http://www.opengis.net/kml/2.2\""
" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">"
"<Document>"
"<Placemark><TimeSpan><begin>1988</begin><end>1999</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1989-04</begin><end>1999-05</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1990-02-03</begin><end>1999-04-08</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1997-07-16T07:30:15Z</begin><end>1997-08-17T02:35:12Z</end></TimeSpan></Placemark>"
"<Placemark><TimeSpan><begin>1997-07-16T10:30:15+03:00</begin><end>1998-07-16T10:30:15+03:00</end></TimeSpan></Placemark>"
"</Document>"
"</kml>" );
GeoDataDocument* dataDocument = parseKml( centerContent );
QCOMPARE( dataDocument->placemarkList().size(), 5 );
GeoDataPlacemark* placemark1 = dataDocument->placemarkList().at( 0 );
QCOMPARE( placemark1->timeSpan().begin().date().year(), 1988 );
QCOMPARE( placemark1->timeSpan().end().date().year(), 1999 );
GeoDataPlacemark* placemark2 = dataDocument->placemarkList().at( 1 );
QCOMPARE( placemark2->timeSpan().begin().date().year(), 1989 );
QCOMPARE( placemark2->timeSpan().begin().date().month(), 4 );
QCOMPARE( placemark2->timeSpan().end().date().year(), 1999 );
QCOMPARE( placemark2->timeSpan().end().date().month(), 5 );
GeoDataPlacemark* placemark3 = dataDocument->placemarkList().at( 2 );
QCOMPARE( placemark3->timeSpan().begin().date().year(), 1990 );
QCOMPARE( placemark3->timeSpan().begin().date().month(), 2 );
QCOMPARE( placemark3->timeSpan().begin().date().day(), 3 );
QCOMPARE( placemark3->timeSpan().end().date().year(), 1999 );
QCOMPARE( placemark3->timeSpan().end().date().month(), 4 );
QCOMPARE( placemark3->timeSpan().end().date().day(), 8 );
GeoDataPlacemark* placemark4 = dataDocument->placemarkList().at( 3 );
QCOMPARE( placemark4->timeSpan().begin(), QDateTime::fromString( "1997-07-16T07:30:15Z", Qt::ISODate ) );
QCOMPARE( placemark4->timeSpan().end(), QDateTime::fromString( "1997-08-17T02:35:12Z", Qt::ISODate ) );
GeoDataPlacemark* placemark5 = dataDocument->placemarkList().at( 4 );
QCOMPARE( placemark5->timeSpan().begin(), QDateTime::fromString( "1997-07-16T10:30:15+03:00", Qt::ISODate ) );
QCOMPARE( placemark5->timeSpan().end(), QDateTime::fromString( "1998-07-16T10:30:15+03:00", Qt::ISODate ) );
delete dataDocument;
}
QTEST_MAIN( TestTimeStamp )
#include "TestTimeSpan.moc"
|
Fix moc inclusion
|
Fix moc inclusion
|
C++
|
lgpl-2.1
|
probonopd/marble,utkuaydin/marble,tzapzoor/marble,probonopd/marble,tucnak/marble,adraghici/marble,quannt24/marble,AndreiDuma/marble,quannt24/marble,probonopd/marble,probonopd/marble,tucnak/marble,tzapzoor/marble,utkuaydin/marble,quannt24/marble,AndreiDuma/marble,adraghici/marble,David-Gil/marble-dev,probonopd/marble,tzapzoor/marble,quannt24/marble,tzapzoor/marble,rku/marble,quannt24/marble,rku/marble,Earthwings/marble,tzapzoor/marble,AndreiDuma/marble,AndreiDuma/marble,quannt24/marble,tucnak/marble,adraghici/marble,tzapzoor/marble,utkuaydin/marble,tucnak/marble,tucnak/marble,David-Gil/marble-dev,rku/marble,Earthwings/marble,rku/marble,Earthwings/marble,Earthwings/marble,tucnak/marble,AndreiDuma/marble,utkuaydin/marble,tucnak/marble,probonopd/marble,probonopd/marble,tzapzoor/marble,utkuaydin/marble,David-Gil/marble-dev,tzapzoor/marble,rku/marble,Earthwings/marble,quannt24/marble,rku/marble,David-Gil/marble-dev,Earthwings/marble,AndreiDuma/marble,adraghici/marble,David-Gil/marble-dev,adraghici/marble,utkuaydin/marble,adraghici/marble,David-Gil/marble-dev
|
706019b42e4029f62ea09c7d20abd48b6da76dab
|
tests/farm_example.cpp
|
tests/farm_example.cpp
|
/**
* @version GrPPI v0.1
* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.
* @license GNU/GPL, see LICENSE.txt
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You have received a copy of the GNU General Public License in LICENSE.txt
* also available in <http://www.gnu.org/licenses/gpl.html>.
*
* See COPYRIGHT.txt for copyright notices and details.
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <chrono>
#include <farm.h>
using namespace std;
using namespace grppi;
std::vector<int> read_list(std::istream & is){
std::vector<int> result;
string line;
is >> ws;
if(!getline(is,line)) return result;
istringstream iline{line};
int x;
while(iline >> x){
result.push_back(x);
}
return result;
}
std::string read_line(std::istream & is){
std::string res;
std::string line;
is >> ws;
if(!getline(is,line)) return res;
return line;
}
void farm_example1() {
#ifndef NTHREADS
#define NTHREADS 6
#endif
#ifdef SEQ
sequential_execution p{};
#elif OMP
parallel_execution_omp p{NTHREADS};
#elif TBB
parallel_execution_tbb p{NTHREADS};
#elif THR
parallel_execution_thr p{NTHREADS};
#else
sequential_execution p{};
#endif
std::ifstream is{"txt/filelist.txt"};
if (!is.good()) { cerr << "TXT file not found!" << endl; return; }
farm(p,
// farm generator as lambda
[&]() {
auto f = read_line(is);
return ( f.empty() ) ? optional<std::string>( ) : optional<std::string>( f );
},
// farm kernel as lambda
[&]( std::string fname ) {
std::fstream file (fname);
auto v = read_list(file);
int acumm = 0;
for(int j = 0; j< v.size() ; j++) {
acumm += v[j];
}
file << acumm;
}
);
}
int main() {
//$ auto start = std::chrono::high_resolution_clock::now();
farm_example1();
//$ auto elapsed = std::chrono::high_resolution_clock::now() - start;
//$ long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ).count();
//$ std::cout << "Execution time : " << microseconds << " us" << std::endl;
return 0;
}
|
/**
* @version GrPPI v0.1
* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.
* @license GNU/GPL, see LICENSE.txt
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You have received a copy of the GNU General Public License in LICENSE.txt
* also available in <http://www.gnu.org/licenses/gpl.html>.
*
* See COPYRIGHT.txt for copyright notices and details.
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <chrono>
#include <farm.h>
using namespace std;
using namespace grppi;
std::vector<int> read_list(std::istream & is){
std::vector<int> result;
string line;
is >> ws;
if(!getline(is,line)) return result;
istringstream iline{line};
int x;
while(iline >> x){
result.push_back(x);
}
return result;
}
std::string read_line(std::istream & is){
std::string res;
std::string line;
is >> ws;
if(!getline(is,line)) return res;
return line;
}
void farm_example1() {
#ifndef NTHREADS
#define NTHREADS 6
#endif
#ifdef SEQ
sequential_execution p{};
#elif OMP
parallel_execution_omp p{NTHREADS};
#elif TBB
parallel_execution_tbb p{NTHREADS};
#elif THR
parallel_execution_thr p{NTHREADS};
#else
sequential_execution p{};
#endif
std::ifstream is{"txt/filelist.txt"};
if (!is.good()) { cerr << "TXT file not found!" << endl; return; }
farm(p,
// farm generator as lambda
[&]() {
auto f = read_line(is);
return ( f.empty() ) ? optional<std::string>( ) : optional<std::string>( f );
},
// farm kernel as lambda
[&]( std::string fname ) {
std::fstream file (fname);
auto v = read_list(file);
int acumm = 0;
for(int j = 0; j< v.size() ; j++) {
acumm += v[j];
}
file << acumm;
}
);
}
int main() {
//$ auto start = std::chrono::high_resolution_clock::now();
farm_example1();
//$ auto elapsed = std::chrono::high_resolution_clock::now() - start;
//$ long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>( elapsed ).count();
//$ std::cout << "Execution time : " << microseconds << " us" << std::endl;
return 0;
}
|
Revert farm_example
|
Revert farm_example
|
C++
|
apache-2.0
|
arcosuc3m/grppi,arcosuc3m/grppi
|
fb2d333a6fcf6b04acc0eee712dafacae850c919
|
agency/flattened_executor.hpp
|
agency/flattened_executor.hpp
|
#pragma once
#include <type_traits>
#include <agency/detail/tuple.hpp>
#include <agency/executor_traits.hpp>
#include <agency/execution_categories.hpp>
#include <agency/nested_executor.hpp>
#include <agency/detail/factory.hpp>
namespace agency
{
template<class Executor>
class flattened_executor
{
// probably shouldn't insist on a nested executor
static_assert(
detail::is_nested_execution_category<typename executor_traits<Executor>::execution_category>::value,
"Execution category of Executor must be nested."
);
public:
// XXX what is the execution category of a flattened executor?
using execution_category = parallel_execution_tag;
using base_executor_type = Executor;
// XXX maybe use whichever of the first two elements of base_executor_type::shape_type has larger dimensionality?
using shape_type = size_t;
template<class T>
using future = typename executor_traits<base_executor_type>::template future<T>;
future<void> make_ready_future()
{
return executor_traits<base_executor_type>::make_ready_future(base_executor());
}
flattened_executor(const base_executor_type& base_executor = base_executor_type())
: min_inner_size_(1000),
outer_subscription_(std::max(1u, log2(std::min(1u,std::thread::hardware_concurrency())))),
base_executor_(base_executor)
{}
template<class Function, class Future, class Factory>
future<void> then_execute(Function f, shape_type shape, Future& dependency, Factory shared_factory)
{
return this->then_execute_impl(base_executor(), dependency, f, shape, shared_factory);
}
const base_executor_type& base_executor() const
{
return base_executor_;
}
base_executor_type& base_executor()
{
return base_executor_;
}
private:
using partition_type = typename executor_traits<base_executor_type>::shape_type;
template<class Function>
struct then_execute_generic_functor
{
Function f;
shape_type shape;
partition_type partitioning;
template<class Index, class T>
void operator()(const Index& idx, T& outer_shared_param, const agency::detail::unit&)
{
auto flat_idx = agency::detail::get<0>(idx) * agency::detail::get<1>(partitioning) + agency::detail::get<1>(idx);
if(flat_idx < shape)
{
f(flat_idx, outer_shared_param);
}
}
template<class Index, class T1, class T2>
void operator()(const Index& idx, T1& past_shared_param, T2& outer_shared_param, const agency::detail::ignore_t&)
{
auto flat_idx = agency::detail::get<0>(idx) * agency::detail::get<1>(partitioning) + agency::detail::get<1>(idx);
if(flat_idx < shape)
{
f(flat_idx, past_shared_param, outer_shared_param);
}
}
};
template<class OtherExecutor, class Future, class Function, class Factory>
future<void> then_execute_impl(OtherExecutor& exec, Future& dependency, Function f, shape_type shape, Factory shared_factory)
{
auto partitioning = partition(shape);
return executor_traits<OtherExecutor>::then_execute(exec, then_execute_generic_functor<Function>{f, shape, partitioning}, partitioning, dependency, shared_factory, agency::detail::unit_factory());
}
template<class Function, class OuterExecutor, class InnerExecutor>
struct then_execute_nested_functor
{
nested_executor<OuterExecutor,InnerExecutor>& exec;
Function f;
shape_type shape;
partition_type partitioning;
template<class Index, class T>
void operator()(const Index& outer_idx, T& shared_param)
{
auto subgroup_begin = outer_idx * agency::detail::get<1>(partitioning);
auto subgroup_end = std::min(shape, subgroup_begin + agency::detail::get<1>(partitioning));
using inner_index_type = typename executor_traits<InnerExecutor>::index_type;
executor_traits<InnerExecutor>::execute(exec.inner_executor(), [=,&shared_param](const inner_index_type& inner_idx) mutable
{
auto index = subgroup_begin + inner_idx;
f(index, shared_param);
},
subgroup_end - subgroup_begin
);
}
template<class Index, class T1, class T2>
void operator()(const Index& outer_idx, T1& past_shared_param, T2& shared_param)
{
auto subgroup_begin = outer_idx * agency::detail::get<1>(partitioning);
auto subgroup_end = std::min(shape, subgroup_begin + agency::detail::get<1>(partitioning));
using inner_index_type = typename executor_traits<InnerExecutor>::index_type;
executor_traits<InnerExecutor>::execute(exec.inner_executor(), [=,&past_shared_param,&shared_param](const inner_index_type& inner_idx) mutable
{
auto index = subgroup_begin + inner_idx;
f(index, past_shared_param, shared_param);
},
subgroup_end - subgroup_begin
);
}
};
// we can avoid the if(flat_idx < shape) branch above by providing a specialization for nested_executor
template<class OuterExecutor, class InnerExecutor, class Function, class Future, class Factory>
future<void> then_execute_impl(nested_executor<OuterExecutor,InnerExecutor>& exec, Function f, shape_type shape, Future& dependency, Factory shared_factory)
{
auto partitioning = partition(shape);
return executor_traits<OuterExecutor>::then_execute(exec.outer_executor(),
then_execute_nested_functor<Function,OuterExecutor,InnerExecutor>{exec,f,shape,partitioning},
agency::detail::get<0>(partitioning),
dependency,
shared_factory);
}
// returns (outer size, inner size)
partition_type partition(shape_type shape) const
{
// avoid division by zero below
// XXX implement me!
// if(is_empty(shape)) return partition_type{};
using outer_shape_type = typename std::tuple_element<0,partition_type>::type;
using inner_shape_type = typename std::tuple_element<1,partition_type>::type;
outer_shape_type outer_size = (shape + min_inner_size_ - 1) / min_inner_size_;
outer_size = std::min<size_t>(outer_subscription_ * std::thread::hardware_concurrency(), outer_size);
inner_shape_type inner_size = (shape + outer_size - 1) / outer_size;
return partition_type{outer_size, inner_size};
}
inline static unsigned int log2(unsigned int x)
{
unsigned int result = 0;
while(x >>= 1) ++result;
return result;
}
size_t min_inner_size_;
size_t outer_subscription_;
base_executor_type base_executor_;
};
} // end agency
|
#pragma once
#include <type_traits>
#include <agency/detail/tuple.hpp>
#include <agency/executor_traits.hpp>
#include <agency/execution_categories.hpp>
#include <agency/nested_executor.hpp>
#include <agency/detail/factory.hpp>
namespace agency
{
template<class Executor>
class flattened_executor
{
// probably shouldn't insist on a nested executor
static_assert(
detail::is_nested_execution_category<typename executor_traits<Executor>::execution_category>::value,
"Execution category of Executor must be nested."
);
public:
// XXX what is the execution category of a flattened executor?
using execution_category = parallel_execution_tag;
using base_executor_type = Executor;
// XXX maybe use whichever of the first two elements of base_executor_type::shape_type has larger dimensionality?
using shape_type = size_t;
template<class T>
using future = typename executor_traits<base_executor_type>::template future<T>;
future<void> make_ready_future()
{
return executor_traits<base_executor_type>::make_ready_future(base_executor());
}
flattened_executor(const base_executor_type& base_executor = base_executor_type())
: min_inner_size_(1000),
outer_subscription_(std::max(1u, log2(std::max(1u,std::thread::hardware_concurrency())))),
base_executor_(base_executor)
{}
template<class Function, class Future, class Factory>
future<void> then_execute(Function f, shape_type shape, Future& dependency, Factory shared_factory)
{
return this->then_execute_impl(base_executor(), dependency, f, shape, shared_factory);
}
const base_executor_type& base_executor() const
{
return base_executor_;
}
base_executor_type& base_executor()
{
return base_executor_;
}
private:
using partition_type = typename executor_traits<base_executor_type>::shape_type;
template<class Function>
struct then_execute_generic_functor
{
Function f;
shape_type shape;
partition_type partitioning;
template<class Index, class T>
void operator()(const Index& idx, T& outer_shared_param, const agency::detail::unit&)
{
auto flat_idx = agency::detail::get<0>(idx) * agency::detail::get<1>(partitioning) + agency::detail::get<1>(idx);
if(flat_idx < shape)
{
f(flat_idx, outer_shared_param);
}
}
template<class Index, class T1, class T2>
void operator()(const Index& idx, T1& past_shared_param, T2& outer_shared_param, const agency::detail::ignore_t&)
{
auto flat_idx = agency::detail::get<0>(idx) * agency::detail::get<1>(partitioning) + agency::detail::get<1>(idx);
if(flat_idx < shape)
{
f(flat_idx, past_shared_param, outer_shared_param);
}
}
};
template<class OtherExecutor, class Future, class Function, class Factory>
future<void> then_execute_impl(OtherExecutor& exec, Future& dependency, Function f, shape_type shape, Factory shared_factory)
{
auto partitioning = partition(shape);
return executor_traits<OtherExecutor>::then_execute(exec, then_execute_generic_functor<Function>{f, shape, partitioning}, partitioning, dependency, shared_factory, agency::detail::unit_factory());
}
template<class Function, class OuterExecutor, class InnerExecutor>
struct then_execute_nested_functor
{
nested_executor<OuterExecutor,InnerExecutor>& exec;
Function f;
shape_type shape;
partition_type partitioning;
template<class Index, class T>
void operator()(const Index& outer_idx, T& shared_param)
{
auto subgroup_begin = outer_idx * agency::detail::get<1>(partitioning);
auto subgroup_end = std::min(shape, subgroup_begin + agency::detail::get<1>(partitioning));
using inner_index_type = typename executor_traits<InnerExecutor>::index_type;
executor_traits<InnerExecutor>::execute(exec.inner_executor(), [=,&shared_param](const inner_index_type& inner_idx) mutable
{
auto index = subgroup_begin + inner_idx;
f(index, shared_param);
},
subgroup_end - subgroup_begin
);
}
template<class Index, class T1, class T2>
void operator()(const Index& outer_idx, T1& past_shared_param, T2& shared_param)
{
auto subgroup_begin = outer_idx * agency::detail::get<1>(partitioning);
auto subgroup_end = std::min(shape, subgroup_begin + agency::detail::get<1>(partitioning));
using inner_index_type = typename executor_traits<InnerExecutor>::index_type;
executor_traits<InnerExecutor>::execute(exec.inner_executor(), [=,&past_shared_param,&shared_param](const inner_index_type& inner_idx) mutable
{
auto index = subgroup_begin + inner_idx;
f(index, past_shared_param, shared_param);
},
subgroup_end - subgroup_begin
);
}
};
// we can avoid the if(flat_idx < shape) branch above by providing a specialization for nested_executor
template<class OuterExecutor, class InnerExecutor, class Function, class Future, class Factory>
future<void> then_execute_impl(nested_executor<OuterExecutor,InnerExecutor>& exec, Function f, shape_type shape, Future& dependency, Factory shared_factory)
{
auto partitioning = partition(shape);
return executor_traits<OuterExecutor>::then_execute(exec.outer_executor(),
then_execute_nested_functor<Function,OuterExecutor,InnerExecutor>{exec,f,shape,partitioning},
agency::detail::get<0>(partitioning),
dependency,
shared_factory);
}
// returns (outer size, inner size)
partition_type partition(shape_type shape) const
{
// avoid division by zero below
// XXX implement me!
// if(is_empty(shape)) return partition_type{};
using outer_shape_type = typename std::tuple_element<0,partition_type>::type;
using inner_shape_type = typename std::tuple_element<1,partition_type>::type;
outer_shape_type outer_size = (shape + min_inner_size_ - 1) / min_inner_size_;
outer_size = std::min<size_t>(outer_subscription_ * std::thread::hardware_concurrency(), outer_size);
inner_shape_type inner_size = (shape + outer_size - 1) / outer_size;
return partition_type{outer_size, inner_size};
}
inline static unsigned int log2(unsigned int x)
{
unsigned int result = 0;
while(x >>= 1) ++result;
return result;
}
size_t min_inner_size_;
size_t outer_subscription_;
base_executor_type base_executor_;
};
} // end agency
|
Fix typo in outer_subscription_ calculation
|
Fix typo in outer_subscription_ calculation
|
C++
|
bsd-3-clause
|
egaburov/agency,egaburov/agency
|
e5c4379fbf8933860392a3b324c60b81fa55328b
|
content/browser/speech/speech_input_browsertest.cc
|
content/browser/speech/speech_input_browsertest.cc
|
// 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 "base/command_line.h"
#include "base/file_path.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/speech/speech_input_dispatcher_host.h"
#include "content/browser/speech/speech_input_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
namespace speech_input {
class FakeSpeechInputManager;
}
// This class does not need to be refcounted (typically done by PostTask) since
// it will outlive the test and gets released only when the test shuts down.
// Disabling refcounting here saves a bit of unnecessary code and the factory
// method can return a plain pointer below as required by the real code.
DISABLE_RUNNABLE_METHOD_REFCOUNT(speech_input::FakeSpeechInputManager);
namespace speech_input {
const char* kTestResult = "Pictures of the moon";
class FakeSpeechInputManager : public SpeechInputManager {
public:
FakeSpeechInputManager()
: caller_id_(0),
delegate_(NULL),
did_cancel_all_(false),
send_fake_response_(true) {
}
std::string grammar() {
return grammar_;
}
bool did_cancel_all() {
return did_cancel_all_;
}
void set_send_fake_response(bool send) {
send_fake_response_ = send;
}
// SpeechInputManager methods.
virtual void StartRecognition(Delegate* delegate,
int caller_id,
int render_process_id,
int render_view_id,
const gfx::Rect& element_rect,
const std::string& language,
const std::string& grammar,
const std::string& origin_url) {
VLOG(1) << "StartRecognition invoked.";
EXPECT_EQ(0, caller_id_);
EXPECT_EQ(NULL, delegate_);
caller_id_ = caller_id;
delegate_ = delegate;
grammar_ = grammar;
if (send_fake_response_) {
// Give the fake result in a short while.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&FakeSpeechInputManager::SetFakeRecognitionResult));
}
}
virtual void CancelRecognition(int caller_id) {
VLOG(1) << "CancelRecognition invoked.";
EXPECT_EQ(caller_id_, caller_id);
caller_id_ = 0;
delegate_ = NULL;
}
virtual void StopRecording(int caller_id) {
VLOG(1) << "StopRecording invoked.";
EXPECT_EQ(caller_id_, caller_id);
// Nothing to do here since we aren't really recording.
}
virtual void CancelAllRequestsWithDelegate(Delegate* delegate) {
VLOG(1) << "CancelAllRequestsWithDelegate invoked.";
// delegate_ is set to NULL if a fake result was received (see below), so
// check that delegate_ matches the incoming parameter only when there is
// no fake result sent.
EXPECT_TRUE(send_fake_response_ || delegate_ == delegate);
did_cancel_all_ = true;
}
private:
void SetFakeRecognitionResult() {
if (caller_id_) { // Do a check in case we were cancelled..
VLOG(1) << "Setting fake recognition result.";
delegate_->DidCompleteRecording(caller_id_);
SpeechInputResultArray results;
results.push_back(SpeechInputResultItem(ASCIIToUTF16(kTestResult), 1.0));
delegate_->SetRecognitionResult(caller_id_, results);
delegate_->DidCompleteRecognition(caller_id_);
caller_id_ = 0;
delegate_ = NULL;
VLOG(1) << "Finished setting fake recognition result.";
}
}
int caller_id_;
Delegate* delegate_;
std::string grammar_;
bool did_cancel_all_;
bool send_fake_response_;
};
class SpeechInputBrowserTest : public InProcessBrowserTest {
public:
// InProcessBrowserTest methods
virtual void SetUpCommandLine(CommandLine* command_line) {
EXPECT_TRUE(!command_line->HasSwitch(switches::kDisableSpeechInput));
}
GURL testUrl(const FilePath::CharType* filename) {
const FilePath kTestDir(FILE_PATH_LITERAL("speech"));
return ui_test_utils::GetTestUrl(kTestDir, FilePath(filename));
}
protected:
void LoadAndStartSpeechInputTest(const FilePath::CharType* filename) {
// The test page calculates the speech button's coordinate in the page on
// load & sets that coordinate in the URL fragment. We send mouse down & up
// events at that coordinate to trigger speech recognition.
GURL test_url = testUrl(filename);
ui_test_utils::NavigateToURL(browser(), test_url);
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 0;
mouse_event.y = 0;
mouse_event.clickCount = 1;
TabContents* tab_contents = browser()->GetSelectedTabContents();
tab_contents->render_view_host()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab_contents->render_view_host()->ForwardMouseEvent(mouse_event);
}
void RunSpeechInputTest(const FilePath::CharType* filename) {
LoadAndStartSpeechInputTest(filename);
// The fake speech input manager would receive the speech input
// request and return the test string as recognition result. The test page
// then sets the URL fragment as 'pass' if it received the expected string.
TabContents* tab_contents = browser()->GetSelectedTabContents();
ui_test_utils::WaitForNavigations(&tab_contents->controller(), 1);
EXPECT_EQ("pass", browser()->GetSelectedTabContents()->GetURL().ref());
}
// InProcessBrowserTest methods.
virtual void SetUpInProcessBrowserTestFixture() {
fake_speech_input_manager_.set_send_fake_response(true);
speech_input_manager_ = &fake_speech_input_manager_;
// Inject the fake manager factory so that the test result is returned to
// the web page.
SpeechInputDispatcherHost::set_manager_accessor(&fakeManagerAccessor);
}
virtual void TearDownInProcessBrowserTestFixture() {
speech_input_manager_ = NULL;
}
// Factory method.
static SpeechInputManager* fakeManagerAccessor() {
return speech_input_manager_;
}
FakeSpeechInputManager fake_speech_input_manager_;
// This is used by the static |fakeManagerAccessor|, and it is a pointer
// rather than a direct instance per the style guide.
static SpeechInputManager* speech_input_manager_;
};
SpeechInputManager* SpeechInputBrowserTest::speech_input_manager_ = NULL;
// Marked as DISABLED due to http://crbug.com/51337
//
// TODO(satish): Once this flakiness has been fixed, add a second test here to
// check for sending many clicks in succession to the speech button and verify
// that it doesn't cause any crash but works as expected. This should act as the
// test for http://crbug.com/59173
//
// TODO(satish): Similar to above, once this flakiness has been fixed add
// another test here to check that when speech recognition is in progress and
// a renderer crashes, we get a call to
// SpeechInputManager::CancelAllRequestsWithDelegate.
//
// Marked as DISABLED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_TestBasicRecognition DISABLED_TestBasicRecognition
#else
#define MAYBE_TestBasicRecognition TestBasicRecognition
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestBasicRecognition) {
RunSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
EXPECT_TRUE(fake_speech_input_manager_.grammar().empty());
}
// Marked as FLAKY due to http://crbug.com/51337
// Marked as DISALBED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_GrammarAttribute DISABLED_GrammarAttribute
#else
#define MAYBE_GrammarAttribute GrammarAttribute
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_GrammarAttribute) {
RunSpeechInputTest(FILE_PATH_LITERAL("grammar_attribute.html"));
EXPECT_EQ("http://example.com/grammar.xml",
fake_speech_input_manager_.grammar());
}
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, TestCancelAll) {
// The test checks that the cancel-all callback gets issued when a session
// is pending, so don't send a fake response.
fake_speech_input_manager_.set_send_fake_response(false);
LoadAndStartSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
// Make the renderer crash. This should trigger SpeechInputDispatcherHost to
// cancel all pending sessions.
GURL test_url("about:crash");
ui_test_utils::NavigateToURL(browser(), test_url);
EXPECT_TRUE(fake_speech_input_manager_.did_cancel_all());
}
} // namespace speech_input
|
// 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 "base/command_line.h"
#include "base/file_path.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/speech/speech_input_dispatcher_host.h"
#include "content/browser/speech/speech_input_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
namespace speech_input {
class FakeSpeechInputManager;
}
// This class does not need to be refcounted (typically done by PostTask) since
// it will outlive the test and gets released only when the test shuts down.
// Disabling refcounting here saves a bit of unnecessary code and the factory
// method can return a plain pointer below as required by the real code.
DISABLE_RUNNABLE_METHOD_REFCOUNT(speech_input::FakeSpeechInputManager);
namespace speech_input {
const char* kTestResult = "Pictures of the moon";
class FakeSpeechInputManager : public SpeechInputManager {
public:
FakeSpeechInputManager()
: caller_id_(0),
delegate_(NULL),
did_cancel_all_(false),
send_fake_response_(true) {
}
std::string grammar() {
return grammar_;
}
bool did_cancel_all() {
return did_cancel_all_;
}
void set_send_fake_response(bool send) {
send_fake_response_ = send;
}
// SpeechInputManager methods.
virtual void StartRecognition(Delegate* delegate,
int caller_id,
int render_process_id,
int render_view_id,
const gfx::Rect& element_rect,
const std::string& language,
const std::string& grammar,
const std::string& origin_url) {
VLOG(1) << "StartRecognition invoked.";
EXPECT_EQ(0, caller_id_);
EXPECT_EQ(NULL, delegate_);
caller_id_ = caller_id;
delegate_ = delegate;
grammar_ = grammar;
if (send_fake_response_) {
// Give the fake result in a short while.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&FakeSpeechInputManager::SetFakeRecognitionResult));
}
}
virtual void CancelRecognition(int caller_id) {
VLOG(1) << "CancelRecognition invoked.";
EXPECT_EQ(caller_id_, caller_id);
caller_id_ = 0;
delegate_ = NULL;
}
virtual void StopRecording(int caller_id) {
VLOG(1) << "StopRecording invoked.";
EXPECT_EQ(caller_id_, caller_id);
// Nothing to do here since we aren't really recording.
}
virtual void CancelAllRequestsWithDelegate(Delegate* delegate) {
VLOG(1) << "CancelAllRequestsWithDelegate invoked.";
// delegate_ is set to NULL if a fake result was received (see below), so
// check that delegate_ matches the incoming parameter only when there is
// no fake result sent.
EXPECT_TRUE(send_fake_response_ || delegate_ == delegate);
did_cancel_all_ = true;
}
private:
void SetFakeRecognitionResult() {
if (caller_id_) { // Do a check in case we were cancelled..
VLOG(1) << "Setting fake recognition result.";
delegate_->DidCompleteRecording(caller_id_);
SpeechInputResultArray results;
results.push_back(SpeechInputResultItem(ASCIIToUTF16(kTestResult), 1.0));
delegate_->SetRecognitionResult(caller_id_, results);
delegate_->DidCompleteRecognition(caller_id_);
caller_id_ = 0;
delegate_ = NULL;
VLOG(1) << "Finished setting fake recognition result.";
}
}
int caller_id_;
Delegate* delegate_;
std::string grammar_;
bool did_cancel_all_;
bool send_fake_response_;
};
class SpeechInputBrowserTest : public InProcessBrowserTest {
public:
// InProcessBrowserTest methods
virtual void SetUpCommandLine(CommandLine* command_line) {
EXPECT_TRUE(!command_line->HasSwitch(switches::kDisableSpeechInput));
}
GURL testUrl(const FilePath::CharType* filename) {
const FilePath kTestDir(FILE_PATH_LITERAL("speech"));
return ui_test_utils::GetTestUrl(kTestDir, FilePath(filename));
}
protected:
void LoadAndStartSpeechInputTest(const FilePath::CharType* filename) {
// The test page calculates the speech button's coordinate in the page on
// load & sets that coordinate in the URL fragment. We send mouse down & up
// events at that coordinate to trigger speech recognition.
GURL test_url = testUrl(filename);
ui_test_utils::NavigateToURL(browser(), test_url);
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 0;
mouse_event.y = 0;
mouse_event.clickCount = 1;
TabContents* tab_contents = browser()->GetSelectedTabContents();
tab_contents->render_view_host()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab_contents->render_view_host()->ForwardMouseEvent(mouse_event);
}
void RunSpeechInputTest(const FilePath::CharType* filename) {
LoadAndStartSpeechInputTest(filename);
// The fake speech input manager would receive the speech input
// request and return the test string as recognition result. The test page
// then sets the URL fragment as 'pass' if it received the expected string.
TabContents* tab_contents = browser()->GetSelectedTabContents();
ui_test_utils::WaitForNavigations(&tab_contents->controller(), 1);
EXPECT_EQ("pass", browser()->GetSelectedTabContents()->GetURL().ref());
}
// InProcessBrowserTest methods.
virtual void SetUpInProcessBrowserTestFixture() {
fake_speech_input_manager_.set_send_fake_response(true);
speech_input_manager_ = &fake_speech_input_manager_;
// Inject the fake manager factory so that the test result is returned to
// the web page.
SpeechInputDispatcherHost::set_manager_accessor(&fakeManagerAccessor);
}
virtual void TearDownInProcessBrowserTestFixture() {
speech_input_manager_ = NULL;
}
// Factory method.
static SpeechInputManager* fakeManagerAccessor() {
return speech_input_manager_;
}
FakeSpeechInputManager fake_speech_input_manager_;
// This is used by the static |fakeManagerAccessor|, and it is a pointer
// rather than a direct instance per the style guide.
static SpeechInputManager* speech_input_manager_;
};
SpeechInputManager* SpeechInputBrowserTest::speech_input_manager_ = NULL;
// Marked as DISABLED due to http://crbug.com/51337
//
// TODO(satish): Once this flakiness has been fixed, add a second test here to
// check for sending many clicks in succession to the speech button and verify
// that it doesn't cause any crash but works as expected. This should act as the
// test for http://crbug.com/59173
//
// TODO(satish): Similar to above, once this flakiness has been fixed add
// another test here to check that when speech recognition is in progress and
// a renderer crashes, we get a call to
// SpeechInputManager::CancelAllRequestsWithDelegate.
//
// Marked as DISABLED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_TestBasicRecognition DISABLED_TestBasicRecognition
#else
#define MAYBE_TestBasicRecognition TestBasicRecognition
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestBasicRecognition) {
RunSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
EXPECT_TRUE(fake_speech_input_manager_.grammar().empty());
}
// Marked as FLAKY due to http://crbug.com/51337
// Marked as DISALBED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_GrammarAttribute DISABLED_GrammarAttribute
#else
#define MAYBE_GrammarAttribute GrammarAttribute
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_GrammarAttribute) {
RunSpeechInputTest(FILE_PATH_LITERAL("grammar_attribute.html"));
EXPECT_EQ("http://example.com/grammar.xml",
fake_speech_input_manager_.grammar());
}
// Marked as DISABLED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_TestCancelAll DISABLED_TestCancelAll
#else
#define MAYBE_TestCancelAll TestCancelAll
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestCancelAll) {
// The test checks that the cancel-all callback gets issued when a session
// is pending, so don't send a fake response.
fake_speech_input_manager_.set_send_fake_response(false);
LoadAndStartSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
// Make the renderer crash. This should trigger SpeechInputDispatcherHost to
// cancel all pending sessions.
GURL test_url("about:crash");
ui_test_utils::NavigateToURL(browser(), test_url);
EXPECT_TRUE(fake_speech_input_manager_.did_cancel_all());
}
} // namespace speech_input
|
Disable the newly added SpeechInputBrowserTest.TestCancelAll in official release builds. This is done because the test times out in the official builders, just like the other SpeechInputBrowserTest.* tests.
|
Disable the newly added SpeechInputBrowserTest.TestCancelAll in official release builds.
This is done because the test times out in the official builders, just like the other
SpeechInputBrowserTest.* tests.
BUG=71227
TEST=TestCancelAll should not be run in official builders.
[email protected]
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@78827 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
cdf0e6219c58331d99c634bf54f774fb5088ce8b
|
ui/src/virtualconsole/vcproperties.cpp
|
ui/src/virtualconsole/vcproperties.cpp
|
/*
Q Light Controller Plus
vcproperties.cpp
Copyright (c) Heikki Junnila
Massimo Callegari
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.txt
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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QWidget>
#include <QDebug>
#include "qlcfile.h"
#include "virtualconsole.h"
#include "inputoutputmap.h"
#include "vcproperties.h"
#include "vcframe.h"
#include "doc.h"
/*****************************************************************************
* Properties Initialization
*****************************************************************************/
VCProperties::VCProperties()
: m_size(QSize(1920, 1080))
, m_gmChannelMode(GrandMaster::Intensity)
, m_gmValueMode(GrandMaster::Reduce)
, m_gmSliderMode(GrandMaster::Normal)
, m_gmInputUniverse(InputOutputMap::invalidUniverse())
, m_gmInputChannel(QLCChannel::invalid())
{
}
VCProperties::VCProperties(const VCProperties& properties)
: m_size(properties.m_size)
, m_gmChannelMode(properties.m_gmChannelMode)
, m_gmValueMode(properties.m_gmValueMode)
, m_gmSliderMode(properties.m_gmSliderMode)
, m_gmInputUniverse(properties.m_gmInputUniverse)
, m_gmInputChannel(properties.m_gmInputChannel)
{
}
VCProperties::~VCProperties()
{
}
VCProperties &VCProperties::operator=(const VCProperties &props)
{
if (this != &props)
{
m_size = props.size();
m_gmChannelMode = props.m_gmChannelMode;
m_gmValueMode = props.m_gmValueMode;
m_gmSliderMode = props.m_gmSliderMode;
m_gmInputUniverse = props.m_gmInputUniverse;
m_gmInputChannel = props.m_gmInputChannel;
}
return *this;
}
/*****************************************************************************
* Size
*****************************************************************************/
void VCProperties::setSize(const QSize& size)
{
m_size = size;
}
QSize VCProperties::size() const
{
return m_size;
}
/*****************************************************************************
* Grand Master
*****************************************************************************/
void VCProperties::setGrandMasterChannelMode(GrandMaster::ChannelMode mode)
{
m_gmChannelMode = mode;
}
GrandMaster::ChannelMode VCProperties::grandMasterChannelMode() const
{
return m_gmChannelMode;
}
void VCProperties::setGrandMasterValueMode(GrandMaster::ValueMode mode)
{
m_gmValueMode = mode;
}
GrandMaster::ValueMode VCProperties::grandMasterValueMode() const
{
return m_gmValueMode;
}
void VCProperties::setGrandMasterSliderMode(GrandMaster::SliderMode mode)
{
m_gmSliderMode = mode;
}
GrandMaster::SliderMode VCProperties::grandMasterSlideMode() const
{
return m_gmSliderMode;
}
void VCProperties::setGrandMasterInputSource(quint32 universe, quint32 channel)
{
m_gmInputUniverse = universe;
m_gmInputChannel = channel;
}
quint32 VCProperties::grandMasterInputUniverse() const
{
return m_gmInputUniverse;
}
quint32 VCProperties::grandMasterInputChannel() const
{
return m_gmInputChannel;
}
/*****************************************************************************
* Load & Save
*****************************************************************************/
bool VCProperties::loadXML(QXmlStreamReader &root)
{
if (root.name() != KXMLQLCVCProperties)
{
qWarning() << Q_FUNC_INFO << "Virtual console properties node not found";
return false;
}
QString str;
while (root.readNextStartElement())
{
if (root.name() == KXMLQLCVCPropertiesSize)
{
QSize sz;
/* Width */
str = root.attributes().value(KXMLQLCVCPropertiesSizeWidth).toString();
if (str.isEmpty() == false)
sz.setWidth(str.toInt());
/* Height */
str = root.attributes().value(KXMLQLCVCPropertiesSizeHeight).toString();
if (str.isEmpty() == false)
sz.setHeight(str.toInt());
/* Set size if both are valid */
if (sz.isValid() == true)
setSize(sz);
root.skipCurrentElement();
}
else if (root.name() == KXMLQLCVCPropertiesGrandMaster)
{
QXmlStreamAttributes attrs = root.attributes();
str = attrs.value(KXMLQLCVCPropertiesGrandMasterChannelMode).toString();
setGrandMasterChannelMode(GrandMaster::stringToChannelMode(str));
str = attrs.value(KXMLQLCVCPropertiesGrandMasterValueMode).toString();
setGrandMasterValueMode(GrandMaster::stringToValueMode(str));
if (attrs.hasAttribute(KXMLQLCVCPropertiesGrandMasterSliderMode))
{
str = attrs.value(KXMLQLCVCPropertiesGrandMasterSliderMode).toString();
setGrandMasterSliderMode(GrandMaster::stringToSliderMode(str));
}
QXmlStreamReader::TokenType tType = root.readNext();
if (tType == QXmlStreamReader::Characters)
tType = root.readNext();
// check if there is a Input tag defined
if (tType == QXmlStreamReader::StartElement)
{
if (root.name() == KXMLQLCVCPropertiesInput)
{
quint32 universe = InputOutputMap::invalidUniverse();
quint32 channel = QLCChannel::invalid();
/* External input */
if (loadXMLInput(root, &universe, &channel) == true)
setGrandMasterInputSource(universe, channel);
}
root.skipCurrentElement();
}
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown virtual console property tag:"
<< root.name().toString();
root.skipCurrentElement();
}
}
return true;
}
bool VCProperties::saveXML(QXmlStreamWriter *doc) const
{
Q_ASSERT(doc != NULL);
/* Properties entry */
doc->writeStartElement(KXMLQLCVCProperties);
/* Size */
doc->writeStartElement(KXMLQLCVCPropertiesSize);
doc->writeAttribute(KXMLQLCVCPropertiesSizeWidth, QString::number(size().width()));
doc->writeAttribute(KXMLQLCVCPropertiesSizeHeight, QString::number(size().height()));
doc->writeEndElement();
/***********************
* Grand Master slider *
***********************/
doc->writeStartElement(KXMLQLCVCPropertiesGrandMaster);
/* Channel mode */
doc->writeAttribute(KXMLQLCVCPropertiesGrandMasterChannelMode,
GrandMaster::channelModeToString(m_gmChannelMode));
/* Value mode */
doc->writeAttribute(KXMLQLCVCPropertiesGrandMasterValueMode,
GrandMaster::valueModeToString(m_gmValueMode));
/* Slider mode */
doc->writeAttribute(KXMLQLCVCPropertiesGrandMasterSliderMode,
GrandMaster::sliderModeToString(m_gmSliderMode));
/* Grand Master external input */
if (m_gmInputUniverse != InputOutputMap::invalidUniverse() &&
m_gmInputChannel != QLCChannel::invalid())
{
doc->writeStartElement(KXMLQLCVCPropertiesInput);
doc->writeAttribute(KXMLQLCVCPropertiesInputUniverse,
QString("%1").arg(m_gmInputUniverse));
doc->writeAttribute(KXMLQLCVCPropertiesInputChannel,
QString("%1").arg(m_gmInputChannel));
doc->writeEndElement();
}
/* End the <GrandMaster> tag */
doc->writeEndElement();
/* End the <Properties> tag */
doc->writeEndElement();
return true;
}
bool VCProperties::loadXMLInput(QXmlStreamReader &root, quint32* universe, quint32* channel)
{
/* External input */
if (root.name() != KXMLQLCVCPropertiesInput)
return false;
QXmlStreamAttributes attrs = root.attributes();
/* Universe */
QString str = attrs.value(KXMLQLCVCPropertiesInputUniverse).toString();
if (str.isEmpty() == false)
*universe = str.toUInt();
else
*universe = InputOutputMap::invalidUniverse();
/* Channel */
str = attrs.value(KXMLQLCVCPropertiesInputChannel).toString();
if (str.isEmpty() == false)
*channel = str.toUInt();
else
*channel = QLCChannel::invalid();
root.skipCurrentElement();
/* Verdict */
if (*universe != InputOutputMap::invalidUniverse() &&
*channel != QLCChannel::invalid())
{
return true;
}
else
{
return false;
}
}
|
/*
Q Light Controller Plus
vcproperties.cpp
Copyright (c) Heikki Junnila
Massimo Callegari
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.txt
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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QWidget>
#include <QDebug>
#include "qlcfile.h"
#include "virtualconsole.h"
#include "inputoutputmap.h"
#include "vcproperties.h"
#include "vcframe.h"
#include "doc.h"
/*****************************************************************************
* Properties Initialization
*****************************************************************************/
VCProperties::VCProperties()
: m_size(QSize(1920, 1080))
, m_gmChannelMode(GrandMaster::Intensity)
, m_gmValueMode(GrandMaster::Reduce)
, m_gmSliderMode(GrandMaster::Normal)
, m_gmInputUniverse(InputOutputMap::invalidUniverse())
, m_gmInputChannel(QLCChannel::invalid())
{
}
VCProperties::VCProperties(const VCProperties& properties)
: m_size(properties.m_size)
, m_gmChannelMode(properties.m_gmChannelMode)
, m_gmValueMode(properties.m_gmValueMode)
, m_gmSliderMode(properties.m_gmSliderMode)
, m_gmInputUniverse(properties.m_gmInputUniverse)
, m_gmInputChannel(properties.m_gmInputChannel)
{
}
VCProperties::~VCProperties()
{
}
VCProperties &VCProperties::operator=(const VCProperties &props)
{
if (this != &props)
{
m_size = props.m_size;
m_gmChannelMode = props.m_gmChannelMode;
m_gmValueMode = props.m_gmValueMode;
m_gmSliderMode = props.m_gmSliderMode;
m_gmInputUniverse = props.m_gmInputUniverse;
m_gmInputChannel = props.m_gmInputChannel;
}
return *this;
}
/*****************************************************************************
* Size
*****************************************************************************/
void VCProperties::setSize(const QSize& size)
{
m_size = size;
}
QSize VCProperties::size() const
{
return m_size;
}
/*****************************************************************************
* Grand Master
*****************************************************************************/
void VCProperties::setGrandMasterChannelMode(GrandMaster::ChannelMode mode)
{
m_gmChannelMode = mode;
}
GrandMaster::ChannelMode VCProperties::grandMasterChannelMode() const
{
return m_gmChannelMode;
}
void VCProperties::setGrandMasterValueMode(GrandMaster::ValueMode mode)
{
m_gmValueMode = mode;
}
GrandMaster::ValueMode VCProperties::grandMasterValueMode() const
{
return m_gmValueMode;
}
void VCProperties::setGrandMasterSliderMode(GrandMaster::SliderMode mode)
{
m_gmSliderMode = mode;
}
GrandMaster::SliderMode VCProperties::grandMasterSlideMode() const
{
return m_gmSliderMode;
}
void VCProperties::setGrandMasterInputSource(quint32 universe, quint32 channel)
{
m_gmInputUniverse = universe;
m_gmInputChannel = channel;
}
quint32 VCProperties::grandMasterInputUniverse() const
{
return m_gmInputUniverse;
}
quint32 VCProperties::grandMasterInputChannel() const
{
return m_gmInputChannel;
}
/*****************************************************************************
* Load & Save
*****************************************************************************/
bool VCProperties::loadXML(QXmlStreamReader &root)
{
if (root.name() != KXMLQLCVCProperties)
{
qWarning() << Q_FUNC_INFO << "Virtual console properties node not found";
return false;
}
QString str;
while (root.readNextStartElement())
{
if (root.name() == KXMLQLCVCPropertiesSize)
{
QSize sz;
/* Width */
str = root.attributes().value(KXMLQLCVCPropertiesSizeWidth).toString();
if (str.isEmpty() == false)
sz.setWidth(str.toInt());
/* Height */
str = root.attributes().value(KXMLQLCVCPropertiesSizeHeight).toString();
if (str.isEmpty() == false)
sz.setHeight(str.toInt());
/* Set size if both are valid */
if (sz.isValid() == true)
setSize(sz);
root.skipCurrentElement();
}
else if (root.name() == KXMLQLCVCPropertiesGrandMaster)
{
QXmlStreamAttributes attrs = root.attributes();
str = attrs.value(KXMLQLCVCPropertiesGrandMasterChannelMode).toString();
setGrandMasterChannelMode(GrandMaster::stringToChannelMode(str));
str = attrs.value(KXMLQLCVCPropertiesGrandMasterValueMode).toString();
setGrandMasterValueMode(GrandMaster::stringToValueMode(str));
if (attrs.hasAttribute(KXMLQLCVCPropertiesGrandMasterSliderMode))
{
str = attrs.value(KXMLQLCVCPropertiesGrandMasterSliderMode).toString();
setGrandMasterSliderMode(GrandMaster::stringToSliderMode(str));
}
QXmlStreamReader::TokenType tType = root.readNext();
if (tType == QXmlStreamReader::Characters)
tType = root.readNext();
// check if there is a Input tag defined
if (tType == QXmlStreamReader::StartElement)
{
if (root.name() == KXMLQLCVCPropertiesInput)
{
quint32 universe = InputOutputMap::invalidUniverse();
quint32 channel = QLCChannel::invalid();
/* External input */
if (loadXMLInput(root, &universe, &channel) == true)
setGrandMasterInputSource(universe, channel);
}
root.skipCurrentElement();
}
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown virtual console property tag:"
<< root.name().toString();
root.skipCurrentElement();
}
}
return true;
}
bool VCProperties::saveXML(QXmlStreamWriter *doc) const
{
Q_ASSERT(doc != NULL);
/* Properties entry */
doc->writeStartElement(KXMLQLCVCProperties);
/* Size */
doc->writeStartElement(KXMLQLCVCPropertiesSize);
doc->writeAttribute(KXMLQLCVCPropertiesSizeWidth, QString::number(size().width()));
doc->writeAttribute(KXMLQLCVCPropertiesSizeHeight, QString::number(size().height()));
doc->writeEndElement();
/***********************
* Grand Master slider *
***********************/
doc->writeStartElement(KXMLQLCVCPropertiesGrandMaster);
/* Channel mode */
doc->writeAttribute(KXMLQLCVCPropertiesGrandMasterChannelMode,
GrandMaster::channelModeToString(m_gmChannelMode));
/* Value mode */
doc->writeAttribute(KXMLQLCVCPropertiesGrandMasterValueMode,
GrandMaster::valueModeToString(m_gmValueMode));
/* Slider mode */
doc->writeAttribute(KXMLQLCVCPropertiesGrandMasterSliderMode,
GrandMaster::sliderModeToString(m_gmSliderMode));
/* Grand Master external input */
if (m_gmInputUniverse != InputOutputMap::invalidUniverse() &&
m_gmInputChannel != QLCChannel::invalid())
{
doc->writeStartElement(KXMLQLCVCPropertiesInput);
doc->writeAttribute(KXMLQLCVCPropertiesInputUniverse,
QString("%1").arg(m_gmInputUniverse));
doc->writeAttribute(KXMLQLCVCPropertiesInputChannel,
QString("%1").arg(m_gmInputChannel));
doc->writeEndElement();
}
/* End the <GrandMaster> tag */
doc->writeEndElement();
/* End the <Properties> tag */
doc->writeEndElement();
return true;
}
bool VCProperties::loadXMLInput(QXmlStreamReader &root, quint32* universe, quint32* channel)
{
/* External input */
if (root.name() != KXMLQLCVCPropertiesInput)
return false;
QXmlStreamAttributes attrs = root.attributes();
/* Universe */
QString str = attrs.value(KXMLQLCVCPropertiesInputUniverse).toString();
if (str.isEmpty() == false)
*universe = str.toUInt();
else
*universe = InputOutputMap::invalidUniverse();
/* Channel */
str = attrs.value(KXMLQLCVCPropertiesInputChannel).toString();
if (str.isEmpty() == false)
*channel = str.toUInt();
else
*channel = QLCChannel::invalid();
root.skipCurrentElement();
/* Verdict */
if (*universe != InputOutputMap::invalidUniverse() &&
*channel != QLCChannel::invalid())
{
return true;
}
else
{
return false;
}
}
|
improve the previous commit
|
ui: improve the previous commit
|
C++
|
apache-2.0
|
kripton/qlcplus,plugz/qlcplus,kripton/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,sbenejam/qlcplus,kripton/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,plugz/qlcplus,plugz/qlcplus,mcallegari/qlcplus,sbenejam/qlcplus,kripton/qlcplus,mcallegari/qlcplus,plugz/qlcplus,kripton/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,mcallegari/qlcplus,plugz/qlcplus,plugz/qlcplus,mcallegari/qlcplus,plugz/qlcplus,sbenejam/qlcplus,sbenejam/qlcplus,kripton/qlcplus,kripton/qlcplus
|
33df9715c43163344c3f171c627cbe0ba6e941eb
|
src/import/generic/memory/lib/utils/mss_field.H
|
src/import/generic/memory/lib/utils/mss_field.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/mss_field.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_field.H
/// @brief API for data fields and operations
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Louis Stermole <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_FIELD_H_
#define _MSS_FIELD_H_
#ifdef __PPE__
#include <mss_generic_check.H>
#else
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mss_generic_check.H>
#endif
// reused TARGTID & TARGTIDFORMAT macro defined in generic/memory/lib/utils/mss_generic_check.H
namespace mss
{
///
/// @brief endian fields for use as a template selecor
///
enum class endian
{
BIG,
LITTLE,
};
///
/// @class field_t
/// @brief data structure for byte fields
/// @tparam E endian type for this field
/// @note holds byte index, start bit, and bit length of a decoded field
///
template< endian E >
class field_t
{
private:
const size_t iv_byte;
const size_t iv_start;
const size_t iv_length;
public:
// default ctor deleted
field_t() = delete;
///
/// @brief ctor
/// @param[in] i_byte_index
/// @param[in] i_start_bit
/// @param[in] i_bit_length
///
constexpr field_t(const size_t i_byte_index,
const size_t i_start_bit,
const size_t i_bit_length)
: iv_byte(i_byte_index),
iv_start(i_start_bit),
iv_length(i_bit_length)
{}
///
/// @brief default dtor
///
~field_t() = default;
///
/// @brief Byte index getter
/// @return the byte index for this field
///
const size_t get_byte(const std::vector<uint8_t>& i_data) const;
///
/// @brief Starting bit getter
/// @return the starting bit position for this field
///
constexpr size_t get_start() const
{
return iv_start;
}
///
/// @brief bit length getter
/// @return the bit length of this field
///
constexpr size_t get_length() const
{
return iv_length;
}
};// field_t
///
/// @brief Byte index getter - big endian specialization
/// @return the byte index for this field
///
template<>
inline const size_t field_t<mss::endian::BIG>::get_byte(const std::vector<uint8_t>& i_data) const
{
return ( i_data.size() - 1 ) - iv_byte;
}
///
/// @brief Byte index getter - big endian specialization
/// @return the byte index for this field
///
template<>
inline const size_t field_t<mss::endian::LITTLE>::get_byte(const std::vector<uint8_t>& i_data) const
{
return iv_byte;
}
///
/// @brief Checks input field against a custom conditional
/// @tparam T field input type
/// @tparam F Callable object type
/// @param[in] i_field Extracted field
/// @param[in] i_comparison_val value we are comparing against
/// @param[in] i_op comparison operator function object
/// @return boolean true or false
///
template < typename T, typename F >
inline bool conditional(const T i_field,
const size_t i_comparison_val,
const F i_op)
{
return i_op(i_field, i_comparison_val);
}
///
/// @brief Helper function to extract byte information
/// @tparam E endian type
/// @tparam F the field to extract
/// @tparam T the fapi2 target type
/// @tparam OT output type
/// @tparam FFDC ffdc code type
/// @param[in] i_target the fapi2 target
/// @param[in] i_data the data
/// @param[in] i_ffdc_codes FFDC code
/// @param[out] o_value raw value for this field
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
fapi2::TargetType T,
typename OT,
typename FFDC >
inline fapi2::ReturnCode get_field(const fapi2::Target<T>& i_target,
const std::vector<uint8_t>& i_data,
const FFDC i_ffdc_codes,
OT& o_value)
{
const size_t BYTE = F.get_byte(i_data);
FAPI_TRY(check::index_within_bounds(i_target, BYTE, i_data.size(), i_ffdc_codes));
{
// clear out stale state
o_value = 0;
// Extracting desired bits
// API enforces uint8_t vector data, so no conversion check needed to uint8_t buffer
fapi2::buffer<uint8_t>(i_data[BYTE]).extractToRight<F.get_start(), F.get_length()>(o_value);
FAPI_DBG(TARGTIDFORMAT " data[%d] = 0x%02x. Field with start bit %d, bit len %d, has data 0x%02x.",
TARGTID,
BYTE,
i_data[BYTE],
F.get_start(),
F.get_length(),
o_value);
}
fapi_try_exit:
return fapi2::current_err;
}
#ifndef __PPE__
///
/// @brief Helper function to set byte field information
/// @tparam E endian type
/// @tparam F the field to extract
/// @tparam T the fapi2 target type
/// @tparam IT input type
/// @tparam FFDC ffdc code type
/// @param[in] i_target the fapi2 target
/// @param[in] i_setting the setting to set
/// @param[in] i_ffdc_codes FFDC code
/// @param[in,out] io_data the data to modify
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
fapi2::TargetType T,
typename IT,
typename FFDC >
inline fapi2::ReturnCode set_field(const fapi2::Target<T>& i_target,
const IT i_setting,
const FFDC i_ffdc_codes,
std::vector<uint8_t>& io_data)
{
const size_t BYTE = F.get_byte(io_data);
FAPI_TRY(check::index_within_bounds(i_target, BYTE, io_data.size(), i_ffdc_codes));
FAPI_TRY(check::invalid_type_conversion<uint8_t>(i_target, i_setting, i_ffdc_codes));
{
// Insert desired setting
fapi2::buffer<uint8_t> l_buffer(io_data[BYTE]);
l_buffer.template insertFromRight<F.get_start(), F.get_length()>(i_setting);
// Safe to set since no implicit conversion errors will occur here
io_data[BYTE] = l_buffer;
}
FAPI_DBG("%s data[%d] = 0x%02x. Field with start bit %d, bit len %d, has data 0x%02x.",
spd::c_str(i_target),
BYTE,
io_data[BYTE],
F.get_start(),
F.get_length(),
i_setting);
fapi_try_exit:
return fapi2::current_err;
}
#endif
///
/// @brief byte field reader
/// @tparam E endian type
/// @tparam F the byte field to read
/// @tparam TT traits associated with F - required
/// @tparam T the fapi2 target type
/// @param[in] i_target the dimm target
/// @param[in] i_data the data
/// @param[in] i_ffdc_codes FFDC code
/// @param[out] o_value raw value for this field
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
typename TT,
fapi2::TargetType T,
typename OT,
typename FFDC >
inline fapi2::ReturnCode get_field( const fapi2::Target<T>& i_target,
const std::vector<uint8_t>& i_data,
const FFDC i_ffdc_codes,
OT& o_value )
{
uint8_t l_temp = 0;
FAPI_TRY( (get_field<E, F>(i_target, i_data, i_ffdc_codes, l_temp)),
"Failed get_field() for " TARGTIDFORMAT, TARGTID );
// Test if retrieved data seems valid
FAPI_TRY( check::invalid_value(i_target,
conditional( l_temp,
TT::COMPARISON_VAL,
typename TT::template COMPARISON_OP<uint8_t>() ),
F.get_byte(i_data),
l_temp,
i_ffdc_codes,
TT::FIELD_STR),
"%s failed check::invalid_value() for %s",
TT::FIELD_STR, spd::c_str(i_target) );
// Implicit (possible) promotion during conversion is safe
o_value = static_cast<OT>(l_temp);
FAPI_DBG("%s: 0x%02x for %s",
TT::FIELD_STR,
o_value,
spd::c_str(i_target));
fapi_try_exit:
return fapi2::current_err;
}
#ifndef __PPE__
///
/// @brief byte field writer
/// @tparam E endian type
/// @tparam F the byte field to read
/// @tparam TT traits associated with writer
/// @tparam T the fapi2 target type
/// @tparam IT input type
/// @tparam FFDC ffdc code type
/// @param[in] i_target the dimm target
/// @param[in] i_setting value to set for field
/// @param[in] i_ffdc_codes FFDC code
/// @param[in,out] io_data the data to modify
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
typename TT,
fapi2::TargetType T,
typename IT,
typename FFDC >
inline fapi2::ReturnCode set_field( const fapi2::Target<T>& i_target,
const IT i_setting,
const FFDC i_ffdc_codes,
std::vector<uint8_t>& io_data )
{
const size_t BYTE = F.get_byte(io_data);
// Test if the data we want to set is valid for this field
FAPI_TRY( check::invalid_value(i_target,
conditional( i_setting,
TT::COMPARISON_VAL,
typename TT::template COMPARISON_OP<IT>() ),
BYTE,
i_setting,
i_ffdc_codes),
"Failed fail_for_invalid_value() for %s", spd::c_str(i_target) );
FAPI_TRY( (set_field<E, F>(i_target, i_setting, i_ffdc_codes, io_data)),
"Failed set_field() for %s", spd::c_str(i_target) );
FAPI_DBG("%s: Set value of 0x%02x. Data for buffer at byte %d, is now 0x%02x for %s",
TT::FIELD_STR,
i_setting,
BYTE,
io_data[BYTE],
spd::c_str(i_target));
fapi_try_exit:
return fapi2::current_err;
}
#endif // PPE
}// mss
#endif // include guard
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/mss_field.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_field.H
/// @brief API for data fields and operations
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Louis Stermole <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_FIELD_H_
#define _MSS_FIELD_H_
#ifdef __PPE__
#include <mss_generic_check.H>
#else
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mss_generic_check.H>
#endif
// reused TARGTID & TARGTIDFORMAT macro defined in generic/memory/lib/utils/mss_generic_check.H
namespace mss
{
///
/// @brief endian fields for use as a template selecor
///
enum class endian
{
BIG,
LITTLE,
};
///
/// @class field_t
/// @brief data structure for byte fields
/// @tparam E endian type for this field
/// @note holds byte index, start bit, and bit length of a decoded field
///
template< endian E >
class field_t
{
private:
const size_t iv_byte;
const size_t iv_start;
const size_t iv_length;
public:
// default ctor deleted
field_t() = delete;
///
/// @brief ctor
/// @param[in] i_byte_index
/// @param[in] i_start_bit
/// @param[in] i_bit_length
///
constexpr field_t(const size_t i_byte_index,
const size_t i_start_bit,
const size_t i_bit_length)
: iv_byte(i_byte_index),
iv_start(i_start_bit),
iv_length(i_bit_length)
{}
///
/// @brief default dtor
///
~field_t() = default;
///
/// @brief Byte index getter
/// @return the byte index for this field
///
const size_t get_byte(const std::vector<uint8_t>& i_data) const;
///
/// @brief Starting bit getter
/// @return the starting bit position for this field
///
constexpr size_t get_start() const
{
return iv_start;
}
///
/// @brief bit length getter
/// @return the bit length of this field
///
constexpr size_t get_length() const
{
return iv_length;
}
};// field_t
///
/// @brief Byte index getter - big endian specialization
/// @return the byte index for this field
///
template<>
inline const size_t field_t<mss::endian::BIG>::get_byte(const std::vector<uint8_t>& i_data) const
{
return ( i_data.size() - 1 ) - iv_byte;
}
///
/// @brief Byte index getter - big endian specialization
/// @return the byte index for this field
///
template<>
inline const size_t field_t<mss::endian::LITTLE>::get_byte(const std::vector<uint8_t>& i_data) const
{
return iv_byte;
}
///
/// @brief Checks input field against a custom conditional
/// @tparam T field input type
/// @tparam F Callable object type
/// @param[in] i_field Extracted field
/// @param[in] i_comparison_val value we are comparing against
/// @param[in] i_op comparison operator function object
/// @return boolean true or false
///
template < typename T, typename F >
inline bool conditional(const T i_field,
const size_t i_comparison_val,
const F i_op)
{
return i_op(i_field, i_comparison_val);
}
///
/// @brief Helper function to extract byte information
/// @tparam E endian type
/// @tparam F the field to extract
/// @tparam T the fapi2 target type
/// @tparam OT output type
/// @tparam FFDC ffdc code type
/// @param[in] i_target the fapi2 target
/// @param[in] i_data the data
/// @param[in] i_ffdc_codes FFDC code
/// @param[out] o_value raw value for this field
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
fapi2::TargetType T,
typename OT,
typename FFDC >
inline fapi2::ReturnCode get_field(const fapi2::Target<T>& i_target,
const std::vector<uint8_t>& i_data,
const FFDC i_ffdc_codes,
OT& o_value)
{
const size_t BYTE = F.get_byte(i_data);
FAPI_TRY(check::index_within_bounds(i_target, BYTE, i_data.size(), i_ffdc_codes));
{
// clear out stale state
o_value = 0;
// Extracting desired bits
// API enforces uint8_t vector data, so no conversion check needed to uint8_t buffer
fapi2::buffer<uint8_t>(i_data[BYTE]).extractToRight<F.get_start(), F.get_length()>(o_value);
#ifndef __PPE__
FAPI_DBG(TARGTIDFORMAT " data[%d] = 0x%02x. Field with start bit %d, bit len %d, has data 0x%02x.",
TARGTID,
BYTE,
i_data[BYTE],
F.get_start(),
F.get_length(),
o_value);
#endif
}
fapi_try_exit:
return fapi2::current_err;
}
#ifndef __PPE__
///
/// @brief Helper function to set byte field information
/// @tparam E endian type
/// @tparam F the field to extract
/// @tparam T the fapi2 target type
/// @tparam IT input type
/// @tparam FFDC ffdc code type
/// @param[in] i_target the fapi2 target
/// @param[in] i_setting the setting to set
/// @param[in] i_ffdc_codes FFDC code
/// @param[in,out] io_data the data to modify
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
fapi2::TargetType T,
typename IT,
typename FFDC >
inline fapi2::ReturnCode set_field(const fapi2::Target<T>& i_target,
const IT i_setting,
const FFDC i_ffdc_codes,
std::vector<uint8_t>& io_data)
{
const size_t BYTE = F.get_byte(io_data);
FAPI_TRY(check::index_within_bounds(i_target, BYTE, io_data.size(), i_ffdc_codes));
FAPI_TRY(check::invalid_type_conversion<uint8_t>(i_target, i_setting, i_ffdc_codes));
{
// Insert desired setting
fapi2::buffer<uint8_t> l_buffer(io_data[BYTE]);
l_buffer.template insertFromRight<F.get_start(), F.get_length()>(i_setting);
// Safe to set since no implicit conversion errors will occur here
io_data[BYTE] = l_buffer;
}
FAPI_DBG("%s data[%d] = 0x%02x. Field with start bit %d, bit len %d, has data 0x%02x.",
spd::c_str(i_target),
BYTE,
io_data[BYTE],
F.get_start(),
F.get_length(),
i_setting);
fapi_try_exit:
return fapi2::current_err;
}
#endif // PPE
///
/// @brief byte field reader
/// @tparam E endian type
/// @tparam F the byte field to read
/// @tparam TT traits associated with F - required
/// @tparam T the fapi2 target type
/// @param[in] i_target the dimm target
/// @param[in] i_data the data
/// @param[in] i_ffdc_codes FFDC code
/// @param[out] o_value raw value for this field
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
typename TT,
fapi2::TargetType T,
typename OT,
typename FFDC >
inline fapi2::ReturnCode get_field( const fapi2::Target<T>& i_target,
const std::vector<uint8_t>& i_data,
const FFDC i_ffdc_codes,
OT& o_value )
{
uint8_t l_temp = 0;
FAPI_TRY( (get_field<E, F>(i_target, i_data, i_ffdc_codes, l_temp)),
"Failed get_field() for " TARGTIDFORMAT, TARGTID );
// Test if retrieved data seems valid
FAPI_TRY( check::invalid_value(i_target,
conditional( l_temp,
TT::COMPARISON_VAL,
typename TT::template COMPARISON_OP<uint8_t>() ),
F.get_byte(i_data),
l_temp,
i_ffdc_codes,
TT::FIELD_STR),
"%s failed check::invalid_value() for %s",
TT::FIELD_STR, spd::c_str(i_target) );
// Implicit (possible) promotion during conversion is safe
o_value = static_cast<OT>(l_temp);
#ifndef __PPE__
FAPI_DBG("%s: 0x%02x for %s",
TT::FIELD_STR,
o_value,
spd::c_str(i_target));
#endif
fapi_try_exit:
return fapi2::current_err;
}
#ifndef __PPE__
///
/// @brief byte field writer
/// @tparam E endian type
/// @tparam F the byte field to read
/// @tparam TT traits associated with writer
/// @tparam T the fapi2 target type
/// @tparam IT input type
/// @tparam FFDC ffdc code type
/// @param[in] i_target the dimm target
/// @param[in] i_setting value to set for field
/// @param[in] i_ffdc_codes FFDC code
/// @param[in,out] io_data the data to modify
/// @return FAPI2_RC_SUCCESS iff okay
///
template< mss::endian E,
const mss::field_t<E>& F,
typename TT,
fapi2::TargetType T,
typename IT,
typename FFDC >
inline fapi2::ReturnCode set_field( const fapi2::Target<T>& i_target,
const IT i_setting,
const FFDC i_ffdc_codes,
std::vector<uint8_t>& io_data )
{
const size_t BYTE = F.get_byte(io_data);
// Test if the data we want to set is valid for this field
FAPI_TRY( check::invalid_value(i_target,
conditional( i_setting,
TT::COMPARISON_VAL,
typename TT::template COMPARISON_OP<IT>() ),
BYTE,
i_setting,
i_ffdc_codes),
"Failed fail_for_invalid_value() for %s", spd::c_str(i_target) );
FAPI_TRY( (set_field<E, F>(i_target, i_setting, i_ffdc_codes, io_data)),
"Failed set_field() for %s", spd::c_str(i_target) );
FAPI_DBG("%s: Set value of 0x%02x. Data for buffer at byte %d, is now 0x%02x for %s",
TT::FIELD_STR,
i_setting,
BYTE,
io_data[BYTE],
spd::c_str(i_target));
fapi_try_exit:
return fapi2::current_err;
}
#endif // PPE
}// mss
#endif // include guard
|
Exclude a FAPI_DBG statement invalid on PPE
|
Exclude a FAPI_DBG statement invalid on PPE
The PPE plat implementation of FAPI_DBG has more limitations than the
x86 implementation. This particular FAPI_DBG statement has more
arguments than are supported on PPE and for that reason, will not
compile for PPE if FAPI tracing is enabled. By excluding this statement
for PPE, it can be compiled with tracing on.
Change-Id: I39a03ee6d6d354d2e2aae6d3d6fff5db97e2fe26
Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/103987
Tested-by: Jenkins Server <[email protected]>
Reviewed-by: David S McDermott <[email protected]>
Tested-by: PPE CI <[email protected]>
Tested-by: FSP CI Jenkins <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Justin D Ginn <[email protected]>
Reviewed-by: NAREN A DEVAIAH <[email protected]>
Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/103991
Tested-by: Jenkins OP Build CI <[email protected]>
Tested-by: Jenkins Combined Simics CI <[email protected]>
Reviewed-by: Nicholas E Bofferding <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
98589f255fb46bc4a54b1922a63cd8849f30d06d
|
chrome/browser/gtk/about_chrome_dialog.cc
|
chrome/browser/gtk/about_chrome_dialog.cc
|
// 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/gtk/about_chrome_dialog.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_version_info.h"
#include "base/gfx/gtk_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/gtk_util.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "webkit/glue/webkit_glue.h"
namespace {
// The URLs that you navigate to when clicking the links in the About dialog.
const char* const kAcknowledgements = "about:credits";
const char* const kTOS = "about:terms";
// Left or right margin.
const int kPanelHorizMargin = 13;
// Top or bottom margin.
const int kPanelVertMargin = 20;
// Extra spacing between product name and version number.
const int kExtraLineSpacing = 5;
// These are used as placeholder text around the links in the text in the about
// dialog.
const char* kBeginLinkChr = "BEGIN_LINK_CHR";
const char* kBeginLinkOss = "BEGIN_LINK_OSS";
// We don't actually use this one.
// const char* kEndLinkChr = "END_LINK_CHR";
const char* kEndLinkOss = "END_LINK_OSS";
const char* kBeginLink = "BEGIN_LINK";
const char* kEndLink = "END_LINK";
void OnDialogResponse(GtkDialog* dialog, int response_id) {
// We're done.
gtk_widget_destroy(GTK_WIDGET(dialog));
}
void FixLabelWrappingCallback(GtkWidget *label,
GtkAllocation *allocation,
gpointer data) {
gtk_widget_set_size_request(label, allocation->width, -1);
}
GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {
GtkWidget* label = gtk_label_new(NULL);
char* markup = g_markup_printf_escaped(format, str.c_str());
gtk_label_set_markup(GTK_LABEL(label), markup);
g_free(markup);
// Left align it.
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
return label;
}
void OnLinkButtonClick(GtkWidget* button, const char* url) {
BrowserList::GetLastActive()->
OpenURL(GURL(url), GURL(), NEW_WINDOW, PageTransition::LINK);
}
const char* GetChromiumUrl() {
static std::string url(l10n_util::GetStringUTF8(IDS_CHROMIUM_PROJECT_URL));
return url.c_str();
}
} // namespace
void ShowAboutDialogForProfile(GtkWindow* parent, Profile* profile) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
static GdkPixbuf* background = rb.GetPixbufNamed(IDR_ABOUT_BACKGROUND);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
std::wstring current_version = version_info->file_version();
#if !defined(GOOGLE_CHROME_BUILD)
current_version += L" (";
current_version += version_info->last_change();
current_version += L")";
#endif
// Build the dialog.
GtkWidget* dialog = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_ABOUT_CHROME_TITLE).c_str(),
parent,
GTK_DIALOG_MODAL,
GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
NULL);
// Pick up the style set in gtk_util.cc:InitRCStyles().
// The layout of this dialog is special because the logo should be flush
// with the edges of the window.
gtk_widget_set_name(dialog, "about-dialog");
gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);
GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
// Use an event box to get the background painting correctly
GtkWidget* ebox = gtk_event_box_new();
gtk_widget_modify_bg(ebox, GTK_STATE_NORMAL, &gfx::kGdkWhite);
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
GtkWidget* text_alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(text_alignment),
kPanelVertMargin, kPanelVertMargin,
kPanelHorizMargin, kPanelHorizMargin);
GtkWidget* text_vbox = gtk_vbox_new(FALSE, kExtraLineSpacing);
GtkWidget* product_label = MakeMarkupLabel(
"<span font_desc=\"18\" weight=\"bold\" style=\"normal\">%s</span>",
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME));
gtk_box_pack_start(GTK_BOX(text_vbox), product_label, FALSE, FALSE, 0);
GtkWidget* version_label = gtk_label_new(WideToUTF8(current_version).c_str());
gtk_misc_set_alignment(GTK_MISC(version_label), 0.0, 0.5);
gtk_label_set_selectable(GTK_LABEL(version_label), TRUE);
gtk_box_pack_start(GTK_BOX(text_vbox), version_label, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(text_alignment), text_vbox);
gtk_box_pack_start(GTK_BOX(hbox), text_alignment, TRUE, TRUE, 0);
GtkWidget* image_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(image_vbox),
gtk_image_new_from_pixbuf(background),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), image_vbox, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(ebox), hbox);
gtk_box_pack_start(GTK_BOX(content_area), ebox, TRUE, TRUE, 0);
// We use a separate box for the licensing etc. text. See the comment near
// the top of this function about using a special layout for this dialog.
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(vbox),
gtk_util::kContentAreaBorder);
GtkWidget* copyright_label = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_COPYRIGHT));
gtk_box_pack_start(GTK_BOX(vbox), copyright_label, TRUE, TRUE, 5);
std::string license = l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_LICENSE);
bool chromium_url_appears_first =
license.find(kBeginLinkChr) < license.find(kBeginLinkOss);
size_t link1 = license.find(kBeginLink);
DCHECK(link1 != std::string::npos);
size_t link1_end = license.find(kEndLink, link1);
DCHECK(link1_end != std::string::npos);
size_t link2 = license.find(kBeginLink, link1_end);
DCHECK(link2 != std::string::npos);
size_t link2_end = license.find(kEndLink, link2);
DCHECK(link1_end != std::string::npos);
GtkWidget* license_chunk1 = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
license.substr(0, link1));
GtkWidget* license_chunk2 = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
license.substr(link1_end + strlen(kEndLinkOss),
link2 - link1_end - strlen(kEndLinkOss)));
GtkWidget* license_chunk3 = MakeMarkupLabel(
"<span size=\"smaller\">%s</span>",
license.substr(link2_end + strlen(kEndLinkOss)));
std::string first_link_text =
std::string("<span size=\"smaller\">") +
license.substr(link1 + strlen(kBeginLinkOss),
link1_end - link1 - strlen(kBeginLinkOss)) +
std::string("</span>");
std::string second_link_text =
std::string("<span size=\"smaller\">") +
license.substr(link2 + strlen(kBeginLinkOss),
link2_end - link2 - strlen(kBeginLinkOss)) +
std::string("</span>");
GtkWidget* first_link =
gtk_chrome_link_button_new_with_markup(first_link_text.c_str());
GtkWidget* second_link =
gtk_chrome_link_button_new_with_markup(second_link_text.c_str());
if (!chromium_url_appears_first) {
GtkWidget* swap = second_link;
second_link = first_link;
first_link = swap;
}
g_signal_connect(chromium_url_appears_first ? first_link : second_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(GetChromiumUrl()));
g_signal_connect(chromium_url_appears_first ? second_link : first_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(kAcknowledgements));
GtkWidget* license_hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk1,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), first_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk2,
FALSE, FALSE, 0);
// Since there's no good way to dynamically wrap the license block, force
// a line break right before the second link (which matches en-US Windows
// chromium).
GtkWidget* license_hbox2 = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), second_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), license_chunk3,
FALSE, FALSE, 0);
GtkWidget* license_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox2, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), license_vbox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(content_area), vbox, TRUE, TRUE, 0);
g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), NULL);
gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
gtk_widget_show_all(dialog);
}
|
// 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/gtk/about_chrome_dialog.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_version_info.h"
#include "base/gfx/gtk_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/gtk_util.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "webkit/glue/webkit_glue.h"
namespace {
// The URLs that you navigate to when clicking the links in the About dialog.
const char* const kAcknowledgements = "about:credits";
const char* const kTOS = "about:terms";
// Left or right margin.
const int kPanelHorizMargin = 13;
// Top or bottom margin.
const int kPanelVertMargin = 20;
// Extra spacing between product name and version number.
const int kExtraLineSpacing = 5;
// These are used as placeholder text around the links in the text in the about
// dialog.
const char* kBeginLinkChr = "BEGIN_LINK_CHR";
const char* kBeginLinkOss = "BEGIN_LINK_OSS";
// We don't actually use this one.
// const char* kEndLinkChr = "END_LINK_CHR";
const char* kEndLinkOss = "END_LINK_OSS";
const char* kBeginLink = "BEGIN_LINK";
const char* kEndLink = "END_LINK";
const char* kSmaller = "<span size=\"smaller\">%s</span>";
void OnDialogResponse(GtkDialog* dialog, int response_id) {
// We're done.
gtk_widget_destroy(GTK_WIDGET(dialog));
}
void FixLabelWrappingCallback(GtkWidget *label,
GtkAllocation *allocation,
gpointer data) {
gtk_widget_set_size_request(label, allocation->width, -1);
}
GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {
GtkWidget* label = gtk_label_new(NULL);
char* markup = g_markup_printf_escaped(format, str.c_str());
gtk_label_set_markup(GTK_LABEL(label), markup);
g_free(markup);
// Left align it.
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
return label;
}
void OnLinkButtonClick(GtkWidget* button, const char* url) {
BrowserList::GetLastActive()->
OpenURL(GURL(url), GURL(), NEW_WINDOW, PageTransition::LINK);
}
const char* GetChromiumUrl() {
static std::string url(l10n_util::GetStringUTF8(IDS_CHROMIUM_PROJECT_URL));
return url.c_str();
}
std::string Smaller(const std::string& text) {
return std::string("<span size=\"smaller\">") + text + std::string("</span>");
}
} // namespace
void ShowAboutDialogForProfile(GtkWindow* parent, Profile* profile) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
static GdkPixbuf* background = rb.GetPixbufNamed(IDR_ABOUT_BACKGROUND);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
std::wstring current_version = version_info->file_version();
#if !defined(GOOGLE_CHROME_BUILD)
current_version += L" (";
current_version += version_info->last_change();
current_version += L")";
#endif
// Build the dialog.
GtkWidget* dialog = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_ABOUT_CHROME_TITLE).c_str(),
parent,
GTK_DIALOG_MODAL,
GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
NULL);
// Pick up the style set in gtk_util.cc:InitRCStyles().
// The layout of this dialog is special because the logo should be flush
// with the edges of the window.
gtk_widget_set_name(dialog, "about-dialog");
gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);
GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
// Use an event box to get the background painting correctly
GtkWidget* ebox = gtk_event_box_new();
gtk_widget_modify_bg(ebox, GTK_STATE_NORMAL, &gfx::kGdkWhite);
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
GtkWidget* text_alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(text_alignment),
kPanelVertMargin, kPanelVertMargin,
kPanelHorizMargin, kPanelHorizMargin);
GtkWidget* text_vbox = gtk_vbox_new(FALSE, kExtraLineSpacing);
GdkColor black = gfx::kGdkBlack;
GtkWidget* product_label = MakeMarkupLabel(
"<span font_desc=\"18\" weight=\"bold\" style=\"normal\">%s</span>",
l10n_util::GetStringUTF8(IDS_PRODUCT_NAME));
gtk_widget_modify_fg(product_label, GTK_STATE_NORMAL, &black);
gtk_box_pack_start(GTK_BOX(text_vbox), product_label, FALSE, FALSE, 0);
GtkWidget* version_label = gtk_label_new(WideToUTF8(current_version).c_str());
gtk_misc_set_alignment(GTK_MISC(version_label), 0.0, 0.5);
gtk_label_set_selectable(GTK_LABEL(version_label), TRUE);
gtk_widget_modify_fg(version_label, GTK_STATE_NORMAL, &black);
gtk_box_pack_start(GTK_BOX(text_vbox), version_label, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(text_alignment), text_vbox);
gtk_box_pack_start(GTK_BOX(hbox), text_alignment, TRUE, TRUE, 0);
GtkWidget* image_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(image_vbox),
gtk_image_new_from_pixbuf(background),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), image_vbox, FALSE, FALSE, 0);
gtk_container_add(GTK_CONTAINER(ebox), hbox);
gtk_box_pack_start(GTK_BOX(content_area), ebox, TRUE, TRUE, 0);
// We use a separate box for the licensing etc. text. See the comment near
// the top of this function about using a special layout for this dialog.
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(vbox),
gtk_util::kContentAreaBorder);
GtkWidget* copyright_label = MakeMarkupLabel(
kSmaller, l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_COPYRIGHT));
gtk_box_pack_start(GTK_BOX(vbox), copyright_label, TRUE, TRUE, 5);
std::string license = l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_LICENSE);
bool chromium_url_appears_first =
license.find(kBeginLinkChr) < license.find(kBeginLinkOss);
size_t link1 = license.find(kBeginLink);
DCHECK(link1 != std::string::npos);
size_t link1_end = license.find(kEndLink, link1);
DCHECK(link1_end != std::string::npos);
size_t link2 = license.find(kBeginLink, link1_end);
DCHECK(link2 != std::string::npos);
size_t link2_end = license.find(kEndLink, link2);
DCHECK(link1_end != std::string::npos);
GtkWidget* license_chunk1 = MakeMarkupLabel(
kSmaller, license.substr(0, link1));
GtkWidget* license_chunk2 = MakeMarkupLabel(
kSmaller,
license.substr(link1_end + strlen(kEndLinkOss),
link2 - link1_end - strlen(kEndLinkOss)));
GtkWidget* license_chunk3 = MakeMarkupLabel(
kSmaller, license.substr(link2_end + strlen(kEndLinkOss)));
std::string first_link_text = Smaller(
license.substr(link1 + strlen(kBeginLinkOss),
link1_end - link1 - strlen(kBeginLinkOss)));
std::string second_link_text = Smaller(
license.substr(link2 + strlen(kBeginLinkOss),
link2_end - link2 - strlen(kBeginLinkOss)));
GtkWidget* first_link =
gtk_chrome_link_button_new_with_markup(first_link_text.c_str());
GtkWidget* second_link =
gtk_chrome_link_button_new_with_markup(second_link_text.c_str());
if (!chromium_url_appears_first) {
GtkWidget* swap = second_link;
second_link = first_link;
first_link = swap;
}
g_signal_connect(chromium_url_appears_first ? first_link : second_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(GetChromiumUrl()));
g_signal_connect(chromium_url_appears_first ? second_link : first_link,
"clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(kAcknowledgements));
GtkWidget* license_hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk1,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), first_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox), license_chunk2,
FALSE, FALSE, 0);
// Since there's no good way to dynamically wrap the license block, force
// a line break right before the second link (which matches en-US Windows
// chromium).
GtkWidget* license_hbox2 = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), second_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_hbox2), license_chunk3,
FALSE, FALSE, 0);
GtkWidget* license_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(license_vbox), license_hbox2, FALSE, FALSE, 0);
#if defined(GOOGLE_CHROME_BUILD)
std::vector<size_t> url_offsets;
std::wstring text = l10n_util::GetStringF(IDS_ABOUT_TERMS_OF_SERVICE,
std::wstring(),
std::wstring(),
&url_offsets);
std::string tos_link_text = Smaller(
l10n_util::GetStringUTF8(IDS_TERMS_OF_SERVICE));
GtkWidget* tos_chunk1 = MakeMarkupLabel(
kSmaller, WideToUTF8(text.substr(0, url_offsets[0])).c_str());
GtkWidget* tos_link =
gtk_chrome_link_button_new_with_markup(tos_link_text.c_str());
GtkWidget* tos_chunk2 = MakeMarkupLabel(
kSmaller, WideToUTF8(text.substr(url_offsets[0])).c_str());
GtkWidget* tos_hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(tos_hbox), tos_chunk1, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tos_hbox), tos_link, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tos_hbox), tos_chunk2, FALSE, FALSE, 0);
g_signal_connect(tos_link, "clicked", G_CALLBACK(OnLinkButtonClick),
const_cast<char*>(kTOS));
#endif
gtk_box_pack_start(GTK_BOX(vbox), license_vbox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), tos_hbox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(content_area), vbox, TRUE, TRUE, 0);
g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), NULL);
gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
gtk_widget_show_all(dialog);
}
|
Make chrome version legible in about:chrome dialog for dark themes.
|
Make chrome version legible in about:chrome dialog for dark themes.
Add Terms of Service link for google chrome (not chromium).
BUG=16544
TEST=use dark theme, look at version in about:chrome
Review URL: http://codereview.chromium.org/155454
git-svn-id: http://src.chromium.org/svn/trunk/src@20570 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: f306af6d341b3d6aabb7da0d932bd9ce70149489
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
c1301f68c20aa44ca575298c94c1d32d751a3227
|
obj2vector.hh
|
obj2vector.hh
|
#if !defined(_OBJ2VECTOR_)
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::ifstream;
using std::ofstream;
using std::getline;
using std::istringstream;
using std::stringstream;
using std::vector;
using std::pair;
using std::ceil;
template <typename T> class match_t;
template <typename T> class tilter;
template <typename T> bool clockwise(const Eigen::Matrix<T, 2, 1>& p0, const Eigen::Matrix<T, 2, 1>& p1, const Eigen::Matrix<T, 2, 1>& p2) {
Eigen::Matrix<T, 2, 1> p10(p1 - p0), p20(p2 - p0);
const T Pi(T(4) * atan2(T(1), T(1)));
T theta((atan2(p10[1], p10[0]) - atan2(p20[1], p20[0]) + Pi) / (T(2) * Pi));
theta -= ceil(theta);
theta += T(1);
theta -= ceil(theta);
if(theta * T(2) * Pi - Pi < T(0))
return true;
return false;
}
// N.B. delaunay trianglation algorithm best works but this isn't.
// terrible inefficient and imcomplete temporary stub.
template <typename T> vector<Eigen::Matrix<int, 3, 1> > loadBumpSimpleMesh(const vector<Eigen::Matrix<T, 3, 1> >& dst, const vector<int>& dstpoints) {
vector<Eigen::Matrix<int, 3, 1> > res;
for(int i = 0; i < dstpoints.size(); i ++) {
cerr << "mesh: " << i << "/" << dstpoints.size() << endl;
for(int j = i + 1; j < dstpoints.size(); j ++)
for(int k = j + 1; k < dstpoints.size(); k ++) {
int ii(i), jj(j), kk(k);
Eigen::Matrix<T, 2, 1> p0, p1, p2;
p0[0] = dst[dstpoints[ii]][0];
p0[1] = dst[dstpoints[ii]][1];
p1[0] = dst[dstpoints[jj]][0];
p1[1] = dst[dstpoints[jj]][1];
p2[0] = dst[dstpoints[kk]][0];
p2[1] = dst[dstpoints[kk]][1];
// make sure counter clockwise.
if(clockwise(p0, p1, p2)) {
jj = k;
kk = j;
}
// XXX have a glitch, on the same line.
if((p0[0] == p1[0] && p1[0] == p2[0]) ||
(p0[1] == p1[1] && p1[1] == p2[1]))
continue;
bool flag(false);
// brute force.
for(int l = 0; l < dstpoints.size() && !flag; l ++) {
Eigen::Matrix<T, 4, 4> dc;
dc(0, 0) = dst[dstpoints[ii]][0];
dc(0, 1) = dst[dstpoints[ii]][1];
dc(1, 0) = dst[dstpoints[jj]][0];
dc(1, 1) = dst[dstpoints[jj]][1];
dc(2, 0) = dst[dstpoints[kk]][0];
dc(2, 1) = dst[dstpoints[kk]][1];
dc(3, 0) = dst[dstpoints[l]][0];
dc(3, 1) = dst[dstpoints[l]][1];
for(int m = 0; m < dc.rows(); m ++) {
dc(m, 2) = dc(m, 0) * dc(m, 0) + dc(m, 1) * dc(m, 1);
dc(m, 3) = T(1);
}
if(dc.determinant() > T(0)) {
flag = true;
break;
}
}
if(!flag) {
Eigen::Matrix<int, 3, 1> buf;
buf[0] = i;
buf[1] = j;
buf[2] = k;
res.push_back(buf);
}
}
}
return res;
}
template <typename T> bool saveobj(const vector<Eigen::Matrix<T, 3, 1> >& data, const vector<Eigen::Matrix<int, 3, 1> >& polys, const char* filename) {
ofstream output;
output.open(filename, std::ios::out);
if(output.is_open()) {
for(int i = 0; i < data.size(); i ++)
output << "v " << data[i][0] << " " << data[i][1] << " " << data[i][2] * T(8) << endl;
for(int i = 0; i < polys.size(); i ++)
output << "f " << polys[i][0] + 1 << " " << polys[i][1] + 1 << " " << polys[i][2] + 1 << endl;
output.close();
} else {
cerr << "Unable to open file: " << filename << endl;
return false;
}
return true;
}
template <typename T> bool loadobj(vector<Eigen::Matrix<T, 3, 1> >& data, vector<Eigen::Matrix<int, 3, 1> >& polys, const char* filename) {
ifstream input;
input.open(filename);
if(input.is_open()) {
string work;
while(getline(input, work)) {
int i = 0;
for(; i < work.size() && work[i] == ' '; i ++);
if(i + 1 < work.size() && work[i] == 'v' && work[i + 1] == ' ') {
stringstream sub(work.substr(i + 2, work.size() - (i + 2)));
Eigen::Matrix<T, 3, 1> buf;
sub >> buf[0];
sub >> buf[1];
sub >> buf[2];
data.push_back(buf);
} else if(i < work.size() && work[i] == 'f') {
stringstream sub(work.substr(i + 1, work.size() - (i + 1)));
Eigen::Matrix<int, 3, 1> wbuf;
int widx(0);
bool flag(false);
while(!sub.eof() && !sub.bad()) {
sub >> wbuf[widx];
if(wbuf[widx] >= 0)
wbuf[widx] --;
widx ++;
if(sub.eof() || sub.bad())
break;
if(widx > 2)
flag = true;
widx %= 3;
if(flag)
polys.push_back(wbuf);
sub.ignore(20, ' ');
}
}
}
for(int i = 0; i < polys.size(); i ++)
for(int j = 0; j < polys[i].size(); j ++)
polys[i][j] = ((polys[i][j] % (2 * data.size())) + 2 * data.size()) % data.size();
input.close();
} else {
cerr << "Unable to open file: " << filename << endl;
return false;
}
return true;
}
#define _OBJ2VECTOR_
#endif
|
#if !defined(_OBJ2VECTOR_)
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::ifstream;
using std::ofstream;
using std::getline;
using std::istringstream;
using std::stringstream;
using std::vector;
using std::pair;
using std::floor;
template <typename T> class match_t;
template <typename T> class tilter;
template <typename T> bool clockwise(const Eigen::Matrix<T, 2, 1>& p0, const Eigen::Matrix<T, 2, 1>& p1, const Eigen::Matrix<T, 2, 1>& p2) {
Eigen::Matrix<T, 2, 1> p10(p1 - p0), p20(p2 - p0);
const T Pi(T(4) * atan2(T(1), T(1)));
T theta((atan2(p10[1], p10[0]) - atan2(p20[1], p20[0]) + Pi) / (T(2) * Pi));
theta -= floor(theta);
theta += T(1);
theta -= floor(theta);
if(theta * T(2) * Pi - Pi < T(0))
return true;
return false;
}
// N.B. delaunay trianglation algorithm best works but this isn't.
// terrible inefficient and imcomplete temporary stub.
template <typename T> vector<Eigen::Matrix<int, 3, 1> > loadBumpSimpleMesh(const vector<Eigen::Matrix<T, 3, 1> >& dst, const vector<int>& dstpoints) {
vector<Eigen::Matrix<int, 3, 1> > res;
for(int i = 0; i < dstpoints.size(); i ++) {
cerr << "mesh: " << i << "/" << dstpoints.size() << endl;
for(int j = i + 1; j < dstpoints.size(); j ++)
for(int k = j + 1; k < dstpoints.size(); k ++) {
int ii(i), jj(j), kk(k);
Eigen::Matrix<T, 2, 1> p0, p1, p2;
p0[0] = dst[dstpoints[ii]][0];
p0[1] = dst[dstpoints[ii]][1];
p1[0] = dst[dstpoints[jj]][0];
p1[1] = dst[dstpoints[jj]][1];
p2[0] = dst[dstpoints[kk]][0];
p2[1] = dst[dstpoints[kk]][1];
// make sure counter clockwise.
if(clockwise(p0, p1, p2)) {
jj = k;
kk = j;
}
// XXX have a glitch, on the same line.
if((p0[0] == p1[0] && p1[0] == p2[0]) ||
(p0[1] == p1[1] && p1[1] == p2[1]))
continue;
bool flag(false);
// brute force.
for(int l = 0; l < dstpoints.size() && !flag; l ++) {
Eigen::Matrix<T, 4, 4> dc;
dc(0, 0) = dst[dstpoints[ii]][0];
dc(0, 1) = dst[dstpoints[ii]][1];
dc(1, 0) = dst[dstpoints[jj]][0];
dc(1, 1) = dst[dstpoints[jj]][1];
dc(2, 0) = dst[dstpoints[kk]][0];
dc(2, 1) = dst[dstpoints[kk]][1];
dc(3, 0) = dst[dstpoints[l]][0];
dc(3, 1) = dst[dstpoints[l]][1];
for(int m = 0; m < dc.rows(); m ++) {
dc(m, 2) = dc(m, 0) * dc(m, 0) + dc(m, 1) * dc(m, 1);
dc(m, 3) = T(1);
}
if(dc.determinant() > T(0)) {
flag = true;
break;
}
}
if(!flag) {
Eigen::Matrix<int, 3, 1> buf;
buf[0] = i;
buf[1] = j;
buf[2] = k;
res.push_back(buf);
}
}
}
return res;
}
template <typename T> bool saveobj(const vector<Eigen::Matrix<T, 3, 1> >& data, const vector<Eigen::Matrix<int, 3, 1> >& polys, const char* filename) {
ofstream output;
output.open(filename, std::ios::out);
if(output.is_open()) {
for(int i = 0; i < data.size(); i ++)
output << "v " << data[i][0] << " " << data[i][1] << " " << data[i][2] * T(8) << endl;
for(int i = 0; i < polys.size(); i ++)
output << "f " << polys[i][0] + 1 << " " << polys[i][1] + 1 << " " << polys[i][2] + 1 << endl;
output.close();
} else {
cerr << "Unable to open file: " << filename << endl;
return false;
}
return true;
}
template <typename T> bool loadobj(vector<Eigen::Matrix<T, 3, 1> >& data, vector<Eigen::Matrix<int, 3, 1> >& polys, const char* filename) {
ifstream input;
input.open(filename);
if(input.is_open()) {
string work;
while(getline(input, work)) {
int i = 0;
for(; i < work.size() && work[i] == ' '; i ++);
if(i + 1 < work.size() && work[i] == 'v' && work[i + 1] == ' ') {
stringstream sub(work.substr(i + 2, work.size() - (i + 2)));
Eigen::Matrix<T, 3, 1> buf;
sub >> buf[0];
sub >> buf[1];
sub >> buf[2];
data.push_back(buf);
} else if(i < work.size() && work[i] == 'f') {
stringstream sub(work.substr(i + 1, work.size() - (i + 1)));
Eigen::Matrix<int, 3, 1> wbuf;
int widx(0);
bool flag(false);
while(!sub.eof() && !sub.bad()) {
sub >> wbuf[widx];
if(wbuf[widx] >= 0)
wbuf[widx] --;
widx ++;
if(sub.eof() || sub.bad())
break;
if(widx > 2)
flag = true;
widx %= 3;
if(flag)
polys.push_back(wbuf);
sub.ignore(20, ' ');
}
}
}
for(int i = 0; i < polys.size(); i ++)
for(int j = 0; j < polys[i].size(); j ++)
polys[i][j] = ((polys[i][j] % (2 * data.size())) + 2 * data.size()) % data.size();
input.close();
} else {
cerr << "Unable to open file: " << filename << endl;
return false;
}
return true;
}
#define _OBJ2VECTOR_
#endif
|
Fix ceil to floor, clockwise function.
|
Fix ceil to floor, clockwise function.
|
C++
|
bsd-3-clause
|
bitsofcotton/goki_check_cc,bitsofcotton/goki_check_cc
|
4a17e91b8cc4cc324af747bbcf0703971679e124
|
iree/compiler/Dialect/Flow/Transforms/PrePostPartitioningConversion.cpp
|
iree/compiler/Dialect/Flow/Transforms/PrePostPartitioningConversion.cpp
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 <utility>
#include "iree/compiler/Dialect/Flow/Conversion/HLOToFlow/ConvertHLOToFlow.h"
#include "iree/compiler/Dialect/Flow/Conversion/StandardToFlow/ConvertStandardToFlow.h"
#include "iree/compiler/Dialect/Flow/Conversion/TypeConverter.h"
#include "iree/compiler/Dialect/Flow/IR/FlowDialect.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Module.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/DialectConversion.h"
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
#include "tensorflow/compiler/mlir/xla/transforms/rewriters.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
class PrePartitioningConversionPass
: public PassWrapper<PrePartitioningConversionPass, FunctionPass> {
public:
void runOnFunction() override {
auto *context = &getContext();
FlowTypeConverter typeConverter;
ConversionTarget conversionTarget(*context);
OwningRewritePatternList conversionPatterns;
conversionTarget.addLegalDialect<IREE::Flow::FlowDialect>();
// Standard ops always pass through as import code may have produced some
// and control flow should have been legalized from HLO to std.
// The flow dialect uses std.module and std.func for its structure and they
// must be allowed.
conversionTarget.addLegalDialect<StandardOpsDialect>();
conversionTarget.addLegalOp<FuncOp>();
// Allow XLA HLO ops - we explicitly mark the ones we don't want below.
conversionTarget.addLegalDialect<xla_hlo::XlaHloDialect>();
// Control flow must be converted to standard form via
// xla_hlo::createLegalizeControlFlowPass() prior to conversion.
conversionTarget.addIllegalOp<xla_hlo::ConditionalOp, xla_hlo::WhileOp>();
// We don't support broadcast_dimensions as part of ops, so materialize
// any such attributes to dedicated xla_hlo.broadcast_in_dim ops.
xla_hlo::SetupMaterializeBroadcastsLegality(context, &conversionTarget);
xla_hlo::PopulateMaterializeBroadcastsPatterns(context,
&conversionPatterns);
// Early conversion of ops that have matches we want to route through.
// For example, DynamicUpdateSlice should end up as a stream operation.
setupDirectHLOToFlowLegality(context, conversionTarget);
populateHLOToFlowPatterns(context, conversionPatterns);
setupDirectStandardToFlowLegality(context, conversionTarget);
populateStandardToFlowPatterns(context, conversionPatterns);
if (failed(applyPartialConversion(getFunction(), conversionTarget,
conversionPatterns, &typeConverter))) {
getFunction().emitError() << "module is not in a compatible input format";
return signalPassFailure();
}
}
};
class PostPartitioningConversionPass
: public PassWrapper<PostPartitioningConversionPass, FunctionPass> {
public:
void runOnFunction() override {
auto *context = &getContext();
ConversionTarget conversionTarget(getContext());
FlowTypeConverter typeConverter;
OwningRewritePatternList conversionPatterns;
// We have completed all flow op creation at this point.
conversionTarget.addLegalDialect<IREE::Flow::FlowDialect>();
// Standard ops always pass through as import code may have produced some
// and control flow should have been legalized from HLO to std.
// The flow dialect uses std.module and std.func for its structure and they
// must be allowed.
conversionTarget.addLegalDialect<StandardOpsDialect>();
conversionTarget.addLegalOp<ModuleOp, ModuleTerminatorOp, FuncOp>();
// Pick up any remaining HLO ops that were not partitioned.
populateHLOToFlowPatterns(context, conversionPatterns);
populateStandardToFlowPatterns(context, conversionPatterns);
if (failed(applyPartialConversion(getFunction(), conversionTarget,
conversionPatterns, &typeConverter))) {
getFunction().emitError() << "module is not in a compatible input format";
return signalPassFailure();
}
}
};
std::unique_ptr<OperationPass<FuncOp>> createPrePartitioningConversionPass() {
return std::make_unique<PrePartitioningConversionPass>();
}
std::unique_ptr<OperationPass<FuncOp>> createPostPartitioningConversionPass() {
return std::make_unique<PostPartitioningConversionPass>();
}
static PassRegistration<PrePartitioningConversionPass> prePass(
"iree-flow-pre-partitioning-conversion",
"Dialect conversion prior to partitioning");
static PassRegistration<PostPartitioningConversionPass> postPass(
"iree-flow-post-partitioning-conversion",
"Dialect conversion after partitioning");
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 <utility>
#include "iree/compiler/Dialect/Flow/Conversion/HLOToFlow/ConvertHLOToFlow.h"
#include "iree/compiler/Dialect/Flow/Conversion/StandardToFlow/ConvertStandardToFlow.h"
#include "iree/compiler/Dialect/Flow/Conversion/TypeConverter.h"
#include "iree/compiler/Dialect/Flow/IR/FlowDialect.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Module.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/DialectConversion.h"
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
#include "tensorflow/compiler/mlir/xla/transforms/rewriters.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
class PrePartitioningConversionPass
: public PassWrapper<PrePartitioningConversionPass, FunctionPass> {
public:
void runOnFunction() override {
auto *context = &getContext();
FlowTypeConverter typeConverter;
ConversionTarget conversionTarget(*context);
OwningRewritePatternList conversionPatterns;
conversionTarget.addLegalDialect<IREE::Flow::FlowDialect>();
// Standard ops always pass through as import code may have produced some
// and control flow should have been legalized from HLO to std.
// The flow dialect uses std.module and std.func for its structure and they
// must be allowed.
conversionTarget.addLegalDialect<StandardOpsDialect>();
conversionTarget.addLegalOp<FuncOp>();
// Allow XLA HLO ops - we explicitly mark the ones we don't want below.
conversionTarget.addLegalDialect<xla_hlo::XlaHloDialect>();
// Control flow must be converted to standard form via
// xla_hlo::createLegalizeControlFlowPass() prior to conversion.
conversionTarget.addIllegalOp<xla_hlo::IfOp, xla_hlo::WhileOp>();
// We don't support broadcast_dimensions as part of ops, so materialize
// any such attributes to dedicated xla_hlo.broadcast_in_dim ops.
xla_hlo::SetupMaterializeBroadcastsLegality(context, &conversionTarget);
xla_hlo::PopulateMaterializeBroadcastsPatterns(context,
&conversionPatterns);
// Early conversion of ops that have matches we want to route through.
// For example, DynamicUpdateSlice should end up as a stream operation.
setupDirectHLOToFlowLegality(context, conversionTarget);
populateHLOToFlowPatterns(context, conversionPatterns);
setupDirectStandardToFlowLegality(context, conversionTarget);
populateStandardToFlowPatterns(context, conversionPatterns);
if (failed(applyPartialConversion(getFunction(), conversionTarget,
conversionPatterns, &typeConverter))) {
getFunction().emitError() << "module is not in a compatible input format";
return signalPassFailure();
}
}
};
class PostPartitioningConversionPass
: public PassWrapper<PostPartitioningConversionPass, FunctionPass> {
public:
void runOnFunction() override {
auto *context = &getContext();
ConversionTarget conversionTarget(getContext());
FlowTypeConverter typeConverter;
OwningRewritePatternList conversionPatterns;
// We have completed all flow op creation at this point.
conversionTarget.addLegalDialect<IREE::Flow::FlowDialect>();
// Standard ops always pass through as import code may have produced some
// and control flow should have been legalized from HLO to std.
// The flow dialect uses std.module and std.func for its structure and they
// must be allowed.
conversionTarget.addLegalDialect<StandardOpsDialect>();
conversionTarget.addLegalOp<ModuleOp, ModuleTerminatorOp, FuncOp>();
// Pick up any remaining HLO ops that were not partitioned.
populateHLOToFlowPatterns(context, conversionPatterns);
populateStandardToFlowPatterns(context, conversionPatterns);
if (failed(applyPartialConversion(getFunction(), conversionTarget,
conversionPatterns, &typeConverter))) {
getFunction().emitError() << "module is not in a compatible input format";
return signalPassFailure();
}
}
};
std::unique_ptr<OperationPass<FuncOp>> createPrePartitioningConversionPass() {
return std::make_unique<PrePartitioningConversionPass>();
}
std::unique_ptr<OperationPass<FuncOp>> createPostPartitioningConversionPass() {
return std::make_unique<PostPartitioningConversionPass>();
}
static PassRegistration<PrePartitioningConversionPass> prePass(
"iree-flow-pre-partitioning-conversion",
"Dialect conversion prior to partitioning");
static PassRegistration<PostPartitioningConversionPass> postPass(
"iree-flow-post-partitioning-conversion",
"Dialect conversion after partitioning");
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
|
Rename xla_hlo.conditional to xla_hlo.if.
|
Rename xla_hlo.conditional to xla_hlo.if.
This is part of separating xla_hlo.conditional op into two separate ops: xla_hlo.if to handle predicated conditional and xla_hlo.case to handle indexed conditional. A follow up CL would add xla_hlo.case op
PiperOrigin-RevId: 312307608
|
C++
|
apache-2.0
|
google/iree,iree-org/iree,google/iree,iree-org/iree,iree-org/iree,iree-org/iree,google/iree,google/iree,google/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,iree-org/iree
|
16b7ba1d2d78709ab9d362520c338c1a096135d3
|
C++/flip-game-ii.cpp
|
C++/flip-game-ii.cpp
|
// Time: O(n^(c+1)), n is length of string, c is count of "++"
// Space: O(c), recursion would be called at most c in depth.
class Solution {
public:
bool canWin(string s) {
int n = s.length();
bool other_win = true;
for (int i = 0; other_win && i < n - 1; ++i) { // O(n) time
if (s[i] == '+') {
for (; other_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time
s[i] = s[i + 1] = '-';
other_win = canWin(s); // F(n, c) = n * F(n, c - 1) = ... = n^c * F(n, 0) = n^(c+1)
s[i] = s[i + 1] = '+';
}
}
}
return !other_win;
}
};
|
// Time: O(n^(c+1)), n is length of string, c is count of "++"
// Space: O(c), recursion would be called at most c in depth.
class Solution {
public:
bool canWin(string s) {
int n = s.length();
bool is_win = false;
for (int i = 0; !is_win && i < n - 1; ++i) { // O(n) time
if (s[i] == '+') {
for (; !is_win && i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time
s[i] = s[i + 1] = '-';
is_win = !canWin(s); // F(n, c) = n * F(n, c - 1) = ... = n^c * F(n, 0) = n^(c+1)
s[i] = s[i + 1] = '+';
}
}
}
return is_win;
}
};
|
Update flip-game-ii.cpp
|
Update flip-game-ii.cpp
|
C++
|
mit
|
kamyu104/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,kamyu104/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,jaredkoontz/leetcode
|
33c5e0d7b7088b369c39542a6b3cddd352d0a549
|
Source/modules/indexeddb/IDBTransactionTest.cpp
|
Source/modules/indexeddb/IDBTransactionTest.cpp
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/indexeddb/IDBTransaction.h"
#include "core/dom/DOMError.h"
#include "core/dom/Document.h"
#include "modules/indexeddb/IDBDatabase.h"
#include "modules/indexeddb/IDBDatabaseCallbacks.h"
#include "modules/indexeddb/IDBPendingTransactionMonitor.h"
#include "platform/SharedBuffer.h"
#include "public/platform/WebIDBDatabase.h"
#include <gtest/gtest.h>
using namespace WebCore;
using blink::WebIDBDatabase;
namespace {
class IDBTransactionTest : public testing::Test {
public:
IDBTransactionTest()
: m_scope(v8::Isolate::GetCurrent())
{
m_scope.scriptState()->setExecutionContext(Document::create());
}
v8::Isolate* isolate() const { return m_scope.isolate(); }
ScriptState* scriptState() const { return m_scope.scriptState(); }
ExecutionContext* executionContext() { return m_scope.scriptState()->executionContext(); }
private:
V8TestingScope m_scope;
};
class FakeWebIDBDatabase FINAL : public blink::WebIDBDatabase {
public:
static PassOwnPtr<FakeWebIDBDatabase> create() { return adoptPtr(new FakeWebIDBDatabase()); }
virtual void commit(long long transactionId) OVERRIDE { }
virtual void abort(long long transactionId) OVERRIDE { }
virtual void close() OVERRIDE { }
private:
FakeWebIDBDatabase() { }
};
class FakeIDBDatabaseCallbacks FINAL : public IDBDatabaseCallbacks {
public:
static FakeIDBDatabaseCallbacks* create() { return new FakeIDBDatabaseCallbacks(); }
virtual void onVersionChange(int64_t oldVersion, int64_t newVersion) OVERRIDE { }
virtual void onForcedClose() OVERRIDE { }
virtual void onAbort(int64_t transactionId, PassRefPtrWillBeRawPtr<DOMError> error) OVERRIDE { }
virtual void onComplete(int64_t transactionId) OVERRIDE { }
private:
FakeIDBDatabaseCallbacks() { }
};
TEST_F(IDBTransactionTest, EnsureLifetime)
{
OwnPtr<FakeWebIDBDatabase> backend = FakeWebIDBDatabase::create();
Persistent<IDBDatabase> db = IDBDatabase::create(executionContext(), backend.release(), FakeIDBDatabaseCallbacks::create());
const int64_t transactionId = 1234;
const Vector<String> transactionScope;
Persistent<IDBTransaction> transaction = IDBTransaction::create(executionContext(), transactionId, transactionScope, blink::WebIDBDatabase::TransactionReadOnly, db.get());
PersistentHeapHashSet<WeakMember<IDBTransaction> > set;
set.add(transaction);
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
Persistent<IDBRequest> request = IDBRequest::create(scriptState(), IDBAny::createUndefined(), transaction.get());
IDBPendingTransactionMonitor::from(*executionContext()).deactivateNewTransactions();
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
// This will generate an abort() call to the back end which is dropped by the fake proxy,
// so an explicit onAbort call is made.
executionContext()->stopActiveDOMObjects();
transaction->onAbort(DOMError::create(AbortError, "Aborted"));
transaction.clear();
Heap::collectAllGarbage();
EXPECT_EQ(0u, set.size());
}
TEST_F(IDBTransactionTest, TransactionFinish)
{
OwnPtr<FakeWebIDBDatabase> backend = FakeWebIDBDatabase::create();
Persistent<IDBDatabase> db = IDBDatabase::create(executionContext(), backend.release(), FakeIDBDatabaseCallbacks::create());
const int64_t transactionId = 1234;
const Vector<String> transactionScope;
Persistent<IDBTransaction> transaction = IDBTransaction::create(executionContext(), transactionId, transactionScope, blink::WebIDBDatabase::TransactionReadOnly, db.get());
PersistentHeapHashSet<WeakMember<IDBTransaction> > set;
set.add(transaction);
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
IDBPendingTransactionMonitor::from(*executionContext()).deactivateNewTransactions();
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
transaction.clear();
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
// Stop the context, so events don't get queued (which would keep the transaction alive).
executionContext()->stopActiveDOMObjects();
// Fire an abort to make sure this doesn't free the transaction during use. The test
// will not fail if it is, but ASAN would notice the error.
db->onAbort(transactionId, DOMError::create(AbortError, "Aborted"));
// onAbort() should have cleared the transaction's reference to the database.
Heap::collectAllGarbage();
EXPECT_EQ(0u, set.size());
}
} // namespace
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/indexeddb/IDBTransaction.h"
#include "core/dom/DOMError.h"
#include "core/dom/Document.h"
#include "modules/indexeddb/IDBDatabase.h"
#include "modules/indexeddb/IDBDatabaseCallbacks.h"
#include "modules/indexeddb/IDBPendingTransactionMonitor.h"
#include "platform/SharedBuffer.h"
#include "public/platform/WebIDBDatabase.h"
#include <gtest/gtest.h>
using namespace WebCore;
using blink::WebIDBDatabase;
namespace {
class IDBTransactionTest : public testing::Test {
public:
IDBTransactionTest()
: m_scope(v8::Isolate::GetCurrent())
{
m_scope.scriptState()->setExecutionContext(Document::create());
}
v8::Isolate* isolate() const { return m_scope.isolate(); }
ScriptState* scriptState() const { return m_scope.scriptState(); }
ExecutionContext* executionContext() { return m_scope.scriptState()->executionContext(); }
private:
V8TestingScope m_scope;
};
class FakeWebIDBDatabase FINAL : public blink::WebIDBDatabase {
public:
static PassOwnPtr<FakeWebIDBDatabase> create() { return adoptPtr(new FakeWebIDBDatabase()); }
virtual void commit(long long transactionId) OVERRIDE { }
virtual void abort(long long transactionId) OVERRIDE { }
virtual void close() OVERRIDE { }
private:
FakeWebIDBDatabase() { }
};
class FakeIDBDatabaseCallbacks FINAL : public IDBDatabaseCallbacks {
public:
static FakeIDBDatabaseCallbacks* create() { return new FakeIDBDatabaseCallbacks(); }
virtual void onVersionChange(int64_t oldVersion, int64_t newVersion) OVERRIDE { }
virtual void onForcedClose() OVERRIDE { }
virtual void onAbort(int64_t transactionId, PassRefPtrWillBeRawPtr<DOMError> error) OVERRIDE { }
virtual void onComplete(int64_t transactionId) OVERRIDE { }
private:
FakeIDBDatabaseCallbacks() { }
};
// crbug.com/379616
#if ENABLE(OILPAN)
#define MAYBE_EnsureLifetime DISABLED_EnsureLifetime
#else
#define MAYBE_EnsureLifetime EnsureLifetime
#endif
TEST_F(IDBTransactionTest, MAYBE_EnsureLifetime)
{
OwnPtr<FakeWebIDBDatabase> backend = FakeWebIDBDatabase::create();
Persistent<IDBDatabase> db = IDBDatabase::create(executionContext(), backend.release(), FakeIDBDatabaseCallbacks::create());
const int64_t transactionId = 1234;
const Vector<String> transactionScope;
Persistent<IDBTransaction> transaction = IDBTransaction::create(executionContext(), transactionId, transactionScope, blink::WebIDBDatabase::TransactionReadOnly, db.get());
PersistentHeapHashSet<WeakMember<IDBTransaction> > set;
set.add(transaction);
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
Persistent<IDBRequest> request = IDBRequest::create(scriptState(), IDBAny::createUndefined(), transaction.get());
IDBPendingTransactionMonitor::from(*executionContext()).deactivateNewTransactions();
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
// This will generate an abort() call to the back end which is dropped by the fake proxy,
// so an explicit onAbort call is made.
executionContext()->stopActiveDOMObjects();
transaction->onAbort(DOMError::create(AbortError, "Aborted"));
transaction.clear();
Heap::collectAllGarbage();
EXPECT_EQ(0u, set.size());
}
TEST_F(IDBTransactionTest, TransactionFinish)
{
OwnPtr<FakeWebIDBDatabase> backend = FakeWebIDBDatabase::create();
Persistent<IDBDatabase> db = IDBDatabase::create(executionContext(), backend.release(), FakeIDBDatabaseCallbacks::create());
const int64_t transactionId = 1234;
const Vector<String> transactionScope;
Persistent<IDBTransaction> transaction = IDBTransaction::create(executionContext(), transactionId, transactionScope, blink::WebIDBDatabase::TransactionReadOnly, db.get());
PersistentHeapHashSet<WeakMember<IDBTransaction> > set;
set.add(transaction);
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
IDBPendingTransactionMonitor::from(*executionContext()).deactivateNewTransactions();
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
transaction.clear();
Heap::collectAllGarbage();
EXPECT_EQ(1u, set.size());
// Stop the context, so events don't get queued (which would keep the transaction alive).
executionContext()->stopActiveDOMObjects();
// Fire an abort to make sure this doesn't free the transaction during use. The test
// will not fail if it is, but ASAN would notice the error.
db->onAbort(transactionId, DOMError::create(AbortError, "Aborted"));
// onAbort() should have cleared the transaction's reference to the database.
Heap::collectAllGarbage();
EXPECT_EQ(0u, set.size());
}
} // namespace
|
Disable IDBTransactionTest.EnsureLifetime if ENABLE(OILPAN).
|
Disable IDBTransactionTest.EnsureLifetime if ENABLE(OILPAN).
BUG=379616
[email protected]
Review URL: https://codereview.chromium.org/308963003
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@175249 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,modulexcite/blink,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,modulexcite/blink,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,ondra-novak/blink,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,jtg-gg/blink,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,ondra-novak/blink,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,smishenk/blink-crosswalk,modulexcite/blink,Bysmyyr/blink-crosswalk,ondra-novak/blink,nwjs/blink,Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,ondra-novak/blink,ondra-novak/blink,jtg-gg/blink,XiaosongWei/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,smishenk/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,ondra-novak/blink,kurli/blink-crosswalk,ondra-novak/blink,modulexcite/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,nwjs/blink,PeterWangIntel/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,nwjs/blink,kurli/blink-crosswalk,kurli/blink-crosswalk,modulexcite/blink,nwjs/blink,modulexcite/blink,smishenk/blink-crosswalk,nwjs/blink,nwjs/blink,nwjs/blink,modulexcite/blink,smishenk/blink-crosswalk,jtg-gg/blink,nwjs/blink,hgl888/blink-crosswalk-efl,jtg-gg/blink,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,Pluto-tv/blink-crosswalk,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,hgl888/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,nwjs/blink,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,nwjs/blink,Pluto-tv/blink-crosswalk,XiaosongWei/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,ondra-novak/blink,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,jtg-gg/blink,ondra-novak/blink,XiaosongWei/blink-crosswalk
|
4e7dee38f6ca2b62c362333e068623d65d6e43cd
|
tools/tfserver/main.cpp
|
tools/tfserver/main.cpp
|
/* Copyright (c) 2010-2013, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QTextCodec>
#include <QStringList>
#include <QMap>
#include <TWebApplication>
#include <TThreadApplicationServer>
#include <TPreforkApplicationServer>
#include <TMultiplexingServer>
#include <TSystemGlobal>
#include <stdlib.h>
#include "tsystemglobal.h"
#include "signalhandler.h"
using namespace TreeFrog;
#define CTRL_C_OPTION "--ctrlc-enable"
#define SOCKET_OPTION "-s"
#if QT_VERSION >= 0x050000
static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
QByteArray msg = message.toLocal8Bit();
switch (type) {
case QtFatalMsg:
case QtCriticalMsg:
tSystemError("%s (%s:%u %s)", msg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
tSystemWarn("%s (%s:%u %s)", msg.constData(), context.file, context.line, context.function);
break;
case QtDebugMsg:
tSystemDebug("%s (%s:%u %s)", msg.constData(), context.file, context.line, context.function);
break;
default:
break;
}
}
#else
static void messageOutput(QtMsgType type, const char *msg)
{
switch (type) {
case QtFatalMsg:
case QtCriticalMsg:
tSystemError("%s", msg);
break;
case QtWarningMsg:
tSystemWarn("%s", msg);
break;
case QtDebugMsg:
tSystemDebug("%s", msg);
break;
default:
break;
}
}
#endif // QT_VERSION >= 0x050000
#if defined(Q_OS_UNIX)
static void writeFailure(const void *data, int size)
{
tSystemError("%s", QByteArray((const char *)data, size).data());
}
#endif
static QMap<QString, QString> convertArgs(const QStringList &args)
{
QMap<QString, QString> map;
for (int i = 1; i < args.count(); ++i) {
if (args.value(i).startsWith('-')) {
if (args.value(i + 1).startsWith('-')) {
map.insert(args.value(i), QString());
} else {
map.insert(args.value(i), args.value(i + 1));
++i;
}
}
}
return map;
}
int main(int argc, char *argv[])
{
TWebApplication webapp(argc, argv);
TApplicationServerBase *server = 0;
int ret = -1;
// Setup loggers
tSetupSystemLogger();
tSetupAccessLogger();
tSetupQueryLogger();
tSetupAppLoggers();
#if QT_VERSION >= 0x050000
qInstallMessageHandler(messageOutput);
#else
qInstallMsgHandler(messageOutput);
#endif
QMap<QString, QString> args = convertArgs(QCoreApplication::arguments());
int sock = args.value(SOCKET_OPTION).toInt();
#if defined(Q_OS_UNIX)
webapp.watchUnixSignal(SIGTERM);
if (!args.contains(CTRL_C_OPTION)) {
webapp.ignoreUnixSignal(SIGINT);
}
// Setup signal handlers for SIGSEGV, SIGILL, SIGFPE, SIGABRT and SIGBUS
setupFailureWriter(writeFailure);
setupSignalHandler();
#elif defined(Q_OS_WIN)
if (!args.contains(CTRL_C_OPTION)) {
webapp.ignoreConsoleSignal();
}
#endif
// Sets the app locale
QString loc = webapp.appSettings().value("Locale").toString().trimmed();
if (!loc.isEmpty()) {
QLocale locale(loc);
QLocale::setDefault(locale);
tSystemInfo("Application's default locale: %s", qPrintable(locale.name()));
}
// Sets codec
QTextCodec *codec = webapp.codecForInternal();
QTextCodec::setCodecForLocale(codec);
#if QT_VERSION < 0x050000
QTextCodec::setCodecForTr(codec);
QTextCodec::setCodecForCStrings(codec);
tSystemDebug("setCodecForTr: %s", codec->name().data());
tSystemDebug("setCodecForCStrings: %s", codec->name().data());
#endif
if (!webapp.webRootExists()) {
tSystemError("No such directory");
goto finish;
}
tSystemDebug("Web Root: %s", qPrintable(webapp.webRootPath()));
if (!webapp.appSettingsFileExists()) {
tSystemError("Settings file not found");
goto finish;
}
#ifdef Q_OS_WIN
if (sock <= 0) {
int port = webapp.appSettings().value("ListenPort").toInt();
if (port <= 0 || port > USHRT_MAX) {
tSystemError("Invalid port number: %d", port);
goto finish;
}
TApplicationServerBase::nativeSocketInit();
sock = TApplicationServerBase::nativeListen(QHostAddress::Any, port);
}
#endif
if (sock <= 0) {
tSystemError("Invalid socket descriptor: %d", sock);
goto finish;
}
switch (webapp.multiProcessingModule()) {
case TWebApplication::Thread:
server = new TThreadApplicationServer(sock, &webapp);
break;
case TWebApplication::Prefork: {
TPreforkApplicationServer *svr = new TPreforkApplicationServer(&webapp);
if (svr->setSocketDescriptor(sock)) {
tSystemDebug("Set socket descriptor: %d", sock);
} else {
tSystemError("Failed to set socket descriptor: %d", sock);
goto finish;
}
server = svr;
break; }
case TWebApplication::Hybrid:
#ifdef Q_OS_LINUX
// Sets a listening socket descriptor
TMultiplexingServer::instantiate(sock);
tSystemDebug("Set socket descriptor: %d", sock);
server = TMultiplexingServer::instance();
#else
tFatal("Unsupported MPM: hybrid");
#endif
break;
default:
break;
}
if (!server->start()) {
tSystemError("Server open failed");
goto finish;
}
ret = webapp.exec();
finish:
// Release loggers
tReleaseAppLoggers();
tReleaseQueryLogger();
tReleaseAccessLogger();
tReleaseSystemLogger();
_exit(ret);
return ret;
}
|
/* Copyright (c) 2010-2013, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QTextCodec>
#include <QStringList>
#include <QMap>
#include <TWebApplication>
#include <TThreadApplicationServer>
#include <TPreforkApplicationServer>
#include <TMultiplexingServer>
#include <TSystemGlobal>
#include <stdlib.h>
#include "tsystemglobal.h"
#include "signalhandler.h"
using namespace TreeFrog;
#define CTRL_C_OPTION "--ctrlc-enable"
#define SOCKET_OPTION "-s"
#if QT_VERSION >= 0x050000
static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
QByteArray msg = message.toLocal8Bit();
switch (type) {
case QtFatalMsg:
case QtCriticalMsg:
tSystemError("%s (%s:%u %s)", msg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
tSystemWarn("%s (%s:%u %s)", msg.constData(), context.file, context.line, context.function);
break;
case QtDebugMsg:
tSystemDebug("%s (%s:%u %s)", msg.constData(), context.file, context.line, context.function);
break;
default:
break;
}
}
#else
static void messageOutput(QtMsgType type, const char *msg)
{
switch (type) {
case QtFatalMsg:
case QtCriticalMsg:
tSystemError("%s", msg);
break;
case QtWarningMsg:
tSystemWarn("%s", msg);
break;
case QtDebugMsg:
tSystemDebug("%s", msg);
break;
default:
break;
}
}
#endif // QT_VERSION >= 0x050000
#if defined(Q_OS_UNIX)
static void writeFailure(const void *data, int size)
{
tSystemError("%s", QByteArray((const char *)data, size).data());
}
#endif
static QMap<QString, QString> convertArgs(const QStringList &args)
{
QMap<QString, QString> map;
for (int i = 1; i < args.count(); ++i) {
if (args.value(i).startsWith('-')) {
if (args.value(i + 1).startsWith('-')) {
map.insert(args.value(i), QString());
} else {
map.insert(args.value(i), args.value(i + 1));
++i;
}
}
}
return map;
}
int main(int argc, char *argv[])
{
TWebApplication webapp(argc, argv);
TApplicationServerBase *server = 0;
int ret = -1;
// Setup loggers
tSetupSystemLogger();
tSetupAccessLogger();
tSetupQueryLogger();
tSetupAppLoggers();
#if QT_VERSION >= 0x050000
qInstallMessageHandler(messageOutput);
#else
qInstallMsgHandler(messageOutput);
#endif
QMap<QString, QString> args = convertArgs(QCoreApplication::arguments());
int sock = args.value(SOCKET_OPTION).toInt();
#if defined(Q_OS_UNIX)
webapp.watchUnixSignal(SIGTERM);
if (!args.contains(CTRL_C_OPTION)) {
webapp.ignoreUnixSignal(SIGINT);
}
// Setup signal handlers for SIGSEGV, SIGILL, SIGFPE, SIGABRT and SIGBUS
setupFailureWriter(writeFailure);
setupSignalHandler();
#elif defined(Q_OS_WIN)
if (!args.contains(CTRL_C_OPTION)) {
webapp.ignoreConsoleSignal();
}
#endif
// Sets the app locale
QString loc = webapp.appSettings().value("Locale").toString().trimmed();
if (!loc.isEmpty()) {
QLocale locale(loc);
QLocale::setDefault(locale);
tSystemInfo("Application's default locale: %s", qPrintable(locale.name()));
}
// Sets codec
QTextCodec *codec = webapp.codecForInternal();
QTextCodec::setCodecForLocale(codec);
#if QT_VERSION < 0x050000
QTextCodec::setCodecForTr(codec);
QTextCodec::setCodecForCStrings(codec);
tSystemDebug("setCodecForTr: %s", codec->name().data());
tSystemDebug("setCodecForCStrings: %s", codec->name().data());
#endif
if (!webapp.webRootExists()) {
tSystemError("No such directory");
goto finish;
}
tSystemDebug("Web Root: %s", qPrintable(webapp.webRootPath()));
if (!webapp.appSettingsFileExists()) {
tSystemError("Settings file not found");
goto finish;
}
#ifdef Q_OS_WIN
if (sock <= 0) {
int port = webapp.appSettings().value("ListenPort").toInt();
if (port <= 0 || port > USHRT_MAX) {
tSystemError("Invalid port number: %d", port);
goto finish;
}
TApplicationServerBase::nativeSocketInit();
sock = TApplicationServerBase::nativeListen(QHostAddress::Any, port);
}
#endif
if (sock <= 0) {
tSystemError("Invalid socket descriptor: %d", sock);
goto finish;
}
switch (webapp.multiProcessingModule()) {
case TWebApplication::Thread:
server = new TThreadApplicationServer(sock, &webapp);
break;
case TWebApplication::Prefork: {
TPreforkApplicationServer *svr = new TPreforkApplicationServer(&webapp);
if (svr->setSocketDescriptor(sock)) {
tSystemDebug("Set socket descriptor: %d", sock);
} else {
tSystemError("Failed to set socket descriptor: %d", sock);
goto finish;
}
server = svr;
break; }
case TWebApplication::Hybrid:
#ifdef Q_OS_LINUX
// Sets a listening socket descriptor
TMultiplexingServer::instantiate(sock);
tSystemDebug("Set socket descriptor: %d", sock);
server = TMultiplexingServer::instance();
#else
tFatal("Unsupported MPM: hybrid");
#endif
break;
default:
break;
}
if (!server->start()) {
tSystemError("Server open failed");
goto finish;
}
ret = webapp.exec();
server->stop();
finish:
// Release loggers
tReleaseAppLoggers();
tReleaseQueryLogger();
tReleaseAccessLogger();
tReleaseSystemLogger();
_exit(ret);
return ret;
}
|
add stopping app server after exec().
|
add stopping app server after exec().
|
C++
|
bsd-3-clause
|
seem-sky/treefrog-framework,Akhilesh05/treefrog-framework,skipbit/treefrog-framework,treefrogframework/treefrog-framework,ThomasGueldner/treefrog-framework,Akhilesh05/treefrog-framework,froglogic/treefrog-framework,gonboy/treefrog-framework,AmiArt/treefrog-framework,gonboy/treefrog-framework,Akhilesh05/treefrog-framework,seem-sky/treefrog-framework,skipbit/treefrog-framework,hks2002/treefrog-framework,treefrogframework/treefrog-framework,treefrogframework/treefrog-framework,ThomasGueldner/treefrog-framework,seem-sky/treefrog-framework,AmiArt/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,froglogic/treefrog-framework,froglogic/treefrog-framework,hks2002/treefrog-framework,Akhilesh05/treefrog-framework,froglogic/treefrog-framework,AmiArt/treefrog-framework,ThomasGueldner/treefrog-framework,skipbit/treefrog-framework,gonboy/treefrog-framework,gonboy/treefrog-framework,ThomasGueldner/treefrog-framework,treefrogframework/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,treefrogframework/treefrog-framework,froglogic/treefrog-framework,skipbit/treefrog-framework,gonboy/treefrog-framework,skipbit/treefrog-framework,hks2002/treefrog-framework,ThomasGueldner/treefrog-framework
|
7708627144f5bb8c6524be96e7854039a6502e86
|
core/deleter.hh
|
core/deleter.hh
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DELETER_HH_
#define DELETER_HH_
#include <memory>
#include <cstdlib>
#include <assert.h>
#include <type_traits>
class deleter final {
public:
struct impl;
struct raw_object_tag {};
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
deleter() = default;
deleter(const deleter&) = delete;
deleter(deleter&& x) : _impl(x._impl) { x._impl = nullptr; }
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
~deleter();
deleter& operator=(deleter&& x);
deleter& operator=(deleter&) = delete;
impl& operator*() const { return *_impl; }
impl* operator->() const { return _impl; }
impl* get() const { return _impl; }
void unshare();
deleter share();
explicit operator bool() const { return bool(_impl); }
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
void append(deleter d);
private:
static bool is_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
struct deleter::impl {
unsigned refs = 1;
deleter next;
impl(deleter next) : next(std::move(next)) {}
virtual ~impl() {}
};
inline
deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline
deleter& deleter::operator=(deleter&& x) {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
virtual ~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
template <typename Deleter>
deleter
make_deleter(deleter next, Deleter d) {
return deleter(new lambda_deleter_impl<Deleter>(std::move(next), std::move(d)));
}
template <typename Deleter>
deleter
make_deleter(Deleter d) {
return make_deleter(deleter(), std::move(d));
}
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
virtual ~free_deleter_impl() override { std::free(obj); }
};
inline
deleter
deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline
void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
assert(next_impl != d._impl);
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl));
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
inline
deleter
make_free_deleter(void* obj) {
return deleter(deleter::raw_object_tag(), obj);
}
inline
deleter
make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
#endif /* DELETER_HH_ */
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DELETER_HH_
#define DELETER_HH_
#include <memory>
#include <cstdlib>
#include <assert.h>
#include <type_traits>
class deleter final {
public:
struct impl;
struct raw_object_tag {};
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
deleter() = default;
deleter(const deleter&) = delete;
deleter(deleter&& x) : _impl(x._impl) { x._impl = nullptr; }
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
~deleter();
deleter& operator=(deleter&& x);
deleter& operator=(deleter&) = delete;
impl& operator*() const { return *_impl; }
impl* operator->() const { return _impl; }
impl* get() const { return _impl; }
void unshare();
deleter share();
explicit operator bool() const { return bool(_impl); }
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
void append(deleter d);
private:
static bool is_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
struct deleter::impl {
unsigned refs = 1;
deleter next;
impl(deleter next) : next(std::move(next)) {}
virtual ~impl() {}
};
inline
deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline
deleter& deleter::operator=(deleter&& x) {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
virtual ~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
template <typename Deleter>
deleter
make_deleter(deleter next, Deleter d) {
return deleter(new lambda_deleter_impl<Deleter>(std::move(next), std::move(d)));
}
template <typename Deleter>
deleter
make_deleter(Deleter d) {
return make_deleter(deleter(), std::move(d));
}
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
virtual ~free_deleter_impl() override { std::free(obj); }
};
inline
deleter
deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline
void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
assert(next_impl != d._impl);
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl));
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
inline
deleter
make_free_deleter(void* obj) {
if (!obj) {
return deleter();
}
return deleter(deleter::raw_object_tag(), obj);
}
inline
deleter
make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
#endif /* DELETER_HH_ */
|
improve make_free_deleter() with null input
|
deleter: improve make_free_deleter() with null input
While make_free_deleter(nullptr) will function correctly,
deleter::operator bool() on the result will not.
Fix by checking for null, and avoiding the free deleter optimization in
that case -- it doesn't help anyway.
|
C++
|
agpl-3.0
|
raphaelsc/scylla,bowlofstew/seastar,avikivity/seastar,acbellini/scylla,glommer/scylla,respu/scylla,phonkee/scylla,wildinto/seastar,dwdm/scylla,eklitzke/scylla,raphaelsc/seastar,wildinto/seastar,avikivity/scylla,hongliangzhao/seastar,dwdm/scylla,mixja/seastar,flashbuckets/seastar,chunshengster/seastar,sjperkins/seastar,acbellini/scylla,acbellini/seastar,dwdm/seastar,senseb/scylla,kjniemi/scylla,senseb/scylla,dwdm/scylla,rluta/scylla,kjniemi/seastar,kjniemi/seastar,kangkot/scylla,koolhazz/seastar,scylladb/scylla,avikivity/scylla,aruanruan/scylla,rentongzhang/scylla,chunshengster/seastar,linearregression/scylla,capturePointer/scylla,slivne/seastar,scylladb/scylla,respu/scylla,glommer/scylla,eklitzke/scylla,sjperkins/seastar,flashbuckets/seastar,dreamsxin/seastar,mixja/seastar,wildinto/scylla,gwicke/scylla,stamhe/seastar,anzihenry/seastar,phonkee/scylla,xtao/seastar,jonathanleang/seastar,hongliangzhao/seastar,ducthangho/imdb,stamhe/scylla,aruanruan/scylla,avikivity/scylla,tempbottle/scylla,scylladb/scylla-seastar,anzihenry/seastar,kjniemi/seastar,bowlofstew/seastar,norcimo5/seastar,rentongzhang/scylla,justintung/scylla,mixja/seastar,justintung/scylla,bzero/seastar,cloudius-systems/seastar,syuu1228/seastar,asias/scylla,scylladb/scylla-seastar,scylladb/seastar,rluta/scylla,linearregression/seastar,kjniemi/scylla,raphaelsc/scylla,duarten/scylla,capturePointer/scylla,avikivity/seastar,syuu1228/seastar,shyamalschandra/seastar,victorbriz/scylla,gwicke/scylla,tempbottle/scylla,kjniemi/scylla,scylladb/scylla-seastar,kangkot/scylla,rluta/scylla,scylladb/seastar,aruanruan/scylla,shyamalschandra/seastar,leejir/seastar,koolhazz/seastar,senseb/scylla,capturePointer/scylla,asias/scylla,linearregression/seastar,guiquanz/scylla,norcimo5/seastar,asias/scylla,bowlofstew/scylla,joerg84/seastar,respu/scylla,justintung/scylla,guiquanz/scylla,koolhazz/seastar,leejir/seastar,raphaelsc/seastar,cloudius-systems/seastar,printedheart/seastar,wildinto/scylla,avikivity/seastar,bzero/seastar,tempbottle/scylla,flashbuckets/seastar,gwicke/scylla,jonathanleang/seastar,shaunstanislaus/scylla,shaunstanislaus/scylla,joerg84/seastar,shyamalschandra/seastar,kangkot/scylla,scylladb/scylla,printedheart/seastar,tempbottle/seastar,bowlofstew/scylla,acbellini/scylla,tempbottle/seastar,syuu1228/seastar,guiquanz/scylla,eklitzke/scylla,linearregression/scylla,wildinto/seastar,slivne/seastar,linearregression/scylla,duarten/scylla,leejir/seastar,xtao/seastar,hongliangzhao/seastar,wildinto/scylla,stamhe/seastar,scylladb/scylla,glommer/scylla,dreamsxin/seastar,victorbriz/scylla,ducthangho/imdb,joerg84/seastar,bowlofstew/seastar,printedheart/seastar,acbellini/seastar,stamhe/scylla,rentongzhang/scylla,scylladb/seastar,chunshengster/seastar,slivne/seastar,linearregression/seastar,norcimo5/seastar,xtao/seastar,phonkee/scylla,raphaelsc/seastar,duarten/scylla,cloudius-systems/seastar,shaunstanislaus/scylla,tempbottle/seastar,bzero/seastar,sjperkins/seastar,stamhe/seastar,stamhe/scylla,ducthangho/imdb,dreamsxin/seastar,bowlofstew/scylla,jonathanleang/seastar,dwdm/seastar,acbellini/seastar,victorbriz/scylla,anzihenry/seastar,raphaelsc/scylla,dwdm/seastar
|
e744d0bc8ce11125065f228fa9b74904285e8485
|
tree/treeplayer/test/leafs.cxx
|
tree/treeplayer/test/leafs.cxx
|
#include "ROOT/RMakeUnique.hxx"
#include "TInterpreter.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include "gtest/gtest.h"
#include "data.h"
#include "RErrorIgnoreRAII.hxx"
TEST(TTreeReaderLeafs, LeafListCaseA) {
// From "Case A" of the TTree class doc:
const char* str = "This is a null-terminated string literal";
signed char SChar = 2;
unsigned char UChar = 3;
signed short SShort = 4;
unsigned short UShort = 5;
signed int SInt = 6;
unsigned int UInt = 7;
float Float = 8.;
double Double = 9.;
long long SLL = 10;
unsigned long long ULL = 11;
long SL = 12;
unsigned long UL = 13;
bool Bool = true;
auto tree = std::make_unique<TTree>("T", "In-memory test tree");
tree->Branch("C", &str, "C/C");
tree->Branch("B", &SChar, "B/B");
tree->Branch("b", &UChar, "b/b");
tree->Branch("S", &SShort, "S/S");
tree->Branch("s", &UShort, "s/s");
tree->Branch("I", &SInt, "I/I");
tree->Branch("i", &UInt, "i/i");
tree->Branch("F", &Float, "F/F");
tree->Branch("D", &Double, "D/D");
tree->Branch("L", &SLL, "L/L");
tree->Branch("l", &ULL, "l/l");
tree->Branch("G", &SL, "G/G");
tree->Branch("g", &UL, "g/g");
tree->Branch("O", &Bool, "O/O");
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader TR(tree.get());
//TTreeReaderValue<const char*> trStr(TR, "C");
TTreeReaderValue<signed char> trSChar(TR, "B");
TTreeReaderValue<unsigned char> trUChar(TR, "b");
TTreeReaderValue<signed short> trSShort(TR, "S");
TTreeReaderValue<unsigned short> trUShort(TR, "s");
TTreeReaderValue<signed int> trSInt(TR, "I");
TTreeReaderValue<unsigned int> trUInt(TR, "i");
TTreeReaderValue<float> trFloat(TR, "F");
TTreeReaderValue<double> trDouble(TR, "D");
TTreeReaderValue<signed long long> trSLL(TR, "L");
TTreeReaderValue<unsigned long long> trULL(TR, "l");
TTreeReaderValue<signed long> trSL(TR, "G");
TTreeReaderValue<unsigned long> trUL(TR, "g");
TTreeReaderValue<bool> trBool(TR, "O");
TR.SetEntry(1);
//EXPECT_STREQ(str, *trStr);
EXPECT_EQ(SChar, *trSChar);
EXPECT_EQ(UChar, *trUChar);
EXPECT_EQ(SShort, *trSShort);
EXPECT_EQ(UShort, *trUShort);
EXPECT_EQ(SInt, *trSInt);
EXPECT_EQ(UInt, *trUInt);
EXPECT_FLOAT_EQ(Float, *trFloat);
EXPECT_DOUBLE_EQ(Double, *trDouble);
EXPECT_EQ(SLL, *trSLL);
EXPECT_EQ(ULL, *trULL);
EXPECT_EQ(SL, *trSL);
EXPECT_EQ(UL, *trUL);
EXPECT_EQ(Bool, *trBool);
}
std::unique_ptr<TTree> CreateTree() {
TInterpreter::EErrorCode error = TInterpreter::kNoError;
gInterpreter->ProcessLine("#include \"data.h\"", &error);
if (error != TInterpreter::kNoError)
return {};
Data data;
auto tree = std::make_unique<TTree>("T", "test tree");
tree->Branch("Data", &data);
data.fArray = new double[4]{12., 13., 14., 15.};
data.fSize = 4;
data.fUArray = new float[2]{42., 43.};
data.fUSize = 2;
data.fVec = { 17., 18., 19., 20., 21., 22.};
data.fDouble32 = 17.;
data.fFloat16 = 44.;
tree->Fill();
data.fVec.clear();
data.fVec.resize(3210, 1001.f); // ROOT-8747
tree->Fill();
data.fVec.clear();
data.fVec.resize(2, 42.f); // ROOT-8747
tree->Fill();
tree->ResetBranchAddresses();
return tree;
}
TEST(TTreeReaderLeafs, LeafList) {
auto tree = CreateTree();
ASSERT_NE(nullptr, tree.get());
TTreeReader tr(tree.get());
TTreeReaderArray<double> arr(tr, "fArray");
TTreeReaderArray<float> arrU(tr, "fUArray");
TTreeReaderArray<double> vec(tr, "fVec");
TTreeReaderValue<Double32_t> d32(tr, "fDouble32");
TTreeReaderValue<Float16_t> f16(tr, "fFloat16");
tr.Next();
EXPECT_EQ(4u, arr.GetSize());
EXPECT_EQ(2u, arrU.GetSize());
EXPECT_EQ(6u, vec.GetSize());
//FAILS EXPECT_FLOAT_EQ(13., arr[1]);
//FAILS EXPECT_DOUBLE_EQ(43., arrU[1]);
EXPECT_DOUBLE_EQ(19., vec[2]);
EXPECT_DOUBLE_EQ(17., vec[0]);
// T->Scan("fUArray") claims fUArray only has one instance per row.
EXPECT_FLOAT_EQ(17, *d32);
EXPECT_FLOAT_EQ(44, *f16);
tr.Next();
EXPECT_FLOAT_EQ(1001.f, vec[1]); // ROOT-8747
EXPECT_EQ(3210u, vec.GetSize());
tr.Next();
EXPECT_FLOAT_EQ(42.f, vec[1]); // ROOT-8747
EXPECT_EQ(2u, vec.GetSize());
tree.release();
}
TEST(TTreeReaderLeafs, TArrayD) {
// https://root-forum.cern.ch/t/tarrayd-in-ttreereadervalue/24495
auto tree = std::make_unique<TTree>("TTreeReaderLeafsTArrayD", "In-memory test tree");
TArrayD arrD(7);
for (int i = 0; i < arrD.GetSize(); ++i)
arrD.SetAt(i + 2., i);
tree->Branch("arrD", &arrD);
tree->Fill();
tree->Fill();
tree->Fill();
tree->ResetBranchAddresses();
TTreeReader tr(tree.get());
TTreeReaderValue<TArrayD> arr(tr, "arrD");
tr.SetEntry(1);
EXPECT_EQ(7, arr->GetSize());
EXPECT_DOUBLE_EQ(4., (*arr)[2]);
EXPECT_DOUBLE_EQ(2., (*arr)[0]);
}
TEST(TTreeReaderLeafs, ArrayWithReaderValue)
{
// reading a float[] with a TTreeReaderValue should cause an error
auto tree = std::make_unique<TTree>("arraywithreadervaluetree", "test tree");
std::vector<double> arr = {42., 84.};
tree->Branch("arr", arr.data(), "arr[2]/D");
tree->Fill();
tree->ResetBranchAddresses();
TTreeReader tr(tree.get());
TTreeReaderValue<double> valueOfArr(tr, "arr");
{
RErrorIgnoreRAII errorIgnRAII;
tr.Next();
*valueOfArr;
}
EXPECT_FALSE(valueOfArr.IsValid());
}
TEST(TTreeReaderLeafs, NamesWithDots)
{
gInterpreter->ProcessLine(".L data.h+");
TTree tree("t", "t");
V v;
v.a = 64;
tree.Branch("v", &v, "a/I");
W w;
w.v.a = 132;
tree.Branch("w", &w);
tree.Fill();
TTreeReader tr(&tree);
TTreeReaderValue<int> rv(tr, "v.a");
tr.Next();
EXPECT_EQ(*rv, 64) << "The wrong leaf has been read!";
}
// This is ROOT-9743
struct Event {
float bla = 3.14f;
int truth_type = 1;
};
TEST(TTreeReaderLeafs, MultipleReaders) {
TTree t("t","t");
Event event;
t.Branch ("event", &event, "bla/F:truth_type/I");
t.Fill();
TTreeReader r(&t);
TTreeReaderValue<int> v1(r, "event.truth_type");
TTreeReaderValue<int> v2(r, "event.truth_type");
TTreeReaderValue<int> v3(r, "event.truth_type");
r.Next();
EXPECT_EQ(*v1, 1) << "Wrong value read for rv1!";
EXPECT_EQ(*v2, 1) << "Wrong value read for rv2!";
EXPECT_EQ(*v3, 1) << "Wrong value read for rv3!";
}
|
#include "ROOT/RMakeUnique.hxx"
#include "TInterpreter.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include "gtest/gtest.h"
#include "data.h"
#include "RErrorIgnoreRAII.hxx"
TEST(TTreeReaderLeafs, LeafListCaseA) {
// From "Case A" of the TTree class doc:
const char* str = "This is a null-terminated string literal";
signed char SChar = 2;
unsigned char UChar = 3;
signed short SShort = 4;
unsigned short UShort = 5;
signed int SInt = 6;
unsigned int UInt = 7;
float Float = 8.;
double Double = 9.;
long long SLL = 10;
unsigned long long ULL = 11;
long SL = 12;
unsigned long UL = 13;
bool Bool = true;
auto tree = std::make_unique<TTree>("T", "In-memory test tree");
tree->Branch("C", &str, "C/C");
tree->Branch("B", &SChar, "B/B");
tree->Branch("b", &UChar, "b/b");
tree->Branch("S", &SShort, "S/S");
tree->Branch("s", &UShort, "s/s");
tree->Branch("I", &SInt, "I/I");
tree->Branch("i", &UInt, "i/i");
tree->Branch("F", &Float, "F/F");
tree->Branch("D", &Double, "D/D");
tree->Branch("L", &SLL, "L/L");
tree->Branch("l", &ULL, "l/l");
tree->Branch("G", &SL, "G/G");
tree->Branch("g", &UL, "g/g");
tree->Branch("O", &Bool, "O/O");
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader TR(tree.get());
//TTreeReaderValue<const char*> trStr(TR, "C");
TTreeReaderValue<signed char> trSChar(TR, "B");
TTreeReaderValue<unsigned char> trUChar(TR, "b");
TTreeReaderValue<signed short> trSShort(TR, "S");
TTreeReaderValue<unsigned short> trUShort(TR, "s");
TTreeReaderValue<signed int> trSInt(TR, "I");
TTreeReaderValue<unsigned int> trUInt(TR, "i");
TTreeReaderValue<float> trFloat(TR, "F");
TTreeReaderValue<double> trDouble(TR, "D");
TTreeReaderValue<signed long long> trSLL(TR, "L");
TTreeReaderValue<unsigned long long> trULL(TR, "l");
TTreeReaderValue<signed long> trSL(TR, "G");
TTreeReaderValue<unsigned long> trUL(TR, "g");
TTreeReaderValue<bool> trBool(TR, "O");
TR.SetEntry(1);
//EXPECT_STREQ(str, *trStr);
EXPECT_EQ(SChar, *trSChar);
EXPECT_EQ(UChar, *trUChar);
EXPECT_EQ(SShort, *trSShort);
EXPECT_EQ(UShort, *trUShort);
EXPECT_EQ(SInt, *trSInt);
EXPECT_EQ(UInt, *trUInt);
EXPECT_FLOAT_EQ(Float, *trFloat);
EXPECT_DOUBLE_EQ(Double, *trDouble);
EXPECT_EQ(SLL, *trSLL);
EXPECT_EQ(ULL, *trULL);
EXPECT_EQ(SL, *trSL);
EXPECT_EQ(UL, *trUL);
EXPECT_EQ(Bool, *trBool);
}
std::unique_ptr<TTree> CreateTree() {
TInterpreter::EErrorCode error = TInterpreter::kNoError;
gInterpreter->ProcessLine("#include \"data.h\"", &error);
if (error != TInterpreter::kNoError)
return {};
Data data;
auto tree = std::make_unique<TTree>("T", "test tree");
tree->Branch("Data", &data);
data.fArray = new double[4]{12., 13., 14., 15.};
data.fSize = 4;
data.fUArray = new float[2]{42., 43.};
data.fUSize = 2;
data.fVec = { 17., 18., 19., 20., 21., 22.};
data.fDouble32 = 17.;
data.fFloat16 = 44.;
tree->Fill();
data.fVec.clear();
data.fVec.resize(3210, 1001.f); // ROOT-8747
tree->Fill();
data.fVec.clear();
data.fVec.resize(2, 42.f); // ROOT-8747
tree->Fill();
tree->ResetBranchAddresses();
return tree;
}
TEST(TTreeReaderLeafs, LeafList) {
auto tree = CreateTree();
ASSERT_NE(nullptr, tree.get());
TTreeReader tr(tree.get());
TTreeReaderArray<double> arr(tr, "fArray");
TTreeReaderArray<float> arrU(tr, "fUArray");
TTreeReaderArray<double> vec(tr, "fVec");
TTreeReaderValue<Double32_t> d32(tr, "fDouble32");
TTreeReaderValue<Float16_t> f16(tr, "fFloat16");
tr.Next();
EXPECT_EQ(4u, arr.GetSize());
EXPECT_EQ(2u, arrU.GetSize());
EXPECT_EQ(6u, vec.GetSize());
//FAILS EXPECT_FLOAT_EQ(13., arr[1]);
//FAILS EXPECT_DOUBLE_EQ(43., arrU[1]);
EXPECT_DOUBLE_EQ(19., vec[2]);
EXPECT_DOUBLE_EQ(17., vec[0]);
// T->Scan("fUArray") claims fUArray only has one instance per row.
EXPECT_FLOAT_EQ(17, *d32);
EXPECT_FLOAT_EQ(44, *f16);
tr.Next();
EXPECT_FLOAT_EQ(1001.f, vec[1]); // ROOT-8747
EXPECT_EQ(3210u, vec.GetSize());
tr.Next();
EXPECT_FLOAT_EQ(42.f, vec[1]); // ROOT-8747
EXPECT_EQ(2u, vec.GetSize());
tree.release();
}
TEST(TTreeReaderLeafs, TArrayD) {
// https://root-forum.cern.ch/t/tarrayd-in-ttreereadervalue/24495
auto tree = std::make_unique<TTree>("TTreeReaderLeafsTArrayD", "In-memory test tree");
TArrayD arrD(7);
for (int i = 0; i < arrD.GetSize(); ++i)
arrD.SetAt(i + 2., i);
tree->Branch("arrD", &arrD);
tree->Fill();
tree->Fill();
tree->Fill();
tree->ResetBranchAddresses();
TTreeReader tr(tree.get());
TTreeReaderValue<TArrayD> arr(tr, "arrD");
tr.SetEntry(1);
EXPECT_EQ(7, arr->GetSize());
EXPECT_DOUBLE_EQ(4., (*arr)[2]);
EXPECT_DOUBLE_EQ(2., (*arr)[0]);
}
TEST(TTreeReaderLeafs, ArrayWithReaderValue)
{
// reading a float[] with a TTreeReaderValue should cause an error
auto tree = std::make_unique<TTree>("arraywithreadervaluetree", "test tree");
std::vector<double> arr = {42., 84.};
tree->Branch("arr", arr.data(), "arr[2]/D");
tree->Fill();
tree->ResetBranchAddresses();
TTreeReader tr(tree.get());
TTreeReaderValue<double> valueOfArr(tr, "arr");
{
RErrorIgnoreRAII errorIgnRAII;
tr.Next();
*valueOfArr;
}
EXPECT_FALSE(valueOfArr.IsValid());
}
TEST(TTreeReaderLeafs, NamesWithDots)
{
gInterpreter->ProcessLine(".L data.h+");
TTree tree("t", "t");
V v;
v.a = 64;
tree.Branch("v", &v, "a/I");
W w;
w.v.a = 132;
tree.Branch("w", &w);
tree.Fill();
TTreeReader tr(&tree);
TTreeReaderValue<int> rv(tr, "v.a");
tr.Next();
EXPECT_EQ(*rv, 64) << "The wrong leaf has been read!";
}
// This is ROOT-9743
struct Event {
float bla = 3.14f;
int truth_type = 1;
};
TEST(TTreeReaderLeafs, MultipleReaders) {
TTree t("t","t");
Event event;
t.Branch ("event", &event, "bla/F:truth_type/I");
t.Fill();
TTreeReader r(&t);
TTreeReaderValue<int> v1(r, "event.truth_type");
TTreeReaderValue<int> v2(r, "event.truth_type");
TTreeReaderValue<int> v3(r, "event.truth_type");
r.Next();
EXPECT_EQ(*v1, 1) << "Wrong value read for rv1!";
EXPECT_EQ(*v2, 1) << "Wrong value read for rv2!";
EXPECT_EQ(*v3, 1) << "Wrong value read for rv3!";
}
// Test for https://github.com/root-project/root/issues/6881
TEST(TTreeReaderLeafs, BranchAndLeafWithDifferentNames)
{
TTree t("t", "t");
int x = 42;
t.Branch("x", &x, "y/I");
t.Fill();
TTreeReader r(&t);
TTreeReaderValue<int> rv(r, "x");
ASSERT_TRUE(r.Next());
EXPECT_EQ(*rv, 42);
EXPECT_FALSE(r.Next());
}
|
Add test for #6881 (different leaf/branch names)
|
[treereader] Add test for #6881 (different leaf/branch names)
|
C++
|
lgpl-2.1
|
olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root
|
1e639b28dc8d4379c397e14fdf5e9268975f8d65
|
lib/xray/xray_init.cc
|
lib/xray/xray_init.cc
|
//===-- xray_init.cc --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
// XRay initialisation logic.
//===----------------------------------------------------------------------===//
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>
#include "sanitizer_common/sanitizer_common.h"
#include "xray_defs.h"
#include "xray_flags.h"
#include "xray_interface_internal.h"
extern "C" {
void __xray_init();
extern const XRaySledEntry __start_xray_instr_map[] __attribute__((weak));
extern const XRaySledEntry __stop_xray_instr_map[] __attribute__((weak));
extern const XRayFunctionSledIndex __start_xray_fn_idx[] __attribute__((weak));
extern const XRayFunctionSledIndex __stop_xray_fn_idx[] __attribute__((weak));
}
using namespace __xray;
// When set to 'true' this means the XRay runtime has been initialised. We use
// the weak symbols defined above (__start_xray_inst_map and
// __stop_xray_instr_map) to initialise the instrumentation map that XRay uses
// for runtime patching/unpatching of instrumentation points.
//
// FIXME: Support DSO instrumentation maps too. The current solution only works
// for statically linked executables.
__sanitizer::atomic_uint8_t XRayInitialized{0};
// This should always be updated before XRayInitialized is updated.
__sanitizer::SpinMutex XRayInstrMapMutex;
XRaySledMap XRayInstrMap;
// Global flag to determine whether the flags have been initialized.
__sanitizer::atomic_uint8_t XRayFlagsInitialized{0};
// A mutex to allow only one thread to initialize the XRay data structures.
__sanitizer::SpinMutex XRayInitMutex;
// __xray_init() will do the actual loading of the current process' memory map
// and then proceed to look for the .xray_instr_map section/segment.
void __xray_init() XRAY_NEVER_INSTRUMENT {
__sanitizer::SpinMutexLock Guard(&XRayInitMutex);
// Short-circuit if we've already initialized XRay before.
if (__sanitizer::atomic_load(&XRayInitialized,
__sanitizer::memory_order_acquire))
return;
if (!__sanitizer::atomic_load(&XRayFlagsInitialized,
__sanitizer::memory_order_acquire)) {
initializeFlags();
__sanitizer::atomic_store(&XRayFlagsInitialized, true,
__sanitizer::memory_order_release);
}
if (__start_xray_instr_map == nullptr) {
if (Verbosity())
Report("XRay instrumentation map missing. Not initializing XRay.\n");
return;
}
{
__sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
XRayInstrMap.Sleds = __start_xray_instr_map;
XRayInstrMap.Entries = __stop_xray_instr_map - __start_xray_instr_map;
XRayInstrMap.SledsIndex = __start_xray_fn_idx;
XRayInstrMap.Functions = __stop_xray_fn_idx - __start_xray_fn_idx;
}
__sanitizer::atomic_store(&XRayInitialized, true,
__sanitizer::memory_order_release);
#ifndef XRAY_NO_PREINIT
if (flags()->patch_premain)
__xray_patch();
#endif
}
// Only add the preinit array initialization if the sanitizers can.
#if !defined(XRAY_NO_PREINIT) && SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"),
used)) void (*__local_xray_preinit)(void) = __xray_init;
#endif
|
//===-- xray_init.cc --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
// XRay initialisation logic.
//===----------------------------------------------------------------------===//
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>
#include "sanitizer_common/sanitizer_common.h"
#include "xray_defs.h"
#include "xray_flags.h"
#include "xray_interface_internal.h"
extern "C" {
void __xray_init();
extern const XRaySledEntry __start_xray_instr_map[] __attribute__((weak));
extern const XRaySledEntry __stop_xray_instr_map[] __attribute__((weak));
extern const XRayFunctionSledIndex __start_xray_fn_idx[] __attribute__((weak));
extern const XRayFunctionSledIndex __stop_xray_fn_idx[] __attribute__((weak));
}
using namespace __xray;
// When set to 'true' this means the XRay runtime has been initialised. We use
// the weak symbols defined above (__start_xray_inst_map and
// __stop_xray_instr_map) to initialise the instrumentation map that XRay uses
// for runtime patching/unpatching of instrumentation points.
//
// FIXME: Support DSO instrumentation maps too. The current solution only works
// for statically linked executables.
__sanitizer::atomic_uint8_t XRayInitialized{0};
// This should always be updated before XRayInitialized is updated.
__sanitizer::SpinMutex XRayInstrMapMutex;
XRaySledMap XRayInstrMap;
// Global flag to determine whether the flags have been initialized.
__sanitizer::atomic_uint8_t XRayFlagsInitialized{0};
// A mutex to allow only one thread to initialize the XRay data structures.
__sanitizer::SpinMutex XRayInitMutex;
// __xray_init() will do the actual loading of the current process' memory map
// and then proceed to look for the .xray_instr_map section/segment.
void __xray_init() XRAY_NEVER_INSTRUMENT {
__sanitizer::SpinMutexLock Guard(&XRayInitMutex);
// Short-circuit if we've already initialized XRay before.
if (__sanitizer::atomic_load(&XRayInitialized,
__sanitizer::memory_order_acquire))
return;
if (!__sanitizer::atomic_load(&XRayFlagsInitialized,
__sanitizer::memory_order_acquire)) {
initializeFlags();
__sanitizer::atomic_store(&XRayFlagsInitialized, true,
__sanitizer::memory_order_release);
}
if (__start_xray_instr_map == nullptr) {
if (Verbosity())
Report("XRay instrumentation map missing. Not initializing XRay.\n");
return;
}
{
__sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
XRayInstrMap.Sleds = __start_xray_instr_map;
XRayInstrMap.Entries = __stop_xray_instr_map - __start_xray_instr_map;
XRayInstrMap.SledsIndex = __start_xray_fn_idx;
XRayInstrMap.Functions = __stop_xray_fn_idx - __start_xray_fn_idx;
}
__sanitizer::atomic_store(&XRayInitialized, true,
__sanitizer::memory_order_release);
#ifndef XRAY_NO_PREINIT
if (flags()->patch_premain)
__xray_patch();
#endif
}
#if !defined(XRAY_NO_PREINIT) && SANITIZER_CAN_USE_PREINIT_ARRAY
// Only add the preinit array initialization if the sanitizers can.
__attribute__((section(".preinit_array"),
used)) void (*__local_xray_preinit)(void) = __xray_init;
#else
// If we cannot use the .preinit_array section, we should instead use dynamic
// initialisation.
static bool UNUSED __local_xray_dyninit = [] {
__xray_init();
return true;
}();
#endif
|
Use dynamic initialisation as an alternative
|
[XRay][compiler-rt][Darwin] Use dynamic initialisation as an alternative
Summary:
In cases where we can't use the .preinit_array section (as in Darwin for
example) we instead use dynamic initialisation. We know that this
alternative approach will race with the initializers of other objects at
global scope, but this is strictly better than nothing.
Reviewers: kubamracek, nglevin
Subscribers: llvm-commits
Differential Revision: https://reviews.llvm.org/D40599
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@319366 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
a57c0dd9c0618eceffeabc2891aa3b1be4096cdb
|
tests/src/tags/tag-database-test-suite.cpp
|
tests/src/tags/tag-database-test-suite.cpp
|
#include "tag-database-test-suite.h"
#include <QtTest>
#include "tags/tag.h"
TagDatabaseTestSuite::TagDatabaseTestSuite(TagDatabase *database)
: m_database(database)
{}
void TagDatabaseTestSuite::initTestCase()
{
m_database->load();
m_database->setTags(QList<Tag>());
}
void TagDatabaseTestSuite::testTypesProperlyLoaded()
{
QMap<int, TagType> types = m_database->tagTypes();
QCOMPARE(types.count(), 4);
QCOMPARE(types.keys(), QList<int>() << 0 << 1 << 3 << 4);
QCOMPARE(types.value(0).name(), QString("general"));
QCOMPARE(types.value(1).name(), QString("artist"));
QCOMPARE(types.value(3).name(), QString("copyright"));
QCOMPARE(types.value(4).name(), QString("character"));
}
void TagDatabaseTestSuite::testEmptyContainsNone()
{
m_database->setTags(QList<Tag>());
QTime timer;
timer.start();
QMap<QString, TagType> types = m_database->getTagTypes(QStringList() << "tag1" << "tag3");
int elapsed = timer.elapsed();
QCOMPARE(types.count(), 0);
qDebug() << "Elapsed" << elapsed << "ms";
QVERIFY(elapsed < 20);
}
void TagDatabaseTestSuite::testFilledContainsAll()
{
m_database->setTags(QList<Tag>() << Tag("tag1", TagType("general")) << Tag("tag2", TagType("artist")) << Tag("tag3", TagType("copyright")) << Tag("tag4", TagType("character")));
QTime timer;
timer.start();
QMap<QString, TagType> types = m_database->getTagTypes(QStringList() << "tag1" << "tag3");
int elapsed = timer.elapsed();
QCOMPARE(types.count(), 2);
QCOMPARE(types.contains("tag1"), true);
QCOMPARE(types.contains("tag3"), true);
QCOMPARE(types.value("tag1").name(), QString("general"));
QCOMPARE(types.value("tag3").name(), QString("copyright"));
qDebug() << "Elapsed" << elapsed << "ms";
QVERIFY(elapsed < 10);
}
void TagDatabaseTestSuite::testFilledContainsSome()
{
m_database->setTags(QList<Tag>() << Tag("tag1", TagType("general")) << Tag("tag2", TagType("artist")) << Tag("tag3", TagType("copyright")) << Tag("tag4", TagType("character")));
QTime timer;
timer.start();
QMap<QString, TagType> types = m_database->getTagTypes(QStringList() << "tag1" << "tag3" << "tag5" << "missing_tag");
int elapsed = timer.elapsed();
QCOMPARE(types.count(), 2);
QCOMPARE(types.contains("tag1"), true);
QCOMPARE(types.contains("tag3"), true);
QCOMPARE(types.contains("tag5"), false);
QCOMPARE(types.contains("missing_tag"), false);
QCOMPARE(types.value("tag1").name(), QString("general"));
QCOMPARE(types.value("tag3").name(), QString("copyright"));
qDebug() << "Elapsed" << elapsed << "ms";
QVERIFY(elapsed < 10);
}
|
#include "tag-database-test-suite.h"
#include <QtTest>
#include "tags/tag.h"
TagDatabaseTestSuite::TagDatabaseTestSuite(TagDatabase *database)
: m_database(database)
{}
void TagDatabaseTestSuite::initTestCase()
{
m_database->load();
m_database->setTags(QList<Tag>());
}
void TagDatabaseTestSuite::testTypesProperlyLoaded()
{
QMap<int, TagType> types = m_database->tagTypes();
QCOMPARE(types.count(), 4);
QCOMPARE(types.keys(), QList<int>() << 0 << 1 << 3 << 4);
QCOMPARE(types.value(0).name(), QString("general"));
QCOMPARE(types.value(1).name(), QString("artist"));
QCOMPARE(types.value(3).name(), QString("copyright"));
QCOMPARE(types.value(4).name(), QString("character"));
}
void TagDatabaseTestSuite::testEmptyContainsNone()
{
m_database->setTags(QList<Tag>());
QTime timer;
timer.start();
QMap<QString, TagType> types = m_database->getTagTypes(QStringList() << "tag1" << "tag3");
int elapsed = timer.elapsed();
QCOMPARE(types.count(), 0);
qDebug() << "Elapsed" << elapsed << "ms";
QVERIFY(elapsed < 20);
QCOMPARE(m_database->count(), 0);
}
void TagDatabaseTestSuite::testFilledContainsAll()
{
m_database->setTags(QList<Tag>() << Tag("tag1", TagType("general")) << Tag("tag2", TagType("artist")) << Tag("tag3", TagType("copyright")) << Tag("tag4", TagType("character")));
QTime timer;
timer.start();
QMap<QString, TagType> types = m_database->getTagTypes(QStringList() << "tag1" << "tag3");
int elapsed = timer.elapsed();
QCOMPARE(types.count(), 2);
QCOMPARE(types.contains("tag1"), true);
QCOMPARE(types.contains("tag3"), true);
QCOMPARE(types.value("tag1").name(), QString("general"));
QCOMPARE(types.value("tag3").name(), QString("copyright"));
qDebug() << "Elapsed" << elapsed << "ms";
QVERIFY(elapsed < 10);
QCOMPARE(m_database->count(), 4);
}
void TagDatabaseTestSuite::testFilledContainsSome()
{
m_database->setTags(QList<Tag>() << Tag("tag1", TagType("general")) << Tag("tag2", TagType("artist")) << Tag("tag3", TagType("copyright")) << Tag("tag4", TagType("character")));
QTime timer;
timer.start();
QMap<QString, TagType> types = m_database->getTagTypes(QStringList() << "tag1" << "tag3" << "tag5" << "missing_tag");
int elapsed = timer.elapsed();
QCOMPARE(types.count(), 2);
QCOMPARE(types.contains("tag1"), true);
QCOMPARE(types.contains("tag3"), true);
QCOMPARE(types.contains("tag5"), false);
QCOMPARE(types.contains("missing_tag"), false);
QCOMPARE(types.value("tag1").name(), QString("general"));
QCOMPARE(types.value("tag3").name(), QString("copyright"));
qDebug() << "Elapsed" << elapsed << "ms";
QVERIFY(elapsed < 10);
}
|
Add tests for TagDatabase::count
|
Add tests for TagDatabase::count
|
C++
|
apache-2.0
|
Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber
|
afbe3ea870ca40cfc1fff67ff80533b0bd3b4bd2
|
sd/source/ui/inc/fuediglu.hxx
|
sd/source/ui/inc/fuediglu.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_FU_EDIT_GLUE_POINTS_HXX
#define SD_FU_EDIT_GLUE_POINTS_HXX
#include "fudraw.hxx"
namespace sd {
/*************************************************************************
|*
|* FuEditGluePoints
|*
\************************************************************************/
class SD_DLLPUBLIC FuEditGluePoints
: public FuDraw
{
public:
TYPEINFO();
static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent );
virtual void DoExecute( SfxRequest& rReq );
// Mouse- & Key-Events
virtual sal_Bool KeyInput(const KeyEvent& rKEvt);
virtual sal_Bool MouseMove(const MouseEvent& rMEvt);
virtual sal_Bool MouseButtonUp(const MouseEvent& rMEvt);
virtual sal_Bool MouseButtonDown(const MouseEvent& rMEvt);
virtual sal_Bool Command(const CommandEvent& rCEvt);
virtual void ReceiveRequest(SfxRequest& rReq);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
protected:
FuEditGluePoints (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuEditGluePoints (void);
};
} // end of namespace sd
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_FU_EDIT_GLUE_POINTS_HXX
#define SD_FU_EDIT_GLUE_POINTS_HXX
#include "fudraw.hxx"
namespace sd {
/*************************************************************************
|*
|* FuEditGluePoints
|*
\************************************************************************/
class FuEditGluePoints
: public FuDraw
{
public:
TYPEINFO();
static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent );
virtual void DoExecute( SfxRequest& rReq );
// Mouse- & Key-Events
virtual sal_Bool KeyInput(const KeyEvent& rKEvt);
virtual sal_Bool MouseMove(const MouseEvent& rMEvt);
virtual sal_Bool MouseButtonUp(const MouseEvent& rMEvt);
virtual sal_Bool MouseButtonDown(const MouseEvent& rMEvt);
virtual sal_Bool Command(const CommandEvent& rCEvt);
virtual void ReceiveRequest(SfxRequest& rReq);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
protected:
FuEditGluePoints (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuEditGluePoints (void);
};
} // end of namespace sd
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Remove SD_DLLPUBLIC, it breaks Windows build.
|
Remove SD_DLLPUBLIC, it breaks Windows build.
If there is a method that needs to be public, better SD_DLLPUBLIC just that one.
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
0bb18b98553179fc20bdfb022d86b737c70f51b2
|
cpp/src/toppra/solver/qpOASES-wrapper.cpp
|
cpp/src/toppra/solver/qpOASES-wrapper.cpp
|
#include <toppra/solver/qpOASES-wrapper.hpp>
#include <qpOASES.hpp>
#include <toppra/toppra.hpp>
namespace toppra {
namespace solver {
struct qpOASESWrapper::Impl {
qpOASES::SQProblem qp;
Impl(Eigen::Index nV, Eigen::Index nC)
: qp (nV, nC)
{
qpOASES::Options options;
options.printLevel = qpOASES::PL_NONE;
qp.setOptions( options );
}
};
value_type qpOASESWrapper::m_defaultBoundary = 1e16;
void qpOASESWrapper::setDefaultBoundary (const value_type& v)
{
m_defaultBoundary = v;
}
qpOASESWrapper::qpOASESWrapper () {}
void qpOASESWrapper::initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path,
const Vector& times)
{
Solver::initialize (constraints, path, times);
m_boundary = m_defaultBoundary;
// Currently only support Canonical Linear Constraint
Eigen::Index nC = 2; // First constraint is x + 2 D u <= xnext_max, second is xnext_min <= x + 2D u
for (const Solver::LinearConstraintParams& linParam : m_constraintsParams.lin)
nC += linParam.F[0].rows();
Eigen::Index nV (nbVars());
assert(nV == 2);
m_A = RMatrix::Zero(nC, nV);
m_lA = -Vector::Ones(nC);
m_hA = -Vector::Ones(nC);
m_impl = std::unique_ptr<Impl>(new Impl(nV, nC));
}
qpOASESWrapper::~qpOASESWrapper ()
{
}
bool qpOASESWrapper::solveStagewiseOptim(std::size_t i,
const Matrix& H, const Vector& g,
const Bound& x, const Bound& xNext,
Vector& solution)
{
TOPPRA_LOG_DEBUG("stage: i="<<i);
Eigen::Index N (nbStages());
assert (i <= N);
assert(x(0) <= x(1));
Bound l (Bound::Constant(-m_boundary)),
h (Bound::Constant( m_boundary));
l[1] = std::max(l[1], x[0]);
h[1] = std::min(h[1], x[1]);
if (i < N) {
value_type delta = deltas()[i];
m_A.row(0) << -2 * delta, -1;
m_hA[0] = std::min(- xNext[0],m_boundary);
m_lA[0] = - m_boundary;
m_A.row(1) << 2 * delta, 1;
m_hA[1] = std::min(xNext[1],m_boundary);
m_lA[1] = -m_boundary;
} else {
m_A.topRows<2>().setZero();
m_lA.head<2>().setConstant(-1);
m_hA.head<2>().setOnes();
}
Eigen::Index cur_index = 2;
for (const Solver::LinearConstraintParams& lin : m_constraintsParams.lin)
{
std::size_t j (lin.F.size() == 1 ? 0 : i);
const Matrix& _F (lin.F[j]);
const Vector& _g (lin.g[j]);
Eigen::Index nC (_F.rows());
m_A.block(cur_index, 0, nC, 1) = _F * lin.a[i];
m_A.block(cur_index, 1, nC, 1) = _F * lin.b[i];
m_hA.segment(cur_index, nC) = (_g - _F * lin.c[i]).cwiseMin(m_boundary);
m_lA.segment(cur_index, nC).setConstant(-m_boundary);
cur_index += nC;
}
for (const Solver::BoxConstraintParams& box : m_constraintsParams.box)
{
if (!box.u.empty()) {
l[0] = std::max(l[0], box.u[i][0]);
h[0] = std::min(h[0], box.u[i][1]);
}
if (!box.x.empty()) {
l[1] = std::max(l[1], box.x[i][0]);
h[1] = std::min(h[1], box.x[i][1]);
}
}
TOPPRA_LOG_DEBUG("lA: " << std::endl << m_lA);
TOPPRA_LOG_DEBUG("hA: " << std::endl << m_hA);
TOPPRA_LOG_DEBUG(" A: " << std::endl << m_A);
TOPPRA_LOG_DEBUG("l : " << std::endl << l);
TOPPRA_LOG_DEBUG("h : " << std::endl << h);
qpOASES::returnValue res;
// TODO I assumed 1000 is the argument nWSR of the SQProblem.init function.
//res = self.solver.init(
// H, g, self._A, l, h, self._lA, self._hA, np.array([1000])
//)
int nWSR = 1000;
// Make sure bounds are correct
if ((h.array() < l.array()).any()) {
TOPPRA_LOG_DEBUG("qpOASES: invalid box boundaries:"
"\nlower: " << l <<
"\nupper: " << h);
return false;
}
if ((m_hA.array() < m_lA.array()).any()) {
TOPPRA_LOG_DEBUG("qpOASES: invalid linear inequality bounds:"
"\nlower: " << m_lA.transpose() <<
"\nupper: " << m_hA.transpose());
return false;
}
if (H.size() == 0) {
m_impl->qp.setHessianType(qpOASES::HST_ZERO);
res = m_impl->qp.init (NULL, g.data(),
m_A.data(),
l.data(), h.data(),
m_lA.data(), m_hA.data(),
nWSR);
} else {
m_H = H; // Convert to row-major
res = m_impl->qp.init (m_H.data(), g.data(),
m_A.data(),
l.data(), h.data(),
m_lA.data(), m_hA.data(),
nWSR);
}
if (res == qpOASES::SUCCESSFUL_RETURN) {
solution.resize(nbVars());
m_impl->qp.getPrimalSolution(solution.data());
TOPPRA_LOG_DEBUG("solution: " << solution);
solution = solution.cwiseMax(l.transpose());
solution = solution.cwiseMin(h.transpose());
assert((solution.transpose().array() <= h.array()).all());
assert((solution.transpose().array() >= l.array()).all());
return true;
}
TOPPRA_LOG_DEBUG("qpOASES failed. Error code: " <<
qpOASES::MessageHandling::getErrorCodeMessage(res) << " (" << res << ')');
return false;
}
} // namespace solver
} // namespace toppra
|
#include <toppra/solver/qpOASES-wrapper.hpp>
#include <qpOASES.hpp>
#include <toppra/toppra.hpp>
namespace toppra {
namespace solver {
struct qpOASESWrapper::Impl {
qpOASES::SQProblem qp;
Impl(Eigen::Index nV, Eigen::Index nC)
: qp (nV, nC)
{
qpOASES::Options options;
options.printLevel = qpOASES::PL_NONE;
qp.setOptions( options );
}
};
value_type qpOASESWrapper::m_defaultBoundary = 1e16;
void qpOASESWrapper::setDefaultBoundary (const value_type& v)
{
m_defaultBoundary = v;
}
qpOASESWrapper::qpOASESWrapper () {}
void qpOASESWrapper::initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path,
const Vector& times)
{
Solver::initialize (constraints, path, times);
m_boundary = m_defaultBoundary;
// Currently only support Canonical Linear Constraint
Eigen::Index nC = 2; // First constraint is x + 2 D u <= xnext_max, second is xnext_min <= x + 2D u
for (const Solver::LinearConstraintParams& linParam : m_constraintsParams.lin)
nC += linParam.F[0].rows();
Eigen::Index nV (nbVars());
assert(nV == 2);
m_A = RMatrix::Zero(nC, nV);
m_lA = -Vector::Ones(nC);
m_hA = -Vector::Ones(nC);
m_impl = std::unique_ptr<Impl>(new Impl(nV, nC));
}
qpOASESWrapper::~qpOASESWrapper ()
{
}
bool qpOASESWrapper::solveStagewiseOptim(std::size_t i,
const Matrix& H, const Vector& g,
const Bound& x, const Bound& xNext,
Vector& solution)
{
TOPPRA_LOG_DEBUG("stage: i="<<i);
Eigen::Index N (nbStages());
assert (i <= N);
assert(x(0) <= x(1));
Bound l (Bound::Constant(-m_boundary)),
h (Bound::Constant( m_boundary));
l[1] = std::max(l[1], x[0]);
h[1] = std::min(h[1], x[1]);
if (i < N) {
value_type delta = deltas()[i];
m_A.row(0) << -2 * delta, -1;
m_hA[0] = std::min(- xNext[0],m_boundary);
m_lA[0] = - m_boundary;
m_A.row(1) << 2 * delta, 1;
m_hA[1] = std::min(xNext[1],m_boundary);
m_lA[1] = -m_boundary;
} else {
m_A.topRows<2>().setZero();
m_lA.head<2>().setConstant(-1);
m_hA.head<2>().setOnes();
}
Eigen::Index cur_index = 2;
for (const Solver::LinearConstraintParams& lin : m_constraintsParams.lin)
{
std::size_t j (lin.F.size() == 1 ? 0 : i);
const Matrix& _F (lin.F[j]);
const Vector& _g (lin.g[j]);
Eigen::Index nC (_F.rows());
m_A.block(cur_index, 0, nC, 1) = _F * lin.a[i];
m_A.block(cur_index, 1, nC, 1) = _F * lin.b[i];
m_hA.segment(cur_index, nC) = (_g - _F * lin.c[i]).cwiseMin(m_boundary);
m_lA.segment(cur_index, nC).setConstant(-m_boundary);
cur_index += nC;
}
for (const Solver::BoxConstraintParams& box : m_constraintsParams.box)
{
if (!box.u.empty()) {
l[0] = std::max(l[0], box.u[i][0]);
h[0] = std::min(h[0], box.u[i][1]);
}
if (!box.x.empty()) {
l[1] = std::max(l[1], box.x[i][0]);
h[1] = std::min(h[1], box.x[i][1]);
}
}
TOPPRA_LOG_DEBUG("qpOASES QP:\n"
<< "g: " << g.transpose() << '\n'
<< "lA: " << m_lA.transpose() << '\n'
<< "hA: " << m_hA.transpose() << '\n'
<< "l: " << l << '\n'
<< "h: " << h << '\n'
<< "A:\n" << m_A);
qpOASES::returnValue res;
// TODO I assumed 1000 is the argument nWSR of the SQProblem.init function.
//res = self.solver.init(
// H, g, self._A, l, h, self._lA, self._hA, np.array([1000])
//)
int nWSR = 1000;
// Make sure bounds are correct
if ((h.array() < l.array()).any()) {
TOPPRA_LOG_DEBUG("qpOASES: invalid box boundaries:"
"\nlower: " << l <<
"\nupper: " << h);
return false;
}
if ((m_hA.array() < m_lA.array()).any()) {
TOPPRA_LOG_DEBUG("qpOASES: invalid linear inequality bounds:"
"\nlower: " << m_lA.transpose() <<
"\nupper: " << m_hA.transpose());
return false;
}
if (H.size() == 0) {
m_impl->qp.setHessianType(qpOASES::HST_ZERO);
res = m_impl->qp.init (NULL, g.data(),
m_A.data(),
l.data(), h.data(),
m_lA.data(), m_hA.data(),
nWSR);
} else {
m_H = H; // Convert to row-major
res = m_impl->qp.init (m_H.data(), g.data(),
m_A.data(),
l.data(), h.data(),
m_lA.data(), m_hA.data(),
nWSR);
}
if (res == qpOASES::SUCCESSFUL_RETURN) {
solution.resize(nbVars());
m_impl->qp.getPrimalSolution(solution.data());
TOPPRA_LOG_DEBUG("solution: " << solution.transpose());
#ifdef TOPPRA_DEBUG_ON
{
Vector lambdas (m_impl->qp.getNV() + m_impl->qp.getNC());
m_impl->qp.getDualSolution(lambdas.data());
TOPPRA_LOG_DEBUG("dual solution: " << lambdas.transpose());
}
#endif
solution = solution.cwiseMax(l.transpose());
solution = solution.cwiseMin(h.transpose());
assert((solution.transpose().array() <= h.array()).all());
assert((solution.transpose().array() >= l.array()).all());
return true;
}
TOPPRA_LOG_DEBUG("qpOASES failed. Error code: " <<
qpOASES::MessageHandling::getErrorCodeMessage(res) << " (" << res << ')');
return false;
}
} // namespace solver
} // namespace toppra
|
Fix debug output.
|
[C++][Minor] Fix debug output.
|
C++
|
mit
|
hungpham2511/toppra,hungpham2511/toppra,hungpham2511/toppra
|
b7da9b3f3bce2700581a956422702393e8afa3f6
|
tools/seec-trace-view/StateGraphViewer.cpp
|
tools/seec-trace-view/StateGraphViewer.cpp
|
//===- tools/seec-trace-view/StateGraphViewer.cpp -------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/DotGraph.hpp"
#include "seec/Util/ScopeExit.hpp"
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#if !wxUSE_WEBVIEW_WEBKIT && !wxUSE_WEBVIEW_IE
#error "wxWebView backend required!"
#endif
#include <wx/webview.h>
#include "seec/wxWidgets/CleanPreprocessor.h"
#include <gvc.h>
#include <memory>
#include "StateGraphViewer.hpp"
#include "TraceviewerFrame.hpp"
//------------------------------------------------------------------------------
// StateGraphViewerPanel
//------------------------------------------------------------------------------
StateGraphViewerPanel::~StateGraphViewerPanel()
{
if (GraphvizContext)
gvFreeContext(GraphvizContext);
}
bool StateGraphViewerPanel::Create(wxWindow *Parent,
wxWindowID ID,
wxPoint const &Position,
wxSize const &Size)
{
if (!wxPanel::Create(Parent, ID, Position, Size))
return false;
auto Sizer = new wxBoxSizer(wxVERTICAL);
WebView = wxWebView::New(this, wxID_ANY);
if (!WebView) {
wxLogDebug("wxWebView::New failed.");
return false;
}
Sizer->Add(WebView, wxSizerFlags(1).Expand());
SetSizerAndFit(Sizer);
GraphvizContext = gvContext();
return true;
}
void
StateGraphViewerPanel::show(std::shared_ptr<StateAccessToken> Access,
seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread)
{
CurrentAccess = std::move(Access);
if (!WebView)
return;
// Create a graph of the process state in dot format.
std::string GraphString;
{
// Lock the current state while we read from it.
auto Lock = CurrentAccess->getAccess();
if (!Lock)
return;
llvm::raw_string_ostream GraphStream {GraphString};
seec::cm::writeDotGraph(Process, GraphStream);
}
std::unique_ptr<char []> Buffer {new char [GraphString.size() + 1]};
if (!Buffer)
return;
memcpy(Buffer.get(), GraphString.data(), GraphString.size());
Buffer[GraphString.size()] = 0;
GraphString.clear();
// Parse the graph into Graphviz's internal format.
Agraph_t *Graph = agmemread(Buffer.get());
auto const FreeGraph = seec::scopeExit([=] () { agclose(Graph); });
// Layout the graph.
gvLayout(GraphvizContext, Graph, "dot");
auto const FreeLayout =
seec::scopeExit([=] () { gvFreeLayout(GraphvizContext, Graph); });
// Render the graph as SVG.
char *RenderedData = nullptr;
unsigned RenderedLength = 0;
auto const FreeData =
seec::scopeExit([=] () { if (RenderedData) free(RenderedData); });
gvRenderData(GraphvizContext, Graph, "svg", &RenderedData, &RenderedLength);
// Show the SVG as the webpage.
WebView->SetPage(wxString{RenderedData, RenderedLength}, wxString{});
}
void StateGraphViewerPanel::clear()
{
WebView->SetPage(wxString{}, wxString{});
}
|
//===- tools/seec-trace-view/StateGraphViewer.cpp -------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/DotGraph.hpp"
#include "seec/Util/ScopeExit.hpp"
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#if !wxUSE_WEBVIEW_WEBKIT && !wxUSE_WEBVIEW_IE
#error "wxWebView backend required!"
#endif
#include <wx/webview.h>
#include "seec/wxWidgets/CleanPreprocessor.h"
#include <gvc.h>
#include <memory>
#include "StateGraphViewer.hpp"
#include "TraceViewerFrame.hpp"
//------------------------------------------------------------------------------
// StateGraphViewerPanel
//------------------------------------------------------------------------------
StateGraphViewerPanel::~StateGraphViewerPanel()
{
if (GraphvizContext)
gvFreeContext(GraphvizContext);
}
bool StateGraphViewerPanel::Create(wxWindow *Parent,
wxWindowID ID,
wxPoint const &Position,
wxSize const &Size)
{
if (!wxPanel::Create(Parent, ID, Position, Size))
return false;
auto Sizer = new wxBoxSizer(wxVERTICAL);
WebView = wxWebView::New(this, wxID_ANY);
if (!WebView) {
wxLogDebug("wxWebView::New failed.");
return false;
}
Sizer->Add(WebView, wxSizerFlags(1).Expand());
SetSizerAndFit(Sizer);
GraphvizContext = gvContext();
return true;
}
void
StateGraphViewerPanel::show(std::shared_ptr<StateAccessToken> Access,
seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread)
{
CurrentAccess = std::move(Access);
if (!WebView)
return;
// Create a graph of the process state in dot format.
std::string GraphString;
{
// Lock the current state while we read from it.
auto Lock = CurrentAccess->getAccess();
if (!Lock)
return;
llvm::raw_string_ostream GraphStream {GraphString};
seec::cm::writeDotGraph(Process, GraphStream);
}
std::unique_ptr<char []> Buffer {new char [GraphString.size() + 1]};
if (!Buffer)
return;
memcpy(Buffer.get(), GraphString.data(), GraphString.size());
Buffer[GraphString.size()] = 0;
GraphString.clear();
// Parse the graph into Graphviz's internal format.
Agraph_t *Graph = agmemread(Buffer.get());
auto const FreeGraph = seec::scopeExit([=] () { agclose(Graph); });
// Layout the graph.
gvLayout(GraphvizContext, Graph, "dot");
auto const FreeLayout =
seec::scopeExit([=] () { gvFreeLayout(GraphvizContext, Graph); });
// Render the graph as SVG.
char *RenderedData = nullptr;
unsigned RenderedLength = 0;
auto const FreeData =
seec::scopeExit([=] () { if (RenderedData) free(RenderedData); });
gvRenderData(GraphvizContext, Graph, "svg", &RenderedData, &RenderedLength);
// Show the SVG as the webpage.
WebView->SetPage(wxString{RenderedData, RenderedLength}, wxString{});
}
void StateGraphViewerPanel::clear()
{
WebView->SetPage(wxString{}, wxString{});
}
|
Fix typo.
|
Fix typo.
|
C++
|
mit
|
mheinsen/seec,seec-team/seec,mheinsen/seec,seec-team/seec,seec-team/seec,mheinsen/seec,mheinsen/seec,seec-team/seec,seec-team/seec,mheinsen/seec
|
3cc47418a8cc2bc1d0f3800766c541e8cf429c7a
|
modules/cutehmi_stupid_1/src/cutehmi/stupid/internal/DatabaseThread.cpp
|
modules/cutehmi_stupid_1/src/cutehmi/stupid/internal/DatabaseThread.cpp
|
#include "../../../../include/cutehmi/stupid/internal/DatabaseThread.hpp"
#include <QSqlDatabase>
#include <QCoreApplication>
#include <QAbstractEventDispatcher>
namespace cutehmi {
namespace stupid {
namespace internal {
DatabaseThread::DatabaseThread():
m(new Members)
{
}
QString DatabaseThread::Error::str() const
{
switch (code()) {
case Error::NOT_CONFIGURED:
return tr("Database connection has not been configured.");
case Error::UNABLE_TO_CONNECT:
return tr("Unable to establish database connection.");
default:
return Error::str();
}
}
void DatabaseThread::moveDatabaseConnectionData(std::unique_ptr<stupid::DatabaseConnectionData> dbData)
{
Q_ASSERT_X(!isRunning(), __FUNCTION__, "altering connection data while database thread is running");
m->dbData = std::move(dbData);
}
stupid::DatabaseConnectionData * DatabaseThread::dbData() const
{
return m->dbData.get();
}
void DatabaseThread::run()
{
QMutexLocker locker(& m->runLock);
if (m->dbData) {
QSqlDatabase db = QSqlDatabase::addDatabase(m->dbData->type, m->dbData->connectionName);
db.setHostName(m->dbData->hostName);
db.setPort(m->dbData->port);
db.setDatabaseName(m->dbData->databaseName);
db.setUserName(m->dbData->userName);
db.setPassword(m->dbData->password);
if (db.open()) {
CUTEHMI_LOG_DEBUG("[TODO provide App with a UI for signaling errors] Connected with database.");
emit connected();
} else {
CUTEHMI_LOG_DEBUG("[TODO provide App with a UI for signaling errors] Could not connect with database.");
emit error(errorInfo(Error(Error::UNABLE_TO_CONNECT)));
}
exec();
} else {
emit (errorInfo(Error(Error::NOT_CONFIGURED)));
exec();
}
if (m->dbData) {
{
QSqlDatabase db = QSqlDatabase::database(m->dbData->connectionName, false);
db.close();
}
emit disconnected();
QSqlDatabase::removeDatabase(m->dbData->connectionName);
}
}
}
}
}
//(c)MP: Copyright © 2018, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
#include "../../../../include/cutehmi/stupid/internal/DatabaseThread.hpp"
#include <QSqlDatabase>
#include <QCoreApplication>
#include <QAbstractEventDispatcher>
namespace cutehmi {
namespace stupid {
namespace internal {
DatabaseThread::DatabaseThread():
m(new Members)
{
}
QString DatabaseThread::Error::str() const
{
switch (code()) {
case Error::NOT_CONFIGURED:
return tr("Database connection has not been configured.");
case Error::UNABLE_TO_CONNECT:
return tr("Unable to establish database connection.");
default:
return Error::str();
}
}
void DatabaseThread::moveDatabaseConnectionData(std::unique_ptr<stupid::DatabaseConnectionData> dbData)
{
Q_ASSERT_X(!isRunning(), __FUNCTION__, "altering connection data while database thread is running");
m->dbData = std::move(dbData);
}
stupid::DatabaseConnectionData * DatabaseThread::dbData() const
{
return m->dbData.get();
}
void DatabaseThread::run()
{
QMutexLocker locker(& m->runLock);
if (m->dbData) {
QSqlDatabase db = QSqlDatabase::addDatabase(m->dbData->type, m->dbData->connectionName);
db.setHostName(m->dbData->hostName);
db.setPort(m->dbData->port);
db.setDatabaseName(m->dbData->databaseName);
db.setUserName(m->dbData->userName);
db.setPassword(m->dbData->password);
if (db.open()) {
CUTEHMI_LOG_DEBUG("Connected with database.");
emit connected();
} else {
CUTEHMI_LOG_DEBUG("Could not connect with database.");
emit error(errorInfo(Error(Error::UNABLE_TO_CONNECT)));
}
exec();
} else {
emit (errorInfo(Error(Error::NOT_CONFIGURED)));
exec();
}
if (m->dbData) {
{
QSqlDatabase db = QSqlDatabase::database(m->dbData->connectionName, false);
db.close();
}
emit disconnected();
QSqlDatabase::removeDatabase(m->dbData->connectionName);
}
}
}
}
}
//(c)MP: Copyright © 2018, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
Remove 'TODO' reminder
|
Remove 'TODO' reminder
|
C++
|
mit
|
michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI
|
58104b02e328d823c4e4075b0ef411ab47c6f790
|
firmware/src/fork_motor_controller.cpp
|
firmware/src/fork_motor_controller.cpp
|
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include "control_loop.h"
#include "constants.h"
#include "fork_motor_controller.h"
#include "MPU6050.h"
#include "SystemState.h"
namespace hardware {
const uint8_t ccr_channel = 2; // PWM Channel 2
const float max_current = 6.0f; // Copley Controls ACJ-055-18
const float torque_constant = 106.459f * constants::Nm_per_ozfin;
const float max_steer_angle = 45.0f * constants::rad_per_degree;
ForkMotorController::ForkMotorController()
: MotorController("Fork"),
e_(STM32_TIM3, constants::fork_counts_per_revolution),
m_(GPIOF, GPIOF_STEER_DIR, GPIOF_STEER_ENABLE, GPIOF_STEER_FAULT,
STM32_TIM1, ccr_channel, max_current, torque_constant),
derivative_filter_{0, 10*2*constants::pi,
10*2*constants::pi, constants::loop_period_s},
yaw_rate_command_{0.0f},
estimation_threshold_{-1.0f / constants::wheel_radius},
estimation_triggered_{false},
control_triggered_{false},
control_delay_{10u},
disturb_A_{0.0f}, disturb_f_{0.0f}
{
instances[fork] = this;
}
ForkMotorController::~ForkMotorController()
{
instances[fork] = 0;
}
void ForkMotorController::set_reference(float yaw_rate)
{
yaw_rate_command_ = yaw_rate;
}
void ForkMotorController::set_estimation_threshold(float speed)
{
estimation_threshold_ = speed / -constants::wheel_radius;
}
void ForkMotorController::set_control_delay(uint32_t N)
{
control_delay_= N;
}
void ForkMotorController::set_sinusoidal_disturbance(float A, float f)
{
disturb_A_ = A;
disturb_f_ = f;
}
void ForkMotorController::disable()
{
m_.disable();
}
void ForkMotorController::enable()
{
m_.enable();
}
void ForkMotorController::set_estimation_threshold_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 1) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
if (fmc) {
fmc->set_estimation_threshold(tofloat(argv[0]));
chprintf(chp, "%s estimation threshold set to %f.\r\n", fmc->name(),
fmc->estimation_threshold_);
} else {
chprintf(chp, "Enable collection before setting estimation threshold.\r\n");
}
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
void ForkMotorController::set_control_delay_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 1) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
if (fmc) {
uint32_t N = std::atoi(argv[0]);
fmc->set_control_delay(N);
chprintf(chp, "%s control delay set to begin %u samples after estimation.\r\n", fmc->name(),
fmc->control_delay_);
} else {
chprintf(chp, "Enable collection before setting control threshold.\r\n");
}
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
void ForkMotorController::set_thresholds_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 2) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
fmc->set_estimation_threshold(tofloat(argv[0]));
uint32_t N = std::atoi(argv[0]);
fmc->set_control_delay(N);
chprintf(chp, "%s estimation threshold set to %f.\r\n", fmc->name(),
fmc->estimation_threshold_);
chprintf(chp, "%s control delay set to begin %u samples after estimation.\r\n",
fmc->name(), fmc->control_delay_);
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
void ForkMotorController::disturb_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 2) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
float A = tofloat(argv[0]);
float f = tofloat(argv[1]);
fmc->set_sinusoidal_disturbance(A, f);
chprintf(chp, "Sinusoidal disturbance enabled.\r\n");
chprintf(chp, "A = %f, f = %f.\r\n", A, f);
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
float ForkMotorController::sinusoidal_disturbance_torque(const Sample& s) const {
return disturb_A_ * std::sin(constants::two_pi * disturb_f_ * s.system_time *
constants::system_timer_seconds_per_count);
}
void ForkMotorController::update(Sample & s)
{
s.encoder.steer = e_.get_angle();
s.encoder.steer_rate = derivative_filter_.output(s.encoder.steer);
derivative_filter_.update(s.encoder.steer); // update for next iteration
s.set_point.yaw_rate = yaw_rate_command_;
s.motor_torque.desired_steer = 0.0f;
if (should_estimate(s) && fork_control_.set_sample(s)) {
float torque = fork_control_.compute_updated_torque(m_.get_torque());
if (should_control(s)) {
if (should_disturb(s) && s.bike_state == BikeState::RUNNING)
torque += sinusoidal_disturbance_torque(s);
s.motor_torque.desired_steer = torque;
m_.set_torque(torque);
} else {
m_.set_torque(0.0f);
}
} else {
m_.set_torque(0.0f);
}
s.motor_torque.steer = m_.get_torque();
if (e_.rotation_direction())
s.system_state |= systemstate::SteerEncoderDir;
if (m_.is_enabled())
s.system_state |= systemstate::SteerMotorEnable;
if (m_.has_fault())
s.system_state |= systemstate::SteerMotorFault;
if (m_.current_direction())
s.system_state |= systemstate::SteerMotorCurrentDir;
s.threshold.estimation = estimation_threshold_;
s.threshold.control = 0.0f; // control_threshold_;
s.has_threshold = true;
}
// estimation/control thresholds are in terms of wheel rate, which is defined
// to be negative when the speed of the bicycle is positive. estimation/control
// should occur when speed > threshold which is equivalent to rate < threshold.
bool ForkMotorController::should_estimate(const Sample& s)
{
if (!estimation_triggered_) {
estimation_triggered_ = s.encoder.rear_wheel_rate < estimation_threshold_;
fork_control_.set_state(0.0f, s.encoder.steer,
s.mpu6050.gyroscope_x, s.encoder.steer_rate);
}
return estimation_triggered_;
}
bool ForkMotorController::should_control(const Sample& s)
{
if (!control_triggered_)
control_triggered_ = --control_delay_ == 0;
return control_triggered_ && std::abs(s.encoder.steer) < max_steer_angle;
}
bool ForkMotorController::should_disturb(const Sample& s)
{
if (!disturb_triggered_) {
const float norm = std::sqrt(std::pow(s.estimate.lean, 2.0f) +
std::pow(s.estimate.steer, 2.0f) +
std::pow(s.estimate.lean_rate, 2.0f) +
std::pow(s.estimate.steer_rate, 2.0f));
disturb_triggered_ = s.bike_state == BikeState::RUNNING && norm < 0.5;
}
return disturb_triggered_;
}
} // namespace hardware
|
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include "control_loop.h"
#include "constants.h"
#include "fork_motor_controller.h"
#include "MPU6050.h"
#include "SystemState.h"
namespace hardware {
const uint8_t ccr_channel = 2; // PWM Channel 2
const float max_current = 6.0f; // Copley Controls ACJ-055-18
const float torque_constant = 106.459f * constants::Nm_per_ozfin;
const float max_steer_angle = 45.0f * constants::rad_per_degree;
ForkMotorController::ForkMotorController()
: MotorController("Fork"),
e_(STM32_TIM3, constants::fork_counts_per_revolution),
m_(GPIOF, GPIOF_STEER_DIR, GPIOF_STEER_ENABLE, GPIOF_STEER_FAULT,
STM32_TIM1, ccr_channel, max_current, torque_constant),
derivative_filter_{0, 10*2*constants::pi,
10*2*constants::pi, constants::loop_period_s},
yaw_rate_command_{0.0f},
estimation_threshold_{-1.0f / constants::wheel_radius},
estimation_triggered_{false},
control_triggered_{false},
disturb_triggered_{false},
control_delay_{10u},
disturb_A_{0.0f}, disturb_f_{0.0f}
{
instances[fork] = this;
}
ForkMotorController::~ForkMotorController()
{
instances[fork] = 0;
}
void ForkMotorController::set_reference(float yaw_rate)
{
yaw_rate_command_ = yaw_rate;
}
void ForkMotorController::set_estimation_threshold(float speed)
{
estimation_threshold_ = speed / -constants::wheel_radius;
}
void ForkMotorController::set_control_delay(uint32_t N)
{
control_delay_= N;
}
void ForkMotorController::set_sinusoidal_disturbance(float A, float f)
{
disturb_A_ = A;
disturb_f_ = f;
}
void ForkMotorController::disable()
{
m_.disable();
}
void ForkMotorController::enable()
{
m_.enable();
}
void ForkMotorController::set_estimation_threshold_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 1) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
if (fmc) {
fmc->set_estimation_threshold(tofloat(argv[0]));
chprintf(chp, "%s estimation threshold set to %f.\r\n", fmc->name(),
fmc->estimation_threshold_);
} else {
chprintf(chp, "Enable collection before setting estimation threshold.\r\n");
}
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
void ForkMotorController::set_control_delay_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 1) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
if (fmc) {
uint32_t N = std::atoi(argv[0]);
fmc->set_control_delay(N);
chprintf(chp, "%s control delay set to begin %u samples after estimation.\r\n", fmc->name(),
fmc->control_delay_);
} else {
chprintf(chp, "Enable collection before setting control threshold.\r\n");
}
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
void ForkMotorController::set_thresholds_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 2) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
fmc->set_estimation_threshold(tofloat(argv[0]));
uint32_t N = std::atoi(argv[0]);
fmc->set_control_delay(N);
chprintf(chp, "%s estimation threshold set to %f.\r\n", fmc->name(),
fmc->estimation_threshold_);
chprintf(chp, "%s control delay set to begin %u samples after estimation.\r\n",
fmc->name(), fmc->control_delay_);
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
void ForkMotorController::disturb_shell(BaseSequentialStream *chp,
int argc, char *argv[])
{
if (argc == 2) {
ForkMotorController* fmc = reinterpret_cast<ForkMotorController*>(instances[fork]);
float A = tofloat(argv[0]);
float f = tofloat(argv[1]);
fmc->set_sinusoidal_disturbance(A, f);
chprintf(chp, "Sinusoidal disturbance enabled.\r\n");
chprintf(chp, "A = %f, f = %f.\r\n", A, f);
} else {
chprintf(chp, "Invalid usage.\r\n");
}
}
float ForkMotorController::sinusoidal_disturbance_torque(const Sample& s) const {
return disturb_A_ * std::sin(constants::two_pi * disturb_f_ * s.system_time *
constants::system_timer_seconds_per_count);
}
void ForkMotorController::update(Sample & s)
{
s.encoder.steer = e_.get_angle();
s.encoder.steer_rate = derivative_filter_.output(s.encoder.steer);
derivative_filter_.update(s.encoder.steer); // update for next iteration
s.set_point.yaw_rate = yaw_rate_command_;
s.motor_torque.desired_steer = 0.0f;
if (should_estimate(s) && fork_control_.set_sample(s)) {
float torque = fork_control_.compute_updated_torque(m_.get_torque());
if (should_control(s)) {
if (should_disturb(s) && s.bike_state == BikeState::RUNNING)
torque += sinusoidal_disturbance_torque(s);
s.motor_torque.desired_steer = torque;
m_.set_torque(torque);
} else {
m_.set_torque(0.0f);
}
} else {
m_.set_torque(0.0f);
}
s.motor_torque.steer = m_.get_torque();
if (e_.rotation_direction())
s.system_state |= systemstate::SteerEncoderDir;
if (m_.is_enabled())
s.system_state |= systemstate::SteerMotorEnable;
if (m_.has_fault())
s.system_state |= systemstate::SteerMotorFault;
if (m_.current_direction())
s.system_state |= systemstate::SteerMotorCurrentDir;
s.threshold.estimation = estimation_threshold_;
s.threshold.control = 0.0f; // control_threshold_;
s.has_threshold = true;
}
// estimation/control thresholds are in terms of wheel rate, which is defined
// to be negative when the speed of the bicycle is positive. estimation/control
// should occur when speed > threshold which is equivalent to rate < threshold.
bool ForkMotorController::should_estimate(const Sample& s)
{
if (!estimation_triggered_) {
estimation_triggered_ = s.encoder.rear_wheel_rate < estimation_threshold_;
fork_control_.set_state(0.0f, s.encoder.steer,
s.mpu6050.gyroscope_x, s.encoder.steer_rate);
}
return estimation_triggered_;
}
bool ForkMotorController::should_control(const Sample& s)
{
if (!control_triggered_)
control_triggered_ = --control_delay_ == 0;
return control_triggered_ && std::abs(s.encoder.steer) < max_steer_angle;
}
bool ForkMotorController::should_disturb(const Sample& s)
{
if (!disturb_triggered_) {
bool at_ref_speed = std::abs(s.encoder.rear_wheel_rate - s.set_point.theta_R_dot) <
std::abs(0.05f * s.set_point.theta_R_dot);
const float norm = std::sqrt(std::pow(s.estimate.lean, 2.0f) +
std::pow(s.estimate.steer, 2.0f) +
std::pow(s.estimate.lean_rate, 2.0f) +
std::pow(s.estimate.steer_rate, 2.0f));
disturb_triggered_ = s.bike_state == BikeState::RUNNING && norm < 0.5f && at_ref_speed;
}
return disturb_triggered_;
}
} // namespace hardware
|
Enable disturbance after reaching speed setpoint.
|
Enable disturbance after reaching speed setpoint.
|
C++
|
bsd-2-clause
|
hazelnusse/robot.bicycle,hazelnusse/robot.bicycle,hazelnusse/robot.bicycle,hazelnusse/robot.bicycle,hazelnusse/robot.bicycle
|
15a60f086b17c7a5ba527b3e037f065592e36182
|
src/lib/src/commands/commands.cpp
|
src/lib/src/commands/commands.cpp
|
#include "commands/commands.h"
#include <QDir>
#include <QProcess>
#include <QSettings>
#include "commands/sql-worker.h"
#include "logger.h"
#include "models/filename.h"
#include "models/profile.h"
#include "tags/tag.h"
Commands::Commands(Profile *profile)
: m_profile(profile)
{
QSettings *settings = profile->getSettings();
m_commandTagBefore = settings->value("Exec/tag_before").toString();
m_commandImage = settings->value("Exec/image").toString();
m_commandTagAfter = settings->value("Exec/tag_after", settings->value("tag").toString()).toString();
m_mysqlSettings.before = settings->value("Exec/SQL/before").toString();
m_mysqlSettings.tagBefore = settings->value("Exec/SQL/tag_before").toString();
m_mysqlSettings.image = settings->value("Exec/SQL/image").toString();
m_mysqlSettings.tagAfter = settings->value("Exec/SQL/tag_after", settings->value("tag").toString()).toString();
m_mysqlSettings.after = settings->value("Exec/SQL/after").toString();
m_sqlWorker = new SqlWorker(
settings->value("Exec/SQL/driver", "QMYSQL").toString(),
settings->value("Exec/SQL/host").toString(),
settings->value("Exec/SQL/user").toString(),
settings->value("Exec/SQL/password").toString(),
settings->value("Exec/SQL/database").toString());
m_sqlWorker->setObjectName("SqlThread");
}
Commands::~Commands()
{
m_sqlWorker->deleteLater();
}
bool Commands::start() const
{
return m_sqlWorker->connect();
}
bool Commands::before() const
{
if (!m_mysqlSettings.before.isEmpty()) {
return sqlExec(m_mysqlSettings.before);
}
return true;
}
bool Commands::image(const Image &img, const QString &path)
{
// Normal commands
if (!m_commandImage.isEmpty()) {
Filename fn(m_commandImage);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::None);
for (QString exec : execs) {
exec.replace("%path:nobackslash%", QDir::toNativeSeparators(path).replace("\\", "/"))
.replace("%path%", QDir::toNativeSeparators(path));
log(QStringLiteral("Execution of \"%1\"").arg(exec));
Logger::getInstance().logCommand(exec);
const int code = QProcess::execute(exec);
if (code != 0) {
log(QStringLiteral("Error executing command (return code: %1)").arg(code), Logger::Error);
}
}
}
// SQL commands
if (!m_mysqlSettings.image.isEmpty()) {
Filename fn(m_mysqlSettings.image);
fn.setEscapeMethod(&SqlWorker::escape);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::None);
for (QString exec : execs) {
exec.replace("%path:nobackslash%", m_sqlWorker->escape(QDir::toNativeSeparators(path).replace("\\", "/")))
.replace("%path%", m_sqlWorker->escape(QDir::toNativeSeparators(path)));
if (!sqlExec(exec)) {
return false;
}
}
}
return true;
}
bool Commands::tag(const Image &img, const Tag &tag, bool after)
{
const QString original = QString(tag.text()).replace(" ", "_");
QString command = after ? m_commandTagAfter : m_commandTagBefore;
if (!command.isEmpty()) {
Filename fn(command);
fn.setEscapeMethod(&SqlWorker::escape);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::KeepInvalidTokens);
for (QString exec : execs) {
exec.replace("%tag%", original)
.replace("%original%", tag.text())
.replace("%type%", tag.type().name())
.replace("%number%", QString::number(tag.type().number()));
log(QStringLiteral("Execution of \"%1\"").arg(exec));
Logger::getInstance().logCommand(exec);
const int code = QProcess::execute(exec);
if (code != 0) {
log(QStringLiteral("Error executing command (return code: %1)").arg(code), Logger::Error);
}
}
}
QString commandSql = after ? m_mysqlSettings.tagAfter : m_mysqlSettings.tagBefore;
if (!commandSql.isEmpty()) {
start();
Filename fn(commandSql);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::KeepInvalidTokens);
for (QString exec : execs) {
exec.replace("%tag%", m_sqlWorker->escape(original))
.replace("%original%", m_sqlWorker->escape(tag.text()))
.replace("%type%", m_sqlWorker->escape(tag.type().name()))
.replace("%number%", QString::number(tag.type().number()));
if (!sqlExec(exec)) {
return false;
}
}
}
return true;
}
bool Commands::after() const
{
if (!m_mysqlSettings.after.isEmpty()) {
return sqlExec(m_mysqlSettings.after);
}
return true;
}
bool Commands::sqlExec(const QString &sql) const
{
QMetaObject::invokeMethod(m_sqlWorker, "execute", Qt::QueuedConnection, Q_ARG(QString, sql));
return true;
}
|
#include "commands/commands.h"
#include <QDir>
#include <QProcess>
#include <QSettings>
#include "commands/sql-worker.h"
#include "logger.h"
#include "models/filename.h"
#include "models/profile.h"
#include "tags/tag.h"
Commands::Commands(Profile *profile)
: m_profile(profile)
{
QSettings *settings = profile->getSettings();
m_commandTagBefore = settings->value("Exec/tag_before").toString();
m_commandImage = settings->value("Exec/image").toString();
m_commandTagAfter = settings->value("Exec/tag_after", settings->value("Exec/tag").toString()).toString();
m_mysqlSettings.before = settings->value("Exec/SQL/before").toString();
m_mysqlSettings.tagBefore = settings->value("Exec/SQL/tag_before").toString();
m_mysqlSettings.image = settings->value("Exec/SQL/image").toString();
m_mysqlSettings.tagAfter = settings->value("Exec/SQL/tag_after", settings->value("Exec/SQL/tag").toString()).toString();
m_mysqlSettings.after = settings->value("Exec/SQL/after").toString();
m_sqlWorker = new SqlWorker(
settings->value("Exec/SQL/driver", "QMYSQL").toString(),
settings->value("Exec/SQL/host").toString(),
settings->value("Exec/SQL/user").toString(),
settings->value("Exec/SQL/password").toString(),
settings->value("Exec/SQL/database").toString());
m_sqlWorker->setObjectName("SqlThread");
}
Commands::~Commands()
{
m_sqlWorker->deleteLater();
}
bool Commands::start() const
{
return m_sqlWorker->connect();
}
bool Commands::before() const
{
if (!m_mysqlSettings.before.isEmpty()) {
return sqlExec(m_mysqlSettings.before);
}
return true;
}
bool Commands::image(const Image &img, const QString &path)
{
// Normal commands
if (!m_commandImage.isEmpty()) {
Filename fn(m_commandImage);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::None);
for (QString exec : execs) {
exec.replace("%path:nobackslash%", QDir::toNativeSeparators(path).replace("\\", "/"))
.replace("%path%", QDir::toNativeSeparators(path));
log(QStringLiteral("Execution of \"%1\"").arg(exec));
Logger::getInstance().logCommand(exec);
const int code = QProcess::execute(exec);
if (code != 0) {
log(QStringLiteral("Error executing command (return code: %1)").arg(code), Logger::Error);
}
}
}
// SQL commands
if (!m_mysqlSettings.image.isEmpty()) {
Filename fn(m_mysqlSettings.image);
fn.setEscapeMethod(&SqlWorker::escape);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::None);
for (QString exec : execs) {
exec.replace("%path:nobackslash%", m_sqlWorker->escape(QDir::toNativeSeparators(path).replace("\\", "/")))
.replace("%path%", m_sqlWorker->escape(QDir::toNativeSeparators(path)));
if (!sqlExec(exec)) {
return false;
}
}
}
return true;
}
bool Commands::tag(const Image &img, const Tag &tag, bool after)
{
const QString original = QString(tag.text()).replace(" ", "_");
QString command = after ? m_commandTagAfter : m_commandTagBefore;
if (!command.isEmpty()) {
Filename fn(command);
fn.setEscapeMethod(&SqlWorker::escape);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::KeepInvalidTokens);
for (QString exec : execs) {
exec.replace("%tag%", original)
.replace("%original%", tag.text())
.replace("%type%", tag.type().name())
.replace("%number%", QString::number(tag.type().number()));
log(QStringLiteral("Execution of \"%1\"").arg(exec));
Logger::getInstance().logCommand(exec);
const int code = QProcess::execute(exec);
if (code != 0) {
log(QStringLiteral("Error executing command (return code: %1)").arg(code), Logger::Error);
}
}
}
QString commandSql = after ? m_mysqlSettings.tagAfter : m_mysqlSettings.tagBefore;
if (!commandSql.isEmpty()) {
start();
Filename fn(commandSql);
QStringList execs = fn.path(img, m_profile, QString(), 0, Filename::KeepInvalidTokens);
for (QString exec : execs) {
exec.replace("%tag%", m_sqlWorker->escape(original))
.replace("%original%", m_sqlWorker->escape(tag.text()))
.replace("%type%", m_sqlWorker->escape(tag.type().name()))
.replace("%number%", QString::number(tag.type().number()));
if (!sqlExec(exec)) {
return false;
}
}
}
return true;
}
bool Commands::after() const
{
if (!m_mysqlSettings.after.isEmpty()) {
return sqlExec(m_mysqlSettings.after);
}
return true;
}
bool Commands::sqlExec(const QString &sql) const
{
QMetaObject::invokeMethod(m_sqlWorker, "execute", Qt::QueuedConnection, Q_ARG(QString, sql));
return true;
}
|
Fix commands fallback for old tag syntax not working
|
Fix commands fallback for old tag syntax not working
|
C++
|
apache-2.0
|
Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber
|
ff92cacdb6ef707fc34f3f5e35a60320544d9272
|
soccer/radio/NetworkRadio.cpp
|
soccer/radio/NetworkRadio.cpp
|
#include "NetworkRadio.hpp"
#include <Utils.hpp>
#include "Geometry2d/Util.hpp"
#include "PacketConvert.hpp"
#include "status.h"
using namespace boost::asio;
using ip::udp;
NetworkRadio::NetworkRadio(int server_port)
: _socket(_context, udp::endpoint(udp::v4(), server_port)),
_send_buffers(Robots_Per_Team) {
_connections.resize(Robots_Per_Team);
startReceive();
}
void NetworkRadio::startReceive() {
// Set a receive callback
_socket.async_receive_from(
boost::asio::buffer(_recv_buffer), _robot_endpoint,
[this](const boost::system::error_code& error, std::size_t num_bytes) {
receivePacket(error, num_bytes);
});
}
bool NetworkRadio::isOpen() const { return _socket.is_open(); }
void NetworkRadio::send(Packet::RadioTx& radioTx) {
// Get a list of all the IP addresses this packet needs to be sent to
for (int robot_idx = 0; robot_idx < radioTx.robots_size(); robot_idx++) {
const Packet::Control& control = radioTx.robots(robot_idx).control();
uint32_t robot_id = radioTx.robots(robot_idx).uid();
// Build the control packet for this robot.
std::array<uint8_t, rtp::HeaderSize + sizeof(rtp::RobotTxMessage)>&
forward_packet_buffer = _send_buffers[robot_idx];
rtp::Header* header =
reinterpret_cast<rtp::Header*>(&forward_packet_buffer[0]);
fill_header(header);
rtp::RobotTxMessage* body = reinterpret_cast<rtp::RobotTxMessage*>(
&forward_packet_buffer[rtp::HeaderSize]);
from_robot_tx_proto(radioTx.robots(robot_idx), body);
// Fetch the connection
auto maybe_connection = _connections.at(robot_id);
// If there exists a connection, we can send.
if (maybe_connection) {
const RobotConnection& connection = maybe_connection.value();
// Check if we've timed out.
if (RJ::now() + kTimeout < connection.last_received) {
// Remove the endpoint from the IP map and the connection list
assert(_robot_ip_map.erase(connection.endpoint) == 1);
_connections.at(robot_id) = std::nullopt;
} else {
// Send to the given IP address
const udp::endpoint& robot_endpoint = connection.endpoint;
_socket.async_send_to(
boost::asio::buffer(forward_packet_buffer), robot_endpoint,
[](const boost::system::error_code& error,
std::size_t num_bytes) {
// Handle errors.
if (error) {
std::cerr << "Error sending: " << error
<< " in " __FILE__ << std::endl;
}
});
}
}
}
}
void NetworkRadio::receive() {
// Let boost::asio handle callbacks
_context.poll();
}
void NetworkRadio::receivePacket(const boost::system::error_code& error,
std::size_t num_bytes) {
if (error) {
std::cerr << "Error receiving: " << error << " in " __FILE__
<< std::endl;
return;
} else if (num_bytes != rtp::ReverseSize) {
std::cerr << "Invalid packet length: expected " << rtp::ReverseSize
<< ", got " << num_bytes << std::endl;
return;
}
rtp::RobotStatusMessage* msg = reinterpret_cast<rtp::RobotStatusMessage*>(
&_recv_buffer[rtp::HeaderSize]);
_robot_endpoint.port(25566);
// Find out which robot this corresponds to.
int robot_id = msg->uid;
auto iter = _robot_ip_map.find(_robot_endpoint);
if (iter != _robot_ip_map.end() && iter->second != robot_id) {
// Make sure this IP address isn't mapped to another robot ID.
// If it is, remove the entry and the connections corresponding
// to both this ID and this IP address.
_connections.at(iter->second) = std::nullopt;
_robot_ip_map.erase(iter);
_connections.at(msg->uid) = std::nullopt;
}
// Update assignments.
if (!_connections.at(robot_id)) {
_connections.at(robot_id) = RobotConnection{_robot_endpoint, RJ::now()};
_robot_ip_map.insert({_robot_endpoint, robot_id});
} else {
// Update the timeout watchdog
_connections.at(robot_id)->last_received = RJ::now();
}
// Extract the protobuf form
Packet::RadioRx packet = convert_rx_rtp_to_proto(*msg);
{
// Add reverse packets
std::lock_guard<std::mutex> lock(_reverse_packets_mutex);
_reversePackets.push_back(packet);
}
// Restart receiving
startReceive();
}
void NetworkRadio::switchTeam(bool) {}
|
#include "NetworkRadio.hpp"
#include <Utils.hpp>
#include "Geometry2d/Util.hpp"
#include "PacketConvert.hpp"
#include "status.h"
using namespace boost::asio;
using ip::udp;
NetworkRadio::NetworkRadio(int server_port)
: _socket(_context, udp::endpoint(udp::v4(), server_port)),
_send_buffers(Num_Shells) {
_connections.resize(Num_Shells);
startReceive();
}
void NetworkRadio::startReceive() {
// Set a receive callback
_socket.async_receive_from(
boost::asio::buffer(_recv_buffer), _robot_endpoint,
[this](const boost::system::error_code& error, std::size_t num_bytes) {
receivePacket(error, num_bytes);
});
}
bool NetworkRadio::isOpen() const { return _socket.is_open(); }
void NetworkRadio::send(Packet::RadioTx& radioTx) {
// Get a list of all the IP addresses this packet needs to be sent to
for (int robot_idx = 0; robot_idx < radioTx.robots_size(); robot_idx++) {
const Packet::Control& control = radioTx.robots(robot_idx).control();
uint32_t robot_id = radioTx.robots(robot_idx).uid();
// Build the control packet for this robot.
std::array<uint8_t, rtp::HeaderSize + sizeof(rtp::RobotTxMessage)>&
forward_packet_buffer = _send_buffers[robot_idx];
rtp::Header* header =
reinterpret_cast<rtp::Header*>(&forward_packet_buffer[0]);
fill_header(header);
rtp::RobotTxMessage* body = reinterpret_cast<rtp::RobotTxMessage*>(
&forward_packet_buffer[rtp::HeaderSize]);
from_robot_tx_proto(radioTx.robots(robot_idx), body);
// Fetch the connection
auto maybe_connection = _connections.at(robot_id);
// If there exists a connection, we can send.
if (maybe_connection) {
const RobotConnection& connection = maybe_connection.value();
// Check if we've timed out.
if (RJ::now() + kTimeout < connection.last_received) {
// Remove the endpoint from the IP map and the connection list
assert(_robot_ip_map.erase(connection.endpoint) == 1);
_connections.at(robot_id) = std::nullopt;
} else {
// Send to the given IP address
const udp::endpoint& robot_endpoint = connection.endpoint;
_socket.async_send_to(
boost::asio::buffer(forward_packet_buffer), robot_endpoint,
[](const boost::system::error_code& error,
std::size_t num_bytes) {
// Handle errors.
if (error) {
std::cerr << "Error sending: " << error
<< " in " __FILE__ << std::endl;
}
});
}
}
}
}
void NetworkRadio::receive() {
// Let boost::asio handle callbacks
_context.poll();
}
void NetworkRadio::receivePacket(const boost::system::error_code& error,
std::size_t num_bytes) {
if (error) {
std::cerr << "Error receiving: " << error << " in " __FILE__
<< std::endl;
return;
} else if (num_bytes != rtp::ReverseSize) {
std::cerr << "Invalid packet length: expected " << rtp::ReverseSize
<< ", got " << num_bytes << std::endl;
return;
}
rtp::RobotStatusMessage* msg = reinterpret_cast<rtp::RobotStatusMessage*>(
&_recv_buffer[rtp::HeaderSize]);
_robot_endpoint.port(25566);
// Find out which robot this corresponds to.
int robot_id = msg->uid;
auto iter = _robot_ip_map.find(_robot_endpoint);
if (iter != _robot_ip_map.end() && iter->second != robot_id) {
// Make sure this IP address isn't mapped to another robot ID.
// If it is, remove the entry and the connections corresponding
// to both this ID and this IP address.
_connections.at(iter->second) = std::nullopt;
_robot_ip_map.erase(iter);
_connections.at(msg->uid) = std::nullopt;
}
// Update assignments.
if (!_connections.at(robot_id)) {
_connections.at(robot_id) = RobotConnection{_robot_endpoint, RJ::now()};
_robot_ip_map.insert({_robot_endpoint, robot_id});
} else {
// Update the timeout watchdog
_connections.at(robot_id)->last_received = RJ::now();
}
// Extract the protobuf form
Packet::RadioRx packet = convert_rx_rtp_to_proto(*msg);
{
// Add reverse packets
std::lock_guard<std::mutex> lock(_reverse_packets_mutex);
_reversePackets.push_back(packet);
}
// Restart receiving
startReceive();
}
void NetworkRadio::switchTeam(bool) {}
|
Use Num_Shells robots in network radio
|
Use Num_Shells robots in network radio
- This fixes a crash in the rewrite code, and a bit of UB in the old
code.
|
C++
|
apache-2.0
|
RoboJackets/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software
|
4a6454de94d8940de71cf270ef9169d0fb1eb96a
|
chrome/common/child_process.cc
|
chrome/common/child_process.cc
|
// 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/common/child_process.h"
#if defined(OS_POSIX)
#include <signal.h> // For SigUSR1Handler below.
#endif
#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/thread.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/child_thread.h"
#include "grit/chromium_strings.h"
#if defined(OS_POSIX)
static void SigUSR1Handler(int signal) { }
#endif
ChildProcess* ChildProcess::child_process_;
ChildProcess::ChildProcess()
: ref_count_(0),
shutdown_event_(true, false),
io_thread_("Chrome_ChildIOThread") {
DCHECK(!child_process_);
child_process_ = this;
io_thread_.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));
}
ChildProcess::~ChildProcess() {
DCHECK(child_process_ == this);
// Signal this event before destroying the child process. That way all
// background threads can cleanup.
// For example, in the renderer the RenderThread instances will be able to
// notice shutdown before the render process begins waiting for them to exit.
shutdown_event_.Signal();
// Kill the main thread object before nulling child_process_, since
// destruction code might depend on it.
main_thread_.reset();
child_process_ = NULL;
}
void ChildProcess::AddRefProcess() {
DCHECK(!main_thread_.get() || // null in unittests.
MessageLoop::current() == main_thread_->message_loop());
ref_count_++;
}
void ChildProcess::ReleaseProcess() {
DCHECK(!main_thread_.get() || // null in unittests.
MessageLoop::current() == main_thread_->message_loop());
DCHECK(ref_count_);
DCHECK(child_process_);
if (--ref_count_)
return;
if (main_thread_.get()) // null in unittests.
main_thread_->OnProcessFinalRelease();
}
base::WaitableEvent* ChildProcess::GetShutDownEvent() {
DCHECK(child_process_);
return &child_process_->shutdown_event_;
}
void ChildProcess::WaitForDebugger(const std::wstring& label) {
#if defined(OS_WIN)
std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME);
std::wstring message = label;
message += L" starting with pid: ";
message += UTF8ToWide(base::IntToString(base::GetCurrentProcId()));
title += L" ";
title += label; // makes attaching to process easier
::MessageBox(NULL, message.c_str(), title.c_str(),
MB_OK | MB_SETFOREGROUND);
#elif defined(OS_POSIX)
// TODO(playmobil): In the long term, overriding this flag doesn't seem
// right, either use our own flag or open a dialog we can use.
// This is just to ease debugging in the interim.
LOG(WARNING) << label
<< " ("
<< getpid()
<< ") paused waiting for debugger to attach @ pid";
// Install a signal handler so that pause can be woken.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SigUSR1Handler;
sigaction(SIGUSR1, &sa, NULL);
pause();
#endif // defined(OS_POSIX)
}
|
// 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/common/child_process.h"
#if defined(OS_POSIX)
#include <signal.h> // For SigUSR1Handler below.
#endif
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/thread.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/child_thread.h"
#include "grit/chromium_strings.h"
#if defined(OS_POSIX)
static void SigUSR1Handler(int signal) { }
#endif
ChildProcess* ChildProcess::child_process_;
ChildProcess::ChildProcess()
: ref_count_(0),
shutdown_event_(true, false),
io_thread_("Chrome_ChildIOThread") {
DCHECK(!child_process_);
child_process_ = this;
io_thread_.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));
}
ChildProcess::~ChildProcess() {
DCHECK(child_process_ == this);
// Signal this event before destroying the child process. That way all
// background threads can cleanup.
// For example, in the renderer the RenderThread instances will be able to
// notice shutdown before the render process begins waiting for them to exit.
shutdown_event_.Signal();
// Kill the main thread object before nulling child_process_, since
// destruction code might depend on it.
main_thread_.reset();
child_process_ = NULL;
}
void ChildProcess::AddRefProcess() {
DCHECK(!main_thread_.get() || // null in unittests.
MessageLoop::current() == main_thread_->message_loop());
ref_count_++;
}
void ChildProcess::ReleaseProcess() {
DCHECK(!main_thread_.get() || // null in unittests.
MessageLoop::current() == main_thread_->message_loop());
DCHECK(ref_count_);
DCHECK(child_process_);
if (--ref_count_)
return;
if (main_thread_.get()) // null in unittests.
main_thread_->OnProcessFinalRelease();
}
base::WaitableEvent* ChildProcess::GetShutDownEvent() {
DCHECK(child_process_);
return &child_process_->shutdown_event_;
}
void ChildProcess::WaitForDebugger(const std::wstring& label) {
#if defined(OS_WIN)
#if defined(GOOGLE_CHROME_BUILD)
std::wstring title = L"Google Chrome";
#else // CHROMIUM_BUILD
std::wstring title = L"Chromium";
#endif // CHROMIUM_BUILD
title += L" ";
title += label; // makes attaching to process easier
std::wstring message = label;
message += L" starting with pid: ";
message += UTF8ToWide(base::IntToString(base::GetCurrentProcId()));
::MessageBox(NULL, message.c_str(), title.c_str(),
MB_OK | MB_SETFOREGROUND);
#elif defined(OS_POSIX)
// TODO(playmobil): In the long term, overriding this flag doesn't seem
// right, either use our own flag or open a dialog we can use.
// This is just to ease debugging in the interim.
LOG(WARNING) << label
<< " ("
<< getpid()
<< ") paused waiting for debugger to attach @ pid";
// Install a signal handler so that pause can be woken.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SigUSR1Handler;
sigaction(SIGUSR1, &sa, NULL);
pause();
#endif // defined(OS_POSIX)
}
|
Set the title for wait-for-debugger dialog to be "Chromium". We were fetching the product name from resource bundle, which is not available for child processes that do not need it. Review URL: http://codereview.chromium.org/3176008
|
Set the title for wait-for-debugger dialog to be "Chromium". We were fetching the product name from resource bundle, which is not available for child processes that do not need it.
Review URL: http://codereview.chromium.org/3176008
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@56416 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
3c24ded6967c34738b137024bc58d5c439165591
|
chrome/test/ui/ppapi_uitest.cc
|
chrome/test/ui/ppapi_uitest.cc
|
// 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 "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// TODO(brettw) bug 51345: this failed consistently on one of the bots.
TEST_F(PPAPITest, FAILS_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
#if defined(OS_WIN)
TEST_F(PPAPITest, Scrollbar) {
#else
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
#endif
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
|
// 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 "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
#if defined(OS_WIN) || defined(OS_MAC)
TEST_F(PPAPITest, Graphics2D) {
#else
// http://crbug.com/54150
TEST_F(PPAPITest, FAILS_Graphics2D) {
#endif
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// TODO(brettw) bug 51345: this failed consistently on one of the bots.
TEST_F(PPAPITest, FAILS_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
#if defined(OS_WIN)
TEST_F(PPAPITest, Scrollbar) {
#else
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
#endif
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
|
Disable PPAPITest.Graphics2D on linux while I investigate. It's failing after a webkit roll.
|
Disable PPAPITest.Graphics2D on linux while I investigate. It's failing
after a webkit roll.
BUG=54150
TBR=akalin
Review URL: http://codereview.chromium.org/3334003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@58245 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ondra-novak/chromium.src,dednal/chromium.src,M4sse/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,hujiajie/pa-chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,ltilve/chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,robclark/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,patrickm/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,ltilve/chromium,keishi/chromium,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,anirudhSK/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,Just-D/chromium-1,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,keishi/chromium,Just-D/chromium-1,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,robclark/chromium,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,rogerwang/chromium,anirudhSK/chromium,anirudhSK/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,ltilve/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,littlstar/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,dednal/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,Chilledheart/chromium,M4sse/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,keishi/chromium,rogerwang/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,robclark/chromium,keishi/chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,littlstar/chromium.src,littlstar/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,robclark/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,anirudhSK/chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,keishi/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,robclark/chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,ondra-novak/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,Just-D/chromium-1,M4sse/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,anirudhSK/chromium,ltilve/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,robclark/chromium,patrickm/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,robclark/chromium,Chilledheart/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,hujiajie/pa-chromium,Chilledheart/chromium,Just-D/chromium-1,ltilve/chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,keishi/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,dushu1203/chromium.src,jaruba/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,rogerwang/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,robclark/chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,keishi/chromium
|
2aab40207ab12a7ca62b12c6aa93229192c96e72
|
chrome/test/ui/ppapi_uitest.cc
|
chrome/test/ui/ppapi_uitest.cc
|
// 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 "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
const wchar_t kDocRoot[] = L"third_party/ppapi/tests";
scoped_refptr<net::HTTPTestServer> server(
net::HTTPTestServer::CreateServer(kDocRoot));
ASSERT_TRUE(server);
RunTestURL(server->TestServerPage("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, DeviceContext2D) {
RunTest("DeviceContext2D");
}
TEST_F(PPAPITest, ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
TEST_F(PPAPITest, URLLoader) {
RunTestViaHTTP("URLLoader");
}
TEST_F(PPAPITest, PaintAgggregator) {
RunTestViaHTTP("PaintAggregator");
}
#if defined(OS_LINUX)
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
#else
TEST_F(PPAPITest, Scrollbar) {
#endif
RunTest("Scrollbar");
}
|
// 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 "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
const wchar_t kDocRoot[] = L"third_party/ppapi/tests";
scoped_refptr<net::HTTPTestServer> server(
net::HTTPTestServer::CreateServer(kDocRoot));
ASSERT_TRUE(server);
RunTestURL(server->TestServerPage("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, DeviceContext2D) {
RunTest("DeviceContext2D");
}
TEST_F(PPAPITest, ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
TEST_F(PPAPITest, URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
#if defined(OS_LINUX)
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
#else
TEST_F(PPAPITest, Scrollbar) {
#endif
RunTest("Scrollbar");
}
|
Mark PPAPITest.PaintAggregator flaky BUG=51012 TEST=ui_tests
|
Mark PPAPITest.PaintAggregator flaky
BUG=51012
TEST=ui_tests
Review URL: http://codereview.chromium.org/3064031
git-svn-id: http://src.chromium.org/svn/trunk/src@54639 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 7eaf5c224b44adf4b09fbba8798912dd197a4e12
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
8e741f3da4dd693f4e7933e87b99df9f2b4337e0
|
src/codeformation/Stack.cpp
|
src/codeformation/Stack.cpp
|
#include "codeformation/Stack.h"
#include <cassert>
namespace codeformation {
Stack::~Stack() {
destroy();
}
stdts::optional<Error> Stack::build(const std::string& json) {
try {
std::string error;
auto root = json11::Json::parse(json, error);
if (!error.empty()) {
return Error("Error parsing template: "s + error);
}
json11::Json resources{json11::Json::object{}};
if (root.object_items().count("Resources")) {
resources = root["Resources"];
for (auto& kv : resources.object_items()) {
_resource(resources, kv.first);
}
}
if (root.object_items().count("Outputs")) {
auto outputs = root["Outputs"];
for (auto& kv : outputs.object_items()) {
_outputs[kv.first] = _evaluate(resources, kv.second);
}
}
} catch (Error error) {
return error;
}
return {};
}
std::unique_ptr<Resource> Stack::_createResource(const String& type, Dictionary properties){
std::unique_ptr<Resource> ret;
auto it = _resourceConstructors.find(type);
if (it != _resourceConstructors.end()) {
ret = it->second();
} else {
throw Error("Unknown type: "s + type);
}
ret->setProperties(std::move(properties));
ret->create();
return ret;
}
void Stack::destroy() {
for (auto it = _resourceCreationOrder.rbegin(); it != _resourceCreationOrder.rend(); ++it) {
_resources.erase(*it);
}
}
Resource* Stack::_resource(const json11::Json& resources, const String& name) {
auto it = _resources.find(name);
if (it != _resources.end()) {
return it->second.get();
}
if (!resources.object_items().count(name)) {
throw Error("No resource named "s + name + " was found.");
}
try {
auto resourceObject = resources[name];
if (!resourceObject.object_items().count("Type")) {
throw Error("No Type specified.");
}
if (_resourceCreationRequired.count(name)) {
throw Error("Cyclic dependency.");
}
_resourceCreationRequired.insert(name);
auto properties = _properties(resources, resourceObject);
auto& resource = _resources[name] = _createResource(resourceObject["Type"].string_value(), properties);
_resourceCreationOrder.emplace_back(name);
return resource.get();
} catch (Error error) {
throw Error(error.message, name);
}
}
Dictionary Stack::_properties(const json11::Json& resources, const json11::Json& resource) {
if (!resource.object_items().count("Properties")) {
return {};
}
auto properties = _evaluate(resources, resource["Properties"]);
auto* map = stdts::any_cast<Dictionary>(&properties);
if (!map) {
throw Error("Dictionary expected.");
}
return *map;
}
Any Stack::_evaluate(const json11::Json& resources, const json11::Json& thing) {
switch (thing.type()) {
case json11::Json::NUL:
return nullptr;
case json11::Json::NUMBER:
return thing.number_value();
case json11::Json::BOOL:
return thing.bool_value();
case json11::Json::STRING:
return thing.string_value();
case json11::Json::ARRAY: {
List ret;
for (auto& item : thing.array_items()) {
ret.emplace_back(_evaluate(resources, item));
}
return ret;
}
case json11::Json::OBJECT: {
if (thing.object_items().size() == 1) {
auto key = thing.object_items().begin()->first;
if (key == "Ref") {
auto name = thing[key].string_value();
if (_inputs.count(name)) {
return _inputs[name];
}
return _resource(resources, name)->get();
} else if (key.find("Fn::") == 0) {
auto name = key.substr(4);
if (!_functions.count(name)) {
throw Error("No function named "s + name + " has been defined.");
}
return _functions[name](_evaluate(resources, thing[key]));
}
}
Dictionary ret;
for (auto& kv : thing.object_items()) {
ret[kv.first] = _evaluate(resources, kv.second);
}
return ret;
}
}
}
} // namespace codeformation
|
/**
* Copyright 2016 BitTorrent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "codeformation/Stack.h"
#include <cassert>
namespace codeformation {
Stack::~Stack() {
destroy();
}
stdts::optional<Error> Stack::build(const std::string& json) {
try {
std::string error;
auto root = json11::Json::parse(json, error);
if (!error.empty()) {
return Error("Error parsing template: "s + error);
}
json11::Json resources{json11::Json::object{}};
if (root.object_items().count("Resources")) {
resources = root["Resources"];
for (auto& kv : resources.object_items()) {
_resource(resources, kv.first);
}
}
if (root.object_items().count("Outputs")) {
auto outputs = root["Outputs"];
for (auto& kv : outputs.object_items()) {
_outputs[kv.first] = _evaluate(resources, kv.second);
}
}
} catch (Error error) {
return error;
}
return {};
}
std::unique_ptr<Resource> Stack::_createResource(const String& type, Dictionary properties){
std::unique_ptr<Resource> ret;
auto it = _resourceConstructors.find(type);
if (it != _resourceConstructors.end()) {
ret = it->second();
} else {
throw Error("Unknown type: "s + type);
}
ret->setProperties(std::move(properties));
ret->create();
return ret;
}
void Stack::destroy() {
for (auto it = _resourceCreationOrder.rbegin(); it != _resourceCreationOrder.rend(); ++it) {
_resources.erase(*it);
}
}
Resource* Stack::_resource(const json11::Json& resources, const String& name) {
auto it = _resources.find(name);
if (it != _resources.end()) {
return it->second.get();
}
if (!resources.object_items().count(name)) {
throw Error("No resource named "s + name + " was found.");
}
try {
auto resourceObject = resources[name];
if (!resourceObject.object_items().count("Type")) {
throw Error("No Type specified.");
}
if (_resourceCreationRequired.count(name)) {
throw Error("Cyclic dependency.");
}
_resourceCreationRequired.insert(name);
auto properties = _properties(resources, resourceObject);
auto& resource = _resources[name] = _createResource(resourceObject["Type"].string_value(), properties);
_resourceCreationOrder.emplace_back(name);
return resource.get();
} catch (Error error) {
throw Error(error.message, name);
}
}
Dictionary Stack::_properties(const json11::Json& resources, const json11::Json& resource) {
if (!resource.object_items().count("Properties")) {
return {};
}
auto properties = _evaluate(resources, resource["Properties"]);
auto* map = stdts::any_cast<Dictionary>(&properties);
if (!map) {
throw Error("Dictionary expected.");
}
return *map;
}
Any Stack::_evaluate(const json11::Json& resources, const json11::Json& thing) {
switch (thing.type()) {
case json11::Json::NUL:
return nullptr;
case json11::Json::NUMBER:
return thing.number_value();
case json11::Json::BOOL:
return thing.bool_value();
case json11::Json::STRING:
return thing.string_value();
case json11::Json::ARRAY: {
List ret;
for (auto& item : thing.array_items()) {
ret.emplace_back(_evaluate(resources, item));
}
return ret;
}
case json11::Json::OBJECT: {
if (thing.object_items().size() == 1) {
auto key = thing.object_items().begin()->first;
if (key == "Ref") {
auto name = thing[key].string_value();
if (_inputs.count(name)) {
return _inputs[name];
}
return _resource(resources, name)->get();
} else if (key.find("Fn::") == 0) {
auto name = key.substr(4);
if (!_functions.count(name)) {
throw Error("No function named "s + name + " has been defined.");
}
return _functions[name](_evaluate(resources, thing[key]));
}
}
Dictionary ret;
for (auto& kv : thing.object_items()) {
ret[kv.first] = _evaluate(resources, kv.second);
}
return ret;
}
}
}
} // namespace codeformation
|
Add missing license header
|
Add missing license header
|
C++
|
apache-2.0
|
bittorrent/scraps,bittorrent/scraps,bittorrent/scraps,bittorrent/scraps
|
f4a02d5258a82d7855deef74bc744d8175695561
|
PoissonEditingWrappers.hpp
|
PoissonEditingWrappers.hpp
|
/*=========================================================================
*
* Copyright David Doria 2012 [email protected]
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef PoissonEditingWrappers_HPP
#define PoissonEditingWrappers_HPP
#include "PoissonEditingWrappers.h" // Appease syntax parser
// Submodules
#include "Helpers/Helpers.h"
#include "ITKHelpers/ITKHelpers.h"
// ITK
#include "itkAddImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkComposeImageFilter.h"
#include "itkLaplacianOperator.h"
#include "itkLaplacianImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
// Eigen
#include <Eigen/Sparse>
template <typename TImage>
void FillVectorImage(const TImage* const targetImage, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType*>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillVectorImage()" << std::endl;
if(!mask)
{
throw std::runtime_error("You must specify a mask!");
}
if(guidanceFields.size() != targetImage->GetNumberOfComponentsPerPixel())
{
std::stringstream ss;
ss << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " channels but "
<< guidanceFields.size() << " guidance fields were specified (these must match).";
throw std::runtime_error(ss.str());
}
itk::ImageRegion<2> holeBoundingBox =
ITKHelpers::ComputeBoundingBox(mask, HoleMaskPixelTypeEnum::HOLE);
// Adjust the hole bounding box to be in the target position
itk::ImageRegion<2> holeBoundingBoxPositioned = holeBoundingBox;
holeBoundingBoxPositioned.SetIndex(regionToProcess.GetIndex() +
(holeBoundingBox.GetIndex() - mask->GetLargestPossibleRegion().GetIndex()));
if(!targetImage->GetLargestPossibleRegion().IsInside(holeBoundingBoxPositioned))
{
std::cerr << "Cannot clone at this position! Source image holes are outside of the target image!" << std::endl;
return;
}
// Crop the mask
Mask::Pointer croppedMask = Mask::New();
croppedMask->Allocate();
ITKHelpers::ExtractRegion(mask, holeBoundingBox, croppedMask.GetPointer());
std::cout << "croppedMask region: " << croppedMask->GetLargestPossibleRegion() << std::endl;
// Setup components of the channel-wise processing
typedef itk::Image<typename TypeTraits<typename TImage::PixelType>::ComponentType, 2> ScalarImageType;
typedef itk::ComposeImageFilter<ScalarImageType, TImage> ReassemblerType;
typename ReassemblerType::Pointer reassembler = ReassemblerType::New();
// Perform the Poisson reconstruction on each channel independently
typedef typename TypeTraits<typename TImage::PixelType>::ComponentType ComponentType;
typedef PoissonEditing<ComponentType> PoissonEditingFilterType;
std::vector<PoissonEditingFilterType> poissonFilters;
for(unsigned int component = 0;
component < targetImage->GetNumberOfComponentsPerPixel(); ++component)
{
std::cout << "Filling component " << component << std::endl;
// Disassemble the target image into its components
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
TargetDisassemblerType;
typename TargetDisassemblerType::Pointer targetDisassembler =
TargetDisassemblerType::New();
targetDisassembler->SetIndex(component);
targetDisassembler->SetInput(targetImage);
targetDisassembler->Update();
PoissonEditingParent::GuidanceFieldType::Pointer croppedGuidanceField =
PoissonEditingParent::GuidanceFieldType::New();
croppedGuidanceField->Allocate();
ITKHelpers::ExtractRegion(guidanceFields[component], holeBoundingBox,
croppedGuidanceField.GetPointer());
// Perform the actual filling
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(targetDisassembler->GetOutput());
poissonFilter.SetRegionToProcess(holeBoundingBoxPositioned);
// Disassemble the source image into its components
if(sourceImage)
{
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
SourceDisassemblerType;
typename SourceDisassemblerType::Pointer sourceDisassembler =
SourceDisassemblerType::New();
sourceDisassembler->SetIndex(component);
sourceDisassembler->SetInput(sourceImage);
sourceDisassembler->Update();
typename ScalarImageType::Pointer croppedSourceImage =
ScalarImageType::New();
croppedSourceImage->Allocate();
ITKHelpers::ExtractRegion(sourceDisassembler->GetOutput(), holeBoundingBox,
croppedSourceImage.GetPointer());
poissonFilter.SetSourceImage(croppedSourceImage.GetPointer());
}
poissonFilter.SetGuidanceField(croppedGuidanceField.GetPointer());
poissonFilter.SetMask(croppedMask.GetPointer());
poissonFilter.FillMaskedRegion();
poissonFilters.push_back(poissonFilter);
reassembler->SetInput(component, poissonFilters[component].GetOutput());
} // end loop over components
reassembler->Update();
// std::cout << "Output components per pixel: " << reassembler->GetOutput()->GetNumberOfComponentsPerPixel()
// << std::endl;
// std::cout << "Output size: " << reassembler->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl;
ITKHelpers::DeepCopy(reassembler->GetOutput(), output);
}
/** Specialization for scalar images */
template <typename TScalarPixel>
void FillScalarImage(const itk::Image<TScalarPixel, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
typedef PoissonEditing<TScalarPixel> PoissonEditingFilterType;
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(image);
poissonFilter.SetRegionToProcess(regionToProcess);
poissonFilter.SetGuidanceField(guidanceField);
poissonFilter.SetMask(mask);
// Perform the actual filling
poissonFilter.FillMaskedRegion();
ITKHelpers::DeepCopy(poissonFilter.GetOutput(), output);
}
/** For vector images with smart pointers to different guidance fields.*/
template <typename TImage>
void FillImage(const TImage* const image, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields, TImage* const output,
const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillImage()" << std::endl;
std::vector<PoissonEditingParent::GuidanceFieldType*> guidanceFieldsRaw;
for(unsigned int i = 0; i < guidanceFields.size(); ++i)
{
guidanceFieldsRaw.push_back(guidanceFields[i]);
}
FillVectorImage(image, mask, guidanceFieldsRaw, output, regionToProcess, sourceImage);
}
/** For scalar images. */
template <typename TScalarPixel>
void FillImage(const itk::Image<TScalarPixel, 2>* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
FillScalarImage(image, mask, guidanceField, output, regionToProcess, sourceImage);
}
/** For vector images with the same guidance field for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "Fill image with same guidance field for each channel." << std::endl;
std::vector<PoissonEditingParent::GuidanceFieldType*>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For vector images with different guidance fields for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType*>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
// Always call the vector version, as it is the only one that makes sense
// to have passed a collection of guidance fields.
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For vector images with different guidance fields for each channel. */
template <typename TPixel>
void
FillImage(const itk::VectorImage<TPixel>* const image,
const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType*>& guidanceFields,
itk::VectorImage<TPixel>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::VectorImage<TPixel>* const sourceImage)
{
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For Image<CovariantVector> images. */
template <typename TComponent, unsigned int NumberOfComponents>
void FillImage(const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const sourceImage)
{
std::vector<PoissonEditingParent::GuidanceFieldType*>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
#endif
|
/*=========================================================================
*
* Copyright David Doria 2012 [email protected]
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef PoissonEditingWrappers_HPP
#define PoissonEditingWrappers_HPP
#include "PoissonEditingWrappers.h" // Appease syntax parser
// Submodules
#include "Helpers/Helpers.h"
#include "ITKHelpers/ITKHelpers.h"
// ITK
#include "itkAddImageFilter.h"
#include "itkImageRegionConstIterator.h"
#include "itkComposeImageFilter.h"
#include "itkLaplacianOperator.h"
#include "itkLaplacianImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
// Eigen
#include <Eigen/Sparse>
/** The terminology "targetImage" and "sourceImage" come from Poisson Cloning.
* To interpret these arguments in a Poisson Filling context, there is no source image
* (sourceImage must be nullptr), and the targetImage is the image to be filled.
*/
template <typename TImage>
void FillVectorImage(const TImage* const targetImage, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType*>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillVectorImage()" << std::endl;
if(!mask)
{
throw std::runtime_error("You must specify a mask!");
}
if(guidanceFields.size() != targetImage->GetNumberOfComponentsPerPixel())
{
std::stringstream ss;
ss << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " channels but "
<< guidanceFields.size() << " guidance fields were specified (these must match).";
throw std::runtime_error(ss.str());
}
itk::ImageRegion<2> holeBoundingBox =
ITKHelpers::ComputeBoundingBox(mask, HoleMaskPixelTypeEnum::HOLE);
// Adjust the hole bounding box to be in the target position
itk::ImageRegion<2> holeBoundingBoxPositioned = holeBoundingBox;
holeBoundingBoxPositioned.SetIndex(regionToProcess.GetIndex() +
(holeBoundingBox.GetIndex() - mask->GetLargestPossibleRegion().GetIndex()));
if(!targetImage->GetLargestPossibleRegion().IsInside(holeBoundingBoxPositioned))
{
std::cerr << "Cannot clone at this position! Source image holes are outside of the target image!" << std::endl;
return;
}
// Crop the mask
Mask::Pointer croppedMask = Mask::New();
croppedMask->Allocate();
ITKHelpers::ExtractRegion(mask, holeBoundingBox, croppedMask.GetPointer());
std::cout << "croppedMask region: " << croppedMask->GetLargestPossibleRegion() << std::endl;
// Setup components of the channel-wise processing
typedef itk::Image<typename TypeTraits<typename TImage::PixelType>::ComponentType, 2> ScalarImageType;
typedef itk::ComposeImageFilter<ScalarImageType, TImage> ReassemblerType;
typename ReassemblerType::Pointer reassembler = ReassemblerType::New();
// Perform the Poisson reconstruction on each channel independently
typedef typename TypeTraits<typename TImage::PixelType>::ComponentType ComponentType;
typedef PoissonEditing<ComponentType> PoissonEditingFilterType;
std::vector<PoissonEditingFilterType> poissonFilters;
std::cout << "There are " << targetImage->GetNumberOfComponentsPerPixel() << " components in the output image." << std::endl;
for(unsigned int component = 0;
component < targetImage->GetNumberOfComponentsPerPixel(); ++component)
{
std::cout << "Filling component " << component << std::endl;
// Disassemble the target image into its components
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
TargetDisassemblerType;
typename TargetDisassemblerType::Pointer targetDisassembler =
TargetDisassemblerType::New();
targetDisassembler->SetIndex(component);
targetDisassembler->SetInput(targetImage);
targetDisassembler->Update();
PoissonEditingParent::GuidanceFieldType::Pointer croppedGuidanceField =
PoissonEditingParent::GuidanceFieldType::New();
croppedGuidanceField->Allocate();
ITKHelpers::ExtractRegion(guidanceFields[component], holeBoundingBox,
croppedGuidanceField.GetPointer());
// Perform the actual filling
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(targetDisassembler->GetOutput());
poissonFilter.SetRegionToProcess(holeBoundingBoxPositioned);
// Disassemble the source image into its components
if(sourceImage)
{
typedef itk::VectorIndexSelectionCastImageFilter<TImage, ScalarImageType>
SourceDisassemblerType;
typename SourceDisassemblerType::Pointer sourceDisassembler =
SourceDisassemblerType::New();
sourceDisassembler->SetIndex(component);
sourceDisassembler->SetInput(sourceImage);
sourceDisassembler->Update();
typename ScalarImageType::Pointer croppedSourceImage =
ScalarImageType::New();
croppedSourceImage->Allocate();
ITKHelpers::ExtractRegion(sourceDisassembler->GetOutput(), holeBoundingBox,
croppedSourceImage.GetPointer());
poissonFilter.SetSourceImage(croppedSourceImage.GetPointer());
}
poissonFilter.SetGuidanceField(croppedGuidanceField.GetPointer());
poissonFilter.SetMask(croppedMask.GetPointer());
poissonFilter.FillMaskedRegion();
poissonFilters.push_back(poissonFilter);
reassembler->SetInput(component, poissonFilters[component].GetOutput());
std::cout << "Finished filling component " << component << std::endl;
} // end loop over components
reassembler->Update();
// std::cout << "Output components per pixel: " << reassembler->GetOutput()->GetNumberOfComponentsPerPixel()
// << std::endl;
// std::cout << "Output size: " << reassembler->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl;
ITKHelpers::DeepCopy(reassembler->GetOutput(), output);
}
/** Specialization for scalar images */
template <typename TScalarPixel>
void FillScalarImage(const itk::Image<TScalarPixel, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
typedef PoissonEditing<TScalarPixel> PoissonEditingFilterType;
PoissonEditingFilterType poissonFilter;
poissonFilter.SetTargetImage(image);
poissonFilter.SetRegionToProcess(regionToProcess);
poissonFilter.SetGuidanceField(guidanceField);
poissonFilter.SetMask(mask);
// Perform the actual filling
poissonFilter.FillMaskedRegion();
ITKHelpers::DeepCopy(poissonFilter.GetOutput(), output);
}
/** For vector images with smart pointers to different guidance fields.*/
template <typename TImage>
void FillImage(const TImage* const image, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType::Pointer>& guidanceFields, TImage* const output,
const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillImage()" << std::endl;
std::vector<PoissonEditingParent::GuidanceFieldType*> guidanceFieldsRaw;
for(unsigned int i = 0; i < guidanceFields.size(); ++i)
{
guidanceFieldsRaw.push_back(guidanceFields[i]);
}
FillVectorImage(image, mask, guidanceFieldsRaw, output, regionToProcess, sourceImage);
}
/** For scalar images. */
template <typename TScalarPixel>
void FillImage(const itk::Image<TScalarPixel, 2>* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<TScalarPixel, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<TScalarPixel, 2>* const sourceImage)
{
FillScalarImage(image, mask, guidanceField, output, regionToProcess, sourceImage);
}
/** For vector images with the same guidance field for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
std::cout << "FillImage with same guidance field for each channel." << std::endl;
std::vector<PoissonEditingParent::GuidanceFieldType*>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
std::cout << "Duplicated guidance field for each of the "
<< image->GetNumberOfComponentsPerPixel() << " channels." << std::endl;
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For vector images with different guidance fields for each channel. */
template <typename TImage>
void
FillImage(const TImage* const image, const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType*>& guidanceFields,
TImage* const output, const itk::ImageRegion<2>& regionToProcess,
const TImage* const sourceImage)
{
// Always call the vector version, as it is the only one that makes sense
// to have passed a collection of guidance fields.
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For vector images with different guidance fields for each channel. */
template <typename TPixel>
void
FillImage(const itk::VectorImage<TPixel>* const image,
const Mask* const mask,
const std::vector<PoissonEditingParent::GuidanceFieldType*>& guidanceFields,
itk::VectorImage<TPixel>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::VectorImage<TPixel>* const sourceImage)
{
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
/** For Image<CovariantVector> images. */
template <typename TComponent, unsigned int NumberOfComponents>
void FillImage(const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const image,
const Mask* const mask,
const PoissonEditingParent::GuidanceFieldType* const guidanceField,
itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const output,
const itk::ImageRegion<2>& regionToProcess,
const itk::Image<itk::CovariantVector<TComponent,
NumberOfComponents>, 2>* const sourceImage)
{
std::vector<PoissonEditingParent::GuidanceFieldType*>
guidanceFields(image->GetNumberOfComponentsPerPixel(),
const_cast<PoissonEditingParent::GuidanceFieldType*>(guidanceField));
FillVectorImage(image, mask, guidanceFields, output, regionToProcess, sourceImage);
}
#endif
|
Add an explanation of some terminology.
|
Add an explanation of some terminology.
|
C++
|
apache-2.0
|
daviddoria/PoissonEditing
|
41e3268ccde9b97f15514a55af1a06f49ebbb049
|
arangod/Scheduler/JobQueue.cpp
|
arangod/Scheduler/JobQueue.cpp
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "JobQueue.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
using namespace arangodb;
namespace {
class JobQueueThread final : public Thread {
public:
JobQueueThread(JobQueue* server, boost::asio::io_service* ioService)
: Thread("JobQueueThread"), _jobQueue(server), _ioService(ioService) {}
~JobQueueThread() { shutdown(); }
void beginShutdown() {
Thread::beginShutdown();
_jobQueue->wakeup();
}
public:
void run() {
int idleTries = 0;
auto jobQueue = _jobQueue;
// iterate until we are shutting down
while (!isStopping()) {
++idleTries;
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
LOG_TOPIC(TRACE, Logger::THREADS) << "size of queue #" << i << ": "
<< _jobQueue->queueSize(i);
while (_jobQueue->tryActive()) {
Job* job = nullptr;
if (!_jobQueue->pop(i, job)) {
_jobQueue->releaseActive();
break;
}
LOG_TOPIC(TRACE, Logger::THREADS)
<< "starting next queued job, number currently active "
<< _jobQueue->active();
idleTries = 0;
_ioService->dispatch([jobQueue, job]() {
std::unique_ptr<Job> guard(job);
job->_callback(std::move(job->_handler));
jobQueue->releaseActive();
jobQueue->wakeup();
});
}
}
// we need to check again if more work has arrived after we have
// aquired the lock. The lockfree queue and _nrWaiting are accessed
// using "memory_order_seq_cst", this guarantees that we do not
// miss a signal.
if (idleTries >= 2) {
LOG_TOPIC(TRACE, Logger::THREADS) << "queue manager going to sleep";
_jobQueue->waitForWork();
}
}
}
private:
JobQueue* _jobQueue;
boost::asio::io_service* _ioService;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
JobQueue::JobQueue(size_t queueSize, boost::asio::io_service* ioService)
: _queueAql(queueSize),
_queueRequeue(queueSize),
_queueStandard(queueSize),
_queueUser(queueSize),
_queues{&_queueRequeue, &_queueAql, &_queueStandard, &_queueUser},
_active(0),
_ioService(ioService),
_queueThread(new JobQueueThread(this, _ioService)) {
for (size_t i = 0; i < SYSTEM_QUEUE_SIZE; ++i) {
_queuesSize[i].store(0);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void JobQueue::start() {
_queueThread->start();
}
void JobQueue::beginShutdown() {
_queueThread->beginShutdown();
}
bool JobQueue::tryActive() {
if (!SchedulerFeature::SCHEDULER->tryBlocking()) {
return false;
}
++_active;
return true;
}
void JobQueue::releaseActive() {
SchedulerFeature::SCHEDULER->unworkThread();
--_active;
}
void JobQueue::wakeup() {
CONDITION_LOCKER(guard, _queueCondition);
guard.signal();
}
void JobQueue::waitForWork() {
static uint64_t WAIT_TIME = 1000 * 1000;
CONDITION_LOCKER(guard, _queueCondition);
guard.wait(WAIT_TIME);
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "JobQueue.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
using namespace arangodb;
namespace {
class JobQueueThread final : public Thread {
public:
JobQueueThread(JobQueue* server, boost::asio::io_service* ioService)
: Thread("JobQueueThread"), _jobQueue(server), _ioService(ioService) {}
~JobQueueThread() { shutdown(); }
void beginShutdown() {
Thread::beginShutdown();
_jobQueue->wakeup();
}
public:
void run() {
int idleTries = 0;
auto jobQueue = _jobQueue;
// iterate until we are shutting down
while (!isStopping()) {
++idleTries;
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
LOG_TOPIC(TRACE, Logger::THREADS) << "size of queue #" << i << ": "
<< _jobQueue->queueSize(i);
while (_jobQueue->tryActive()) {
Job* job = nullptr;
if (!_jobQueue->pop(i, job)) {
_jobQueue->releaseActive();
break;
}
LOG_TOPIC(TRACE, Logger::THREADS)
<< "starting next queued job, number currently active "
<< _jobQueue->active();
idleTries = 0;
_ioService->dispatch([jobQueue, job]() {
std::unique_ptr<Job> guard(job);
job->_callback(std::move(job->_handler));
jobQueue->releaseActive();
jobQueue->wakeup();
});
}
}
// we need to check again if more work has arrived after we have
// aquired the lock. The lockfree queue and _nrWaiting are accessed
// using "memory_order_seq_cst", this guarantees that we do not
// miss a signal.
if (idleTries >= 2) {
LOG_TOPIC(TRACE, Logger::THREADS) << "queue manager going to sleep";
_jobQueue->waitForWork();
}
}
// clear all non-processed jobs
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
Job* job = nullptr;
while (_jobQueue->pop(i, job)) {
delete job;
}
}
}
private:
JobQueue* _jobQueue;
boost::asio::io_service* _ioService;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
JobQueue::JobQueue(size_t queueSize, boost::asio::io_service* ioService)
: _queueAql(queueSize),
_queueRequeue(queueSize),
_queueStandard(queueSize),
_queueUser(queueSize),
_queues{&_queueRequeue, &_queueAql, &_queueStandard, &_queueUser},
_active(0),
_ioService(ioService),
_queueThread(new JobQueueThread(this, _ioService)) {
for (size_t i = 0; i < SYSTEM_QUEUE_SIZE; ++i) {
_queuesSize[i].store(0);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void JobQueue::start() {
_queueThread->start();
}
void JobQueue::beginShutdown() {
_queueThread->beginShutdown();
}
bool JobQueue::tryActive() {
if (!SchedulerFeature::SCHEDULER->tryBlocking()) {
return false;
}
++_active;
return true;
}
void JobQueue::releaseActive() {
SchedulerFeature::SCHEDULER->unworkThread();
--_active;
}
void JobQueue::wakeup() {
CONDITION_LOCKER(guard, _queueCondition);
guard.signal();
}
void JobQueue::waitForWork() {
static uint64_t WAIT_TIME = 1000 * 1000;
CONDITION_LOCKER(guard, _queueCondition);
guard.wait(WAIT_TIME);
}
|
clean up job queues on shutdown
|
clean up job queues on shutdown
|
C++
|
apache-2.0
|
baslr/ArangoDB,hkernbach/arangodb,Simran-B/arangodb,baslr/ArangoDB,wiltonlazary/arangodb,Simran-B/arangodb,joerg84/arangodb,joerg84/arangodb,graetzer/arangodb,hkernbach/arangodb,graetzer/arangodb,hkernbach/arangodb,baslr/ArangoDB,baslr/ArangoDB,baslr/ArangoDB,wiltonlazary/arangodb,joerg84/arangodb,Simran-B/arangodb,graetzer/arangodb,joerg84/arangodb,joerg84/arangodb,baslr/ArangoDB,hkernbach/arangodb,baslr/ArangoDB,fceller/arangodb,hkernbach/arangodb,fceller/arangodb,Simran-B/arangodb,Simran-B/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,graetzer/arangodb,fceller/arangodb,fceller/arangodb,hkernbach/arangodb,hkernbach/arangodb,graetzer/arangodb,wiltonlazary/arangodb,fceller/arangodb,arangodb/arangodb,arangodb/arangodb,wiltonlazary/arangodb,Simran-B/arangodb,graetzer/arangodb,joerg84/arangodb,graetzer/arangodb,joerg84/arangodb,arangodb/arangodb,joerg84/arangodb,fceller/arangodb,joerg84/arangodb,joerg84/arangodb,baslr/ArangoDB,Simran-B/arangodb,arangodb/arangodb,arangodb/arangodb,baslr/ArangoDB,Simran-B/arangodb,fceller/arangodb,graetzer/arangodb,hkernbach/arangodb,arangodb/arangodb,graetzer/arangodb,hkernbach/arangodb,graetzer/arangodb,graetzer/arangodb,hkernbach/arangodb,baslr/ArangoDB,baslr/ArangoDB,wiltonlazary/arangodb,joerg84/arangodb,wiltonlazary/arangodb,graetzer/arangodb,Simran-B/arangodb,fceller/arangodb,baslr/ArangoDB,joerg84/arangodb,fceller/arangodb,joerg84/arangodb,graetzer/arangodb,baslr/ArangoDB,fceller/arangodb,baslr/ArangoDB,Simran-B/arangodb,hkernbach/arangodb,hkernbach/arangodb,arangodb/arangodb,graetzer/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,joerg84/arangodb,arangodb/arangodb
|
719ff68fdd6cbcfab612cb8efe3dda3536e81a95
|
platform/javascript/api/javascript_tools_editor_plugin.cpp
|
platform/javascript/api/javascript_tools_editor_plugin.cpp
|
/*************************************************************************/
/* javascript_tools_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#if defined(TOOLS_ENABLED) && defined(JAVASCRIPT_ENABLED)
#include "javascript_tools_editor_plugin.h"
#include "core/config/engine.h"
#include "core/config/project_settings.h"
#include "core/io/dir_access.h"
#include "core/io/file_access.h"
#include "editor/editor_node.h"
#include <emscripten/emscripten.h>
// JavaScript functions defined in library_godot_editor_tools.js
extern "C" {
extern void godot_js_os_download_buffer(const uint8_t *p_buf, int p_buf_size, const char *p_name, const char *p_mime);
}
static void _javascript_editor_init_callback() {
EditorNode::get_singleton()->add_editor_plugin(memnew(JavaScriptToolsEditorPlugin(EditorNode::get_singleton())));
}
void JavaScriptToolsEditorPlugin::initialize() {
EditorNode::add_init_callback(_javascript_editor_init_callback);
}
JavaScriptToolsEditorPlugin::JavaScriptToolsEditorPlugin(EditorNode *p_editor) {
add_tool_menu_item("Download Project Source", callable_mp(this, &JavaScriptToolsEditorPlugin::_download_zip));
}
void JavaScriptToolsEditorPlugin::_download_zip(Variant p_v) {
if (!Engine::get_singleton() || !Engine::get_singleton()->is_editor_hint()) {
WARN_PRINT("Project download is only available in Editor mode");
return;
}
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
FileAccess *src_f;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
zipFile zip = zipOpen2("/tmp/project.zip", APPEND_STATUS_CREATE, nullptr, &io);
String base_path = resource_path.substr(0, resource_path.rfind("/")) + "/";
_zip_recursive(resource_path, base_path, zip);
zipClose(zip, nullptr);
FileAccess *f = FileAccess::open("/tmp/project.zip", FileAccess::READ);
ERR_FAIL_COND_MSG(!f, "Unable to create zip file");
Vector<uint8_t> buf;
buf.resize(f->get_length());
f->get_buffer(buf.ptrw(), buf.size());
godot_js_os_download_buffer(buf.ptr(), buf.size(), "project.zip", "application/zip");
}
void JavaScriptToolsEditorPlugin::_zip_file(String p_path, String p_base_path, zipFile p_zip) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
WARN_PRINT("Unable to open file for zipping: " + p_path);
return;
}
Vector<uint8_t> data;
uint64_t len = f->get_length();
data.resize(len);
f->get_buffer(data.ptrw(), len);
f->close();
memdelete(f);
String path = p_path.replace_first(p_base_path, "");
zipOpenNewFileInZip(p_zip,
path.utf8().get_data(),
nullptr,
nullptr,
0,
nullptr,
0,
nullptr,
Z_DEFLATED,
Z_DEFAULT_COMPRESSION);
zipWriteInFileInZip(p_zip, data.ptr(), data.size());
zipCloseFileInZip(p_zip);
}
void JavaScriptToolsEditorPlugin::_zip_recursive(String p_path, String p_base_path, zipFile p_zip) {
DirAccess *dir = DirAccess::open(p_path);
if (!dir) {
WARN_PRINT("Unable to open dir for zipping: " + p_path);
return;
}
dir->list_dir_begin();
String cur = dir->get_next();
while (!cur.is_empty()) {
String cs = p_path.plus_file(cur);
if (cur == "." || cur == ".." || cur == ".import") {
// Skip
} else if (dir->current_is_dir()) {
String path = cs.replace_first(p_base_path, "") + "/";
zipOpenNewFileInZip(p_zip,
path.utf8().get_data(),
nullptr,
nullptr,
0,
nullptr,
0,
nullptr,
Z_DEFLATED,
Z_DEFAULT_COMPRESSION);
zipCloseFileInZip(p_zip);
_zip_recursive(cs, p_base_path, p_zip);
} else {
_zip_file(cs, p_base_path, p_zip);
}
cur = dir->get_next();
}
}
#endif
|
/*************************************************************************/
/* javascript_tools_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#if defined(TOOLS_ENABLED) && defined(JAVASCRIPT_ENABLED)
#include "javascript_tools_editor_plugin.h"
#include "core/config/engine.h"
#include "core/config/project_settings.h"
#include "core/io/dir_access.h"
#include "core/io/file_access.h"
#include "core/os/time.h"
#include "editor/editor_node.h"
#include <emscripten/emscripten.h>
// JavaScript functions defined in library_godot_editor_tools.js
extern "C" {
extern void godot_js_os_download_buffer(const uint8_t *p_buf, int p_buf_size, const char *p_name, const char *p_mime);
}
static void _javascript_editor_init_callback() {
EditorNode::get_singleton()->add_editor_plugin(memnew(JavaScriptToolsEditorPlugin(EditorNode::get_singleton())));
}
void JavaScriptToolsEditorPlugin::initialize() {
EditorNode::add_init_callback(_javascript_editor_init_callback);
}
JavaScriptToolsEditorPlugin::JavaScriptToolsEditorPlugin(EditorNode *p_editor) {
add_tool_menu_item("Download Project Source", callable_mp(this, &JavaScriptToolsEditorPlugin::_download_zip));
}
void JavaScriptToolsEditorPlugin::_download_zip(Variant p_v) {
if (!Engine::get_singleton() || !Engine::get_singleton()->is_editor_hint()) {
ERR_PRINT("Downloading the project as a ZIP archive is only available in Editor mode.");
return;
}
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
FileAccess *src_f;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
// Name the downloded ZIP file to contain the project name and download date for easier organization.
// Replace characters not allowed (or risky) in Windows file names with safe characters.
// In the project name, all invalid characters become an empty string so that a name
// like "Platformer 2: Godette's Revenge" becomes "platformer_2-_godette-s_revenge".
const String project_name_safe =
GLOBAL_GET("application/config/name").to_lower().replace(" ", "_");
const String datetime_safe =
Time::get_singleton()->get_datetime_string_from_system(false, true).replace(" ", "_");
const String output_name = OS::get_singleton()->get_safe_dir_name(vformat("%s_%s.zip"));
const String output_path = String("/tmp").plus_file(output_name);
zipFile zip = zipOpen2(output_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io);
const String base_path = resource_path.substr(0, resource_path.rfind("/")) + "/";
_zip_recursive(resource_path, base_path, zip);
zipClose(zip, nullptr);
FileAccess *f = FileAccess::open(output_path, FileAccess::READ);
ERR_FAIL_COND_MSG(!f, "Unable to create ZIP file.");
Vector<uint8_t> buf;
buf.resize(f->get_length());
f->get_buffer(buf.ptrw(), buf.size());
godot_js_os_download_buffer(buf.ptr(), buf.size(), output_name.utf8().get_data(), "application/zip");
f->close();
memdelete(f);
// Remove the temporary file since it was sent to the user's native filesystem as a download.
DirAccess::remove_file_or_error(output_path);
}
void JavaScriptToolsEditorPlugin::_zip_file(String p_path, String p_base_path, zipFile p_zip) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
WARN_PRINT("Unable to open file for zipping: " + p_path);
return;
}
Vector<uint8_t> data;
uint64_t len = f->get_length();
data.resize(len);
f->get_buffer(data.ptrw(), len);
f->close();
memdelete(f);
String path = p_path.replace_first(p_base_path, "");
zipOpenNewFileInZip(p_zip,
path.utf8().get_data(),
nullptr,
nullptr,
0,
nullptr,
0,
nullptr,
Z_DEFLATED,
Z_DEFAULT_COMPRESSION);
zipWriteInFileInZip(p_zip, data.ptr(), data.size());
zipCloseFileInZip(p_zip);
}
void JavaScriptToolsEditorPlugin::_zip_recursive(String p_path, String p_base_path, zipFile p_zip) {
DirAccess *dir = DirAccess::open(p_path);
if (!dir) {
WARN_PRINT("Unable to open directory for zipping: " + p_path);
return;
}
dir->list_dir_begin();
String cur = dir->get_next();
while (!cur.is_empty()) {
String cs = p_path.plus_file(cur);
if (cur == "." || cur == ".." || cur == ".import") {
// Skip
} else if (dir->current_is_dir()) {
String path = cs.replace_first(p_base_path, "") + "/";
zipOpenNewFileInZip(p_zip,
path.utf8().get_data(),
nullptr,
nullptr,
0,
nullptr,
0,
nullptr,
Z_DEFLATED,
Z_DEFAULT_COMPRESSION);
zipCloseFileInZip(p_zip);
_zip_recursive(cs, p_base_path, p_zip);
} else {
_zip_file(cs, p_base_path, p_zip);
}
cur = dir->get_next();
}
}
#endif
|
Improve the generated ZIP archive name when using Download Project Source
|
Improve the generated ZIP archive name when using Download Project Source
This makes for easier organization since downloading a project
several times (or several different projects) will result in more
meaningful file names.
|
C++
|
mit
|
Faless/godot,pkowal1982/godot,akien-mga/godot,sanikoyes/godot,vkbsb/godot,josempans/godot,Valentactive/godot,vnen/godot,pkowal1982/godot,guilhermefelipecgs/godot,sanikoyes/godot,vkbsb/godot,ZuBsPaCe/godot,Shockblast/godot,pkowal1982/godot,firefly2442/godot,Zylann/godot,akien-mga/godot,Zylann/godot,vkbsb/godot,akien-mga/godot,Shockblast/godot,godotengine/godot,DmitriySalnikov/godot,DmitriySalnikov/godot,vnen/godot,akien-mga/godot,Valentactive/godot,Zylann/godot,guilhermefelipecgs/godot,Shockblast/godot,firefly2442/godot,DmitriySalnikov/godot,guilhermefelipecgs/godot,Faless/godot,akien-mga/godot,Faless/godot,Faless/godot,akien-mga/godot,Valentactive/godot,godotengine/godot,akien-mga/godot,BastiaanOlij/godot,sanikoyes/godot,Shockblast/godot,josempans/godot,josempans/godot,firefly2442/godot,godotengine/godot,vkbsb/godot,BastiaanOlij/godot,guilhermefelipecgs/godot,Faless/godot,vkbsb/godot,Valentactive/godot,firefly2442/godot,vnen/godot,pkowal1982/godot,godotengine/godot,firefly2442/godot,guilhermefelipecgs/godot,Faless/godot,firefly2442/godot,ZuBsPaCe/godot,vkbsb/godot,akien-mga/godot,pkowal1982/godot,godotengine/godot,DmitriySalnikov/godot,sanikoyes/godot,Shockblast/godot,Valentactive/godot,vnen/godot,josempans/godot,godotengine/godot,ZuBsPaCe/godot,BastiaanOlij/godot,vnen/godot,godotengine/godot,josempans/godot,vkbsb/godot,pkowal1982/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,vkbsb/godot,Zylann/godot,Shockblast/godot,josempans/godot,ZuBsPaCe/godot,sanikoyes/godot,Zylann/godot,pkowal1982/godot,firefly2442/godot,ZuBsPaCe/godot,BastiaanOlij/godot,sanikoyes/godot,BastiaanOlij/godot,BastiaanOlij/godot,guilhermefelipecgs/godot,vnen/godot,Shockblast/godot,Valentactive/godot,godotengine/godot,DmitriySalnikov/godot,Faless/godot,josempans/godot,Zylann/godot,Valentactive/godot,ZuBsPaCe/godot,Zylann/godot,DmitriySalnikov/godot,sanikoyes/godot,guilhermefelipecgs/godot,vnen/godot,josempans/godot,BastiaanOlij/godot,Shockblast/godot,sanikoyes/godot,Zylann/godot,ZuBsPaCe/godot,DmitriySalnikov/godot,pkowal1982/godot,Faless/godot,vnen/godot,Valentactive/godot,firefly2442/godot,BastiaanOlij/godot
|
a1039e1e29ce6dd3822c1953f7311b83ca8478b7
|
src/commands/AveCommand.hpp
|
src/commands/AveCommand.hpp
|
// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#ifndef CFILES_AVERAGE_COMMAND_HPP
#define CFILES_AVERAGE_COMMAND_HPP
#include <map>
#include <chemfiles.hpp>
#include "Averager.hpp"
#include "Command.hpp"
#include "utils.hpp"
namespace docopt {
struct value;
}
/// Base class for time-averaged computations
class AveCommand: public Command {
public:
struct Options {
/// Input trajectory
std::string trajectory;
/// Specific format to use with the trajectory
std::string format = "";
/// Specific steps to use from the trajectory
steps_range steps;
/// Do we have a custom cell to use?
bool custom_cell;
/// Unit cell to use
chemfiles::UnitCell cell;
/// Topology file to use
std::string topology = "";
/// Format to use for the topology file
std::string topology_format = "";
/// Should we try to guess the topology?
bool guess_bonds = false;
};
/// A strinc containing Doctopt style options for all time-averaged commands.
/// It should be added to the command-specific options.
static const std::string AVERAGE_OPTIONS;
virtual ~AveCommand() = default;
int run(int argc, const char* argv[]) override final;
/// Setup the command and the histogram.
/// This function MUST call `AverageCommand::parse_options`.
virtual Averager<double> setup(int argc, const char* argv[]) = 0;
/// Add the data from a `frame` to the `histogram`
virtual void accumulate(const chemfiles::Frame& frame, Histogram<double>& histogram) = 0;
/// Finish the run, and write any output
virtual void finish(const Histogram<double>& histogram) = 0;
protected:
/// Get access to the options for this run
const Options& options() const {return options_;}
/// Parse the options from a doctop map/
void parse_options(const std::map<std::string, docopt::value>& args);
private:
/// Options
Options options_;
/// Averaging histogram for the data
Averager<double> histogram_;
};
#endif
|
// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#ifndef CFILES_AVERAGE_COMMAND_HPP
#define CFILES_AVERAGE_COMMAND_HPP
#include <map>
#include <chemfiles.hpp>
#include "Averager.hpp"
#include "Command.hpp"
#include "utils.hpp"
namespace docopt {
struct value;
}
/// Base class for time-averaged computations
class AveCommand: public Command {
public:
struct Options {
/// Input trajectory
std::string trajectory;
/// Specific format to use with the trajectory
std::string format = "";
/// Specific steps to use from the trajectory
steps_range steps;
/// Do we have a custom cell to use?
bool custom_cell = false;
/// Unit cell to use
chemfiles::UnitCell cell;
/// Topology file to use
std::string topology = "";
/// Format to use for the topology file
std::string topology_format = "";
/// Should we try to guess the topology?
bool guess_bonds = false;
};
/// A strinc containing Doctopt style options for all time-averaged commands.
/// It should be added to the command-specific options.
static const std::string AVERAGE_OPTIONS;
virtual ~AveCommand() = default;
int run(int argc, const char* argv[]) override final;
/// Setup the command and the histogram.
/// This function MUST call `AverageCommand::parse_options`.
virtual Averager<double> setup(int argc, const char* argv[]) = 0;
/// Add the data from a `frame` to the `histogram`
virtual void accumulate(const chemfiles::Frame& frame, Histogram<double>& histogram) = 0;
/// Finish the run, and write any output
virtual void finish(const Histogram<double>& histogram) = 0;
protected:
/// Get access to the options for this run
const Options& options() const {return options_;}
/// Parse the options from a doctop map/
void parse_options(const std::map<std::string, docopt::value>& args);
private:
/// Options
Options options_;
/// Averaging histogram for the data
Averager<double> histogram_;
};
#endif
|
Fix initialisation of custom_cell
|
Fix initialisation of custom_cell
|
C++
|
mpl-2.0
|
chemfiles/chrp,Luthaf/chrp
|
d409a117a204ef4c58caf5c7bd51c9f5647883b4
|
RawSpeed/Camera.cpp
|
RawSpeed/Camera.cpp
|
#include "StdAfx.h"
#include "Camera.h"
#include <iostream>
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
http://www.klauspost.com
*/
namespace RawSpeed {
using namespace pugi;
Camera::Camera(pugi::xml_node &camera) : cfa(iPoint2D(0,0)) {
pugi::xml_attribute key = camera.attribute("make");
if (!key)
ThrowCME("Camera XML Parser: \"make\" attribute not found.");
make = canonical_make = key.as_string();
key = camera.attribute("model");
if (!key)
ThrowCME("Camera XML Parser: \"model\" attribute not found.");
model = canonical_model = canonical_alias = key.as_string();
canonical_id = make + " " + model;
supported = true;
key = camera.attribute("supported");
if (key) {
string s = string(key.as_string());
if (s.compare("no") == 0)
supported = false;
}
key = camera.attribute("mode");
if (key) {
mode = key.as_string();
} else {
mode = string("");
}
key = camera.attribute("decoder_version");
if (key) {
decoderVersion = key.as_int(0);
} else {
decoderVersion = 0;
}
for (xml_node node = camera.first_child(); node; node = node.next_sibling()) {
parseCameraChild(node);
}
}
Camera::Camera( const Camera* camera, uint32 alias_num) : cfa(iPoint2D(0,0))
{
if (alias_num >= camera->aliases.size())
ThrowCME("Camera: Internal error, alias number out of range specified.");
make = camera->make;
model = camera->aliases[alias_num];
canonical_make = camera->canonical_make;
canonical_model = camera->canonical_model;
canonical_alias = camera->canonical_aliases[alias_num];
canonical_id = camera->canonical_id;
mode = camera->mode;
cfa = camera->cfa;
supported = camera->supported;
cropSize = camera->cropSize;
cropPos = camera->cropPos;
decoderVersion = camera->decoderVersion;
for (uint32 i = 0; i < camera->blackAreas.size(); i++) {
blackAreas.push_back(camera->blackAreas[i]);
}
for (uint32 i = 0; i < camera->sensorInfo.size(); i++) {
sensorInfo.push_back(camera->sensorInfo[i]);
}
map<string,string>::const_iterator mi = camera->hints.begin();
for (; mi != camera->hints.end(); ++mi) {
hints.insert(make_pair((*mi).first, (*mi).second));
}
}
Camera::~Camera(void) {
}
static bool isTag(const char_t *a, const char* b) {
return 0 == strcmp(a, b);
}
void Camera::parseCameraChild(xml_node &cur) {
if (isTag(cur.name(), "CFA")) {
if (2 != cur.attribute("width").as_int(0) || 2 != cur.attribute("height").as_int(0)) {
supported = FALSE;
} else {
cfa.setSize(iPoint2D(2,2));
xml_node c = cur.child("Color");
while (c != NULL) {
parseCFA(c);
c = c.next_sibling("Color");
}
}
return;
}
if (isTag(cur.name(), "CFA2")) {
cfa.setSize(iPoint2D(cur.attribute("width").as_int(0),cur.attribute("height").as_int(0)));
xml_node c = cur.child("Color");
while (c != NULL) {
parseCFA(c);
c = c.next_sibling("Color");
}
c = cur.child("ColorRow");
while (c != NULL) {
parseCFA(c);
c = c.next_sibling("ColorRow");
}
return;
}
if (isTag(cur.name(), "Crop")) {
cropPos.x = cur.attribute("x").as_int(0);
cropPos.y = cur.attribute("y").as_int(0);
if (cropPos.x < 0)
ThrowCME("Negative X axis crop specified in camera %s %s", make.c_str(), model.c_str());
if (cropPos.y < 0)
ThrowCME("Negative Y axis crop specified in camera %s %s", make.c_str(), model.c_str());
cropSize.x = cur.attribute("width").as_int(0);
cropSize.y = cur.attribute("height").as_int(0);
return;
}
if (isTag(cur.name(), "Sensor")) {
parseSensorInfo(cur);
return;
}
if (isTag(cur.name(), "BlackAreas")) {
xml_node c = cur.first_child();
while (c != NULL) {
parseBlackAreas(c);
c = c.next_sibling();
}
return;
}
if (isTag(cur.name(), "Aliases")) {
xml_node c = cur.child("Alias");
while (c != NULL) {
parseAlias(c);
c = c.next_sibling();
}
return;
}
if (isTag(cur.name(), "Hints")) {
xml_node c = cur.child("Hint");
while (c != NULL) {
parseHint(c);
c = c.next_sibling();
}
return;
}
if (isTag(cur.name(), "ID")) {
parseID(cur);
return;
}
}
void Camera::parseCFA(xml_node &cur) {
if (isTag(cur.name(), "ColorRow")) {
int y = cur.attribute("y").as_int(-1);
if (y < 0 || y >= cfa.size.y) {
ThrowCME("Invalid y coordinate in CFA array of in camera %s %s", make.c_str(), model.c_str());
}
const char* key = cur.first_child().value();
if ((int)strlen(key) != cfa.size.x) {
ThrowCME("Invalid number of colors in definition for row %d in camera %s %s. Expected %d, found %zu.", y, make.c_str(), model.c_str(), cfa.size.x, strlen(key));
}
for (int x = 0; x < cfa.size.x; x++) {
char v = (char)tolower((int)key[x]);
if (v == 'g')
cfa.setColorAt(iPoint2D(x, y), CFA_GREEN);
else if (v == 'r')
cfa.setColorAt(iPoint2D(x, y), CFA_RED);
else if (v == 'b')
cfa.setColorAt(iPoint2D(x, y), CFA_BLUE);
else if (v == 'f')
cfa.setColorAt(iPoint2D(x, y), CFA_FUJI_GREEN);
else if (v == 'c')
cfa.setColorAt(iPoint2D(x, y), CFA_CYAN);
else if (v == 'm')
cfa.setColorAt(iPoint2D(x, y), CFA_MAGENTA);
else if (v == 'y')
cfa.setColorAt(iPoint2D(x, y), CFA_YELLOW);
else
supported = FALSE;
}
}
if (isTag(cur.name(), "Color")) {
int x = cur.attribute("x").as_int(-1);
if (x < 0 || x >= cfa.size.x) {
ThrowCME("Invalid x coordinate in CFA array of in camera %s %s", make.c_str(), model.c_str());
}
int y = cur.attribute("y").as_int(-1);
if (y < 0 || y >= cfa.size.y) {
ThrowCME("Invalid y coordinate in CFA array of in camera %s %s", make.c_str(), model.c_str());
}
const char* key = cur.first_child().value();
if (isTag(key, "GREEN"))
cfa.setColorAt(iPoint2D(x, y), CFA_GREEN);
else if (isTag(key, "RED"))
cfa.setColorAt(iPoint2D(x, y), CFA_RED);
else if (isTag(key, "BLUE"))
cfa.setColorAt(iPoint2D(x, y), CFA_BLUE);
else if (isTag(key, "FUJIGREEN"))
cfa.setColorAt(iPoint2D(x, y), CFA_FUJI_GREEN);
else if (isTag(key, "CYAN"))
cfa.setColorAt(iPoint2D(x, y), CFA_CYAN);
else if (isTag(key, "MAGENTA"))
cfa.setColorAt(iPoint2D(x, y), CFA_MAGENTA);
else if (isTag(key, "YELLOW"))
cfa.setColorAt(iPoint2D(x, y), CFA_YELLOW);
}
}
void Camera::parseBlackAreas(xml_node &cur) {
if (isTag(cur.name(), "Vertical")) {
int x = cur.attribute("x").as_int(-1);
if (x < 0) {
ThrowCME("Invalid x coordinate in vertical BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
int w = cur.attribute("width").as_int(-1);
if (w < 0) {
ThrowCME("Invalid width in vertical BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
blackAreas.push_back(BlackArea(x, w, true));
} else if (isTag(cur.name(), "Horizontal")) {
int y = cur.attribute("y").as_int(-1);
if (y < 0) {
ThrowCME("Invalid y coordinate in horizontal BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
int h = cur.attribute("height").as_int(-1);
if (h < 0) {
ThrowCME("Invalid width in horizontal BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
blackAreas.push_back(BlackArea(y, h, false));
}
}
vector<int> Camera::MultipleStringToInt(const char *in, const char *tag, const char* attribute) {
int i;
vector<int> ret;
vector<string> v = split_string(string((const char*)in), ' ');
for (uint32 j = 0; j < v.size(); j++) {
#if defined(__unix__) || defined(__APPLE__) || defined(__MINGW32__)
if (EOF == sscanf(v[j].c_str(), "%d", &i))
#else
if (EOF == sscanf_s(v[j].c_str(), "%d", &i))
#endif
ThrowCME("Error parsing attribute %s in tag %s, in camera %s %s.", attribute, tag, make.c_str(), model.c_str());
ret.push_back(i);
}
return ret;
}
void Camera::parseAlias( xml_node &cur )
{
if (isTag(cur.name(), "Alias")) {
aliases.push_back(string(cur.first_child().value()));
pugi::xml_attribute key = cur.attribute("id");
if (key)
canonical_aliases.push_back(string(key.as_string()));
else
canonical_aliases.push_back(string(cur.first_child().value()));
}
}
void Camera::parseHint( xml_node &cur )
{
if (isTag(cur.name(), "Hint")) {
string hint_name, hint_value;
pugi::xml_attribute key = cur.attribute("name");
if (key) {
hint_name = string(key.as_string());
} else
ThrowCME("CameraMetadata: Could not find name for hint for %s %s camera.", make.c_str(), model.c_str());
key = cur.attribute("value");
if (key) {
hint_value = string(key.as_string());
} else
ThrowCME("CameraMetadata: Could not find value for hint %s for %s %s camera.", hint_name.c_str(), make.c_str(), model.c_str());
hints.insert(make_pair(hint_name, hint_value));
}
}
void Camera::parseID( xml_node &cur )
{
if (isTag(cur.name(), "ID")) {
pugi::xml_attribute id_make = cur.attribute("make");
if (id_make) {
canonical_make = string(id_make.as_string());
} else
ThrowCME("CameraMetadata: Could not find make for ID for %s %s camera.", make.c_str(), model.c_str());
pugi::xml_attribute id_model = cur.attribute("model");
if (id_model) {
canonical_model = string(id_model.as_string());
canonical_alias = string(id_model.as_string());
} else
ThrowCME("CameraMetadata: Could not find model for ID for %s %s camera.", make.c_str(), model.c_str());
canonical_id = string(cur.first_child().value());
}
}
void Camera::parseSensorInfo( xml_node &cur )
{
int min_iso = cur.attribute("iso_min").as_int(0);
int max_iso = cur.attribute("iso_max").as_int(0);;
int black = cur.attribute("black").as_int(-1);
int white = cur.attribute("white").as_int(65536);
pugi::xml_attribute key = cur.attribute("black_colors");
vector<int> black_colors;
if (key) {
black_colors = MultipleStringToInt(key.as_string(), cur.name(), "black_colors");
}
key = cur.attribute("iso_list");
if (key) {
vector<int> values = MultipleStringToInt(key.as_string(), cur.name(), "iso_list");
if (!values.empty()) {
for (uint32 i = 0; i < values.size(); i++) {
sensorInfo.push_back(CameraSensorInfo(black, white, values[i], values[i], black_colors));
}
}
} else {
sensorInfo.push_back(CameraSensorInfo(black, white, min_iso, max_iso, black_colors));
}
}
const CameraSensorInfo* Camera::getSensorInfo( int iso )
{
// If only one, just return that
if (sensorInfo.size() == 1)
return &sensorInfo[0];
vector<CameraSensorInfo*> candidates;
vector<CameraSensorInfo>::iterator i = sensorInfo.begin();
do
{
if (i->isIsoWithin(iso))
candidates.push_back(&(*i));
} while (++i != sensorInfo.end());
if (candidates.size() == 1)
return candidates[0];
vector<CameraSensorInfo*>::iterator j = candidates.begin();
do
{
if (!(*j)->isDefault())
return *j;
} while (++j != candidates.end());
// Several defaults??? Just return first
return candidates[0];
}
} // namespace RawSpeed
|
#include "StdAfx.h"
#include "Camera.h"
#include <iostream>
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
http://www.klauspost.com
*/
namespace RawSpeed {
using namespace pugi;
Camera::Camera(pugi::xml_node &camera) : cfa(iPoint2D(0,0)) {
pugi::xml_attribute key = camera.attribute("make");
if (!key)
ThrowCME("Camera XML Parser: \"make\" attribute not found.");
make = canonical_make = key.as_string();
key = camera.attribute("model");
if (!key)
ThrowCME("Camera XML Parser: \"model\" attribute not found.");
model = canonical_model = canonical_alias = key.as_string();
canonical_id = make + " " + model;
supported = true;
key = camera.attribute("supported");
if (key) {
string s = string(key.as_string());
if (s.compare("no") == 0)
supported = false;
}
key = camera.attribute("mode");
if (key) {
mode = key.as_string();
} else {
mode = string("");
}
key = camera.attribute("decoder_version");
if (key) {
decoderVersion = key.as_int(0);
} else {
decoderVersion = 0;
}
for (xml_node node = camera.first_child(); node; node = node.next_sibling()) {
parseCameraChild(node);
}
}
Camera::Camera( const Camera* camera, uint32 alias_num) : cfa(iPoint2D(0,0))
{
if (alias_num >= camera->aliases.size())
ThrowCME("Camera: Internal error, alias number out of range specified.");
make = camera->make;
model = camera->aliases[alias_num];
canonical_make = camera->canonical_make;
canonical_model = camera->canonical_model;
canonical_alias = camera->canonical_aliases[alias_num];
canonical_id = camera->canonical_id;
mode = camera->mode;
cfa = camera->cfa;
supported = camera->supported;
cropSize = camera->cropSize;
cropPos = camera->cropPos;
decoderVersion = camera->decoderVersion;
for (uint32 i = 0; i < camera->blackAreas.size(); i++) {
blackAreas.push_back(camera->blackAreas[i]);
}
for (uint32 i = 0; i < camera->sensorInfo.size(); i++) {
sensorInfo.push_back(camera->sensorInfo[i]);
}
map<string,string>::const_iterator mi = camera->hints.begin();
for (; mi != camera->hints.end(); ++mi) {
hints.insert(make_pair((*mi).first, (*mi).second));
}
}
Camera::~Camera(void) {
}
static bool isTag(const char_t *a, const char* b) {
return 0 == strcmp(a, b);
}
void Camera::parseCameraChild(xml_node &cur) {
if (isTag(cur.name(), "CFA")) {
if (2 != cur.attribute("width").as_int(0) || 2 != cur.attribute("height").as_int(0)) {
supported = FALSE;
} else {
cfa.setSize(iPoint2D(2,2));
xml_node c = cur.child("Color");
while (c != NULL) {
parseCFA(c);
c = c.next_sibling("Color");
}
}
return;
}
if (isTag(cur.name(), "CFA2")) {
cfa.setSize(iPoint2D(cur.attribute("width").as_int(0),cur.attribute("height").as_int(0)));
xml_node c = cur.child("Color");
while (c != NULL) {
parseCFA(c);
c = c.next_sibling("Color");
}
c = cur.child("ColorRow");
while (c != NULL) {
parseCFA(c);
c = c.next_sibling("ColorRow");
}
return;
}
if (isTag(cur.name(), "Crop")) {
cropPos.x = cur.attribute("x").as_int(0);
cropPos.y = cur.attribute("y").as_int(0);
if (cropPos.x < 0)
ThrowCME("Negative X axis crop specified in camera %s %s", make.c_str(), model.c_str());
if (cropPos.y < 0)
ThrowCME("Negative Y axis crop specified in camera %s %s", make.c_str(), model.c_str());
cropSize.x = cur.attribute("width").as_int(0);
cropSize.y = cur.attribute("height").as_int(0);
return;
}
if (isTag(cur.name(), "Sensor")) {
parseSensorInfo(cur);
return;
}
if (isTag(cur.name(), "BlackAreas")) {
xml_node c = cur.first_child();
while (c != NULL) {
parseBlackAreas(c);
c = c.next_sibling();
}
return;
}
if (isTag(cur.name(), "Aliases")) {
xml_node c = cur.child("Alias");
while (c != NULL) {
parseAlias(c);
c = c.next_sibling();
}
return;
}
if (isTag(cur.name(), "Hints")) {
xml_node c = cur.child("Hint");
while (c != NULL) {
parseHint(c);
c = c.next_sibling();
}
return;
}
if (isTag(cur.name(), "ID")) {
parseID(cur);
return;
}
}
void Camera::parseCFA(xml_node &cur) {
if (isTag(cur.name(), "ColorRow")) {
int y = cur.attribute("y").as_int(-1);
if (y < 0 || y >= cfa.size.y) {
ThrowCME("Invalid y coordinate in CFA array of in camera %s %s", make.c_str(), model.c_str());
}
const char* key = cur.first_child().value();
if ((int)strlen(key) != cfa.size.x) {
ThrowCME("Invalid number of colors in definition for row %d in camera %s %s. Expected %d, found %zu.", y, make.c_str(), model.c_str(), cfa.size.x, strlen(key));
}
for (int x = 0; x < cfa.size.x; x++) {
char v = (char)tolower((int)key[x]);
if (v == 'g')
cfa.setColorAt(iPoint2D(x, y), CFA_GREEN);
else if (v == 'r')
cfa.setColorAt(iPoint2D(x, y), CFA_RED);
else if (v == 'b')
cfa.setColorAt(iPoint2D(x, y), CFA_BLUE);
else if (v == 'f')
cfa.setColorAt(iPoint2D(x, y), CFA_FUJI_GREEN);
else if (v == 'c')
cfa.setColorAt(iPoint2D(x, y), CFA_CYAN);
else if (v == 'm')
cfa.setColorAt(iPoint2D(x, y), CFA_MAGENTA);
else if (v == 'y')
cfa.setColorAt(iPoint2D(x, y), CFA_YELLOW);
else
supported = FALSE;
}
}
if (isTag(cur.name(), "Color")) {
int x = cur.attribute("x").as_int(-1);
if (x < 0 || x >= cfa.size.x) {
ThrowCME("Invalid x coordinate in CFA array of in camera %s %s", make.c_str(), model.c_str());
}
int y = cur.attribute("y").as_int(-1);
if (y < 0 || y >= cfa.size.y) {
ThrowCME("Invalid y coordinate in CFA array of in camera %s %s", make.c_str(), model.c_str());
}
const char* key = cur.first_child().value();
if (isTag(key, "GREEN"))
cfa.setColorAt(iPoint2D(x, y), CFA_GREEN);
else if (isTag(key, "RED"))
cfa.setColorAt(iPoint2D(x, y), CFA_RED);
else if (isTag(key, "BLUE"))
cfa.setColorAt(iPoint2D(x, y), CFA_BLUE);
else if (isTag(key, "FUJIGREEN"))
cfa.setColorAt(iPoint2D(x, y), CFA_FUJI_GREEN);
else if (isTag(key, "CYAN"))
cfa.setColorAt(iPoint2D(x, y), CFA_CYAN);
else if (isTag(key, "MAGENTA"))
cfa.setColorAt(iPoint2D(x, y), CFA_MAGENTA);
else if (isTag(key, "YELLOW"))
cfa.setColorAt(iPoint2D(x, y), CFA_YELLOW);
}
}
void Camera::parseBlackAreas(xml_node &cur) {
if (isTag(cur.name(), "Vertical")) {
int x = cur.attribute("x").as_int(-1);
if (x < 0) {
ThrowCME("Invalid x coordinate in vertical BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
int w = cur.attribute("width").as_int(-1);
if (w < 0) {
ThrowCME("Invalid width in vertical BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
blackAreas.push_back(BlackArea(x, w, true));
} else if (isTag(cur.name(), "Horizontal")) {
int y = cur.attribute("y").as_int(-1);
if (y < 0) {
ThrowCME("Invalid y coordinate in horizontal BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
int h = cur.attribute("height").as_int(-1);
if (h < 0) {
ThrowCME("Invalid width in horizontal BlackArea of in camera %s %s", make.c_str(), model.c_str());
}
blackAreas.push_back(BlackArea(y, h, false));
}
}
vector<int> Camera::MultipleStringToInt(const char *in, const char *tag, const char* attribute) {
int i;
vector<int> ret;
vector<string> v = split_string(string((const char*)in), ' ');
for (uint32 j = 0; j < v.size(); j++) {
#if defined(__unix__) || defined(__APPLE__) || defined(__MINGW32__)
if (EOF == sscanf(v[j].c_str(), "%d", &i))
#else
if (EOF == sscanf_s(v[j].c_str(), "%d", &i))
#endif
ThrowCME("Error parsing attribute %s in tag %s, in camera %s %s.", attribute, tag, make.c_str(), model.c_str());
ret.push_back(i);
}
return ret;
}
void Camera::parseAlias( xml_node &cur )
{
if (isTag(cur.name(), "Alias")) {
aliases.push_back(string(cur.first_child().value()));
pugi::xml_attribute key = cur.attribute("id");
if (key)
canonical_aliases.push_back(string(key.as_string()));
else
canonical_aliases.push_back(string(cur.first_child().value()));
}
}
void Camera::parseHint( xml_node &cur )
{
if (isTag(cur.name(), "Hint")) {
string hint_name, hint_value;
pugi::xml_attribute key = cur.attribute("name");
if (key) {
hint_name = string(key.as_string());
} else
ThrowCME("CameraMetadata: Could not find name for hint for %s %s camera.", make.c_str(), model.c_str());
key = cur.attribute("value");
if (key) {
hint_value = string(key.as_string());
} else
ThrowCME("CameraMetadata: Could not find value for hint %s for %s %s camera.", hint_name.c_str(), make.c_str(), model.c_str());
hints.insert(make_pair(hint_name, hint_value));
}
}
void Camera::parseID( xml_node &cur )
{
if (isTag(cur.name(), "ID")) {
pugi::xml_attribute id_make = cur.attribute("make");
if (id_make) {
canonical_make = string(id_make.as_string());
} else
ThrowCME("CameraMetadata: Could not find make for ID for %s %s camera.", make.c_str(), model.c_str());
pugi::xml_attribute id_model = cur.attribute("model");
if (id_model) {
canonical_model = string(id_model.as_string());
canonical_alias = string(id_model.as_string());
} else
ThrowCME("CameraMetadata: Could not find model for ID for %s %s camera.", make.c_str(), model.c_str());
canonical_id = string(cur.first_child().value());
}
}
void Camera::parseSensorInfo( xml_node &cur )
{
int min_iso = cur.attribute("iso_min").as_int(0);
int max_iso = cur.attribute("iso_max").as_int(0);;
int black = cur.attribute("black").as_int(-1);
int white = cur.attribute("white").as_int(65536);
pugi::xml_attribute key = cur.attribute("black_colors");
vector<int> black_colors;
if (key) {
black_colors = MultipleStringToInt(key.as_string(), cur.name(), "black_colors");
}
key = cur.attribute("iso_list");
if (key) {
vector<int> values = MultipleStringToInt(key.as_string(), cur.name(), "iso_list");
if (!values.empty()) {
for (uint32 i = 0; i < values.size(); i++) {
sensorInfo.push_back(CameraSensorInfo(black, white, values[i], values[i], black_colors));
}
}
} else {
sensorInfo.push_back(CameraSensorInfo(black, white, min_iso, max_iso, black_colors));
}
}
const CameraSensorInfo* Camera::getSensorInfo( int iso )
{
if (sensorInfo.empty())
ThrowCME(
"getSensorInfo(): Camera '%s' '%s', mode '%s' has no <Sensor> entries.",
make.c_str(), model.c_str(), mode.c_str());
// If only one, just return that
if (sensorInfo.size() == 1)
return &sensorInfo[0];
vector<CameraSensorInfo*> candidates;
vector<CameraSensorInfo>::iterator i = sensorInfo.begin();
do
{
if (i->isIsoWithin(iso))
candidates.push_back(&(*i));
} while (++i != sensorInfo.end());
if (candidates.size() == 1)
return candidates[0];
vector<CameraSensorInfo*>::iterator j = candidates.begin();
do
{
if (!(*j)->isDefault())
return *j;
} while (++j != candidates.end());
// Several defaults??? Just return first
return candidates[0];
}
} // namespace RawSpeed
|
Throw CME if no <Sensor> entries.
|
Camera::getSensorInfo(): Throw CME if no <Sensor> entries.
Fixes a crash on canon powershot pro70, which is disabled.
|
C++
|
lgpl-2.1
|
LebedevRI/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,anarsoul/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,LebedevRI/rawspeed,anarsoul/rawspeed,darktable-org/rawspeed,darktable-org/rawspeed,darktable-org/rawspeed,anarsoul/rawspeed
|
ef22366455c312b8306d9d05da4c5fab95937d00
|
src/common/DoutStreambuf.cc
|
src/common/DoutStreambuf.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2010 Dreamhost
*
* This 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. See file COPYING.
*
*/
#include "config.h"
#include "common/DoutStreambuf.h"
#include "common/errno.h"
#include "common/Mutex.h"
#include <assert.h>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <streambuf>
#include <string.h>
#include <syslog.h>
///////////////////////////// Globals /////////////////////////////
// TODO: get rid of this lock using thread-local storage
extern Mutex _dout_lock;
/* True if we should output high-priority messages to stderr */
static bool use_stderr = true;
//////////////////////// Helper functions //////////////////////////
static bool empty(const char *str)
{
if (!str)
return true;
if (!str[0])
return true;
return false;
}
static string cpp_str(const char *str)
{
if (!str)
return "(NULL)";
if (str[0] == '\0')
return "(empty)";
return str;
}
static std::string normalize_relative(const char *from)
{
if (from[0] == '/')
return string(from);
std::auto_ptr <char> cwd(get_current_dir_name());
ostringstream oss;
oss << "/" << *cwd << "/" << from;
return oss.str();
}
/* Complain about errors even without a logfile */
static void primitive_log(const std::string &str)
{
std::cerr << str;
std::cerr.flush();
syslog(LOG_USER | LOG_NOTICE, "%s", str.c_str());
}
static inline bool prio_is_visible_on_stderr(int prio)
{
return prio <= 15;
}
static inline int dout_prio_to_syslog_prio(int prio)
{
if (prio <= 3)
return LOG_CRIT;
if (prio <= 5)
return LOG_ERR;
if (prio <= 15)
return LOG_WARNING;
if (prio <= 30)
return LOG_NOTICE;
if (prio <= 40)
return LOG_INFO;
return LOG_DEBUG;
}
static int safe_write(int fd, const char *buf, signed int len)
{
int res;
assert(len != 0);
while (1) {
res = write(fd, buf, len);
if (res < 0) {
int err = errno;
if (err != EINTR) {
ostringstream oss;
oss << __func__ << ": failed to write to fd " << fd << ": "
<< cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
}
len -= res;
buf += res;
if (len <= 0)
return 0;
}
}
static int create_symlink(const string &oldpath, const string &newpath)
{
while (1) {
if (::symlink(oldpath.c_str(), newpath.c_str()) == 0)
return 0;
int err = errno;
if (err == EEXIST) {
// Handle EEXIST
if (::unlink(newpath.c_str())) {
err = errno;
ostringstream oss;
oss << __func__ << ": failed to remove '" << newpath << "': "
<< cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
}
else {
// Other errors
ostringstream oss;
oss << __func__ << ": failed to symlink(oldpath='" << oldpath
<< "', newpath='" << newpath << "'): " << cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
}
}
static std::string get_basename(const std::string &filename)
{
size_t last_slash = filename.find_last_of("/");
if (last_slash == std::string::npos)
return filename;
return filename.substr(last_slash + 1);
}
///////////////////////////// DoutStreambuf /////////////////////////////
template <typename charT, typename traits>
DoutStreambuf<charT, traits>::DoutStreambuf()
: flags(0), ofd(-1)
{
// Initialize get pointer to zero so that underflow is called on the first read.
this->setg(0, 0, 0);
// Initialize output_buffer
_clear_output_buffer();
}
// This function is called when the output buffer is filled.
// In this function, the buffer should be written to wherever it should
// be written to (in this case, the streambuf object that this is controlling).
template <typename charT, typename traits>
typename DoutStreambuf<charT, traits>::int_type
DoutStreambuf<charT, traits>::overflow(DoutStreambuf<charT, traits>::int_type c)
{
{
// zero-terminate the buffer
charT* end_ptr = this->pptr();
*end_ptr++ = '\0';
*end_ptr++ = '\0';
// char buf[1000];
// hex2str(obuf, end_ptr - obuf, buf, sizeof(buf));
// printf("overflow buffer: '%s'\n", buf);
}
// Loop over all lines in the buffer.
int prio = 100;
charT* start = obuf;
while (true) {
char* end = strchrnul(start, '\n');
if (start == end) {
if (*start == '\0')
break;
// skip zero-length lines
++start;
continue;
}
if (*start == '\1') {
// Decode some control characters
++start;
unsigned char tmp = *((unsigned char*)start);
prio = tmp - 11;
++start;
}
*end = '\n';
char next = *(end+1);
*(end+1) = '\0';
// Now 'start' points to a NULL-terminated string, which we want to
// output with priority 'prio'
int len = strlen(start);
if (flags & DOUTSB_FLAG_SYSLOG) {
//printf("syslogging: '%s' len=%d\n", start, len);
syslog(LOG_USER | dout_prio_to_syslog_prio(prio), "%s", start);
}
if (flags & DOUTSB_FLAG_STDOUT) {
// Just write directly out to the stdout fileno. There's no point in
// using something like fputs to write to a temporary buffer,
// because we would just have to flush that temporary buffer
// immediately.
if (safe_write(STDOUT_FILENO, start, len))
flags &= ~DOUTSB_FLAG_STDOUT;
}
if (flags & DOUTSB_FLAG_STDERR) {
// Only write to stderr if the message is important enough.
if (prio_is_visible_on_stderr(prio)) {
if (safe_write(STDERR_FILENO, start, len))
flags &= ~DOUTSB_FLAG_STDERR;
}
}
if (flags & DOUTSB_FLAG_OFILE) {
if (safe_write(ofd, start, len))
flags &= ~DOUTSB_FLAG_OFILE;
}
*(end+1) = next;
start = end + 1;
}
_clear_output_buffer();
// A value different than EOF (or traits::eof() for other traits) signals success.
// If the function fails, either EOF (or traits::eof() for other traits) is returned or an
// exception is thrown.
return traits_ty::not_eof(c);
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::set_use_stderr(bool val)
{
_dout_lock.Lock();
use_stderr = val;
if (val)
flags |= DOUTSB_FLAG_STDERR;
else
flags &= ~DOUTSB_FLAG_STDERR;
_dout_lock.Unlock();
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::read_global_config()
{
assert(_dout_lock.is_locked());
flags = 0;
if (g_conf.log_to_syslog) {
flags |= DOUTSB_FLAG_SYSLOG;
}
if (g_conf.log_to_stdout) {
flags |= DOUTSB_FLAG_STDOUT;
}
if (use_stderr) {
flags |= DOUTSB_FLAG_STDERR;
}
if (g_conf.log_to_file) {
if (_read_ofile_config()) {
flags |= DOUTSB_FLAG_OFILE;
}
}
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::
set_flags(int flags_)
{
assert(_dout_lock.is_locked());
flags = flags_;
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::
set_prio(int prio)
{
charT* p = this->pptr();
*p++ = '\1';
unsigned char val = (prio + 11);
*p++ = val;
this->pbump(2);
}
// call after calling daemon()
template <typename charT, typename traits>
int DoutStreambuf<charT, traits>::rename_output_file()
{
Mutex::Locker l(_dout_lock);
if (!(flags & DOUTSB_FLAG_OFILE))
return 0;
string new_opath(_calculate_opath());
if (opath == new_opath)
return 0;
int ret = ::rename(opath.c_str(), new_opath.c_str());
if (ret) {
int err = errno;
ostringstream oss;
oss << __func__ << ": failed to rename '" << opath << "' to "
<< "'" << new_opath << "': " << cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
opath = new_opath;
// // $type.$id symlink
// if (g_conf.log_per_instance && _dout_name_symlink_path[0])
// create_symlink(_dout_name_symlink_path);
// if (_dout_rank_symlink_path[0])
// create_symlink(_dout_rank_symlink_path);
return 0;
}
template <typename charT, typename traits>
std::string DoutStreambuf<charT, traits>::config_to_str() const
{
assert(_dout_lock.is_locked());
ostringstream oss;
oss << "g_conf.log_to_syslog = " << g_conf.log_to_syslog << "\n";
oss << "g_conf.log_to_stdout = " << g_conf.log_to_stdout << "\n";
oss << "use_stderr = " << use_stderr << "\n";
oss << "g_conf.log_to_file = " << g_conf.log_to_file << "\n";
oss << "g_conf.log_file = '" << cpp_str(g_conf.log_file) << "'\n";
oss << "flags = 0x" << std::hex << flags << std::dec << "\n";
oss << "ofd = " << ofd << "\n";
oss << "opath = '" << opath << "'\n";
return oss.str();
}
// This is called to flush the buffer.
// This is called when we're done with the file stream (or when .flush() is called).
template <typename charT, typename traits>
typename DoutStreambuf<charT, traits>::int_type
DoutStreambuf<charT, traits>::sync()
{
//std::cout << "flush!" << std::endl;
typename DoutStreambuf<charT, traits>::int_type
ret(this->overflow(traits_ty::eof()));
if (ret == traits_ty::eof())
return -1;
return 0;
}
template <typename charT, typename traits>
typename DoutStreambuf<charT, traits>::int_type
DoutStreambuf<charT, traits>::underflow()
{
// We can't read from this
// TODO: some more elegant way of preventing callers from trying to get input from this stream
assert(0);
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::_clear_output_buffer()
{
// Set up the put pointer.
// Overflow is called when this buffer is filled
this->setp(obuf, obuf + OBUF_SZ - 5);
}
template <typename charT, typename traits>
std::string DoutStreambuf<charT, traits>::_calculate_opath() const
{
assert(_dout_lock.is_locked());
if (!empty(g_conf.log_file)) {
return normalize_relative(g_conf.log_file);
}
if (g_conf.log_per_instance) {
char hostname[255];
memset(hostname, 0, sizeof(hostname));
int ret = gethostname(hostname, sizeof(hostname));
if (ret) {
int err = errno;
ostringstream oss;
oss << __func__ << ": error calling gethostname: " << cpp_strerror(err) << "\n";
primitive_log(oss.str());
return "";
}
ostringstream oss;
oss << hostname << "." << getpid();
return oss.str();
}
else {
ostringstream oss;
oss << g_conf.type << "." << g_conf.id << ".log";
return oss.str();
}
}
template <typename charT, typename traits>
bool DoutStreambuf<charT, traits>::_read_ofile_config()
{
opath = _calculate_opath();
if (opath.empty()) {
ostringstream oss;
oss << __func__ << ": _calculate_opath failed.\n";
primitive_log(oss.str());
return false;
}
assert(ofd == -1);
ofd = open(opath.c_str(),
O_CREAT | O_WRONLY | O_CLOEXEC | O_APPEND, S_IWUSR | S_IRUSR);
if (ofd < 0) {
int err = errno;
ostringstream oss;
oss << "failed to open log file '" << opath << "': "
<< cpp_strerror(err) << "\n";
primitive_log(oss.str());
return false;
}
return true;
}
// Explicit template instantiation
template class DoutStreambuf <char>;
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2010 Dreamhost
*
* This 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. See file COPYING.
*
*/
#include "config.h"
#include "common/DoutStreambuf.h"
#include "common/errno.h"
#include "common/Mutex.h"
#include <assert.h>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <streambuf>
#include <string.h>
#include <syslog.h>
///////////////////////////// Globals /////////////////////////////
// TODO: get rid of this lock using thread-local storage
extern Mutex _dout_lock;
/* True if we should output high-priority messages to stderr */
static bool use_stderr = true;
//////////////////////// Helper functions //////////////////////////
static bool empty(const char *str)
{
if (!str)
return true;
if (!str[0])
return true;
return false;
}
static string cpp_str(const char *str)
{
if (!str)
return "(NULL)";
if (str[0] == '\0')
return "(empty)";
return str;
}
static std::string normalize_relative(const char *from)
{
if (from[0] == '/')
return string(from);
char c[512];
char *cwd = getcwd(c, sizeof(c));
ostringstream oss;
oss << cwd << "/" << from;
return oss.str();
}
/* Complain about errors even without a logfile */
static void primitive_log(const std::string &str)
{
std::cerr << str;
std::cerr.flush();
syslog(LOG_USER | LOG_NOTICE, "%s", str.c_str());
}
static inline bool prio_is_visible_on_stderr(int prio)
{
return prio <= 15;
}
static inline int dout_prio_to_syslog_prio(int prio)
{
if (prio <= 3)
return LOG_CRIT;
if (prio <= 5)
return LOG_ERR;
if (prio <= 15)
return LOG_WARNING;
if (prio <= 30)
return LOG_NOTICE;
if (prio <= 40)
return LOG_INFO;
return LOG_DEBUG;
}
static int safe_write(int fd, const char *buf, signed int len)
{
int res;
assert(len != 0);
while (1) {
res = write(fd, buf, len);
if (res < 0) {
int err = errno;
if (err != EINTR) {
ostringstream oss;
oss << __func__ << ": failed to write to fd " << fd << ": "
<< cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
}
len -= res;
buf += res;
if (len <= 0)
return 0;
}
}
static int create_symlink(const string &oldpath, const string &newpath)
{
while (1) {
if (::symlink(oldpath.c_str(), newpath.c_str()) == 0)
return 0;
int err = errno;
if (err == EEXIST) {
// Handle EEXIST
if (::unlink(newpath.c_str())) {
err = errno;
ostringstream oss;
oss << __func__ << ": failed to remove '" << newpath << "': "
<< cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
}
else {
// Other errors
ostringstream oss;
oss << __func__ << ": failed to symlink(oldpath='" << oldpath
<< "', newpath='" << newpath << "'): " << cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
}
}
static std::string get_basename(const std::string &filename)
{
size_t last_slash = filename.find_last_of("/");
if (last_slash == std::string::npos)
return filename;
return filename.substr(last_slash + 1);
}
///////////////////////////// DoutStreambuf /////////////////////////////
template <typename charT, typename traits>
DoutStreambuf<charT, traits>::DoutStreambuf()
: flags(0), ofd(-1)
{
// Initialize get pointer to zero so that underflow is called on the first read.
this->setg(0, 0, 0);
// Initialize output_buffer
_clear_output_buffer();
}
// This function is called when the output buffer is filled.
// In this function, the buffer should be written to wherever it should
// be written to (in this case, the streambuf object that this is controlling).
template <typename charT, typename traits>
typename DoutStreambuf<charT, traits>::int_type
DoutStreambuf<charT, traits>::overflow(DoutStreambuf<charT, traits>::int_type c)
{
{
// zero-terminate the buffer
charT* end_ptr = this->pptr();
*end_ptr++ = '\0';
*end_ptr++ = '\0';
// char buf[1000];
// hex2str(obuf, end_ptr - obuf, buf, sizeof(buf));
// printf("overflow buffer: '%s'\n", buf);
}
// Loop over all lines in the buffer.
int prio = 100;
charT* start = obuf;
while (true) {
char* end = strchrnul(start, '\n');
if (start == end) {
if (*start == '\0')
break;
// skip zero-length lines
++start;
continue;
}
if (*start == '\1') {
// Decode some control characters
++start;
unsigned char tmp = *((unsigned char*)start);
prio = tmp - 11;
++start;
}
*end = '\n';
char next = *(end+1);
*(end+1) = '\0';
// Now 'start' points to a NULL-terminated string, which we want to
// output with priority 'prio'
int len = strlen(start);
if (flags & DOUTSB_FLAG_SYSLOG) {
//printf("syslogging: '%s' len=%d\n", start, len);
syslog(LOG_USER | dout_prio_to_syslog_prio(prio), "%s", start);
}
if (flags & DOUTSB_FLAG_STDOUT) {
// Just write directly out to the stdout fileno. There's no point in
// using something like fputs to write to a temporary buffer,
// because we would just have to flush that temporary buffer
// immediately.
if (safe_write(STDOUT_FILENO, start, len))
flags &= ~DOUTSB_FLAG_STDOUT;
}
if (flags & DOUTSB_FLAG_STDERR) {
// Only write to stderr if the message is important enough.
if (prio_is_visible_on_stderr(prio)) {
if (safe_write(STDERR_FILENO, start, len))
flags &= ~DOUTSB_FLAG_STDERR;
}
}
if (flags & DOUTSB_FLAG_OFILE) {
if (safe_write(ofd, start, len))
flags &= ~DOUTSB_FLAG_OFILE;
}
*(end+1) = next;
start = end + 1;
}
_clear_output_buffer();
// A value different than EOF (or traits::eof() for other traits) signals success.
// If the function fails, either EOF (or traits::eof() for other traits) is returned or an
// exception is thrown.
return traits_ty::not_eof(c);
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::set_use_stderr(bool val)
{
_dout_lock.Lock();
use_stderr = val;
if (val)
flags |= DOUTSB_FLAG_STDERR;
else
flags &= ~DOUTSB_FLAG_STDERR;
_dout_lock.Unlock();
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::read_global_config()
{
assert(_dout_lock.is_locked());
flags = 0;
if (g_conf.log_to_syslog) {
flags |= DOUTSB_FLAG_SYSLOG;
}
if (g_conf.log_to_stdout) {
flags |= DOUTSB_FLAG_STDOUT;
}
if (use_stderr) {
flags |= DOUTSB_FLAG_STDERR;
}
if (g_conf.log_to_file) {
if (_read_ofile_config()) {
flags |= DOUTSB_FLAG_OFILE;
}
}
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::
set_flags(int flags_)
{
assert(_dout_lock.is_locked());
flags = flags_;
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::
set_prio(int prio)
{
charT* p = this->pptr();
*p++ = '\1';
unsigned char val = (prio + 11);
*p++ = val;
this->pbump(2);
}
// call after calling daemon()
template <typename charT, typename traits>
int DoutStreambuf<charT, traits>::rename_output_file()
{
Mutex::Locker l(_dout_lock);
if (!(flags & DOUTSB_FLAG_OFILE))
return 0;
string new_opath(_calculate_opath());
if (opath == new_opath)
return 0;
int ret = ::rename(opath.c_str(), new_opath.c_str());
if (ret) {
int err = errno;
ostringstream oss;
oss << __func__ << ": failed to rename '" << opath << "' to "
<< "'" << new_opath << "': " << cpp_strerror(err) << "\n";
primitive_log(oss.str());
return err;
}
opath = new_opath;
// // $type.$id symlink
// if (g_conf.log_per_instance && _dout_name_symlink_path[0])
// create_symlink(_dout_name_symlink_path);
// if (_dout_rank_symlink_path[0])
// create_symlink(_dout_rank_symlink_path);
return 0;
}
template <typename charT, typename traits>
std::string DoutStreambuf<charT, traits>::config_to_str() const
{
assert(_dout_lock.is_locked());
ostringstream oss;
oss << "g_conf.log_to_syslog = " << g_conf.log_to_syslog << "\n";
oss << "g_conf.log_to_stdout = " << g_conf.log_to_stdout << "\n";
oss << "use_stderr = " << use_stderr << "\n";
oss << "g_conf.log_to_file = " << g_conf.log_to_file << "\n";
oss << "g_conf.log_file = '" << cpp_str(g_conf.log_file) << "'\n";
oss << "flags = 0x" << std::hex << flags << std::dec << "\n";
oss << "ofd = " << ofd << "\n";
oss << "opath = '" << opath << "'\n";
return oss.str();
}
// This is called to flush the buffer.
// This is called when we're done with the file stream (or when .flush() is called).
template <typename charT, typename traits>
typename DoutStreambuf<charT, traits>::int_type
DoutStreambuf<charT, traits>::sync()
{
//std::cout << "flush!" << std::endl;
typename DoutStreambuf<charT, traits>::int_type
ret(this->overflow(traits_ty::eof()));
if (ret == traits_ty::eof())
return -1;
return 0;
}
template <typename charT, typename traits>
typename DoutStreambuf<charT, traits>::int_type
DoutStreambuf<charT, traits>::underflow()
{
// We can't read from this
// TODO: some more elegant way of preventing callers from trying to get input from this stream
assert(0);
}
template <typename charT, typename traits>
void DoutStreambuf<charT, traits>::_clear_output_buffer()
{
// Set up the put pointer.
// Overflow is called when this buffer is filled
this->setp(obuf, obuf + OBUF_SZ - 5);
}
template <typename charT, typename traits>
std::string DoutStreambuf<charT, traits>::_calculate_opath() const
{
assert(_dout_lock.is_locked());
if (!empty(g_conf.log_file)) {
return normalize_relative(g_conf.log_file);
}
if (g_conf.log_per_instance) {
char hostname[255];
memset(hostname, 0, sizeof(hostname));
int ret = gethostname(hostname, sizeof(hostname));
if (ret) {
int err = errno;
ostringstream oss;
oss << __func__ << ": error calling gethostname: " << cpp_strerror(err) << "\n";
primitive_log(oss.str());
return "";
}
ostringstream oss;
oss << hostname << "." << getpid();
return oss.str();
}
else {
ostringstream oss;
oss << g_conf.type << "." << g_conf.id << ".log";
return oss.str();
}
}
template <typename charT, typename traits>
bool DoutStreambuf<charT, traits>::_read_ofile_config()
{
opath = _calculate_opath();
if (opath.empty()) {
ostringstream oss;
oss << __func__ << ": _calculate_opath failed.\n";
primitive_log(oss.str());
return false;
}
assert(ofd == -1);
ofd = open(opath.c_str(),
O_CREAT | O_WRONLY | O_CLOEXEC | O_APPEND, S_IWUSR | S_IRUSR);
if (ofd < 0) {
int err = errno;
ostringstream oss;
oss << "failed to open log file '" << opath << "': "
<< cpp_strerror(err) << "\n";
primitive_log(oss.str());
return false;
}
return true;
}
// Explicit template instantiation
template class DoutStreambuf <char>;
|
fix normalize_relative
|
logging: fix normalize_relative
Signed-off-by: Colin McCabe <[email protected]>
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
e9df46bfa039c0e0f14514f0023d1a00f2f68df3
|
trunk/libmesh/src/solvers/exact_solution.C
|
trunk/libmesh/src/solvers/exact_solution.C
|
// $Id: exact_solution.C,v 1.25 2006-04-05 16:14:27 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "dof_map.h"
#include "elem.h"
#include "exact_solution.h"
#include "equation_systems.h"
#include "fe.h"
#include "fe_interface.h"
#include "mesh.h"
#include "quadrature.h"
#include "tensor_value.h"
#include "vector_value.h"
ExactSolution::ExactSolution(EquationSystems& es) :
_exact_value (NULL),
_exact_deriv (NULL),
_exact_hessian (NULL),
_equation_systems(es),
_mesh(es.get_mesh()),
_extra_order(0)
{
// Initialize the _errors data structure which holds all
// the eventual values of the error.
for (unsigned int sys=0; sys<_equation_systems.n_systems(); ++sys)
{
// Reference to the system
const System& system = _equation_systems.get_system(sys);
// The name of the system
const std::string& sys_name = system.name();
// The SystemErrorMap to be inserted
ExactSolution::SystemErrorMap sem;
for (unsigned int var=0; var<system.n_vars(); ++var)
{
// The name of this variable
const std::string& var_name = system.variable_name(var);
sem[var_name] = std::vector<Number>(3, 0.);
}
_errors[sys_name] = sem;
}
}
void ExactSolution::attach_exact_value (Number fptr(const Point& p,
const Parameters& parameters,
const std::string& sys_name,
const std::string& unknown_name))
{
assert (fptr != NULL);
_exact_value = fptr;
}
void ExactSolution::attach_exact_deriv (Gradient fptr(const Point& p,
const Parameters& parameters,
const std::string& sys_name,
const std::string& unknown_name))
{
assert (fptr != NULL);
_exact_deriv = fptr;
}
void ExactSolution::attach_exact_hessian (Tensor fptr(const Point& p,
const Parameters& parameters,
const std::string& sys_name,
const std::string& unknown_name))
{
assert (fptr != NULL);
_exact_hessian = fptr;
}
std::vector<Number>& ExactSolution::_check_inputs(const std::string& sys_name,
const std::string& unknown_name)
{
// Be sure that an exact_value function has been attached
if (_exact_value == NULL)
{
std::cerr << "Cannot compute error, you must provide a "
<< "function which computes the exact solution."
<< std::endl;
error();
}
// Make sure the requested sys_name exists.
std::map<std::string, SystemErrorMap>::iterator sys_iter =
_errors.find(sys_name);
if (sys_iter == _errors.end())
{
std::cerr << "Sorry, couldn't find the requested system '"
<< sys_name << "'."
<< std::endl;
error();
}
// Make sure the requested unknown_name exists.
SystemErrorMap::iterator var_iter = (*sys_iter).second.find(unknown_name);
if (var_iter == (*sys_iter).second.end())
{
std::cerr << "Sorry, couldn't find the requested variable '"
<< unknown_name << "'."
<< std::endl;
error();
}
// Return a reference to the proper error entry
return (*var_iter).second;
}
void ExactSolution::compute_error(const std::string& sys_name,
const std::string& unknown_name)
{
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
this->_compute_error(sys_name,
unknown_name,
error_vals);
}
Number ExactSolution::l2_error(const std::string& sys_name,
const std::string& unknown_name)
{
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
// Return the square root of the first component of the
// computed error.
return std::sqrt(error_vals[0]);
}
Number ExactSolution::h1_error(const std::string& sys_name,
const std::string& unknown_name)
{
// Check to be sure the user has supplied the exact derivative function
if (_exact_deriv == NULL)
{
std::cerr << "Cannot compute H1 error, you must provide a "
<< "function which computes the gradient of the exact solution."
<< std::endl;
error();
}
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
// Return the square root of the sum of the computed errors.
return std::sqrt(error_vals[0] + error_vals[1]);
}
Number ExactSolution::h2_error(const std::string& sys_name,
const std::string& unknown_name)
{
// Check to be sure the user has supplied the exact derivative function
if (_exact_deriv == NULL || _exact_hessian == NULL)
{
std::cerr << "Cannot compute H2 error, you must provide functions "
<< "which computes the gradient and hessian of the "
<< "exact solution."
<< std::endl;
error();
}
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
// Return the square root of the sum of the computed errors.
return std::sqrt(error_vals[0] + error_vals[1] + error_vals[2]);
}
void ExactSolution::_compute_error(const std::string& sys_name,
const std::string& unknown_name,
std::vector<Number>& error_vals)
{
// Get a reference to the system whose error is being computed.
const System& computed_system
= _equation_systems.get_system (sys_name);
// Get a reference to the dofmap for that system
const DofMap& computed_dof_map = computed_system.get_dof_map();
// Zero the error before summation
error_vals = std::vector<Number>(3, 0.);
// get the EquationSystems parameters
const Parameters& parameters = this->_equation_systems.parameters;
// Get the current time, in case the exact solution depends on it.
// Steady systems of equations do not have a time parameter, so this
// routine needs to take that into account.
// FIXME!!!
// const Real time = 0.;//_equation_systems.parameter("time");
// Construct Quadrature rule based on default quadrature order
const unsigned int var = computed_system.variable_number(unknown_name);
const FEType& fe_type = computed_dof_map.variable_type(var);
AutoPtr<QBase> qrule =
fe_type.default_quadrature_rule (_mesh.mesh_dimension(),
_extra_order);
// Construct finite element object
AutoPtr<FEBase> fe(FEBase::build(_mesh.mesh_dimension(), fe_type));
// Attach quadrature rule to FE object
fe->attach_quadrature_rule (qrule.get());
// The Jacobian*weight at the quadrature points.
const std::vector<Real>& JxW = fe->get_JxW();
// The value of the shape functions at the quadrature points
// i.e. phi(i) = phi_values[i][qp]
const std::vector<std::vector<Real> >& phi_values = fe->get_phi();
// The value of the shape function gradients at the quadrature points
const std::vector<std::vector<RealGradient> >& dphi_values = fe->get_dphi();
#ifdef ENABLE_SECOND_DERIVATIVES
// The value of the shape function second derivatives at the quadrature points
const std::vector<std::vector<RealTensor> >& d2phi_values = fe->get_d2phi();
#endif
// The XYZ locations (in physical space) of the quadrature points
const std::vector<Point>& q_point = fe->get_xyz();
// The global degree of freedom indices associated
// with the local degrees of freedom.
std::vector<unsigned int> dof_indices;
//
// Begin the loop over the elements
//
MeshBase::const_element_iterator el = _mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_el = _mesh.active_local_elements_end();
for ( ; el != end_el; ++el)
{
// Store a pointer to the element we are currently
// working on. This allows for nicer syntax later.
const Elem* elem = *el;
// reinitialize the element-specific data
// for the current element
fe->reinit (elem);
// Get the local to global degree of freedom maps
computed_dof_map.dof_indices (elem, dof_indices, var);
// The number of quadrature points
const unsigned int n_qp = qrule->n_points();
// The number of shape functions
const unsigned int n_sf = dof_indices.size();
//
// Begin the loop over the Quadrature points.
//
for (unsigned int qp=0; qp<n_qp; qp++)
{
// Real u_h = 0.;
// RealGradient grad_u_h;
Number u_h = 0.;
#ifndef USE_COMPLEX_NUMBERS
RealGradient grad_u_h;
#else
// Gradient grad_u_h;
RealGradient grad_u_h_re;
RealGradient grad_u_h_im;
#endif
#ifdef ENABLE_SECOND_DERIVATIVES
#ifndef USE_COMPLEX_NUMBERS
RealTensor grad2_u_h;
#else
RealTensor grad2_u_h_re;
RealTensor grad2_u_h_im;
#endif
#endif
// Compute solution values at the current
// quadrature point. This reqiures a sum
// over all the shape functions evaluated
// at the quadrature point.
for (unsigned int i=0; i<n_sf; i++)
{
// Values from current solution.
u_h += phi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#ifndef USE_COMPLEX_NUMBERS
grad_u_h += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#else
grad_u_h_re += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).real();
grad_u_h_im += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).imag();
#endif
#ifdef ENABLE_SECOND_DERIVATIVES
#ifndef USE_COMPLEX_NUMBERS
grad2_u_h += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#else
grad2_u_h_re += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]).real();
grad2_u_h_im += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]).imag();
#endif
#endif
}
#ifdef USE_COMPLEX_NUMBERS
Gradient grad_u_h (grad_u_h_re, grad_u_h_im);
#ifdef ENABLE_SECOND_DERIVATIVES
Tensor grad2_u_h (grad2_u_h_re, grad2_u_h_im);
#endif
#endif
// Compute the value of the error at this quadrature point
// const Real val_error = (u_h - _exact_value(q_point[qp],
const Number val_error = (u_h - _exact_value(q_point[qp],
parameters,
sys_name,
unknown_name));
// Add the squares of the error to each contribution
error_vals[0] += JxW[qp]*(val_error*val_error);
// Compute the value of the error in the gradient at this quadrature point
if (_exact_deriv != NULL)
{
Gradient grad_error = (grad_u_h - _exact_deriv(q_point[qp],
parameters,
sys_name,
unknown_name));
error_vals[1] += JxW[qp]*(grad_error*grad_error);
}
#ifdef ENABLE_SECOND_DERIVATIVES
// Compute the value of the error in the hessian at this quadrature point
if (_exact_hessian != NULL)
{
Tensor grad2_error = (grad2_u_h - _exact_hessian(q_point[qp],
parameters,
sys_name,
unknown_name));
error_vals[2] += JxW[qp]*(grad2_error.contract(grad2_error));
}
#endif
} // end qp loop
} // end element loop
#ifdef HAVE_MPI
if (libMesh::n_processors() > 1)
{
#ifndef USE_COMPLEX_NUMBERS
std::vector<Real> local_errors(3);
// Set local error entries.
local_errors[0] = error_vals[0];
local_errors[1] = error_vals[1];
local_errors[2] = error_vals[2];
std::vector<Real> global_errors(3);
MPI_Allreduce (&local_errors[0],
&global_errors[0],
local_errors.size(),
MPI_REAL,
MPI_SUM,
libMesh::COMM_WORLD);
// Store result back in the pair
error_vals[0] = global_errors[0];
error_vals[1] = global_errors[1];
error_vals[2] = global_errors[2];
// Sanity check
assert (global_errors[0] >= local_errors[0]);
assert (global_errors[1] >= local_errors[1]);
assert (global_errors[2] >= local_errors[2]);
#endif
}
#endif
}
|
// $Id: exact_solution.C,v 1.26 2007-01-31 21:35:21 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "dof_map.h"
#include "elem.h"
#include "exact_solution.h"
#include "equation_systems.h"
#include "fe.h"
#include "fe_interface.h"
#include "mesh.h"
#include "quadrature.h"
#include "tensor_value.h"
#include "vector_value.h"
ExactSolution::ExactSolution(EquationSystems& es) :
_exact_value (NULL),
_exact_deriv (NULL),
_exact_hessian (NULL),
_equation_systems(es),
_mesh(es.get_mesh()),
_extra_order(0)
{
// Initialize the _errors data structure which holds all
// the eventual values of the error.
for (unsigned int sys=0; sys<_equation_systems.n_systems(); ++sys)
{
// Reference to the system
const System& system = _equation_systems.get_system(sys);
// The name of the system
const std::string& sys_name = system.name();
// The SystemErrorMap to be inserted
ExactSolution::SystemErrorMap sem;
for (unsigned int var=0; var<system.n_vars(); ++var)
{
// The name of this variable
const std::string& var_name = system.variable_name(var);
sem[var_name] = std::vector<Number>(3, 0.);
}
_errors[sys_name] = sem;
}
}
void ExactSolution::attach_exact_value (Number fptr(const Point& p,
const Parameters& parameters,
const std::string& sys_name,
const std::string& unknown_name))
{
assert (fptr != NULL);
_exact_value = fptr;
}
void ExactSolution::attach_exact_deriv (Gradient fptr(const Point& p,
const Parameters& parameters,
const std::string& sys_name,
const std::string& unknown_name))
{
assert (fptr != NULL);
_exact_deriv = fptr;
}
void ExactSolution::attach_exact_hessian (Tensor fptr(const Point& p,
const Parameters& parameters,
const std::string& sys_name,
const std::string& unknown_name))
{
assert (fptr != NULL);
_exact_hessian = fptr;
}
std::vector<Number>& ExactSolution::_check_inputs(const std::string& sys_name,
const std::string& unknown_name)
{
// If no exact solution function has been attached, we now
// just compute the solution norm (i.e. the difference from an
// "exact solution" of zero
/*
if (_exact_value == NULL)
{
std::cerr << "Cannot compute error, you must provide a "
<< "function which computes the exact solution."
<< std::endl;
error();
}
*/
// Make sure the requested sys_name exists.
std::map<std::string, SystemErrorMap>::iterator sys_iter =
_errors.find(sys_name);
if (sys_iter == _errors.end())
{
std::cerr << "Sorry, couldn't find the requested system '"
<< sys_name << "'."
<< std::endl;
error();
}
// Make sure the requested unknown_name exists.
SystemErrorMap::iterator var_iter = (*sys_iter).second.find(unknown_name);
if (var_iter == (*sys_iter).second.end())
{
std::cerr << "Sorry, couldn't find the requested variable '"
<< unknown_name << "'."
<< std::endl;
error();
}
// Return a reference to the proper error entry
return (*var_iter).second;
}
void ExactSolution::compute_error(const std::string& sys_name,
const std::string& unknown_name)
{
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
this->_compute_error(sys_name,
unknown_name,
error_vals);
}
Number ExactSolution::l2_error(const std::string& sys_name,
const std::string& unknown_name)
{
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
// Return the square root of the first component of the
// computed error.
return std::sqrt(error_vals[0]);
}
Number ExactSolution::h1_error(const std::string& sys_name,
const std::string& unknown_name)
{
// If the user has supplied no exact derivative function, we
// just integrate the H1 norm of the solution; i.e. its
// difference from an "exact solution" of zero.
/*
if (_exact_deriv == NULL)
{
std::cerr << "Cannot compute H1 error, you must provide a "
<< "function which computes the gradient of the exact solution."
<< std::endl;
error();
}
*/
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
// Return the square root of the sum of the computed errors.
return std::sqrt(error_vals[0] + error_vals[1]);
}
Number ExactSolution::h2_error(const std::string& sys_name,
const std::string& unknown_name)
{
// If the user has supplied no exact derivative functions, we
// just integrate the H1 norm of the solution; i.e. its
// difference from an "exact solution" of zero.
/*
if (_exact_deriv == NULL || _exact_hessian == NULL)
{
std::cerr << "Cannot compute H2 error, you must provide functions "
<< "which computes the gradient and hessian of the "
<< "exact solution."
<< std::endl;
error();
}
*/
// Check the inputs for validity, and get a reference
// to the proper location to store the error
std::vector<Number>& error_vals = this->_check_inputs(sys_name,
unknown_name);
// Return the square root of the sum of the computed errors.
return std::sqrt(error_vals[0] + error_vals[1] + error_vals[2]);
}
void ExactSolution::_compute_error(const std::string& sys_name,
const std::string& unknown_name,
std::vector<Number>& error_vals)
{
// Get a reference to the system whose error is being computed.
const System& computed_system
= _equation_systems.get_system (sys_name);
// Get a reference to the dofmap for that system
const DofMap& computed_dof_map = computed_system.get_dof_map();
// Zero the error before summation
error_vals = std::vector<Number>(3, 0.);
// get the EquationSystems parameters
const Parameters& parameters = this->_equation_systems.parameters;
// Get the current time, in case the exact solution depends on it.
// Steady systems of equations do not have a time parameter, so this
// routine needs to take that into account.
// FIXME!!!
// const Real time = 0.;//_equation_systems.parameter("time");
// Construct Quadrature rule based on default quadrature order
const unsigned int var = computed_system.variable_number(unknown_name);
const FEType& fe_type = computed_dof_map.variable_type(var);
AutoPtr<QBase> qrule =
fe_type.default_quadrature_rule (_mesh.mesh_dimension(),
_extra_order);
// Construct finite element object
AutoPtr<FEBase> fe(FEBase::build(_mesh.mesh_dimension(), fe_type));
// Attach quadrature rule to FE object
fe->attach_quadrature_rule (qrule.get());
// The Jacobian*weight at the quadrature points.
const std::vector<Real>& JxW = fe->get_JxW();
// The value of the shape functions at the quadrature points
// i.e. phi(i) = phi_values[i][qp]
const std::vector<std::vector<Real> >& phi_values = fe->get_phi();
// The value of the shape function gradients at the quadrature points
const std::vector<std::vector<RealGradient> >& dphi_values = fe->get_dphi();
#ifdef ENABLE_SECOND_DERIVATIVES
// The value of the shape function second derivatives at the quadrature points
const std::vector<std::vector<RealTensor> >& d2phi_values = fe->get_d2phi();
#endif
// The XYZ locations (in physical space) of the quadrature points
const std::vector<Point>& q_point = fe->get_xyz();
// The global degree of freedom indices associated
// with the local degrees of freedom.
std::vector<unsigned int> dof_indices;
//
// Begin the loop over the elements
//
MeshBase::const_element_iterator el = _mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_el = _mesh.active_local_elements_end();
for ( ; el != end_el; ++el)
{
// Store a pointer to the element we are currently
// working on. This allows for nicer syntax later.
const Elem* elem = *el;
// reinitialize the element-specific data
// for the current element
fe->reinit (elem);
// Get the local to global degree of freedom maps
computed_dof_map.dof_indices (elem, dof_indices, var);
// The number of quadrature points
const unsigned int n_qp = qrule->n_points();
// The number of shape functions
const unsigned int n_sf = dof_indices.size();
//
// Begin the loop over the Quadrature points.
//
for (unsigned int qp=0; qp<n_qp; qp++)
{
// Real u_h = 0.;
// RealGradient grad_u_h;
Number u_h = 0.;
#ifndef USE_COMPLEX_NUMBERS
RealGradient grad_u_h;
#else
// Gradient grad_u_h;
RealGradient grad_u_h_re;
RealGradient grad_u_h_im;
#endif
#ifdef ENABLE_SECOND_DERIVATIVES
#ifndef USE_COMPLEX_NUMBERS
RealTensor grad2_u_h;
#else
RealTensor grad2_u_h_re;
RealTensor grad2_u_h_im;
#endif
#endif
// Compute solution values at the current
// quadrature point. This reqiures a sum
// over all the shape functions evaluated
// at the quadrature point.
for (unsigned int i=0; i<n_sf; i++)
{
// Values from current solution.
u_h += phi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#ifndef USE_COMPLEX_NUMBERS
grad_u_h += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#else
grad_u_h_re += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).real();
grad_u_h_im += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).imag();
#endif
#ifdef ENABLE_SECOND_DERIVATIVES
#ifndef USE_COMPLEX_NUMBERS
grad2_u_h += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]);
#else
grad2_u_h_re += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]).real();
grad2_u_h_im += d2phi_values[i][qp]*computed_system.current_solution (dof_indices[i]).imag();
#endif
#endif
}
#ifdef USE_COMPLEX_NUMBERS
Gradient grad_u_h (grad_u_h_re, grad_u_h_im);
#ifdef ENABLE_SECOND_DERIVATIVES
Tensor grad2_u_h (grad2_u_h_re, grad2_u_h_im);
#endif
#endif
// Compute the value of the error at this quadrature point
const Number exact_val = _exact_value ?
_exact_value(q_point[qp], parameters, sys_name, unknown_name) :
0.;
const Number val_error = u_h - exact_val;
// Add the squares of the error to each contribution
error_vals[0] += JxW[qp]*(val_error*val_error);
// Compute the value of the error in the gradient at this quadrature point
const Gradient exact_grad = _exact_deriv ?
_exact_deriv(q_point[qp], parameters, sys_name, unknown_name) :
Gradient(0.);
const Gradient grad_error = grad_u_h - exact_grad;
error_vals[1] += JxW[qp]*(grad_error*grad_error);
#ifdef ENABLE_SECOND_DERIVATIVES
// Compute the value of the error in the hessian at this quadrature point
const Tensor exact_hess = _exact_hessian ?
_exact_hessian(q_point[qp], parameters, sys_name, unknown_name) :
Tensor(0.);
const Tensor grad2_error = grad2_u_h - exact_hess;
error_vals[2] += JxW[qp]*(grad2_error.contract(grad2_error));
#endif
} // end qp loop
} // end element loop
#ifdef HAVE_MPI
if (libMesh::n_processors() > 1)
{
#ifndef USE_COMPLEX_NUMBERS
std::vector<Real> local_errors(3);
// Set local error entries.
local_errors[0] = error_vals[0];
local_errors[1] = error_vals[1];
local_errors[2] = error_vals[2];
std::vector<Real> global_errors(3);
MPI_Allreduce (&local_errors[0],
&global_errors[0],
local_errors.size(),
MPI_REAL,
MPI_SUM,
libMesh::COMM_WORLD);
// Store result back in the pair
error_vals[0] = global_errors[0];
error_vals[1] = global_errors[1];
error_vals[2] = global_errors[2];
// Sanity check
assert (global_errors[0] >= local_errors[0]);
assert (global_errors[1] >= local_errors[1]);
assert (global_errors[2] >= local_errors[2]);
#endif
}
#endif
}
|
Use zero exact solution by default
|
Use zero exact solution by default
git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@1824 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
|
C++
|
lgpl-2.1
|
90jrong/libmesh,cahaynes/libmesh,capitalaslash/libmesh,aeslaughter/libmesh,90jrong/libmesh,aeslaughter/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,dschwen/libmesh,friedmud/libmesh,balborian/libmesh,libMesh/libmesh,pbauman/libmesh,aeslaughter/libmesh,cahaynes/libmesh,BalticPinguin/libmesh,libMesh/libmesh,pbauman/libmesh,friedmud/libmesh,dmcdougall/libmesh,vikramvgarg/libmesh,pbauman/libmesh,capitalaslash/libmesh,dschwen/libmesh,balborian/libmesh,cahaynes/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,benkirk/libmesh,capitalaslash/libmesh,benkirk/libmesh,pbauman/libmesh,svallaghe/libmesh,svallaghe/libmesh,dmcdougall/libmesh,svallaghe/libmesh,svallaghe/libmesh,jwpeterson/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,dknez/libmesh,roystgnr/libmesh,dmcdougall/libmesh,jwpeterson/libmesh,roystgnr/libmesh,cahaynes/libmesh,hrittich/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,dknez/libmesh,BalticPinguin/libmesh,hrittich/libmesh,coreymbryant/libmesh,balborian/libmesh,dknez/libmesh,coreymbryant/libmesh,benkirk/libmesh,balborian/libmesh,libMesh/libmesh,dmcdougall/libmesh,friedmud/libmesh,aeslaughter/libmesh,dmcdougall/libmesh,coreymbryant/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,pbauman/libmesh,dknez/libmesh,benkirk/libmesh,libMesh/libmesh,balborian/libmesh,cahaynes/libmesh,capitalaslash/libmesh,aeslaughter/libmesh,pbauman/libmesh,svallaghe/libmesh,dknez/libmesh,dschwen/libmesh,dschwen/libmesh,dmcdougall/libmesh,dmcdougall/libmesh,balborian/libmesh,90jrong/libmesh,coreymbryant/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,hrittich/libmesh,giorgiobornia/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,90jrong/libmesh,roystgnr/libmesh,hrittich/libmesh,friedmud/libmesh,cahaynes/libmesh,hrittich/libmesh,svallaghe/libmesh,hrittich/libmesh,pbauman/libmesh,friedmud/libmesh,balborian/libmesh,cahaynes/libmesh,jwpeterson/libmesh,capitalaslash/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,dschwen/libmesh,benkirk/libmesh,benkirk/libmesh,coreymbryant/libmesh,benkirk/libmesh,pbauman/libmesh,hrittich/libmesh,friedmud/libmesh,friedmud/libmesh,libMesh/libmesh,roystgnr/libmesh,dschwen/libmesh,dknez/libmesh,giorgiobornia/libmesh,90jrong/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,aeslaughter/libmesh,dmcdougall/libmesh,balborian/libmesh,dschwen/libmesh,libMesh/libmesh,dknez/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,benkirk/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,capitalaslash/libmesh,benkirk/libmesh,balborian/libmesh,aeslaughter/libmesh,roystgnr/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,90jrong/libmesh,giorgiobornia/libmesh,libMesh/libmesh,90jrong/libmesh,90jrong/libmesh,aeslaughter/libmesh,coreymbryant/libmesh,roystgnr/libmesh,cahaynes/libmesh,aeslaughter/libmesh,friedmud/libmesh,pbauman/libmesh,dschwen/libmesh,90jrong/libmesh,giorgiobornia/libmesh,hrittich/libmesh,BalticPinguin/libmesh,balborian/libmesh,dknez/libmesh,svallaghe/libmesh,libMesh/libmesh,coreymbryant/libmesh,svallaghe/libmesh,giorgiobornia/libmesh,vikramvgarg/libmesh,friedmud/libmesh,hrittich/libmesh
|
2417a31bddec762267691ea7ff02344949d42557
|
source/architecture/Stack.cpp
|
source/architecture/Stack.cpp
|
/**
* \file
* \brief Stack class implementation
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/architecture/Stack.hpp"
#include "distortos/architecture/initializeStack.hpp"
#include "distortos/architecture/parameters.hpp"
#include "distortos/internal/memory/dummyDeleter.hpp"
#include <cstring>
namespace distortos
{
namespace architecture
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Adjusts storage's address to suit architecture's alignment requirements.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] stackAlignment is required stack alignment
*
* \return adjusted storage's address
*/
void* adjustStorage(void* const storage, const size_t stackAlignment)
{
const auto storageSizeT = reinterpret_cast<size_t>(storage);
const auto offset = (-storageSizeT) & (stackAlignment - 1);
return reinterpret_cast<void*>(storageSizeT + offset);
}
/**
* \brief Adjusts storage's size to suit architecture's alignment requirements,
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] adjustedStorage is an adjusted storage's address
* \param [in] stackAlignment is required stack alignment
*
* \return adjusted storage's size
*/
size_t adjustSize(void* const storage, const size_t size, void* const adjustedStorage, const size_t stackAlignment)
{
const auto offset = static_cast<uint8_t*>(adjustedStorage) - static_cast<uint8_t*>(storage);
return ((size - offset) / stackAlignment) * stackAlignment;
}
/**
* \brief Proxy for initializeStack() which fills stack with 0 before actually initializing it.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] thread is a reference to Thread object passed to function
* \param [in] run is a reference to Thread's "run" function
* \param [in] preTerminationHook is a pointer to Thread's pre-termination hook, nullptr to skip
* \param [in] terminationHook is a reference to Thread's termination hook
*
* \return value that can be used as thread's stack pointer, ready for context switching
*/
void* initializeStackProxy(void* const storage, const size_t size, Thread& thread, void (& run)(Thread&),
void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&))
{
memset(storage, 0, size);
return initializeStack(storage, size, thread, run, preTerminationHook, terminationHook);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Stack::Stack(StorageUniquePointer&& storageUniquePointer, const size_t size, Thread& thread, void (& run)(Thread&),
void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&)) :
storageUniquePointer_{std::move(storageUniquePointer)},
adjustedStorage_{adjustStorage(storageUniquePointer_.get(), stackAlignment)},
adjustedSize_{adjustSize(storageUniquePointer_.get(), size, adjustedStorage_, stackAlignment)},
stackPointer_{initializeStackProxy(adjustedStorage_, adjustedSize_, thread, run, preTerminationHook,
terminationHook)}
{
/// \todo implement minimal size check
}
Stack::Stack(void* const storage, const size_t size) :
storageUniquePointer_{storage, internal::dummyDeleter<void*>},
adjustedStorage_{storage},
adjustedSize_{size},
stackPointer_{}
{
/// \todo implement minimal size check
}
Stack::~Stack()
{
}
} // namespace architecture
} // namespace distortos
|
/**
* \file
* \brief Stack class implementation
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/architecture/Stack.hpp"
#include "distortos/architecture/initializeStack.hpp"
#include "distortos/architecture/parameters.hpp"
#include "distortos/internal/memory/dummyDeleter.hpp"
#include <cstring>
namespace distortos
{
namespace architecture
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Adjusts storage's address to suit architecture's alignment requirements.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] alignment is the required stack alignment, bytes
*
* \return adjusted storage's address
*/
void* adjustStorage(void* const storage, const size_t alignment)
{
return reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(storage) + alignment - 1) / alignment * alignment);
}
/**
* \brief Adjusts storage's size to suit architecture's alignment requirements,
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] adjustedStorage is an adjusted storage's address
* \param [in] stackAlignment is required stack alignment
*
* \return adjusted storage's size
*/
size_t adjustSize(void* const storage, const size_t size, void* const adjustedStorage, const size_t stackAlignment)
{
const auto offset = static_cast<uint8_t*>(adjustedStorage) - static_cast<uint8_t*>(storage);
return ((size - offset) / stackAlignment) * stackAlignment;
}
/**
* \brief Proxy for initializeStack() which fills stack with 0 before actually initializing it.
*
* \param [in] storage is a pointer to stack's storage
* \param [in] size is the size of stack's storage, bytes
* \param [in] thread is a reference to Thread object passed to function
* \param [in] run is a reference to Thread's "run" function
* \param [in] preTerminationHook is a pointer to Thread's pre-termination hook, nullptr to skip
* \param [in] terminationHook is a reference to Thread's termination hook
*
* \return value that can be used as thread's stack pointer, ready for context switching
*/
void* initializeStackProxy(void* const storage, const size_t size, Thread& thread, void (& run)(Thread&),
void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&))
{
memset(storage, 0, size);
return initializeStack(storage, size, thread, run, preTerminationHook, terminationHook);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
Stack::Stack(StorageUniquePointer&& storageUniquePointer, const size_t size, Thread& thread, void (& run)(Thread&),
void (* preTerminationHook)(Thread&), void (& terminationHook)(Thread&)) :
storageUniquePointer_{std::move(storageUniquePointer)},
adjustedStorage_{adjustStorage(storageUniquePointer_.get(), stackAlignment)},
adjustedSize_{adjustSize(storageUniquePointer_.get(), size, adjustedStorage_, stackAlignment)},
stackPointer_{initializeStackProxy(adjustedStorage_, adjustedSize_, thread, run, preTerminationHook,
terminationHook)}
{
/// \todo implement minimal size check
}
Stack::Stack(void* const storage, const size_t size) :
storageUniquePointer_{storage, internal::dummyDeleter<void*>},
adjustedStorage_{storage},
adjustedSize_{size},
stackPointer_{}
{
/// \todo implement minimal size check
}
Stack::~Stack()
{
}
} // namespace architecture
} // namespace distortos
|
Simplify the code in local adjustStorage() from Stack class
|
Simplify the code in local adjustStorage() from Stack class
Simply round up the address to next multiple of alignment.
|
C++
|
mpl-2.0
|
DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos
|
842eca411c907bdffd69e61edf265c93074947db
|
src/CharacterContainer.cpp
|
src/CharacterContainer.cpp
|
// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// illarionserver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include <map>
#include <unordered_map>
#include "globals.hpp"
#include "CharacterContainer.hpp"
#include "Player.hpp"
#include "Monster.hpp"
#include "NPC.hpp"
template <class T>
bool CharacterContainer<T>::getPosition(TYPE_OF_CHARACTER_ID id,position& pos) {
auto i = container.find(id);
if (i!=container.end()) {
pos = (i->second)->getPosition();
return true;
} else {
return false;
}
}
template <class T>
iterator_range<typename CharacterContainer<T>::position_to_id_type::const_iterator> CharacterContainer<T>::projection_x_axis(const position& pos, int r) const {
return {{position_to_id.upper_bound(position(pos.x-r-1,0,0)),position_to_id.upper_bound(position(pos.x+r+1,0,0))}};
}
template <class T>
auto CharacterContainer<T>::find(const std::string &text) const -> pointer {
try {
auto id = boost::lexical_cast<TYPE_OF_CHARACTER_ID>(text);
return find(id);
} catch (boost::bad_lexical_cast &) {
for (const auto &character : container) {
if (comparestrings_nocase(character.second->getName(), text)) {
return character.second;
}
}
}
return nullptr;
}
template <class T>
auto CharacterContainer<T>::find(TYPE_OF_CHARACTER_ID id) const -> pointer {
const auto it = container.find(id);
if (it != container.end()) {
return it->second;
}
return nullptr;
}
template <class T>
auto CharacterContainer<T>::find(const position &pos) const -> pointer {
const auto i = position_to_id.find(pos);
if (i!=position_to_id.end()) {
return find(i->second);
}
return nullptr;
}
template <class T>
void CharacterContainer<T>::update(pointer p, const position& newPosition) {
const auto id = p->getId();
if (!find(id)) {
return;
}
const auto &oldPosition = p->getPosition();
const auto range = position_to_id.equal_range(oldPosition);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == id) {
position_to_id.erase(it);
position_to_id.insert(std::make_pair(newPosition, id));
return;
}
}
}
template <class T>
bool CharacterContainer<T>::erase(TYPE_OF_CHARACTER_ID id) {
position pos;
if (getPosition(id, pos)) {
const auto range = position_to_id.equal_range(pos);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == id) {
position_to_id.erase(it);
break;
}
}
}
return container.erase(id) > 0;
}
template <class T>
auto CharacterContainer<T>::findAllCharactersInRangeOf(const position &pos, int distancemetric) const -> std::vector<pointer> {
std::vector<pointer> temp;
auto candidates = projection_x_axis(pos,distancemetric);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if ((abs(dx) + abs(dy) <= distancemetric) && (-RANGEDOWN <= dz) && (dz <= RANGEUP)) {
if (auto character=find(id)) temp.push_back(character);
}
}
return temp;
}
template <class T>
auto CharacterContainer<T>::findAllCharactersInScreen(const position &pos) const -> std::vector<pointer> {
std::vector<pointer> temp;
const int MAX_SCREEN_RANGE = 30;
auto candidates = projection_x_axis(pos,MAX_SCREEN_RANGE);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (auto character=find(id)) {
if ((abs(dx) + abs(dy) <= character->getScreenRange()) && (-RANGEDOWN <= dz) && (dz <= RANGEUP)) {
temp.push_back(character);
}
}
}
return temp;
}
template <class T>
auto CharacterContainer<T>::findAllAliveCharactersInRangeOf(const position &pos, int distancemetric) const -> std::vector<pointer> {
std::vector<pointer> temp;
auto candidates = projection_x_axis(pos,distancemetric);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (((abs(dx) + abs(dy) <= distancemetric) || (distancemetric==1 && abs(dx)==1 && abs(dy)==1)) && (-RANGEDOWN <= dz) && (dz <= RANGEUP)) {
if (auto character=find(id))
if (character->isAlive())
temp.push_back(character);
}
}
return temp;
}
template <class T>
auto CharacterContainer<T>::findAllAliveCharactersInRangeOfOnSameMap(const position &pos, int distancemetric) const -> std::vector<pointer> {
std::vector<pointer> temp;
auto candidates = projection_x_axis(pos,distancemetric);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (((abs(dx) + abs(dy) <= distancemetric) || (distancemetric==1 && abs(dx)==1 && abs(dy)==1)) && (-RANGEDOWN <= dz) && (dz <= RANGEUP)) {
if (auto character=find(id))
if (character->isAlive())
temp.push_back(character);
}
}
return temp;
}
template <class T>
bool CharacterContainer<T>::findAllCharactersWithXInRangeOf(short int startx, short int endx, std::vector<pointer> &ret) const {
bool found_one = false;
int r = (endx-startx)/2+1;
int x = startx + (endx-startx)/2;
auto candidates = projection_x_axis(position(x,0,0),r);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
if ((p.x >= startx) && (p.x <= endx)) {
if (auto character=find(id))
ret.push_back(character);
}
}
return found_one;
}
template class CharacterContainer<Character>;
template class CharacterContainer<Player>;
template class CharacterContainer<Monster>;
template class CharacterContainer<NPC>;
|
// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// illarionserver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include <map>
#include <unordered_map>
#include "globals.hpp"
#include "CharacterContainer.hpp"
#include "Player.hpp"
#include "Monster.hpp"
#include "NPC.hpp"
template <class T>
bool CharacterContainer<T>::getPosition(TYPE_OF_CHARACTER_ID id,position& pos) {
auto i = container.find(id);
if (i!=container.end()) {
pos = (i->second)->getPosition();
return true;
} else {
return false;
}
}
template <class T>
iterator_range<typename CharacterContainer<T>::position_to_id_type::const_iterator> CharacterContainer<T>::projection_x_axis(const position& pos, int r) const {
return {{position_to_id.upper_bound(position(pos.x-r-1,0,0)),position_to_id.upper_bound(position(pos.x+r+1,0,0))}};
}
template <class T>
auto CharacterContainer<T>::find(const std::string &text) const -> pointer {
try {
auto id = boost::lexical_cast<TYPE_OF_CHARACTER_ID>(text);
return find(id);
} catch (boost::bad_lexical_cast &) {
for (const auto &character : container) {
if (comparestrings_nocase(character.second->getName(), text)) {
return character.second;
}
}
}
return nullptr;
}
template <class T>
auto CharacterContainer<T>::find(TYPE_OF_CHARACTER_ID id) const -> pointer {
const auto it = container.find(id);
if (it != container.end()) {
return it->second;
}
return nullptr;
}
template <class T>
auto CharacterContainer<T>::find(const position &pos) const -> pointer {
const auto i = position_to_id.find(pos);
if (i!=position_to_id.end()) {
return find(i->second);
}
return nullptr;
}
template <class T>
void CharacterContainer<T>::update(pointer p, const position& newPosition) {
const auto id = p->getId();
if (!find(id)) {
return;
}
const auto &oldPosition = p->getPosition();
const auto range = position_to_id.equal_range(oldPosition);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == id) {
position_to_id.erase(it);
position_to_id.insert(std::make_pair(newPosition, id));
return;
}
}
}
template <class T>
bool CharacterContainer<T>::erase(TYPE_OF_CHARACTER_ID id) {
position pos;
if (getPosition(id, pos)) {
const auto range = position_to_id.equal_range(pos);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == id) {
position_to_id.erase(it);
break;
}
}
}
return container.erase(id) > 0;
}
template <class T>
auto CharacterContainer<T>::findAllCharactersInRangeOf(const position &pos, int distancemetric) const -> std::vector<pointer> {
std::vector<pointer> temp;
auto candidates = projection_x_axis(pos,distancemetric);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (abs(dx) <= distancemetric && abs(dy) <= distancemetric && -RANGEDOWN <= dz && dz <= RANGEUP) {
if (auto character=find(id)) temp.push_back(character);
}
}
return temp;
}
template <class T>
auto CharacterContainer<T>::findAllCharactersInScreen(const position &pos) const -> std::vector<pointer> {
std::vector<pointer> temp;
const int MAX_SCREEN_RANGE = 30;
auto candidates = projection_x_axis(pos,MAX_SCREEN_RANGE);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (auto character=find(id)) {
if ((abs(dx) + abs(dy) <= character->getScreenRange()) && (-RANGEDOWN <= dz) && (dz <= RANGEUP)) {
temp.push_back(character);
}
}
}
return temp;
}
template <class T>
auto CharacterContainer<T>::findAllAliveCharactersInRangeOf(const position &pos, int distancemetric) const -> std::vector<pointer> {
std::vector<pointer> temp;
auto candidates = projection_x_axis(pos,distancemetric);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (abs(dx) <= distancemetric && abs(dy) <= distancemetric && -RANGEDOWN <= dz && dz <= RANGEUP) {
if (auto character=find(id))
if (character->isAlive())
temp.push_back(character);
}
}
return temp;
}
template <class T>
auto CharacterContainer<T>::findAllAliveCharactersInRangeOfOnSameMap(const position &pos, int distancemetric) const -> std::vector<pointer> {
std::vector<pointer> temp;
auto candidates = projection_x_axis(pos,distancemetric);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
short int dx = p.x - pos.x;
short int dy = p.y - pos.y;
short int dz = p.z - pos.z;
if (abs(dx) <= distancemetric && abs(dy) <= distancemetric && -RANGEDOWN <= dz && dz <= RANGEUP) {
if (auto character=find(id))
if (character->isAlive())
temp.push_back(character);
}
}
return temp;
}
template <class T>
bool CharacterContainer<T>::findAllCharactersWithXInRangeOf(short int startx, short int endx, std::vector<pointer> &ret) const {
bool found_one = false;
int r = (endx-startx)/2+1;
int x = startx + (endx-startx)/2;
auto candidates = projection_x_axis(position(x,0,0),r);
for (auto& c : candidates) {
const position& p = c.first;
TYPE_OF_CHARACTER_ID id = c.second;
if ((p.x >= startx) && (p.x <= endx)) {
if (auto character=find(id))
ret.push_back(character);
}
}
return found_one;
}
template class CharacterContainer<Character>;
template class CharacterContainer<Player>;
template class CharacterContainer<Monster>;
template class CharacterContainer<NPC>;
|
Use maximum norm for range checks
|
Use maximum norm for range checks
Characters can move diagonally now, so it makes more sense to use
the maximum norm for e.g. fighting.
|
C++
|
agpl-3.0
|
Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server
|
349c93e9ad1d4152417f7fadfad89b3c78e9ee30
|
worker/src/RTC/RTCP/CompoundPacket.cpp
|
worker/src/RTC/RTCP/CompoundPacket.cpp
|
#define MS_CLASS "RTC::RTCP::CompoundPacket"
// #define MS_LOG_DEV
#include "RTC/RTCP/CompoundPacket.hpp"
#include "Logger.hpp"
namespace RTC
{
namespace RTCP
{
/* Instance methods. */
void CompoundPacket::Serialize(uint8_t* data)
{
MS_TRACE();
this->header = data;
// Calculate the total required size for the entire message.
if (HasSenderReport())
{
this->size = this->senderReportPacket.GetSize();
if (this->receiverReportPacket.GetCount() != 0u)
{
this->size += sizeof(ReceiverReport::Header) * this->receiverReportPacket.GetCount();
}
}
// If no sender nor receiver reports are present send an empty Receiver Report
// packet as the head of the compound packet.
else
{
this->size = this->receiverReportPacket.GetSize();
}
if (this->sdesPacket.GetCount() != 0u)
this->size += this->sdesPacket.GetSize();
if (this->xrPacket.Begin() != this->xrPacket.End())
this->size += this->xrPacket.GetSize();
// Fill it.
size_t offset{ 0 };
if (HasSenderReport())
{
this->senderReportPacket.Serialize(this->header);
offset = this->senderReportPacket.GetSize();
// Fix header count field.
auto* header = reinterpret_cast<Packet::CommonHeader*>(this->header);
header->count = 0;
if (this->receiverReportPacket.GetCount() != 0u)
{
// Fix header length field.
size_t length =
((sizeof(SenderReport::Header) +
(sizeof(ReceiverReport::Header) * this->receiverReportPacket.GetCount())) /
4);
header->length = uint16_t{ htons(length) };
// Fix header count field.
header->count = this->receiverReportPacket.GetCount();
auto it = this->receiverReportPacket.Begin();
for (; it != this->receiverReportPacket.End(); ++it)
{
ReceiverReport* report = (*it);
report->Serialize(this->header + offset);
offset += sizeof(ReceiverReport::Header);
}
}
}
else
{
this->receiverReportPacket.Serialize(this->header);
offset = this->receiverReportPacket.GetSize();
}
if (this->sdesPacket.GetCount() != 0u)
offset += this->sdesPacket.Serialize(this->header + offset);
if (this->xrPacket.Begin() != this->xrPacket.End())
offset += this->xrPacket.Serialize(this->header + offset);
}
void CompoundPacket::Dump()
{
MS_TRACE();
MS_DUMP("<CompoundPacket>");
if (HasSenderReport())
{
this->senderReportPacket.Dump();
if (this->receiverReportPacket.GetCount() != 0u)
this->receiverReportPacket.Dump();
}
else
{
this->receiverReportPacket.Dump();
}
if (this->sdesPacket.GetCount() != 0u)
this->sdesPacket.Dump();
if (this->xrPacket.Begin() != this->xrPacket.End())
this->xrPacket.Dump();
MS_DUMP("</CompoundPacket>");
}
void CompoundPacket::AddSenderReport(SenderReport* report)
{
MS_ASSERT(!HasSenderReport(), "a Sender Report is already present");
this->senderReportPacket.AddReport(report);
}
} // namespace RTCP
} // namespace RTC
|
#define MS_CLASS "RTC::RTCP::CompoundPacket"
// #define MS_LOG_DEV
#include "RTC/RTCP/CompoundPacket.hpp"
#include "Logger.hpp"
namespace RTC
{
namespace RTCP
{
/* Instance methods. */
void CompoundPacket::Serialize(uint8_t* data)
{
MS_TRACE();
this->header = data;
// Calculate the total required size for the entire message.
if (HasSenderReport())
{
this->size = this->senderReportPacket.GetSize();
if (this->receiverReportPacket.GetCount() != 0u)
{
this->size += sizeof(ReceiverReport::Header) * this->receiverReportPacket.GetCount();
}
}
// If no sender nor receiver reports are present send an empty Receiver Report
// packet as the head of the compound packet.
else
{
this->size = this->receiverReportPacket.GetSize();
}
if (this->sdesPacket.GetCount() != 0u)
this->size += this->sdesPacket.GetSize();
if (this->xrPacket.Begin() != this->xrPacket.End())
this->size += this->xrPacket.GetSize();
// Fill it.
size_t offset{ 0 };
if (HasSenderReport())
{
this->senderReportPacket.Serialize(this->header);
offset = this->senderReportPacket.GetSize();
// Fix header count field.
auto* header = reinterpret_cast<Packet::CommonHeader*>(this->header);
header->count = 0;
if (this->receiverReportPacket.GetCount() != 0u)
{
// Fix header length field.
size_t length =
((sizeof(SenderReport::Header) +
(sizeof(ReceiverReport::Header) * this->receiverReportPacket.GetCount())) /
4);
header->length = uint16_t{ htons(length) };
// Fix header count field.
header->count = this->receiverReportPacket.GetCount();
auto it = this->receiverReportPacket.Begin();
for (; it != this->receiverReportPacket.End(); ++it)
{
ReceiverReport* report = (*it);
report->Serialize(this->header + offset);
offset += sizeof(ReceiverReport::Header);
}
}
}
else
{
this->receiverReportPacket.Serialize(this->header);
offset = this->receiverReportPacket.GetSize();
}
if (this->sdesPacket.GetCount() != 0u)
offset += this->sdesPacket.Serialize(this->header + offset);
if (this->xrPacket.Begin() != this->xrPacket.End())
this->xrPacket.Serialize(this->header + offset);
}
void CompoundPacket::Dump()
{
MS_TRACE();
MS_DUMP("<CompoundPacket>");
if (HasSenderReport())
{
this->senderReportPacket.Dump();
if (this->receiverReportPacket.GetCount() != 0u)
this->receiverReportPacket.Dump();
}
else
{
this->receiverReportPacket.Dump();
}
if (this->sdesPacket.GetCount() != 0u)
this->sdesPacket.Dump();
if (this->xrPacket.Begin() != this->xrPacket.End())
this->xrPacket.Dump();
MS_DUMP("</CompoundPacket>");
}
void CompoundPacket::AddSenderReport(SenderReport* report)
{
MS_ASSERT(!HasSenderReport(), "a Sender Report is already present");
this->senderReportPacket.AddReport(report);
}
} // namespace RTCP
} // namespace RTC
|
Make clang-tidy happy
|
Make clang-tidy happy
|
C++
|
isc
|
ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup,ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,ibc/MediaSoup,versatica/mediasoup
|
facc95a87b4247c53eeb7838dff9b02d60f29fa2
|
gm/imagefiltersgraph.cpp
|
gm/imagefiltersgraph.cpp
|
/*
* 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 "gm.h"
#include "SkBitmapSource.h"
#include "SkBlurImageFilter.h"
#include "SkMorphologyImageFilter.h"
#include "SkTestImageFilters.h"
///////////////////////////////////////////////////////////////////////////////
class ImageFiltersGraphGM : public skiagm::GM {
public:
ImageFiltersGraphGM() : fInitialized(false) {}
protected:
virtual SkString onShortName() {
return SkString("imagefiltersgraph");
}
void make_bitmap() {
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
fBitmap.allocPixels();
SkDevice device(fBitmap);
SkCanvas canvas(&device);
canvas.clear(0x00000000);
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(0xFFFFFFFF);
paint.setTextSize(SkIntToScalar(96));
const char* str = "e";
canvas.drawText(str, strlen(str), SkIntToScalar(20), SkIntToScalar(70), paint);
}
virtual SkISize onISize() { return SkISize::Make(500, 500); }
virtual void onDraw(SkCanvas* canvas) {
if (!fInitialized) {
this->make_bitmap();
fInitialized = true;
}
canvas->clear(0x00000000);
SkAutoTUnref<SkImageFilter> bitmapSource(new SkBitmapSource(fBitmap));
SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(SK_ColorRED,
SkXfermode::kSrcIn_Mode));
SkAutoTUnref<SkImageFilter> blur(new SkBlurImageFilter(4.0f, 4.0f, bitmapSource));
SkAutoTUnref<SkImageFilter> erode(new SkErodeImageFilter(4, 4, blur));
SkAutoTUnref<SkImageFilter> color(new SkColorFilterImageFilter(cf, erode));
SkAutoTUnref<SkImageFilter> merge(new SkMergeImageFilter(blur, color));
SkPaint paint;
paint.setImageFilter(merge);
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
SkBitmap fBitmap;
bool fInitialized;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory(void*) { return new ImageFiltersGraphGM; }
static skiagm::GMRegistry reg(MyFactory);
|
/*
* 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 "gm.h"
#include "SkBitmapSource.h"
#include "SkBlurImageFilter.h"
#include "SkMorphologyImageFilter.h"
#include "SkTestImageFilters.h"
///////////////////////////////////////////////////////////////////////////////
class ImageFiltersGraphGM : public skiagm::GM {
public:
ImageFiltersGraphGM() : fInitialized(false) {}
protected:
#ifdef SK_BUILD_FOR_ANDROID
// This test is currently broken when using pipe on Android
virtual uint32_t onGetFlags() const SK_OVERRIDE {
return this->INHERITED::onGetFlags() | skiagm::GM::kSkipPipe_Flag;
}
#endif
virtual SkString onShortName() {
return SkString("imagefiltersgraph");
}
void make_bitmap() {
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
fBitmap.allocPixels();
SkDevice device(fBitmap);
SkCanvas canvas(&device);
canvas.clear(0x00000000);
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(0xFFFFFFFF);
paint.setTextSize(SkIntToScalar(96));
const char* str = "e";
canvas.drawText(str, strlen(str), SkIntToScalar(20), SkIntToScalar(70), paint);
}
virtual SkISize onISize() { return SkISize::Make(500, 500); }
virtual void onDraw(SkCanvas* canvas) {
if (!fInitialized) {
this->make_bitmap();
fInitialized = true;
}
canvas->clear(0x00000000);
SkAutoTUnref<SkImageFilter> bitmapSource(new SkBitmapSource(fBitmap));
SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(SK_ColorRED,
SkXfermode::kSrcIn_Mode));
SkAutoTUnref<SkImageFilter> blur(new SkBlurImageFilter(4.0f, 4.0f, bitmapSource));
SkAutoTUnref<SkImageFilter> erode(new SkErodeImageFilter(4, 4, blur));
SkAutoTUnref<SkImageFilter> color(new SkColorFilterImageFilter(cf, erode));
SkAutoTUnref<SkImageFilter> merge(new SkMergeImageFilter(blur, color));
SkPaint paint;
paint.setImageFilter(merge);
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
SkBitmap fBitmap;
bool fInitialized;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory(void*) { return new ImageFiltersGraphGM; }
static skiagm::GMRegistry reg(MyFactory);
|
Disable imagefiltersgraph from running through pipe on android
|
Disable imagefiltersgraph from running through pipe on android
While we figure out what the problem is.
Review URL: https://codereview.appspot.com/6441164
git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@5193 2bbb7eff-a529-9590-31e7-b0007b416f81
|
C++
|
bsd-3-clause
|
mydongistiny/android_external_skia,mozilla-b2g/external_skia,Igalia/skia,ominux/skia,wildermason/external_skia,MinimalOS/external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,MyAOSP/external_chromium_org_third_party_skia,AOSPU/external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,temasek/android_external_skia,mmatyas/skia,MIPS/external-chromium_org-third_party-skia,TeslaProject/external_skia,todotodoo/skia,MinimalOS/external_skia,MinimalOS-AOSP/platform_external_skia,nvoron23/skia,AOSPA-L/android_external_skia,temasek/android_external_skia,TeamEOS/external_skia,jtg-gg/skia,Hybrid-Rom/external_skia,aosp-mirror/platform_external_skia,RadonX-ROM/external_skia,Hikari-no-Tenshi/android_external_skia,zhaochengw/platform_external_skia,AndroidOpenDevelopment/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,vvuk/skia,Infinitive-OS/platform_external_skia,sombree/android_external_skia,mydongistiny/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,Infusion-OS/android_external_skia,spezi77/android_external_skia,MinimalOS/android_external_skia,F-AOSP/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,boulzordev/android_external_skia,AOSPB/external_skia,SlimSaber/android_external_skia,amyvmiwei/skia,Samsung/skia,TeslaProject/external_skia,vvuk/skia,TeslaOS/android_external_skia,ominux/skia,VentureROM-L/android_external_skia,geekboxzone/mmallow_external_skia,Purity-Lollipop/platform_external_skia,mmatyas/skia,YUPlayGodDev/platform_external_skia,Purity-Lollipop/platform_external_skia,Igalia/skia,VentureROM-L/android_external_skia,MIPS/external-chromium_org-third_party-skia,nfxosp/platform_external_skia,jtg-gg/skia,HalCanary/skia-hc,invisiblek/android_external_skia,Jichao/skia,GladeRom/android_external_skia,google/skia,Igalia/skia,samuelig/skia,DesolationStaging/android_external_skia,android-ia/platform_external_skia,sombree/android_external_skia,DiamondLovesYou/skia-sys,sigysmund/platform_external_skia,DARKPOP/external_chromium_org_third_party_skia,aospo/platform_external_skia,Infusion-OS/android_external_skia,Plain-Andy/android_platform_external_skia,sigysmund/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,MinimalOS/external_skia,byterom/android_external_skia,TeamEOS/external_skia,ctiao/platform-external-skia,AOSPA-L/android_external_skia,AsteroidOS/android_external_skia,TeamBliss-LP/android_external_skia,rubenvb/skia,ench0/external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,Omegaphora/external_skia,pcwalton/skia,zhaochengw/platform_external_skia,nox/skia,MarshedOut/android_external_skia,pcwalton/skia,houst0nn/external_skia,F-AOSP/platform_external_skia,TeamExodus/external_skia,DesolationStaging/android_external_skia,MIPS/external-chromium_org-third_party-skia,Purity-Lollipop/platform_external_skia,DesolationStaging/android_external_skia,VRToxin-AOSP/android_external_skia,AOSPB/external_skia,larsbergstrom/skia,mmatyas/skia,FusionSP/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,temasek/android_external_skia,BrokenROM/external_skia,qrealka/skia-hc,Tesla-Redux/android_external_skia,sudosurootdev/external_skia,DiamondLovesYou/skia-sys,ominux/skia,AOSPU/external_chromium_org_third_party_skia,jtg-gg/skia,Infinitive-OS/platform_external_skia,larsbergstrom/skia,rubenvb/skia,pcwalton/skia,MinimalOS/android_external_skia,Infinitive-OS/platform_external_skia,Igalia/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,FusionSP/android_external_skia,geekboxzone/mmallow_external_skia,suyouxin/android_external_skia,Euphoria-OS-Legacy/android_external_skia,shahrzadmn/skia,VRToxin-AOSP/android_external_skia,HalCanary/skia-hc,timduru/platform-external-skia,Fusion-Rom/external_chromium_org_third_party_skia,TeamTwisted/external_skia,ench0/external_chromium_org_third_party_skia,OneRom/external_skia,Jichao/skia,OptiPop/external_skia,Plain-Andy/android_platform_external_skia,nox/skia,google/skia,OptiPop/external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,sudosurootdev/external_skia,OptiPop/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,scroggo/skia,MIPS/external-chromium_org-third_party-skia,OneRom/external_skia,YUPlayGodDev/platform_external_skia,Infusion-OS/android_external_skia,timduru/platform-external-skia,shahrzadmn/skia,Pure-Aosp/android_external_skia,MIPS/external-chromium_org-third_party-skia,xzzz9097/android_external_skia,OptiPop/external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,sudosurootdev/external_skia,BrokenROM/external_skia,mydongistiny/external_chromium_org_third_party_skia,OneRom/external_skia,Jichao/skia,todotodoo/skia,UBERMALLOW/external_skia,Infinitive-OS/platform_external_skia,w3nd1go/android_external_skia,ominux/skia,mydongistiny/external_chromium_org_third_party_skia,AOSPU/external_chromium_org_third_party_skia,google/skia,MinimalOS/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,Omegaphora/external_skia,geekboxzone/lollipop_external_skia,RadonX-ROM/external_skia,BrokenROM/external_skia,Infinitive-OS/platform_external_skia,scroggo/skia,MinimalOS/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,F-AOSP/platform_external_skia,F-AOSP/platform_external_skia,MonkeyZZZZ/platform_external_skia,fire855/android_external_skia,zhaochengw/platform_external_skia,rubenvb/skia,DARKPOP/external_chromium_org_third_party_skia,akiss77/skia,vanish87/skia,w3nd1go/android_external_skia,ench0/external_skia,noselhq/skia,fire855/android_external_skia,android-ia/platform_external_skia,Hybrid-Rom/external_skia,chenlian2015/skia_from_google,chenlian2015/skia_from_google,AsteroidOS/android_external_skia,AOSPB/external_skia,noselhq/skia,Igalia/skia,AOSPB/external_skia,MinimalOS/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,ench0/external_skia,invisiblek/android_external_skia,Hikari-no-Tenshi/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,ench0/external_skia,boulzordev/android_external_skia,AOSP-YU/platform_external_skia,noselhq/skia,VRToxin-AOSP/android_external_skia,SlimSaber/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,akiss77/skia,TeslaProject/external_skia,DiamondLovesYou/skia-sys,qrealka/skia-hc,mydongistiny/external_chromium_org_third_party_skia,wildermason/external_skia,temasek/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,OneRom/external_skia,vvuk/skia,Tesla-Redux/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,codeaurora-unoffical/platform-external-skia,geekboxzone/mmallow_external_skia,aospo/platform_external_skia,AOSP-YU/platform_external_skia,PAC-ROM/android_external_skia,Android-AOSP/external_skia,byterom/android_external_skia,nvoron23/skia,houst0nn/external_skia,android-ia/platform_external_chromium_org_third_party_skia,byterom/android_external_skia,aospo/platform_external_skia,HalCanary/skia-hc,Purity-Lollipop/platform_external_skia,F-AOSP/platform_external_skia,OptiPop/external_skia,nvoron23/skia,tmpvar/skia.cc,shahrzadmn/skia,AOSPA-L/android_external_skia,nfxosp/platform_external_skia,Asteroid-Project/android_external_skia,nox/skia,BrokenROM/external_skia,noselhq/skia,zhaochengw/platform_external_skia,ctiao/platform-external-skia,pcwalton/skia,mmatyas/skia,aosp-mirror/platform_external_skia,TeamEOS/external_chromium_org_third_party_skia,scroggo/skia,AOSPB/external_skia,OptiPop/external_chromium_org_third_party_skia,Omegaphora/external_chromium_org_third_party_skia,Fusion-Rom/android_external_skia,codeaurora-unoffical/platform-external-skia,OptiPop/external_skia,mozilla-b2g/external_skia,Omegaphora/external_chromium_org_third_party_skia,Jichao/skia,mydongistiny/android_external_skia,tmpvar/skia.cc,DiamondLovesYou/skia-sys,Khaon/android_external_skia,sigysmund/platform_external_skia,MarshedOut/android_external_skia,DesolationStaging/android_external_skia,AOSP-YU/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,akiss77/skia,YUPlayGodDev/platform_external_skia,Purity-Lollipop/platform_external_skia,larsbergstrom/skia,ench0/external_chromium_org_third_party_skia,Fusion-Rom/android_external_skia,geekboxzone/lollipop_external_skia,Infusion-OS/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,jtg-gg/skia,spezi77/android_external_skia,MinimalOS/external_skia,VentureROM-L/android_external_skia,vanish87/skia,vvuk/skia,timduru/platform-external-skia,larsbergstrom/skia,FusionSP/external_chromium_org_third_party_skia,mydongistiny/android_external_skia,byterom/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,TeamEOS/external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,FusionSP/external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,Hikari-no-Tenshi/android_external_skia,w3nd1go/android_external_skia,wildermason/external_skia,TeamBliss-LP/android_external_skia,ctiao/platform-external-skia,Android-AOSP/external_skia,Pure-Aosp/android_external_skia,PAC-ROM/android_external_skia,nox/skia,MyAOSP/external_chromium_org_third_party_skia,TeamExodus/external_skia,nox/skia,InfinitiveOS/external_skia,MinimalOS/external_skia,zhaochengw/platform_external_skia,ench0/external_skia,xzzz9097/android_external_skia,sigysmund/platform_external_skia,invisiblek/android_external_skia,Fusion-Rom/android_external_skia,rubenvb/skia,vanish87/skia,invisiblek/android_external_skia,VentureROM-L/android_external_skia,TeamExodus/external_skia,fire855/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,ench0/external_skia,temasek/android_external_skia,HealthyHoney/temasek_SKIA,FusionSP/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,MinimalOS/android_external_skia,spezi77/android_external_skia,RadonX-ROM/external_skia,aosp-mirror/platform_external_skia,pcwalton/skia,mydongistiny/external_chromium_org_third_party_skia,spezi77/android_external_skia,sudosurootdev/external_skia,Fusion-Rom/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,nfxosp/platform_external_skia,suyouxin/android_external_skia,amyvmiwei/skia,Infusion-OS/android_external_skia,TeamTwisted/external_skia,OneRom/external_skia,UBERMALLOW/external_skia,Samsung/skia,Infinitive-OS/platform_external_skia,InfinitiveOS/external_skia,Asteroid-Project/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,mydongistiny/android_external_skia,shahrzadmn/skia,houst0nn/external_skia,AndroidOpenDevelopment/android_external_skia,pcwalton/skia,F-AOSP/platform_external_skia,scroggo/skia,Fusion-Rom/external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,AOSPU/external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,Jichao/skia,boulzordev/android_external_skia,aospo/platform_external_skia,samuelig/skia,Euphoria-OS-Legacy/android_external_skia,amyvmiwei/skia,Purity-Lollipop/platform_external_skia,mmatyas/skia,MonkeyZZZZ/platform_external_skia,AOSPU/external_chromium_org_third_party_skia,boulzordev/android_external_skia,sudosurootdev/external_skia,google/skia,TeamBliss-LP/android_external_skia,google/skia,vanish87/skia,sigysmund/platform_external_skia,vvuk/skia,DesolationStaging/android_external_skia,fire855/android_external_skia,scroggo/skia,xzzz9097/android_external_skia,HalCanary/skia-hc,CyanogenMod/android_external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,TeamTwisted/external_skia,chenlian2015/skia_from_google,TeslaOS/android_external_skia,UBERMALLOW/external_skia,wildermason/external_skia,BrokenROM/external_skia,Omegaphora/external_skia,TeamBliss-LP/android_external_skia,Android-AOSP/external_skia,OptiPop/external_skia,Tesla-Redux/android_external_skia,Fusion-Rom/android_external_skia,vanish87/skia,byterom/android_external_skia,geekboxzone/mmallow_external_skia,pacerom/external_skia,TeamTwisted/external_skia,AsteroidOS/android_external_skia,MarshedOut/android_external_skia,DesolationStaging/android_external_skia,scroggo/skia,Hybrid-Rom/external_skia,nvoron23/skia,TeamTwisted/external_skia,android-ia/platform_external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,AndroidOpenDevelopment/android_external_skia,Khaon/android_external_skia,mozilla-b2g/external_skia,fire855/android_external_skia,AOSPA-L/android_external_skia,temasek/android_external_skia,OptiPop/external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,Plain-Andy/android_platform_external_skia,FusionSP/external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,MIPS/external-chromium_org-third_party-skia,tmpvar/skia.cc,MonkeyZZZZ/platform_external_skia,Hikari-no-Tenshi/android_external_skia,PAC-ROM/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,qrealka/skia-hc,DARKPOP/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,android-ia/platform_external_skia,chenlian2015/skia_from_google,VRToxin-AOSP/android_external_skia,TeslaProject/external_skia,Pure-Aosp/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,nvoron23/skia,w3nd1go/android_external_skia,geekboxzone/lollipop_external_skia,VentureROM-L/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,MinimalOS/external_skia,NamelessRom/android_external_skia,temasek/android_external_skia,AsteroidOS/android_external_skia,samuelig/skia,w3nd1go/android_external_skia,GladeRom/android_external_skia,MinimalOS-AOSP/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,rubenvb/skia,nox/skia,Infusion-OS/android_external_skia,SlimSaber/android_external_skia,TeslaProject/external_skia,nvoron23/skia,Fusion-Rom/android_external_skia,OneRom/external_skia,nox/skia,ominux/skia,TeamEOS/external_skia,nfxosp/platform_external_skia,Igalia/skia,larsbergstrom/skia,xin3liang/platform_external_chromium_org_third_party_skia,larsbergstrom/skia,TeamExodus/external_skia,Asteroid-Project/android_external_skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,AOSP-YU/platform_external_skia,AOSPU/external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,ominux/skia,zhaochengw/platform_external_skia,sombree/android_external_skia,MonkeyZZZZ/platform_external_skia,xzzz9097/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,MarshedOut/android_external_skia,HealthyHoney/temasek_SKIA,Samsung/skia,MinimalOS/android_external_chromium_org_third_party_skia,TeslaProject/external_skia,jtg-gg/skia,NamelessRom/android_external_skia,akiss77/skia,PAC-ROM/android_external_skia,MonkeyZZZZ/platform_external_skia,qrealka/skia-hc,AOSPA-L/android_external_skia,BrokenROM/external_skia,Khaon/android_external_skia,TeamEOS/external_skia,MarshedOut/android_external_skia,MinimalOS/external_skia,AOSPB/external_skia,noselhq/skia,MinimalOS/android_external_skia,todotodoo/skia,samuelig/skia,Omegaphora/external_skia,codeaurora-unoffical/platform-external-skia,pacerom/external_skia,nvoron23/skia,geekboxzone/lollipop_external_skia,mozilla-b2g/external_skia,Infinitive-OS/platform_external_skia,SlimSaber/android_external_skia,geekboxzone/mmallow_external_skia,AOSPA-L/android_external_skia,samuelig/skia,Omegaphora/external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,TeamBliss-LP/android_external_skia,VentureROM-L/android_external_skia,TeslaOS/android_external_skia,timduru/platform-external-skia,NamelessRom/android_external_skia,AOSP-YU/platform_external_skia,Pure-Aosp/android_external_skia,larsbergstrom/skia,vvuk/skia,Fusion-Rom/external_chromium_org_third_party_skia,FusionSP/android_external_skia,pcwalton/skia,InfinitiveOS/external_skia,Euphoria-OS-Legacy/android_external_skia,wildermason/external_skia,geekboxzone/lollipop_external_skia,ench0/external_skia,nfxosp/platform_external_skia,DiamondLovesYou/skia-sys,amyvmiwei/skia,CyanogenMod/android_external_chromium_org_third_party_skia,Pure-Aosp/android_external_skia,qrealka/skia-hc,todotodoo/skia,InfinitiveOS/external_skia,OptiPop/external_skia,F-AOSP/platform_external_skia,Omegaphora/external_skia,TeamTwisted/external_skia,TeamTwisted/external_skia,Jichao/skia,RadonX-ROM/external_skia,Hybrid-Rom/external_skia,rubenvb/skia,MIPS/external-chromium_org-third_party-skia,CyanogenMod/android_external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,rubenvb/skia,todotodoo/skia,google/skia,YUPlayGodDev/platform_external_skia,SlimSaber/android_external_skia,TeslaOS/android_external_skia,pacerom/external_skia,rubenvb/skia,Khaon/android_external_skia,Jichao/skia,sigysmund/platform_external_skia,invisiblek/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,mydongistiny/android_external_skia,houst0nn/external_skia,noselhq/skia,CyanogenMod/android_external_chromium_org_third_party_skia,Jichao/skia,todotodoo/skia,pacerom/external_skia,Tesla-Redux/android_external_skia,nfxosp/platform_external_skia,suyouxin/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,FusionSP/android_external_skia,SlimSaber/android_external_skia,TeamExodus/external_skia,AOSPB/external_skia,google/skia,samuelig/skia,vvuk/skia,tmpvar/skia.cc,GladeRom/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,Omegaphora/external_skia,larsbergstrom/skia,geekboxzone/lollipop_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,HalCanary/skia-hc,zhaochengw/platform_external_skia,MinimalOS-AOSP/platform_external_skia,codeaurora-unoffical/platform-external-skia,Android-AOSP/external_skia,nvoron23/skia,codeaurora-unoffical/platform-external-skia,GladeRom/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,FusionSP/android_external_skia,pcwalton/skia,android-ia/platform_external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,Samsung/skia,TeamTwisted/external_skia,aospo/platform_external_skia,AOSPB/external_skia,MinimalOS/android_external_skia,suyouxin/android_external_skia,AndroidOpenDevelopment/android_external_skia,SlimSaber/android_external_skia,mozilla-b2g/external_skia,TeamEOS/external_skia,Plain-Andy/android_platform_external_skia,MarshedOut/android_external_skia,nfxosp/platform_external_skia,Tesla-Redux/android_external_skia,mydongistiny/android_external_skia,wildermason/external_skia,TeamExodus/external_skia,YUPlayGodDev/platform_external_skia,Khaon/android_external_skia,chenlian2015/skia_from_google,TeamBliss-LP/android_external_skia,Purity-Lollipop/platform_external_skia,FusionSP/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,PAC-ROM/android_external_skia,MinimalOS-AOSP/platform_external_skia,MinimalOS/external_skia,TeamExodus/external_skia,MonkeyZZZZ/platform_external_skia,HealthyHoney/temasek_SKIA,google/skia,TeslaOS/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,rubenvb/skia,amyvmiwei/skia,TeamTwisted/external_skia,mozilla-b2g/external_skia,sigysmund/platform_external_skia,VentureROM-L/android_external_skia,android-ia/platform_external_skia,google/skia,FusionSP/external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,pacerom/external_skia,BrokenROM/external_skia,MinimalOS/external_chromium_org_third_party_skia,OneRom/external_skia,TeamEOS/external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,houst0nn/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,SlimSaber/android_external_skia,Android-AOSP/external_skia,suyouxin/android_external_skia,Hybrid-Rom/external_skia,wildermason/external_skia,ench0/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,mmatyas/skia,xzzz9097/android_external_skia,aosp-mirror/platform_external_skia,GladeRom/android_external_skia,ctiao/platform-external-skia,nfxosp/platform_external_skia,shahrzadmn/skia,MinimalOS/android_external_skia,UBERMALLOW/external_skia,MinimalOS-AOSP/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,Khaon/android_external_skia,FusionSP/android_external_skia,xzzz9097/android_external_skia,TeamEOS/external_skia,nox/skia,ench0/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,nfxosp/platform_external_skia,pcwalton/skia,aosp-mirror/platform_external_skia,ench0/external_chromium_org_third_party_skia,invisiblek/android_external_skia,BrokenROM/external_skia,ominux/skia,VRToxin-AOSP/android_external_skia,NamelessRom/android_external_skia,ominux/skia,NamelessRom/android_external_skia,InfinitiveOS/external_skia,aospo/platform_external_skia,GladeRom/android_external_skia,AndroidOpenDevelopment/android_external_skia,InfinitiveOS/external_skia,YUPlayGodDev/platform_external_skia,mydongistiny/external_chromium_org_third_party_skia,VentureROM-L/android_external_skia,timduru/platform-external-skia,noselhq/skia,PAC-ROM/android_external_skia,HalCanary/skia-hc,OptiPop/external_skia,MinimalOS/external_skia,byterom/android_external_skia,invisiblek/android_external_skia,Hikari-no-Tenshi/android_external_skia,spezi77/android_external_skia,invisiblek/android_external_skia,Omegaphora/external_skia,ominux/skia,w3nd1go/android_external_skia,ctiao/platform-external-skia,akiss77/skia,codeaurora-unoffical/platform-external-skia,todotodoo/skia,ctiao/platform-external-skia,scroggo/skia,Asteroid-Project/android_external_skia,vanish87/skia,ench0/external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,Pure-Aosp/android_external_skia,HalCanary/skia-hc,shahrzadmn/skia,UBERMALLOW/external_skia,boulzordev/android_external_skia,Euphoria-OS-Legacy/android_external_skia,noselhq/skia,tmpvar/skia.cc,xzzz9097/android_external_skia,xzzz9097/android_external_skia,Infusion-OS/android_external_skia,tmpvar/skia.cc,pacerom/external_skia,sombree/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,codeaurora-unoffical/platform-external-skia,jtg-gg/skia,Khaon/android_external_skia,shahrzadmn/skia,qrealka/skia-hc,amyvmiwei/skia,mmatyas/skia,houst0nn/external_skia,TeamEOS/external_skia,samuelig/skia,geekboxzone/mmallow_external_skia,UBERMALLOW/external_skia,Plain-Andy/android_platform_external_skia,byterom/android_external_skia,MinimalOS-AOSP/platform_external_skia,vvuk/skia,MonkeyZZZZ/platform_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,todotodoo/skia,aosp-mirror/platform_external_skia,qrealka/skia-hc,w3nd1go/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Fusion-Rom/android_external_skia,Tesla-Redux/android_external_skia,wildermason/external_skia,AsteroidOS/android_external_skia,ench0/external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,Igalia/skia,Hybrid-Rom/external_skia,Omegaphora/external_chromium_org_third_party_skia,tmpvar/skia.cc,mozilla-b2g/external_skia,aospo/platform_external_skia,shahrzadmn/skia,UBERMALLOW/external_skia,nox/skia,NamelessRom/android_external_skia,fire855/android_external_skia,w3nd1go/android_external_skia,AndroidOpenDevelopment/android_external_skia,ench0/external_skia,OptiPop/external_chromium_org_third_party_skia,Android-AOSP/external_skia,MonkeyZZZZ/platform_external_skia,DiamondLovesYou/skia-sys,AOSP-YU/platform_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,boulzordev/android_external_skia,vanish87/skia,HalCanary/skia-hc,PAC-ROM/android_external_skia,NamelessRom/android_external_skia,AsteroidOS/android_external_skia,sombree/android_external_skia,boulzordev/android_external_skia,Samsung/skia,akiss77/skia,NamelessRom/android_external_skia,mozilla-b2g/external_skia,android-ia/platform_external_skia,Samsung/skia,android-ia/platform_external_skia,Omegaphora/external_skia,TeamExodus/external_skia,mydongistiny/external_chromium_org_third_party_skia,TeamExodus/external_skia,amyvmiwei/skia,GladeRom/android_external_skia,MinimalOS/android_external_skia,ctiao/platform-external-skia,TeslaProject/external_skia,sudosurootdev/external_skia,FusionSP/android_external_skia,chenlian2015/skia_from_google,Samsung/skia,sombree/android_external_skia,vanish87/skia,timduru/platform-external-skia,HalCanary/skia-hc,MonkeyZZZZ/platform_external_skia,Fusion-Rom/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,sombree/android_external_skia,suyouxin/android_external_skia,HealthyHoney/temasek_SKIA,VRToxin-AOSP/android_external_skia,samuelig/skia,OneRom/external_skia,temasek/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,OneRom/external_skia,ench0/external_skia,vanish87/skia,mmatyas/skia,boulzordev/android_external_skia,Infusion-OS/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,todotodoo/skia,OptiPop/external_skia,Asteroid-Project/android_external_skia,suyouxin/android_external_skia,AOSP-YU/platform_external_skia,Pure-Aosp/android_external_skia,GladeRom/android_external_skia,mmatyas/skia,sombree/android_external_skia,DesolationStaging/android_external_skia,tmpvar/skia.cc,YUPlayGodDev/platform_external_skia,qrealka/skia-hc,scroggo/skia,fire855/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Jichao/skia,sigysmund/platform_external_skia,shahrzadmn/skia,houst0nn/external_skia,Pure-Aosp/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,akiss77/skia,Tesla-Redux/android_external_skia,zhaochengw/platform_external_skia,akiss77/skia,TeamBliss-LP/android_external_skia,HealthyHoney/temasek_SKIA,RadonX-ROM/external_skia,AOSPA-L/android_external_skia,Tesla-Redux/android_external_skia,codeaurora-unoffical/platform-external-skia,TeslaOS/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,Samsung/skia,aosp-mirror/platform_external_skia,aospo/platform_external_skia,fire855/android_external_skia,tmpvar/skia.cc,UBERMALLOW/external_skia,geekboxzone/lollipop_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,amyvmiwei/skia,xin3liang/platform_external_chromium_org_third_party_skia,larsbergstrom/skia,YUPlayGodDev/platform_external_skia,akiss77/skia,geekboxzone/mmallow_external_skia,sudosurootdev/external_skia,Fusion-Rom/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,sudosurootdev/external_skia,MinimalOS-AOSP/platform_external_skia,w3nd1go/android_external_skia,byterom/android_external_skia,timduru/platform-external-skia,vvuk/skia,mydongistiny/android_external_skia,RadonX-ROM/external_skia,AOSPU/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,TeslaProject/external_skia,Igalia/skia,Android-AOSP/external_skia,MyAOSP/external_chromium_org_third_party_skia,android-ia/platform_external_skia,android-ia/platform_external_skia,google/skia,xin3liang/platform_external_chromium_org_third_party_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Khaon/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,Plain-Andy/android_platform_external_skia,spezi77/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,AOSPB/external_skia,nvoron23/skia,jtg-gg/skia,noselhq/skia,MIPS/external-chromium_org-third_party-skia,boulzordev/android_external_skia,chenlian2015/skia_from_google,F-AOSP/platform_external_skia,pacerom/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,AOSPA-L/android_external_skia
|
34f5686c1064618eee8aaec092660d0240bd29c9
|
code/permuter/RandomPermuter.cpp
|
code/permuter/RandomPermuter.cpp
|
#include <iterator>
#include <list>
#include <numeric>
#include <vector>
#include <cassert>
#include "Permuter.h"
#include "RandomPermuter.h"
namespace fs_testing {
namespace permuter {
using std::advance;
using std::iota;
using std::list;
using std::mt19937;
using std::uniform_int_distribution;
using std::vector;
using fs_testing::utils::disk_write;
RandomPermuter::RandomPermuter() {
rand = mt19937(42);
}
RandomPermuter::RandomPermuter(vector<disk_write> *data) {
// TODO(ashmrtn): Make a flag to make it random or not.
rand = mt19937(42);
}
void RandomPermuter::init_data(vector<epoch> *data) {
}
bool RandomPermuter::gen_one_state(vector<epoch_op>& res,
PermuteTestResult &log_data) {
// Return if there are no ops to permute and generate a crash state
if (GetEpochs()->size() == 0) {
return false;
}
unsigned int total_elements = 0;
// Find how many elements we will be returning (randomly determined).
uniform_int_distribution<unsigned int> permute_epochs(1, GetEpochs()->size());
unsigned int num_epochs = permute_epochs(rand);
// Don't subtract 1 from this size so that we can send a complete epoch if we
// want.
uniform_int_distribution<unsigned int> permute_requests(1,
GetEpochs()->at(num_epochs - 1).ops.size());
unsigned int num_requests = permute_requests(rand);
if (GetEpochs()->at(num_epochs - 1).ops.size() == 0) {
num_requests = 0;
}
for (unsigned int i = 0; i < num_epochs - 1; ++i) {
total_elements += GetEpochs()->at(i).ops.size();
}
total_elements += num_requests;
res.resize(total_elements);
log_data.crash_state.resize(total_elements);
// Tell CrashMonkey the most recently seen checkpoint for the crash state
// we're generating. We can't just pull the last epoch because it could be the
// case that there's a checkpoint at the end of this disk write epoch.
// Therefore, we should determine 1. if we are writing out this entire epoch,
// and 2. if the checkpoint epoch for this disk write epoch is different than
// the checkpoint epoch of the disk write epoch before this one (indicating
// that this disk write epoch changes checkpoint epochs).
epoch *target = &GetEpochs()->at(num_epochs - 1);
epoch *prev = NULL;
if (num_epochs > 1) {
prev = &GetEpochs()->at(num_epochs - 2);
}
if (num_requests != target->ops.size()) {
log_data.last_checkpoint = (prev) ? prev->checkpoint_epoch : 0;
} else {
log_data.last_checkpoint = target->checkpoint_epoch;
}
auto curr_iter = res.begin();
for (unsigned int i = 0; i < num_epochs; ++i) {
if (GetEpochs()->at(i).overlaps || i == num_epochs - 1) {
unsigned int size =
(i != num_epochs - 1) ? GetEpochs()->at(i).ops.size() : num_requests;
auto res_end = curr_iter + size;
permute_epoch(curr_iter, res_end, GetEpochs()->at(i));
curr_iter = res_end;
} else {
// Use a for loop since vector::insert inserts new elements and we
// resized above to the exact size we will have.
// We will only ever be placing the full epoch here because the above if
// will catch the case where we place only part of an epoch.
for (auto epoch_iter = GetEpochs()->at(i).ops.begin();
epoch_iter != GetEpochs()->at(i).ops.end(); ++epoch_iter) {
*curr_iter = *epoch_iter;
++curr_iter;
}
}
}
// Messy bit to add everything to the logging data struct.
for (unsigned int i = 0; i < res.size(); ++i) {
log_data.crash_state.at(i) = res.at(i).abs_index;
}
return true;
}
void RandomPermuter::permute_epoch(
vector<epoch_op>::iterator& res_start,
vector<epoch_op>::iterator& res_end,
epoch& epoch) {
assert(distance(res_start, res_end) <= epoch.ops.size());
// Even if the number of bios we're placing is less than the number in the
// epoch, allow any bio but the barrier (if present) to be picked.
unsigned int slots = epoch.ops.size();
if (epoch.has_barrier) {
--slots;
}
// Fill the list with the empty slots, either [0, epoch.size() - 1] or
// [0, epoch.size() - 2]. Prefer a list so that removals are fast. We have
// this so that each time we pick a number we can find a bio which we haven't
// already placed.
list<unsigned int> empty_slots(slots);
iota(empty_slots.begin(), empty_slots.end(), 0);
// First case is when we are placing a subset of the bios, the second is when
// we are placing all the bios but a barrier operation is present.
while (res_start != res_end && !empty_slots.empty()) {
// Uniform distribution includes both ends, so we need to subtract 1 from
// the size.
uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1);
auto shift = empty_slots.begin();
advance(shift, uid(rand));
*res_start = epoch.ops.at(*shift);
++res_start;
empty_slots.erase(shift);
}
// We are only placing part of an epoch so we need to return here.
if (res_start == res_end) {
return;
}
assert(epoch.has_barrier);
// Place the barrier operation if it exists since the entire vector already
// exists (i.e. we won't cause extra shifting when adding the other elements).
// Decrement out count of empty slots since we have filled one.
*res_start = epoch.ops.back();
}
} // namespace permuter
} // namespace fs_testing
extern "C" fs_testing::permuter::Permuter* permuter_get_instance(
std::vector<fs_testing::utils::disk_write> *data) {
return new fs_testing::permuter::RandomPermuter(data);
}
extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) {
delete p;
}
|
#include <iterator>
#include <list>
#include <numeric>
#include <vector>
#include <cassert>
#include "Permuter.h"
#include "RandomPermuter.h"
namespace fs_testing {
namespace permuter {
using std::advance;
using std::iota;
using std::list;
using std::mt19937;
using std::uniform_int_distribution;
using std::vector;
using fs_testing::utils::disk_write;
RandomPermuter::RandomPermuter() {
rand = mt19937(42);
}
RandomPermuter::RandomPermuter(vector<disk_write> *data) {
// TODO(ashmrtn): Make a flag to make it random or not.
rand = mt19937(42);
}
void RandomPermuter::init_data(vector<epoch> *data) {
}
bool RandomPermuter::gen_one_state(vector<epoch_op>& res,
PermuteTestResult &log_data) {
// Return if there are no ops to permute and generate a crash state
if (GetEpochs()->size() == 0) {
return false;
}
unsigned int total_elements = 0;
// Find how many elements we will be returning (randomly determined).
uniform_int_distribution<unsigned int> permute_epochs(1, GetEpochs()->size());
unsigned int num_epochs = permute_epochs(rand);
// Don't subtract 1 from this size so that we can send a complete epoch if we
// want.
uniform_int_distribution<unsigned int> permute_requests(1,
GetEpochs()->at(num_epochs - 1).ops.size());
unsigned int num_requests = permute_requests(rand);
// If the last epoch has zero ops, we set num_requests to zero instead of a
// garbage value returned by permute_requests(rand)
if (GetEpochs()->at(num_epochs - 1).ops.size() == 0) {
num_requests = 0;
}
for (unsigned int i = 0; i < num_epochs - 1; ++i) {
total_elements += GetEpochs()->at(i).ops.size();
}
total_elements += num_requests;
res.resize(total_elements);
log_data.crash_state.resize(total_elements);
// Tell CrashMonkey the most recently seen checkpoint for the crash state
// we're generating. We can't just pull the last epoch because it could be the
// case that there's a checkpoint at the end of this disk write epoch.
// Therefore, we should determine 1. if we are writing out this entire epoch,
// and 2. if the checkpoint epoch for this disk write epoch is different than
// the checkpoint epoch of the disk write epoch before this one (indicating
// that this disk write epoch changes checkpoint epochs).
epoch *target = &GetEpochs()->at(num_epochs - 1);
epoch *prev = NULL;
if (num_epochs > 1) {
prev = &GetEpochs()->at(num_epochs - 2);
}
if (num_requests != target->ops.size()) {
log_data.last_checkpoint = (prev) ? prev->checkpoint_epoch : 0;
} else {
log_data.last_checkpoint = target->checkpoint_epoch;
}
auto curr_iter = res.begin();
for (unsigned int i = 0; i < num_epochs; ++i) {
if (GetEpochs()->at(i).overlaps || i == num_epochs - 1) {
unsigned int size =
(i != num_epochs - 1) ? GetEpochs()->at(i).ops.size() : num_requests;
auto res_end = curr_iter + size;
permute_epoch(curr_iter, res_end, GetEpochs()->at(i));
curr_iter = res_end;
} else {
// Use a for loop since vector::insert inserts new elements and we
// resized above to the exact size we will have.
// We will only ever be placing the full epoch here because the above if
// will catch the case where we place only part of an epoch.
for (auto epoch_iter = GetEpochs()->at(i).ops.begin();
epoch_iter != GetEpochs()->at(i).ops.end(); ++epoch_iter) {
*curr_iter = *epoch_iter;
++curr_iter;
}
}
}
// Messy bit to add everything to the logging data struct.
for (unsigned int i = 0; i < res.size(); ++i) {
log_data.crash_state.at(i) = res.at(i).abs_index;
}
return true;
}
void RandomPermuter::permute_epoch(
vector<epoch_op>::iterator& res_start,
vector<epoch_op>::iterator& res_end,
epoch& epoch) {
assert(distance(res_start, res_end) <= epoch.ops.size());
// Even if the number of bios we're placing is less than the number in the
// epoch, allow any bio but the barrier (if present) to be picked.
unsigned int slots = epoch.ops.size();
if (epoch.has_barrier) {
--slots;
}
// Fill the list with the empty slots, either [0, epoch.size() - 1] or
// [0, epoch.size() - 2]. Prefer a list so that removals are fast. We have
// this so that each time we pick a number we can find a bio which we haven't
// already placed.
list<unsigned int> empty_slots(slots);
iota(empty_slots.begin(), empty_slots.end(), 0);
// First case is when we are placing a subset of the bios, the second is when
// we are placing all the bios but a barrier operation is present.
while (res_start != res_end && !empty_slots.empty()) {
// Uniform distribution includes both ends, so we need to subtract 1 from
// the size.
uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1);
auto shift = empty_slots.begin();
advance(shift, uid(rand));
*res_start = epoch.ops.at(*shift);
++res_start;
empty_slots.erase(shift);
}
// We are only placing part of an epoch so we need to return here.
if (res_start == res_end) {
return;
}
assert(epoch.has_barrier);
// Place the barrier operation if it exists since the entire vector already
// exists (i.e. we won't cause extra shifting when adding the other elements).
// Decrement out count of empty slots since we have filled one.
*res_start = epoch.ops.back();
}
} // namespace permuter
} // namespace fs_testing
extern "C" fs_testing::permuter::Permuter* permuter_get_instance(
std::vector<fs_testing::utils::disk_write> *data) {
return new fs_testing::permuter::RandomPermuter(data);
}
extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) {
delete p;
}
|
Update RandomPermuter.cpp
|
Update RandomPermuter.cpp
|
C++
|
apache-2.0
|
utsaslab/crashmonkey,utsaslab/crashmonkey,utsaslab/crashmonkey,utsaslab/crashmonkey
|
915118e995d2672cea5c1f208588f221ccc57af2
|
STEER/AliESDRun.cxx
|
STEER/AliESDRun.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TNamed.h>
#include <TGeoMatrix.h>
#include "AliESDRun.h"
#include "AliESDVertex.h"
#include "AliLog.h"
//-------------------------------------------------------------------------
// Implementation Class AliESDRun
// Run by run data
// for the ESD
// Origin: Christian Klein-Boesing, CERN, [email protected]
//-------------------------------------------------------------------------
ClassImp(AliESDRun)
//______________________________________________________________________________
AliESDRun::AliESDRun() :
TObject(),
fMagneticField(0),
fPeriodNumber(0),
fRunNumber(0),
fRecoVersion(0),
fTriggerClasses(kNTriggerClasses)
{
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
fDiamondCovXY[0]=fDiamondCovXY[2]=3.*3.;
fDiamondCovXY[1]=0.;
fTriggerClasses.SetOwner(kTRUE);
for (Int_t m=0; m<kNPHOSMatrix; m++) fPHOSMatrix[m]=NULL;
for (Int_t sm=0; sm<kNEMCALMatrix; sm++) fEMCALMatrix[sm]=NULL;
}
//______________________________________________________________________________
AliESDRun::AliESDRun(const AliESDRun &esd) :
TObject(esd),
fMagneticField(esd.fMagneticField),
fPeriodNumber(esd.fPeriodNumber),
fRunNumber(esd.fRunNumber),
fRecoVersion(esd.fRecoVersion),
fTriggerClasses(TObjArray(kNTriggerClasses))
{
// Copy constructor
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
for(Int_t m=0; m<kNPHOSMatrix; m++){
if(esd.fPHOSMatrix[m])
fPHOSMatrix[m]=new TGeoHMatrix(*(esd.fPHOSMatrix[m])) ;
else
fPHOSMatrix[m]=NULL;
}
for(Int_t sm=0; sm<kNEMCALMatrix; sm++){
if(esd.fEMCALMatrix[sm])
fEMCALMatrix[sm]=new TGeoHMatrix(*(esd.fEMCALMatrix[sm])) ;
else
fEMCALMatrix[sm]=NULL;
}
}
//______________________________________________________________________________
AliESDRun& AliESDRun::operator=(const AliESDRun &esd)
{
// assigment operator
if(this!=&esd) {
TObject::operator=(esd);
fRunNumber=esd.fRunNumber;
fPeriodNumber=esd.fPeriodNumber;
fRecoVersion=esd.fRecoVersion;
fMagneticField=esd.fMagneticField;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
fTriggerClasses.Clear();
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
for(Int_t m=0; m<kNPHOSMatrix; m++){
if(esd.fPHOSMatrix[m])
fPHOSMatrix[m]=new TGeoHMatrix(*(esd.fPHOSMatrix[m])) ;
else
fPHOSMatrix[m]=0;
}
for(Int_t sm=0; sm<kNEMCALMatrix; sm++){
if(esd.fEMCALMatrix[sm])
fEMCALMatrix[sm]=new TGeoHMatrix(*(esd.fEMCALMatrix[sm])) ;
else
fEMCALMatrix[sm]=0;
}
}
return *this;
}
void AliESDRun::Copy(TObject &obj) const{
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliESDRun *robj = dynamic_cast<AliESDRun*>(&obj);
if(!robj)return; // not an aliesdrun
*robj = *this;
}
//______________________________________________________________________________
AliESDRun::~AliESDRun() {
// Destructor
// Delete PHOS position matrices
for(Int_t m=0; m<kNPHOSMatrix; m++) {
if(fPHOSMatrix[m]) delete fPHOSMatrix[m] ;
fPHOSMatrix[m] = NULL;
}
// Delete PHOS position matrices
for(Int_t sm=0; sm<kNEMCALMatrix; sm++) {
if(fEMCALMatrix[sm]) delete fEMCALMatrix[sm] ;
fEMCALMatrix[sm] = NULL;
}
}
void AliESDRun::SetDiamond(const AliESDVertex *vertex) {
// set the interaction diamond
fDiamondXY[0]=vertex->GetXv();
fDiamondXY[1]=vertex->GetYv();
Double32_t cov[6];
vertex->GetCovMatrix(cov);
fDiamondCovXY[0]=cov[0];
fDiamondCovXY[1]=cov[1];
fDiamondCovXY[2]=cov[2];
}
//______________________________________________________________________________
void AliESDRun::Print(const Option_t *) const
{
// Print some data members
printf("Mean vertex in RUN %d: X=%.4f Y=%.4f cm\n",
GetRunNumber(),GetDiamondX(),GetDiamondY());
printf("Magnetic field = %f T\n",
GetMagneticField());
printf("Event from reconstruction version %d \n",fRecoVersion);
printf("List of active trigger classes: ");
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
printf("%s ",str->GetName());
}
printf("\n");
}
void AliESDRun::Reset()
{
// reset data members
fRunNumber = 0;
fPeriodNumber = 0;
fRecoVersion = 0;
fMagneticField = 0;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
fDiamondCovXY[0]=fDiamondCovXY[2]=3.*3.;
fDiamondCovXY[1]=0.;
fTriggerClasses.Clear();
}
//______________________________________________________________________________
void AliESDRun::SetTriggerClass(const char*name, Int_t index)
{
// Fill the trigger class name
// into the corresponding array
if (index >= kNTriggerClasses || index < 0) {
AliError(Form("Index (%d) is outside the allowed range (0,49)!",index));
return;
}
fTriggerClasses.AddAt(new TNamed(name,NULL),index);
}
//______________________________________________________________________________
const char* AliESDRun::GetTriggerClass(Int_t index) const
{
// Get the trigger class name at
// specified position in the trigger mask
TNamed *trclass = (TNamed *)fTriggerClasses.At(index);
if (trclass)
return trclass->GetName();
else
return "";
}
//______________________________________________________________________________
TString AliESDRun::GetActiveTriggerClasses() const
{
// Construct and return
// the list of trigger classes
// which are present in the run
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
return trclasses;
}
//______________________________________________________________________________
TString AliESDRun::GetFiredTriggerClasses(ULong64_t mask) const
{
// Constructs and returns the
// list of trigger classes that
// have been fired. Uses the trigger
// class mask as an argument.
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
if (mask & (1 << i)) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
}
return trclasses;
}
//______________________________________________________________________________
Bool_t AliESDRun::IsTriggerClassFired(ULong64_t mask, const char *name) const
{
// Checks if the trigger class
// identified by 'name' has been
// fired. Uses the trigger class mask.
TNamed *trclass = (TNamed *)fTriggerClasses.FindObject(name);
if (!trclass) return kFALSE;
Int_t iclass = fTriggerClasses.IndexOf(trclass);
if (iclass < 0) return kFALSE;
if (mask & (1 << iclass))
return kTRUE;
else
return kFALSE;
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TNamed.h>
#include <TGeoMatrix.h>
#include "AliESDRun.h"
#include "AliESDVertex.h"
#include "AliLog.h"
//-------------------------------------------------------------------------
// Implementation Class AliESDRun
// Run by run data
// for the ESD
// Origin: Christian Klein-Boesing, CERN, [email protected]
//-------------------------------------------------------------------------
ClassImp(AliESDRun)
//______________________________________________________________________________
AliESDRun::AliESDRun() :
TObject(),
fMagneticField(0),
fPeriodNumber(0),
fRunNumber(0),
fRecoVersion(0),
fTriggerClasses(kNTriggerClasses)
{
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
fDiamondCovXY[0]=fDiamondCovXY[2]=3.*3.;
fDiamondCovXY[1]=0.;
fTriggerClasses.SetOwner(kTRUE);
for (Int_t m=0; m<kNPHOSMatrix; m++) fPHOSMatrix[m]=NULL;
for (Int_t sm=0; sm<kNEMCALMatrix; sm++) fEMCALMatrix[sm]=NULL;
}
//______________________________________________________________________________
AliESDRun::AliESDRun(const AliESDRun &esd) :
TObject(esd),
fMagneticField(esd.fMagneticField),
fPeriodNumber(esd.fPeriodNumber),
fRunNumber(esd.fRunNumber),
fRecoVersion(esd.fRecoVersion),
fTriggerClasses(TObjArray(kNTriggerClasses))
{
// Copy constructor
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
for(Int_t m=0; m<kNPHOSMatrix; m++){
if(esd.fPHOSMatrix[m])
fPHOSMatrix[m]=new TGeoHMatrix(*(esd.fPHOSMatrix[m])) ;
else
fPHOSMatrix[m]=NULL;
}
for(Int_t sm=0; sm<kNEMCALMatrix; sm++){
if(esd.fEMCALMatrix[sm])
fEMCALMatrix[sm]=new TGeoHMatrix(*(esd.fEMCALMatrix[sm])) ;
else
fEMCALMatrix[sm]=NULL;
}
}
//______________________________________________________________________________
AliESDRun& AliESDRun::operator=(const AliESDRun &esd)
{
// assigment operator
if(this!=&esd) {
TObject::operator=(esd);
fRunNumber=esd.fRunNumber;
fPeriodNumber=esd.fPeriodNumber;
fRecoVersion=esd.fRecoVersion;
fMagneticField=esd.fMagneticField;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
fTriggerClasses.Clear();
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
for(Int_t m=0; m<kNPHOSMatrix; m++){
if(esd.fPHOSMatrix[m])
fPHOSMatrix[m]=new TGeoHMatrix(*(esd.fPHOSMatrix[m])) ;
else
fPHOSMatrix[m]=0;
}
for(Int_t sm=0; sm<kNEMCALMatrix; sm++){
if(esd.fEMCALMatrix[sm])
fEMCALMatrix[sm]=new TGeoHMatrix(*(esd.fEMCALMatrix[sm])) ;
else
fEMCALMatrix[sm]=0;
}
}
return *this;
}
void AliESDRun::Copy(TObject &obj) const{
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliESDRun *robj = dynamic_cast<AliESDRun*>(&obj);
if(!robj)return; // not an aliesdrun
*robj = *this;
}
//______________________________________________________________________________
AliESDRun::~AliESDRun() {
// Destructor
// Delete PHOS position matrices
for(Int_t m=0; m<kNPHOSMatrix; m++) {
if(fPHOSMatrix[m]) delete fPHOSMatrix[m] ;
fPHOSMatrix[m] = NULL;
}
// Delete PHOS position matrices
for(Int_t sm=0; sm<kNEMCALMatrix; sm++) {
if(fEMCALMatrix[sm]) delete fEMCALMatrix[sm] ;
fEMCALMatrix[sm] = NULL;
}
}
void AliESDRun::SetDiamond(const AliESDVertex *vertex) {
// set the interaction diamond
fDiamondXY[0]=vertex->GetXv();
fDiamondXY[1]=vertex->GetYv();
Double32_t cov[6];
vertex->GetCovMatrix(cov);
fDiamondCovXY[0]=cov[0];
fDiamondCovXY[1]=cov[1];
fDiamondCovXY[2]=cov[2];
}
//______________________________________________________________________________
void AliESDRun::Print(const Option_t *) const
{
// Print some data members
printf("Mean vertex in RUN %d: X=%.4f Y=%.4f cm\n",
GetRunNumber(),GetDiamondX(),GetDiamondY());
printf("Magnetic field = %f T\n",
GetMagneticField());
printf("Event from reconstruction version %d \n",fRecoVersion);
printf("List of active trigger classes: ");
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) printf("%s ",str->GetName());
}
printf("\n");
}
void AliESDRun::Reset()
{
// reset data members
fRunNumber = 0;
fPeriodNumber = 0;
fRecoVersion = 0;
fMagneticField = 0;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
fDiamondCovXY[0]=fDiamondCovXY[2]=3.*3.;
fDiamondCovXY[1]=0.;
fTriggerClasses.Clear();
}
//______________________________________________________________________________
void AliESDRun::SetTriggerClass(const char*name, Int_t index)
{
// Fill the trigger class name
// into the corresponding array
if (index >= kNTriggerClasses || index < 0) {
AliError(Form("Index (%d) is outside the allowed range (0,49)!",index));
return;
}
fTriggerClasses.AddAt(new TNamed(name,NULL),index);
}
//______________________________________________________________________________
const char* AliESDRun::GetTriggerClass(Int_t index) const
{
// Get the trigger class name at
// specified position in the trigger mask
TNamed *trclass = (TNamed *)fTriggerClasses.At(index);
if (trclass)
return trclass->GetName();
else
return "";
}
//______________________________________________________________________________
TString AliESDRun::GetActiveTriggerClasses() const
{
// Construct and return
// the list of trigger classes
// which are present in the run
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
return trclasses;
}
//______________________________________________________________________________
TString AliESDRun::GetFiredTriggerClasses(ULong64_t mask) const
{
// Constructs and returns the
// list of trigger classes that
// have been fired. Uses the trigger
// class mask as an argument.
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
if (mask & (1 << i)) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
}
return trclasses;
}
//______________________________________________________________________________
Bool_t AliESDRun::IsTriggerClassFired(ULong64_t mask, const char *name) const
{
// Checks if the trigger class
// identified by 'name' has been
// fired. Uses the trigger class mask.
TNamed *trclass = (TNamed *)fTriggerClasses.FindObject(name);
if (!trclass) return kFALSE;
Int_t iclass = fTriggerClasses.IndexOf(trclass);
if (iclass < 0) return kFALSE;
if (mask & (1 << iclass))
return kTRUE;
else
return kFALSE;
}
|
Fix for bug #56473: Segmentation fault in AliESDRun::Print (Matthias)
|
Fix for bug #56473: Segmentation fault in AliESDRun::Print (Matthias)
|
C++
|
bsd-3-clause
|
alisw/AliRoot,shahor02/AliRoot,shahor02/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,alisw/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,miranov25/AliRoot,miranov25/AliRoot,coppedis/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot
|
2774a57df681a89143bbc5a55bfbd6d25b3ceab8
|
STEER/AliPoints.cxx
|
STEER/AliPoints.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// This class contains the points for the ALICE event display //
// //
//Begin_Html
/*
<img src="picts/AliPointsClass.gif">
*/
//End_Html
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include "TPad.h"
#include "TParticle.h"
#include "TView.h"
#include "AliDetector.h"
#include "AliPoints.h"
#include "AliRun.h"
#include "AliMC.h"
ClassImp(AliPoints)
//_______________________________________________________________________
AliPoints::AliPoints():
fDetector(0),
fIndex(0)
{
//
// Default constructor
//
}
//_______________________________________________________________________
AliPoints::AliPoints(const AliPoints &pts):
TPolyMarker3D(pts),
fDetector(0),
fIndex(0)
{
//
// Copy constructor
//
pts.Copy(*this);
}
//_______________________________________________________________________
AliPoints::AliPoints(Int_t nhits):
TPolyMarker3D(nhits),
fDetector(0),
fIndex(0)
{
//
// Standard constructor
//
ResetBit(kCanDelete);
}
//_______________________________________________________________________
AliPoints::~AliPoints()
{
//
// Default destructor
//
}
//_______________________________________________________________________
void AliPoints::Copy(TObject &pts) const
{
//
// Copy *this onto pts
//
if(this != &pts) {
((TPolyMarker3D*)this)->Copy(dynamic_cast<TPolyMarker3D&>(pts));
(dynamic_cast<AliPoints&>(pts)).fGLList = fGLList;
(dynamic_cast<AliPoints&>(pts)).fLastPoint = fLastPoint;
(dynamic_cast<AliPoints&>(pts)).fDetector = fDetector;
(dynamic_cast<AliPoints&>(pts)).fIndex = fIndex;
}
}
//_______________________________________________________________________
Int_t AliPoints::DistancetoPrimitive(Int_t px, Int_t py)
{
//
//*-*-*-*-*-*-*Compute distance from point px,py to a 3-D polymarker*-*-*-*-*
//*-* =====================================================
//*-*
//*-* Compute the closest distance of approach from point
//*-* px,py to each segment
//*-* of the polyline.
//*-* Returns when the distance found is below DistanceMaximum.
//*-* The distance is computed in pixels units.
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//const Int_t inaxis = 7;
//Int_t dist = 9999;
return TPolyMarker3D::DistancetoPrimitive(px,py);
}
//_______________________________________________________________________
void AliPoints::DumpParticle() const
{
//
// Dump particle corresponding to this point
//
TParticle *particle = GetParticle();
if (particle) particle->Dump();
}
//_______________________________________________________________________
void AliPoints::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
//
//*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*-*-*-*-*
//*-* =========================================
//*-*
//*-* This member function must be implemented to realize the action
//*-* corresponding to the mouse click on the object in the window
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
gPad->SetCursor(kCross);
if (gPad->GetView())
gPad->GetView()->ExecuteRotateView(event, px, py);
}
//_______________________________________________________________________
const Text_t *AliPoints::GetName() const
{
//
// Return name of the Geant3 particle corresponding to this point
//
TParticle *particle = GetParticle();
if (!particle) return "Particle";
return particle->GetName();
}
//_______________________________________________________________________
Text_t *AliPoints::GetObjectInfo(Int_t, Int_t) const
{
//
// Redefines TObject::GetObjectInfo.
// Displays the info (particle,etc
// corresponding to cursor position px,py
//
static char info[64];
sprintf(info,"%s %d",GetName(),fIndex);
return info;
}
//_______________________________________________________________________
TParticle *AliPoints::GetParticle() const
{
//
// Returns pointer to particle index in AliRun::fParticles
//
if (fIndex < 0 || fIndex >= gAlice->GetMCApp()->GetNtrack()) return 0;
else return gAlice->GetMCApp()->Particle(fIndex);
}
//_______________________________________________________________________
void AliPoints::InspectParticle() const
{
//
// Inspect particle corresponding to this point
//
TParticle *particle = GetParticle();
if (particle) particle->Inspect();
}
//_______________________________________________________________________
void AliPoints::Propagate()
{
//
// Set attributes of all detectors to be the attributes of this point
//
Int_t ntracks,track;
TObjArray *points;
AliPoints *pm;
//
TIter next(gAlice->Detectors());
AliDetector *detector;
while((detector = (AliDetector*)(next()))) {
if (!detector->IsActive()) continue;
points = detector->Points();
if (!points) continue;
ntracks = points->GetEntriesFast();
for (track=0;track<ntracks;track++) {
pm = dynamic_cast<AliPoints*>(points->UncheckedAt(track));
if (!pm) continue;
if (fIndex == pm->GetIndex()) {
pm->SetMarkerColor(GetMarkerColor());
pm->SetMarkerSize(GetMarkerSize());
pm->SetMarkerStyle(GetMarkerStyle());
}
}
}
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// This class contains the points for the ALICE event display //
// //
//Begin_Html
/*
<img src="picts/AliPointsClass.gif">
*/
//End_Html
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include "TPad.h"
#include "TParticle.h"
#include "TView.h"
#include "AliDetector.h"
#include "AliPoints.h"
#include "AliRun.h"
#include "AliMC.h"
ClassImp(AliPoints)
//_______________________________________________________________________
AliPoints::AliPoints():
fDetector(0),
fIndex(0)
{
//
// Default constructor
//
}
//_______________________________________________________________________
AliPoints::AliPoints(const AliPoints &pts):
TPolyMarker3D(pts),
fDetector(0),
fIndex(0)
{
//
// Copy constructor
//
pts.Copy(*this);
}
//_______________________________________________________________________
AliPoints::AliPoints(Int_t nhits):
TPolyMarker3D(nhits),
fDetector(0),
fIndex(0)
{
//
// Standard constructor
//
ResetBit(kCanDelete);
}
//_______________________________________________________________________
AliPoints::~AliPoints()
{
//
// Default destructor
//
}
//_______________________________________________________________________
void AliPoints::Copy(TObject &pts) const
{
//
// Copy *this onto pts
//
if((TObject*)this != &pts) {
((TPolyMarker3D*)this)->Copy(dynamic_cast<TPolyMarker3D&>(pts));
(dynamic_cast<AliPoints&>(pts)).fGLList = fGLList;
(dynamic_cast<AliPoints&>(pts)).fLastPoint = fLastPoint;
(dynamic_cast<AliPoints&>(pts)).fDetector = fDetector;
(dynamic_cast<AliPoints&>(pts)).fIndex = fIndex;
}
}
//_______________________________________________________________________
Int_t AliPoints::DistancetoPrimitive(Int_t px, Int_t py)
{
//
//*-*-*-*-*-*-*Compute distance from point px,py to a 3-D polymarker*-*-*-*-*
//*-* =====================================================
//*-*
//*-* Compute the closest distance of approach from point
//*-* px,py to each segment
//*-* of the polyline.
//*-* Returns when the distance found is below DistanceMaximum.
//*-* The distance is computed in pixels units.
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//const Int_t inaxis = 7;
//Int_t dist = 9999;
return TPolyMarker3D::DistancetoPrimitive(px,py);
}
//_______________________________________________________________________
void AliPoints::DumpParticle() const
{
//
// Dump particle corresponding to this point
//
TParticle *particle = GetParticle();
if (particle) particle->Dump();
}
//_______________________________________________________________________
void AliPoints::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
//
//*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*-*-*-*-*
//*-* =========================================
//*-*
//*-* This member function must be implemented to realize the action
//*-* corresponding to the mouse click on the object in the window
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
gPad->SetCursor(kCross);
if (gPad->GetView())
gPad->GetView()->ExecuteRotateView(event, px, py);
}
//_______________________________________________________________________
const Text_t *AliPoints::GetName() const
{
//
// Return name of the Geant3 particle corresponding to this point
//
TParticle *particle = GetParticle();
if (!particle) return "Particle";
return particle->GetName();
}
//_______________________________________________________________________
Text_t *AliPoints::GetObjectInfo(Int_t, Int_t) const
{
//
// Redefines TObject::GetObjectInfo.
// Displays the info (particle,etc
// corresponding to cursor position px,py
//
static char info[64];
sprintf(info,"%s %d",GetName(),fIndex);
return info;
}
//_______________________________________________________________________
TParticle *AliPoints::GetParticle() const
{
//
// Returns pointer to particle index in AliRun::fParticles
//
if (fIndex < 0 || fIndex >= gAlice->GetMCApp()->GetNtrack()) return 0;
else return gAlice->GetMCApp()->Particle(fIndex);
}
//_______________________________________________________________________
void AliPoints::InspectParticle() const
{
//
// Inspect particle corresponding to this point
//
TParticle *particle = GetParticle();
if (particle) particle->Inspect();
}
//_______________________________________________________________________
void AliPoints::Propagate()
{
//
// Set attributes of all detectors to be the attributes of this point
//
Int_t ntracks,track;
TObjArray *points;
AliPoints *pm;
//
TIter next(gAlice->Detectors());
AliDetector *detector;
while((detector = (AliDetector*)(next()))) {
if (!detector->IsActive()) continue;
points = detector->Points();
if (!points) continue;
ntracks = points->GetEntriesFast();
for (track=0;track<ntracks;track++) {
pm = dynamic_cast<AliPoints*>(points->UncheckedAt(track));
if (!pm) continue;
if (fIndex == pm->GetIndex()) {
pm->SetMarkerColor(GetMarkerColor());
pm->SetMarkerSize(GetMarkerSize());
pm->SetMarkerStyle(GetMarkerStyle());
}
}
}
}
|
Change to satisfy gcc 2.95.4)
|
Change to satisfy gcc 2.95.4)
|
C++
|
bsd-3-clause
|
mkrzewic/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,coppedis/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,coppedis/AliRoot,miranov25/AliRoot,shahor02/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,shahor02/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,coppedis/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot
|
5ac9a1dfdb551d9eb16bca9a817cb0cd6ac1119f
|
mainwindow.cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "connectwidget.h"
#include "summarywidget.h"
#include <QStackedWidget>
#include <QtDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStackedWidget *stackWidget = new QStackedWidget(this);
ConnectWidget *connectWidget = new ConnectWidget(stackWidget);
SummaryWidget *summaryWidget = new SummaryWidget(stackWidget);
stackWidget->addWidget(connectWidget);
stackWidget->addWidget(summaryWidget);
setCentralWidget(stackWidget);
connect(connectWidget, &ConnectWidget::dataFetched, summaryWidget, &SummaryWidget::displaySummary);
connect(connectWidget, &ConnectWidget::dataFetched, [=](){stackWidget->setCurrentIndex(1);});
}
MainWindow::~MainWindow()
{
delete ui;
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "connectwidget.h"
#include "summarywidget.h"
#include <QStackedWidget>
#include <QtDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setMinimumSize(809, 500);
QStackedWidget *stackWidget = new QStackedWidget(this);
ConnectWidget *connectWidget = new ConnectWidget(stackWidget);
SummaryWidget *summaryWidget = new SummaryWidget(stackWidget);
stackWidget->addWidget(connectWidget);
stackWidget->addWidget(summaryWidget);
setCentralWidget(stackWidget);
connect(connectWidget, &ConnectWidget::dataFetched, summaryWidget, &SummaryWidget::displaySummary);
connect(connectWidget, &ConnectWidget::dataFetched, [=](){stackWidget->setCurrentIndex(1);});
}
MainWindow::~MainWindow()
{
delete ui;
}
|
Make window bigger
|
Make window bigger
|
C++
|
bsd-2-clause
|
port-42/client
|
8084e25977f3749720362513d68bc02770b91fe4
|
mainwindow.cpp
|
mainwindow.cpp
|
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QKeyEvent>
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>
#include <cassert>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <string>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "gui/vertex_graphics_item.h"
#include "gui/edge_graphics_item.h"
#include "lib/bfs.hpp"
#include "lib/logger.hpp"
MainWindow::MainWindow(Graph *graph, QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), graph_(graph)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
scene->setSceneRect(-1500, -1500, 3000, 3000);
ui->graphicsView->setScene(scene);
ui->graphicsView->setRenderHints(QPainter::Antialiasing);
ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
global_logger_logView_ = ui->txtLogView;
reloadModel();
}
MainWindow::~MainWindow() { delete ui; }
static bool reloading = false;
/// Reloads the whole UI based on the model. Everything is first removed,
/// and then re-created in the same coordinates, so that the user notice anything.
void MainWindow::reloadModel()
{
qDebug() << "Reloading model";
reloading = true;
int selectedVertexValue = -1;
if (scene->selectedItems().size() == 1) {
VertexGraphicsItem* selection = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0));
if (selection) {
selectedVertexValue = selection->value();
}
}
// TODO - promyslet
// selectedVertex_ = nullptr;
vertices_.clear();
scene->clear();
std::unordered_map<Vertex *, VertexGraphicsItem *> vgi_map;
int i = 0;
for (std::unique_ptr<Vertex> &v : graph_->list) {
auto vgi = new VertexGraphicsItem(v.get());
if (!vgi->hasCoordinates()) {
vgi->setCoordinates(80 * (i / 5 + 1) * std::cos(i),
80 * (i / 5 + 1) * std::sin(i));
}
vertices_.push_back(vgi);
scene->addItem(vgi);
if (v->value == selectedVertexValue) {
vgi->setSelected(true);
}
vgi_map[v.get()] = vgi;
i++;
}
for (std::unique_ptr<Vertex> &v : graph_->list) {
Vertex *vertex = v.get();
VertexGraphicsItem *vgi = vgi_map[vertex];
for (Edge &e : vertex->edges) {
graphConnect(vgi, vgi_map[e.to]);
vgi->repaintEdges();
}
}
reloading = false;
}
void MainWindow::keyReleaseEvent(QKeyEvent *e)
{
if (e->key() == Qt::Key_A) {
on_addVertex_clicked();
} else if (e->key() == Qt::Key_C) {
on_addEdge_clicked();
} else if (e->key() == Qt::Key_D) {
delete_selection();
} else if (e->key() == Qt::Key_F) {
searchToggle(true);
} else if (e->key() == Qt::Key_T) {
searchToggle(false);
} else if (e->key() == Qt::Key_N) {
searchStep();
} else if (e->key() == Qt::Key_R) {
if (graph_->start() && graph_->end()) {
bfs_ = new BFS(*graph_, graph_->start(), graph_->end());
graph_->clear_metadata();
scene->update();
}
}
}
void MainWindow::delete_selection()
{
if (scene->selectedItems().size() == 1) {
QGraphicsItem *selectedItem = scene->selectedItems().at(0);
if (VertexGraphicsItem *vgi = dynamic_cast<VertexGraphicsItem *>(selectedItem)) {
if (connectionVertex_ == vgi->value()) {
connectionVertex_ = -1; }
graph_->removeVertex(vgi->vertex);
} else if (EdgeGraphicsItem *egi = dynamic_cast<EdgeGraphicsItem *>(selectedItem)) {
auto from = egi->from;
auto to = egi->to;
graph_->disconnect(from->vertex->value, to->vertex->value);
} else { qDebug() << "Trying to delete something unknown"; }
}
reloadModel();
}
void MainWindow::on_addVertex_clicked()
{
auto v = graph_->add_vertex();
auto pos = ui->graphicsView->mapToScene(mapFromGlobal(QCursor::pos()));
v->x = pos.x();
v->y = pos.y();
reloadModel();
}
void MainWindow::on_addEdge_clicked()
{
VertexGraphicsItem* current = selectedVertex();
if (current) {
// If we already had one selected, revert the selection color
if (connectionVertex_ != -1) {
if (current->value() != connectionVertex_) {
for (VertexGraphicsItem* vgi : vertices_) {
if (vgi->value() == connectionVertex_) {
vgi->selected(false); } }
graph_->connect(current->value(), connectionVertex_);
// Reset the selection after we connect the vertices
connectionVertex_ = -1;
reloadModel();
log_event("Edge added");
}
} else {
current->selected(true);
connectionVertex_ = current->value();
reloadModel();
}
}
}
/// isStart - true for start vertex, false for end vertex
void MainWindow::searchToggle(bool isStart)
{
VertexGraphicsItem* current = selectedVertex();
if (current) {
if (isStart) {
graph_->set_start(current->vertex);
} else {
graph_->set_end(current->vertex); }
reloadModel();
} else {
QMessageBox box;
box.setText("Select a vertex to begin search.");
box.exec();
}
}
void MainWindow::searchStep()
{
if (graph_->search_ready() && bfs_) {
qDebug () << "Stepping search" << bfs_->step();
reloadModel();
} else {
qDebug() << "Search isn't ready yet.";
}
}
/// Returns a selected vertex if there is one, otherwise nullptr.
VertexGraphicsItem* MainWindow::selectedVertex() const
{
VertexGraphicsItem* current = nullptr;
if (scene->selectedItems().size() > 0) {
current = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0));
}
return current;
}
void MainWindow::on_actionNew_clicked()
{
log_event("New graph");
graph_ = new Graph();
connectionVertex_ = -1;
reloadModel();
}
void MainWindow::on_actionSave_clicked()
{
log_event("Save");
}
void MainWindow::on_actionSaveAs_clicked()
{
std::string file = QFileDialog::getSaveFileName().toStdString();
std::ofstream fs(file);
fs << *graph_;
log_event("Graph saved");
}
void MainWindow::on_actionOpen_clicked()
{
auto s = QFileDialog::getOpenFileName();
if (!s.isNull()) {
// TODO - nastavit vsem streamum aby vyhazovaly vyjimky
std::ifstream fs(s.toStdString());
graph_ = Graph::parse_stream(fs);
connectionVertex_ = -1;
reloadModel();
log_event("Graph loaded");
} else {
log_event("Dialog canceled");
}
}
/// Used to add a graphical edge between two vertices. Only ever call this from reloadModel.
void MainWindow::graphConnect(VertexGraphicsItem *v1, VertexGraphicsItem *v2) {
assert(reloading);
auto edge = new EdgeGraphicsItem(v1, v2);
scene->addItem(edge);
v1->edges.push_back(edge);
v2->edges.push_back(edge);
}
|
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QKeyEvent>
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>
#include <cassert>
#include <cmath>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <string>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "gui/vertex_graphics_item.h"
#include "gui/edge_graphics_item.h"
#include "lib/bfs.hpp"
#include "lib/logger.hpp"
MainWindow::MainWindow(Graph *graph, QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), graph_(graph)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
scene->setSceneRect(-1500, -1500, 3000, 3000);
ui->graphicsView->setScene(scene);
ui->graphicsView->setRenderHints(QPainter::Antialiasing);
ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
global_logger_logView_ = ui->txtLogView;
reloadModel();
}
MainWindow::~MainWindow() { delete ui; }
static bool reloading = false;
/// Reloads the whole UI based on the model. Everything is first removed,
/// and then re-created in the same coordinates, so that the user notice anything.
void MainWindow::reloadModel()
{
qDebug() << "Reloading model";
reloading = true;
int selectedVertexValue = -1;
if (scene->selectedItems().size() == 1) {
VertexGraphicsItem* selection = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0));
if (selection) {
selectedVertexValue = selection->value();
}
}
// TODO - promyslet
// selectedVertex_ = nullptr;
vertices_.clear();
scene->clear();
std::unordered_map<Vertex *, VertexGraphicsItem *> vgi_map;
int i = 0;
for (std::unique_ptr<Vertex> &v : graph_->list) {
auto vgi = new VertexGraphicsItem(v.get());
if (!vgi->hasCoordinates()) {
vgi->setCoordinates(80 * (i / 5 + 1) * std::cos(i),
80 * (i / 5 + 1) * std::sin(i));
}
vertices_.push_back(vgi);
scene->addItem(vgi);
if (v->value == selectedVertexValue) {
vgi->setSelected(true);
}
vgi_map[v.get()] = vgi;
i++;
}
for (std::unique_ptr<Vertex> &v : graph_->list) {
Vertex *vertex = v.get();
VertexGraphicsItem *vgi = vgi_map[vertex];
for (Edge &e : vertex->edges) {
graphConnect(vgi, vgi_map[e.to]);
vgi->repaintEdges();
}
}
reloading = false;
}
void MainWindow::keyReleaseEvent(QKeyEvent *e)
{
if (e->key() == Qt::Key_A) {
on_addVertex_clicked();
} else if (e->key() == Qt::Key_C) {
on_addEdge_clicked();
} else if (e->key() == Qt::Key_D) {
delete_selection();
} else if (e->key() == Qt::Key_F) {
searchToggle(true);
} else if (e->key() == Qt::Key_T) {
searchToggle(false);
} else if (e->key() == Qt::Key_N) {
searchStep();
} else if (e->key() == Qt::Key_R) {
if (graph_->start() && graph_->end()) {
bfs_ = new BFS(*graph_, graph_->start(), graph_->end());
graph_->clear_metadata();
scene->update();
}
}
}
void MainWindow::delete_selection()
{
if (scene->selectedItems().size() == 1) {
QGraphicsItem *selectedItem = scene->selectedItems().at(0);
if (VertexGraphicsItem *vgi = dynamic_cast<VertexGraphicsItem *>(selectedItem)) {
if (connectionVertex_ == vgi->value()) {
connectionVertex_ = -1; }
graph_->removeVertex(vgi->vertex);
} else if (EdgeGraphicsItem *egi = dynamic_cast<EdgeGraphicsItem *>(selectedItem)) {
auto from = egi->from;
auto to = egi->to;
graph_->disconnect(from->vertex->value, to->vertex->value);
} else { qDebug() << "Trying to delete something unknown"; }
}
reloadModel();
}
void MainWindow::on_addVertex_clicked()
{
auto v = graph_->add_vertex();
auto pos = ui->graphicsView->mapToScene(mapFromGlobal(QCursor::pos()));
v->x = pos.x();
v->y = pos.y();
reloadModel();
}
void MainWindow::on_addEdge_clicked()
{
VertexGraphicsItem* current = selectedVertex();
if (current) {
// If we already had one selected, revert the selection color
if (connectionVertex_ != -1) {
if (current->value() != connectionVertex_) {
for (VertexGraphicsItem* vgi : vertices_) {
if (vgi->value() == connectionVertex_) {
vgi->selected(false); } }
graph_->connect(current->value(), connectionVertex_);
// Reset the selection after we connect the vertices
connectionVertex_ = -1;
reloadModel();
log_event("Edge added");
}
} else {
current->selected(true);
connectionVertex_ = current->value();
reloadModel();
}
}
}
/// isStart - true for start vertex, false for end vertex
void MainWindow::searchToggle(bool isStart)
{
VertexGraphicsItem* current = selectedVertex();
if (current) {
if (isStart) {
graph_->set_start(current->vertex);
} else {
graph_->set_end(current->vertex); }
reloadModel();
} else {
QMessageBox box;
box.setText("Select a vertex to begin search.");
box.exec();
}
}
void MainWindow::searchStep()
{
if (graph_->search_ready() && bfs_) {
qDebug () << "Stepping search" << bfs_->step();
reloadModel();
} else {
qDebug() << "Search isn't ready yet.";
}
}
/// Returns a selected vertex if there is one, otherwise nullptr.
VertexGraphicsItem* MainWindow::selectedVertex() const
{
VertexGraphicsItem* current = nullptr;
if (scene->selectedItems().size() > 0) {
current = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0));
}
return current;
}
void MainWindow::on_actionNew_clicked()
{
log_event("New graph");
graph_ = new Graph();
connectionVertex_ = -1;
reloadModel();
}
void MainWindow::on_actionSave_clicked()
{
log_event("Save");
}
void MainWindow::on_actionSaveAs_clicked()
{
auto file = QFileDialog::getSaveFileName();
if (!file.isNull()) {
std::ofstream fs(file.toStdString());
fs << *graph_;
log_event("Graph saved");
} else {
log_event("Dialog canceled"); }
}
void MainWindow::on_actionOpen_clicked()
{
// TODO - nastavit vsem streamum aby vyhazovaly vyjimky
auto file = QFileDialog::getOpenFileName();
if (!file.isNull()) {
std::ifstream fs(file.toStdString());
graph_ = Graph::parse_stream(fs);
connectionVertex_ = -1;
reloadModel();
log_event("Graph loaded");
} else {
log_event("Dialog canceled"); }
}
/// Used to add a graphical edge between two vertices. Only ever call this from reloadModel.
void MainWindow::graphConnect(VertexGraphicsItem *v1, VertexGraphicsItem *v2) {
assert(reloading);
auto edge = new EdgeGraphicsItem(v1, v2);
scene->addItem(edge);
v1->edges.push_back(edge);
v2->edges.push_back(edge);
}
|
Handle when save graph dialog is canceled
|
Handle when save graph dialog is canceled
|
C++
|
mit
|
darthdeus/graphite-gui
|
cbb358ae76af52381ed1199d54088e2a4592e15b
|
physics/discrete_trajectory_segment_iterator_body.hpp
|
physics/discrete_trajectory_segment_iterator_body.hpp
|
#include "physics/discrete_trajectory_segment_iterator.hpp"
namespace principia {
namespace physics {
namespace internal_discrete_trajectory_segment_iterator {
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator++() {
++iterator_;
return *this;
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator--() {
--iterator_;
return *this;
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator++(int) { // NOLINT
return DiscreteTrajectorySegmentIterator(segments_, iterator_++);
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator--(int) { // NOLINT
return DiscreteTrajectorySegmentIterator(segments_, iterator_--);
}
template<typename Frame>
typename DiscreteTrajectorySegmentIterator<Frame>::reference
DiscreteTrajectorySegmentIterator<Frame>::operator*() const {
return *iterator_;
}
template<typename Frame>
typename DiscreteTrajectorySegmentIterator<Frame>::pointer
DiscreteTrajectorySegmentIterator<Frame>::operator->() const {
return &*iterator_;
}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator==(
DiscreteTrajectorySegmentIterator const& other) const {
return segments_ == other.segments_ && iterator_ == other.iterator_;
}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator!=(
DiscreteTrajectorySegmentIterator const& other) const {
return !operator==(other);
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>::DiscreteTrajectorySegmentIterator(
not_null<Segments*> const segments,
typename Segments::iterator iterator)
: segments_(segments),
iterator_(iterator) {}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::is_begin() const {
return iterator_ == segments_->begin();
}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::is_end() const {
return iterator_ == segments_->end();
}
template<typename Frame>
DiscreteTrajectorySegmentRange<DiscreteTrajectorySegmentIterator<Frame>>
DiscreteTrajectorySegmentIterator<Frame>::segments() const {
return {DiscreteTrajectorySegmentIterator(segments_, segments_->begin()),
DiscreteTrajectorySegmentIterator(segments_, segments_->end())};
}
template<typename Frame>
typename DiscreteTrajectorySegmentIterator<Frame>::Segments::iterator
DiscreteTrajectorySegmentIterator<Frame>::iterator() const {
return iterator_;
}
} // namespace internal_discrete_trajectory_segment_iterator
} // namespace physics
} // namespace principia
|
#pragma once
#include "physics/discrete_trajectory_segment_iterator.hpp"
namespace principia {
namespace physics {
namespace internal_discrete_trajectory_segment_iterator {
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator++() {
CHECK_NOTNULL(segments_);
++iterator_;
return *this;
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator--() {
CHECK_NOTNULL(segments_);
--iterator_;
return *this;
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator++(int) { // NOLINT
CHECK_NOTNULL(segments_);
return DiscreteTrajectorySegmentIterator(segments_, iterator_++);
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator--(int) { // NOLINT
CHECK_NOTNULL(segments_);
return DiscreteTrajectorySegmentIterator(segments_, iterator_--);
}
template<typename Frame>
typename DiscreteTrajectorySegmentIterator<Frame>::reference
DiscreteTrajectorySegmentIterator<Frame>::operator*() const {
CHECK_NOTNULL(segments_);
return *iterator_;
}
template<typename Frame>
typename DiscreteTrajectorySegmentIterator<Frame>::pointer
DiscreteTrajectorySegmentIterator<Frame>::operator->() const {
CHECK_NOTNULL(segments_);
return &*iterator_;
}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator==(
DiscreteTrajectorySegmentIterator const& other) const {
CHECK_NOTNULL(segments_);
return segments_ == other.segments_ && iterator_ == other.iterator_;
}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator!=(
DiscreteTrajectorySegmentIterator const& other) const {
return !operator==(other);
}
template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>::DiscreteTrajectorySegmentIterator(
not_null<Segments*> const segments,
typename Segments::iterator iterator)
: segments_(segments),
iterator_(iterator) {}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::is_begin() const {
CHECK_NOTNULL(segments_);
return iterator_ == segments_->begin();
}
template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::is_end() const {
CHECK_NOTNULL(segments_);
return iterator_ == segments_->end();
}
template<typename Frame>
DiscreteTrajectorySegmentRange<DiscreteTrajectorySegmentIterator<Frame>>
DiscreteTrajectorySegmentIterator<Frame>::segments() const {
CHECK_NOTNULL(segments_);
return {DiscreteTrajectorySegmentIterator(segments_, segments_->begin()),
DiscreteTrajectorySegmentIterator(segments_, segments_->end())};
}
template<typename Frame>
typename DiscreteTrajectorySegmentIterator<Frame>::Segments::iterator
DiscreteTrajectorySegmentIterator<Frame>::iterator() const {
return iterator_;
}
} // namespace internal_discrete_trajectory_segment_iterator
} // namespace physics
} // namespace principia
|
Check for uninitialized segment iterator.
|
Check for uninitialized segment iterator.
|
C++
|
mit
|
pleroy/Principia,mockingbirdnest/Principia,pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,pleroy/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia
|
2274971efab47cd64d69db75110ff53ff0a7ba4b
|
libtbag/time/Time.cpp
|
libtbag/time/Time.cpp
|
/**
* @file Time.cpp
* @brief Time class implementation.
* @author zer0
* @date 2016-07-17
*/
#include <libtbag/time/Time.hpp>
#include <libtbag/debug/Assert.hpp>
#include <libtbag/pattern/Singleton2.hpp>
#include <libtbag/string/StringUtils.hpp>
#include <libtbag/3rd/date/date.h>
#include <cassert>
#include <cstring>
#include <cmath>
#include <ratio>
#include <mutex>
#include <atomic>
#include <type_traits>
// Where is 'timeval' structure?
// [WARNING] Don't change include order.
#if defined(TBAG_PLATFORM_WINDOWS)
# include <Windows.h>
#else
# include <sys/time.h>
# include <libtbag/dummy/Win32.hpp>
using namespace ::libtbag::dummy::win32;
#endif
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace time {
/* inline */ namespace __impl {
/**
* SafetyTimeGetter class prototype & implementation.
*
* @translate{ko, 이 클래스는 표준C 라이브러리의 데이터 경쟁(Data race)상태를 해결하기 위해 작성되었다.}
*
* @author zer0
* @date 2016-09-22
*
* @remarks
* This class is the solution of the data race conditions.
*/
class SafetyTimeGetter : public ::libtbag::pattern::Singleton2<SafetyTimeGetter>
{
public:
SINGLETON2_PROTOTYPE(SafetyTimeGetter);
public:
using Mutex = std::mutex;
using Guard = std::lock_guard<Mutex>;
private:
mutable Mutex _mutex;
private:
template <typename Predicated>
inline bool tryCatch(Predicated predicated) const
{
try {
Guard g(_mutex);
predicated();
} catch (...) {
return false;
}
return true;
}
public:
inline bool getGmtTime(time_t const & t, tm * output) const
{
return tryCatch([&](){
if (output != nullptr) {
memcpy(output, gmtime(&t), sizeof(tm)); // Position of data race!
}
});
}
inline bool getLocalTime(time_t const & t, tm * output) const
{
return tryCatch([&](){
if (output != nullptr) {
memcpy(output, localtime(&t), sizeof(tm)); // Position of data race!
}
});
}
public:
};
/**
* @author zer0
* @date 2017-04-11
*/
class LocalTimeDiff : public ::libtbag::pattern::Singleton2<LocalTimeDiff>
{
public:
friend class ::libtbag::pattern::Singleton2<LocalTimeDiff>;
private:
std::chrono::system_clock::duration _local_diff;
std::atomic_bool _update_local_diff;
protected:
LocalTimeDiff() : _local_diff(0)
{
_update_local_diff = false;
}
public:
~LocalTimeDiff()
{
// EMPTY.
}
private:
bool updateLocalDiff()
{
time_t time = getCurrentTime();
struct tm gmt_time = {0,};
struct tm local_time = {0,};
bool is_gmt = __impl::SafetyTimeGetter::getInstance()->getGmtTime(time, &gmt_time);
bool is_local = __impl::SafetyTimeGetter::getInstance()->getLocalTime(time, &local_time);
if (is_gmt == false || is_local == false) {
return false;
}
auto gmt_time_point = std::chrono::system_clock::from_time_t(mktime( &gmt_time));
auto local_time_point = std::chrono::system_clock::from_time_t(mktime(&local_time));
_local_diff = (local_time_point - gmt_time_point);
_update_local_diff = true;
return true;
}
public:
std::chrono::system_clock::duration getLocalDiff()
{
if (_update_local_diff == false) {
updateLocalDiff();
}
return _local_diff;
}
};
/**
* @warning
* Epoch time은 UTC 이전(1970/01/01T00:00:00)일 경우 음수로 표현된다. @n
* 이 경우 정상적인 계산이 이루어지지 않는다. @n
* 이 현상을 해결하기 위해 Date(날짜)의 기준을 1970년 이후로 맞춰주면 된다.
*/
template <typename Cut, typename Destination, typename Clock, typename ClockDuration>
typename Destination::rep getTimeFloor(std::chrono::time_point<Clock, ClockDuration> const & time)
{
static_assert(std::ratio_less_equal<typename Cut::period, std::chrono::hours::period>::value,
"Unsupported Cut type.");
static_assert(std::ratio_less<typename Destination::period, typename Cut::period>::value,
"Destination must be less than Cut.");
using TimePoint = std::chrono::time_point<Clock, ClockDuration>;
ClockDuration epoch_time = time.time_since_epoch();
if (epoch_time.count() < 0) {
auto DAYS_OF_EPOCH = date::floor<date::days>(date::years(1970));
auto days = date::floor<date::days>(time);
epoch_time += (DAYS_OF_EPOCH - days.time_since_epoch());
assert(epoch_time.count() >= 0);
}
epoch_time -= std::chrono::duration_cast<Cut>(epoch_time);
assert(epoch_time.count() >= 0);
// [WARNING] It does not work on some platforms:
// return static_cast<int>(result / std::chrono::milliseconds(1));
return std::abs(std::chrono::duration_cast<Destination>(epoch_time).count());
}
void createInstance()
{
LocalTimeDiff::createInstance();
SafetyTimeGetter::createInstance();
}
void releaseInstance()
{
SafetyTimeGetter::releaseInstance();
LocalTimeDiff::releaseInstance();
}
} // namespace __impl
int getYear(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::year_month_day(date::floor<date::days>(time)).year());
}
int getMonth(std::chrono::system_clock::time_point const & time)
{
return static_cast<unsigned>(date::year_month_day(date::floor<date::days>(time)).month());
}
int getDay(std::chrono::system_clock::time_point const & time)
{
return static_cast<unsigned>(date::year_month_day(date::floor<date::days>(time)).day());
}
int getHours(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).hours().count());
}
int getMinutes(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).minutes().count());
}
int getSeconds(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).seconds().count());
}
int getSubSeconds(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).subseconds().count());
}
int getWeek(std::chrono::system_clock::time_point const & time)
{
return static_cast<unsigned>(date::weekday(date::floor<date::days>(time)));
}
std::string getWeekString(std::chrono::system_clock::time_point const & time)
{
switch (getWeek(time)) {
case 0: return "Sun";
case 1: return "Mon";
case 2: return "Tue";
case 3: return "Wed";
case 4: return "Thu";
case 5: return "Fri";
case 6: return "Sat";
default: TBAG_INACCESSIBLE_BLOCK_ASSERT();
}
return "[Unknown]";
}
int getMillisec(std::chrono::system_clock::time_point const & time)
{
using namespace std::chrono;
auto const RESULT = __impl::getTimeFloor<seconds, milliseconds>(time);
assert(0 <= COMPARE_AND(RESULT) < 1000);
return static_cast<int>(RESULT);
}
int getMicrosec(std::chrono::system_clock::time_point const & time)
{
using namespace std::chrono;
auto const RESULT = __impl::getTimeFloor<milliseconds, microseconds>(time);
assert(0 <= COMPARE_AND(RESULT) < 1000);
return static_cast<int>(RESULT);
}
int getNanosec(std::chrono::system_clock::time_point const & time)
{
using namespace std::chrono;
auto const RESULT = __impl::getTimeFloor<microseconds, nanoseconds>(time);
assert(0 <= COMPARE_AND(RESULT) < 1000);
return static_cast<int>(RESULT);
}
int getDays(std::chrono::system_clock::time_point const & time)
{
return date::floor<date::days>(time).time_since_epoch().count();
}
std::string getMillisecMbs(std::chrono::system_clock::time_point const & time)
{
std::string millisec = std::to_string(getMillisec(time));
switch (millisec.size()) {
case 2: return std::string( "0") + millisec;
case 1: return std::string( "00") + millisec;
case 0: return std::string("000") + millisec;
default: return millisec;
}
}
void getMillisecString(std::chrono::system_clock::time_point const & time, std::string & result)
{
result = getMillisecMbs(time);
}
std::chrono::system_clock::time_point getNowSystemClock() TBAG_NOEXCEPT
{
return std::chrono::system_clock::now();
}
time_t getTime(std::chrono::system_clock::time_point const & time_point) TBAG_NOEXCEPT
{
return std::chrono::system_clock::to_time_t(time_point);
}
time_t getCurrentTime() TBAG_NOEXCEPT
{
return getTime(getNowSystemClock());
}
bool getGmtTime(time_t const & t, tm * output)
{
return __impl::SafetyTimeGetter::getInstance()->getGmtTime(t, output);
}
bool getLocalTime(time_t const & t, tm * output)
{
return __impl::SafetyTimeGetter::getInstance()->getLocalTime(t, output);
}
std::chrono::system_clock::duration getCurrentLocalDuration()
{
return __impl::LocalTimeDiff::getInstance()->getLocalDiff();
}
std::string getFormatString(std::string const & format, tm const * t, std::size_t allocate_size)
{
// The expected size of the buffer.
std::vector<char> buffer;
buffer.resize(allocate_size, static_cast<char>(0x00));
std::size_t length = std::strftime(&buffer[0], allocate_size, format.c_str(), t);
if (length >= allocate_size) {
return getFormatString(format, t, allocate_size * 2);
}
return std::string(buffer.begin(), buffer.begin() + length);
}
std::string getLocalTimeZoneAbbreviation()
{
#if defined(TBAG_PLATFORM_UNIX_LIKE)
struct tm local_time = {0,};
if (getLocalTime(getCurrentTime(), &local_time)) {
// MSVC error C2039: 'tm_zone': is not a member of 'tm'
if (local_time.tm_zone != nullptr) {
return std::string(local_time.tm_zone);
}
}
#endif
return std::string();
}
#ifndef UINT64CONST
#define UINT64CONST(x) ((uint64_t)(x##ULL))
#endif
// FILETIME of Jan 1 1970 00:00:00.
TBAG_CONSTEXPR const ULONGLONG WIN32_FILETIME_EPOCH = UINT64CONST(116444736000000000);
static void __win32_gettimeofday(long * sec, long * micro)
{
FILETIME file_time;
SYSTEMTIME system_time;
ULARGE_INTEGER ularge;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
if (sec != nullptr) {
*sec = (long) ((ularge.QuadPart - WIN32_FILETIME_EPOCH) / 10000000L);
}
if (micro != nullptr) {
*micro = (long) (system_time.wMilliseconds * 1000);
}
}
static int __win32_gettimeofday(struct timeval * tp)
{
FILETIME file_time;
SYSTEMTIME system_time;
ULARGE_INTEGER ularge;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
if (tp != nullptr) {
tp->tv_sec = (long) ((ularge.QuadPart - WIN32_FILETIME_EPOCH) / 10000000L);
tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
}
return 0;
}
static int _gettimeofday(struct timeval * tp)
{
#if defined(TBAG_PLATFORM_WINDOWS)
return __win32_gettimeofday(tp);
#else
return ::gettimeofday(tp, nullptr);
#endif
}
Err getTimeOfDay(long * sec, long * micro)
{
timeval tp = {0,};
// timezone information is stored outside the kernel so tzp isn't used anymore.
if (_gettimeofday(&tp) != 0) {
return libtbag::getGlobalSystemError();
}
if (sec != nullptr) {
*sec = tp.tv_sec;
}
if (micro != nullptr) {
*micro = tp.tv_usec;
}
return Err::E_SUCCESS;
}
} // namespace time
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
|
/**
* @file Time.cpp
* @brief Time class implementation.
* @author zer0
* @date 2016-07-17
*/
#include <libtbag/time/Time.hpp>
#include <libtbag/debug/Assert.hpp>
#include <libtbag/pattern/Singleton2.hpp>
#include <libtbag/string/StringUtils.hpp>
#include <libtbag/3rd/date/date.h>
#include <cassert>
#include <cstring>
#include <cmath>
#include <ratio>
#include <mutex>
#include <atomic>
#include <type_traits>
// Where is 'timeval' structure?
// [WARNING] Don't change include order.
#if defined(TBAG_PLATFORM_WINDOWS)
# include <Windows.h>
#else
# include <sys/time.h>
# include <libtbag/dummy/Win32.hpp>
using namespace ::libtbag::dummy::win32;
#endif
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace time {
/* inline */ namespace __impl {
/**
* SafetyTimeGetter class prototype & implementation.
*
* @translate{ko, 이 클래스는 표준C 라이브러리의 데이터 경쟁(Data race)상태를 해결하기 위해 작성되었다.}
*
* @author zer0
* @date 2016-09-22
*
* @remarks
* This class is the solution of the data race conditions.
*/
class SafetyTimeGetter : public ::libtbag::pattern::Singleton2<SafetyTimeGetter>
{
public:
SINGLETON2_PROTOTYPE(SafetyTimeGetter);
public:
using Mutex = std::mutex;
using Guard = std::lock_guard<Mutex>;
private:
mutable Mutex _mutex;
private:
template <typename Predicated>
inline bool tryCatch(Predicated predicated) const
{
try {
Guard g(_mutex);
predicated();
} catch (...) {
return false;
}
return true;
}
public:
inline bool getGmtTime(time_t const & t, tm * output) const
{
return tryCatch([&](){
if (output != nullptr) {
memcpy(output, gmtime(&t), sizeof(tm)); // Position of data race!
}
});
}
inline bool getLocalTime(time_t const & t, tm * output) const
{
return tryCatch([&](){
if (output != nullptr) {
memcpy(output, localtime(&t), sizeof(tm)); // Position of data race!
}
});
}
public:
};
/**
* @author zer0
* @date 2017-04-11
*/
class LocalTimeDiff : public ::libtbag::pattern::Singleton2<LocalTimeDiff>
{
public:
friend class ::libtbag::pattern::Singleton2<LocalTimeDiff>;
private:
std::chrono::system_clock::duration _local_diff;
std::atomic_bool _update_local_diff;
protected:
LocalTimeDiff() : _local_diff(0)
{
_update_local_diff = false;
}
public:
~LocalTimeDiff()
{
// EMPTY.
}
private:
bool updateLocalDiff()
{
time_t time = getCurrentTime();
struct tm gmt_time = {0,};
struct tm local_time = {0,};
bool is_gmt = __impl::SafetyTimeGetter::getInstance()->getGmtTime(time, &gmt_time);
bool is_local = __impl::SafetyTimeGetter::getInstance()->getLocalTime(time, &local_time);
if (is_gmt == false || is_local == false) {
return false;
}
auto gmt_time_point = std::chrono::system_clock::from_time_t(mktime( &gmt_time));
auto local_time_point = std::chrono::system_clock::from_time_t(mktime(&local_time));
_local_diff = (local_time_point - gmt_time_point);
_update_local_diff = true;
return true;
}
public:
std::chrono::system_clock::duration getLocalDiff()
{
if (_update_local_diff == false) {
updateLocalDiff();
}
return _local_diff;
}
};
/**
* @warning
* Epoch time은 UTC 이전(1970/01/01T00:00:00)일 경우 음수로 표현된다. @n
* 이 경우 정상적인 계산이 이루어지지 않는다. @n
* 이 현상을 해결하기 위해 Date(날짜)의 기준을 1970년 이후로 맞춰주면 된다.
*/
template <typename Cut, typename Destination, typename Clock, typename ClockDuration>
typename Destination::rep getTimeFloor(std::chrono::time_point<Clock, ClockDuration> const & time)
{
static_assert(std::ratio_less_equal<typename Cut::period, std::chrono::hours::period>::value,
"Unsupported Cut type.");
static_assert(std::ratio_less<typename Destination::period, typename Cut::period>::value,
"Destination must be less than Cut.");
using TimePoint = std::chrono::time_point<Clock, ClockDuration>;
ClockDuration epoch_time = time.time_since_epoch();
if (epoch_time.count() < 0) {
auto DAYS_OF_EPOCH = date::floor<date::days>(date::years(1970));
auto days = date::floor<date::days>(time);
epoch_time += (DAYS_OF_EPOCH - days.time_since_epoch());
assert(epoch_time.count() >= 0);
}
epoch_time -= std::chrono::duration_cast<Cut>(epoch_time);
assert(epoch_time.count() >= 0);
// [WARNING] It does not work on some platforms:
// return static_cast<int>(result / std::chrono::milliseconds(1));
return std::abs(std::chrono::duration_cast<Destination>(epoch_time).count());
}
void createInstance()
{
LocalTimeDiff::createInstance();
SafetyTimeGetter::createInstance();
}
void releaseInstance()
{
SafetyTimeGetter::releaseInstance();
LocalTimeDiff::releaseInstance();
}
} // namespace __impl
int getYear(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::year_month_day(date::floor<date::days>(time)).year());
}
int getMonth(std::chrono::system_clock::time_point const & time)
{
return static_cast<unsigned>(date::year_month_day(date::floor<date::days>(time)).month());
}
int getDay(std::chrono::system_clock::time_point const & time)
{
return static_cast<unsigned>(date::year_month_day(date::floor<date::days>(time)).day());
}
int getHours(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).hours().count());
}
int getMinutes(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).minutes().count());
}
int getSeconds(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).seconds().count());
}
int getSubSeconds(std::chrono::system_clock::time_point const & time)
{
return static_cast<int>(date::make_time(time - date::floor<date::days>(time)).subseconds().count());
}
int getWeek(std::chrono::system_clock::time_point const & time)
{
return static_cast<unsigned>(date::weekday(date::floor<date::days>(time)));
}
std::string getWeekString(std::chrono::system_clock::time_point const & time)
{
switch (getWeek(time)) {
case 0: return "Sun";
case 1: return "Mon";
case 2: return "Tue";
case 3: return "Wed";
case 4: return "Thu";
case 5: return "Fri";
case 6: return "Sat";
default: TBAG_INACCESSIBLE_BLOCK_ASSERT();
}
return "[Unknown]";
}
int getMillisec(std::chrono::system_clock::time_point const & time)
{
using namespace std::chrono;
auto const RESULT = __impl::getTimeFloor<seconds, milliseconds>(time);
assert(0 <= COMPARE_AND(RESULT) < 1000);
return static_cast<int>(RESULT);
}
int getMicrosec(std::chrono::system_clock::time_point const & time)
{
using namespace std::chrono;
auto const RESULT = __impl::getTimeFloor<milliseconds, microseconds>(time);
assert(0 <= COMPARE_AND(RESULT) < 1000);
return static_cast<int>(RESULT);
}
int getNanosec(std::chrono::system_clock::time_point const & time)
{
using namespace std::chrono;
auto const RESULT = __impl::getTimeFloor<microseconds, nanoseconds>(time);
assert(0 <= COMPARE_AND(RESULT) < 1000);
return static_cast<int>(RESULT);
}
int getDays(std::chrono::system_clock::time_point const & time)
{
return date::floor<date::days>(time).time_since_epoch().count();
}
std::string getMillisecMbs(std::chrono::system_clock::time_point const & time)
{
std::string millisec = std::to_string(getMillisec(time));
switch (millisec.size()) {
case 2: return std::string( "0") + millisec;
case 1: return std::string( "00") + millisec;
case 0: return std::string("000") + millisec;
default: return millisec;
}
}
void getMillisecString(std::chrono::system_clock::time_point const & time, std::string & result)
{
result = getMillisecMbs(time);
}
std::chrono::system_clock::time_point getNowSystemClock() TBAG_NOEXCEPT
{
return std::chrono::system_clock::now();
}
time_t getTime(std::chrono::system_clock::time_point const & time_point) TBAG_NOEXCEPT
{
return std::chrono::system_clock::to_time_t(time_point);
}
time_t getCurrentTime() TBAG_NOEXCEPT
{
return getTime(getNowSystemClock());
}
bool getGmtTime(time_t const & t, tm * output)
{
return __impl::SafetyTimeGetter::getInstance()->getGmtTime(t, output);
}
bool getLocalTime(time_t const & t, tm * output)
{
return __impl::SafetyTimeGetter::getInstance()->getLocalTime(t, output);
}
std::chrono::system_clock::duration getCurrentLocalDuration()
{
return __impl::LocalTimeDiff::getInstance()->getLocalDiff();
}
std::string getFormatString(std::string const & format, tm const * t, std::size_t allocate_size)
{
// The expected size of the buffer.
std::vector<char> buffer;
buffer.resize(allocate_size, static_cast<char>(0x00));
std::size_t length = std::strftime(&buffer[0], allocate_size, format.c_str(), t);
if (length >= allocate_size) {
return getFormatString(format, t, allocate_size * 2);
}
return std::string(buffer.begin(), buffer.begin() + length);
}
std::string getLocalTimeZoneAbbreviation()
{
#if defined(TBAG_PLATFORM_UNIX_LIKE)
struct tm local_time = {0,};
if (getLocalTime(getCurrentTime(), &local_time)) {
// MSVC error C2039: 'tm_zone': is not a member of 'tm'
if (local_time.tm_zone != nullptr) {
return std::string(local_time.tm_zone);
}
}
#endif
return std::string();
}
#ifndef UINT64CONST
#define UINT64CONST(x) ((uint64_t)(x##ULL))
#endif
// FILETIME of Jan 1 1970 00:00:00.
TBAG_CONSTEXPR const ULONGLONG WIN32_FILETIME_EPOCH = UINT64CONST(116444736000000000);
static void __win32_gettimeofday(long * sec, long * micro)
{
FILETIME file_time;
SYSTEMTIME system_time;
ULARGE_INTEGER ularge;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
if (sec != nullptr) {
*sec = (long) ((ularge.QuadPart - WIN32_FILETIME_EPOCH) / 10000000L);
}
if (micro != nullptr) {
*micro = (long) (system_time.wMilliseconds * 1000);
}
}
static int __win32_gettimeofday(long & sec, long & micro)
{
FILETIME file_time;
SYSTEMTIME system_time;
ULARGE_INTEGER ularge;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
ularge.LowPart = file_time.dwLowDateTime;
ularge.HighPart = file_time.dwHighDateTime;
sec = (long) ((ularge.QuadPart - WIN32_FILETIME_EPOCH) / 10000000L);
micro = (long) (system_time.wMilliseconds * 1000);
return 0;
}
static int _gettimeofday(long & sec, long & micro)
{
#if defined(TBAG_PLATFORM_WINDOWS)
return __win32_gettimeofday(tp);
#else
timeval tp = {0,};
// timezone information is stored outside the kernel so tzp isn't used anymore.
int const CODE = gettimeofday(&tp, nullptr);
sec = tp.tv_sec;
micro = tp.tv_usec;
return CODE;
#endif
}
Err getTimeOfDay(long * sec, long * micro)
{
long s, u;
if (_gettimeofday(s, u) != 0) {
return libtbag::getGlobalSystemError();
}
if (sec != nullptr) {
*sec = s;
}
if (micro != nullptr) {
*micro = u;
}
return Err::E_SUCCESS;
}
} // namespace time
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
|
Remove timeval in MSVC.
|
Remove timeval in MSVC.
|
C++
|
mit
|
osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag
|
5d061749f9be5c7a786be892ca5229b60e9eb42c
|
mainwindow.cpp
|
mainwindow.cpp
|
/* This file is part of Zanshin Todo.
Copyright 2008 Kevin Ottens <[email protected]>
Copyright 2008, 2009 Mario Bensi <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "mainwindow.h"
#include <akonadi/control.h>
#include <akonadi/collectionfetchjob.h>
#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KIcon>
#include <KDE/KLocale>
#include <QtGui/QDockWidget>
#include <QtGui/QHeaderView>
#include "actionlisteditor.h"
#include "actionlistview.h"
#include "configdialog.h"
#include "globalmodel.h"
#include "globalsettings.h"
#include "todoflatmodel.h"
#include "sidebar.h"
MainWindow::MainWindow(QWidget *parent)
: KXmlGuiWindow(parent)
{
Akonadi::Control::start();
setupSideBar();
setupCentralWidget();
setupActions();
setupGUI();
restoreColumnState();
applySettings();
actionCollection()->action("project_mode")->trigger();
}
void MainWindow::setupCentralWidget()
{
m_editor = new ActionListEditor(this, actionCollection());
connect(m_sidebar, SIGNAL(noProjectInboxActivated()),
m_editor, SLOT(showNoProjectInbox()));
connect(m_sidebar, SIGNAL(projectActivated(QModelIndex)),
m_editor, SLOT(focusOnProject(QModelIndex)));
connect(m_sidebar, SIGNAL(noContextInboxActivated()),
m_editor, SLOT(showNoContextInbox()));
connect(m_sidebar, SIGNAL(contextActivated(QModelIndex)),
m_editor, SLOT(focusOnContext(QModelIndex)));
setCentralWidget(m_editor);
}
void MainWindow::setupSideBar()
{
m_sidebar = new SideBar(this, actionCollection());
QDockWidget *dock = new QDockWidget(this);
dock->setObjectName("SideBar");
dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);
dock->setWidget(m_sidebar);
addDockWidget(Qt::LeftDockWidgetArea, dock);
}
void MainWindow::setupActions()
{
KActionCollection *ac = actionCollection();
QActionGroup *modeGroup = new QActionGroup(this);
modeGroup->setExclusive(true);
KAction *action = ac->addAction("project_mode", m_sidebar, SLOT(switchToProjectMode()));
action->setText(i18n("Project Mode"));
action->setIcon(KIcon("view-pim-tasks"));
action->setCheckable(true);
modeGroup->addAction(action);
action = ac->addAction("context_mode", m_sidebar, SLOT(switchToContextMode()));
action->setText(i18n("Context Mode"));
action->setIcon(KIcon("view-pim-notes"));
action->setCheckable(true);
modeGroup->addAction(action);
ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog()));
ac->addAction(KStandardAction::Quit, this, SLOT(close()));
}
void MainWindow::closeEvent(QCloseEvent *event)
{
saveColumnsState();
KXmlGuiWindow::closeEvent(event);
}
void MainWindow::saveAutoSaveSettings()
{
saveColumnsState();
KXmlGuiWindow::saveAutoSaveSettings();
}
void MainWindow::saveColumnsState()
{
KConfigGroup cg = autoSaveConfigGroup();
QByteArray state = m_editor->view()->header()->saveState();
cg.writeEntry("MainHeaderState", state.toBase64());
}
void MainWindow::restoreColumnState()
{
KConfigGroup cg = autoSaveConfigGroup();
QByteArray state;
if (cg.hasKey("MainHeaderState")) {
state = cg.readEntry("MainHeaderState", state);
m_editor->view()->header()->restoreState(QByteArray::fromBase64(state));
}
}
void MainWindow::showConfigDialog()
{
if (KConfigDialog::showDialog("settings")) {
return;
}
ConfigDialog *dialog = new ConfigDialog(this, "settings",
GlobalSettings::self());
connect(dialog, SIGNAL(settingsChanged(const QString&)),
this, SLOT(applySettings()));
dialog->show();
}
void MainWindow::applySettings()
{
Akonadi::Collection collection(GlobalSettings::collectionId());
Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(collection, Akonadi::CollectionFetchJob::Base);
job->exec();
GlobalModel::todoFlat()->setCollection(job->collections().first());
}
|
/* This file is part of Zanshin Todo.
Copyright 2008 Kevin Ottens <[email protected]>
Copyright 2008, 2009 Mario Bensi <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "mainwindow.h"
#include <akonadi/control.h>
#include <akonadi/collectionfetchjob.h>
#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KIcon>
#include <KDE/KLocale>
#include <QtGui/QDockWidget>
#include <QtGui/QHeaderView>
#include "actionlisteditor.h"
#include "actionlistview.h"
#include "configdialog.h"
#include "globalmodel.h"
#include "globalsettings.h"
#include "todoflatmodel.h"
#include "sidebar.h"
MainWindow::MainWindow(QWidget *parent)
: KXmlGuiWindow(parent)
{
Akonadi::Control::start();
setupSideBar();
setupCentralWidget();
setupActions();
setupGUI();
restoreColumnState();
applySettings();
actionCollection()->action("project_mode")->trigger();
}
void MainWindow::setupCentralWidget()
{
m_editor = new ActionListEditor(this, actionCollection());
connect(m_sidebar, SIGNAL(noProjectInboxActivated()),
m_editor, SLOT(showNoProjectInbox()));
connect(m_sidebar, SIGNAL(projectActivated(QModelIndex)),
m_editor, SLOT(focusOnProject(QModelIndex)));
connect(m_sidebar, SIGNAL(noContextInboxActivated()),
m_editor, SLOT(showNoContextInbox()));
connect(m_sidebar, SIGNAL(contextActivated(QModelIndex)),
m_editor, SLOT(focusOnContext(QModelIndex)));
setCentralWidget(m_editor);
}
void MainWindow::setupSideBar()
{
m_sidebar = new SideBar(this, actionCollection());
QDockWidget *dock = new QDockWidget(this);
dock->setObjectName("SideBar");
dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);
dock->setWidget(m_sidebar);
addDockWidget(Qt::LeftDockWidgetArea, dock);
}
void MainWindow::setupActions()
{
KActionCollection *ac = actionCollection();
QActionGroup *modeGroup = new QActionGroup(this);
modeGroup->setExclusive(true);
KAction *action = ac->addAction("project_mode", m_sidebar, SLOT(switchToProjectMode()));
action->setText(i18n("Project Mode"));
action->setIcon(KIcon("view-pim-tasks"));
action->setCheckable(true);
modeGroup->addAction(action);
action = ac->addAction("context_mode", m_sidebar, SLOT(switchToContextMode()));
action->setText(i18n("Context Mode"));
action->setIcon(KIcon("view-pim-notes"));
action->setCheckable(true);
modeGroup->addAction(action);
ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog()));
ac->addAction(KStandardAction::Quit, this, SLOT(close()));
}
void MainWindow::closeEvent(QCloseEvent *event)
{
saveColumnsState();
KXmlGuiWindow::closeEvent(event);
}
void MainWindow::saveAutoSaveSettings()
{
saveColumnsState();
KXmlGuiWindow::saveAutoSaveSettings();
}
void MainWindow::saveColumnsState()
{
KConfigGroup cg = autoSaveConfigGroup();
QByteArray state = m_editor->view()->header()->saveState();
cg.writeEntry("MainHeaderState", state.toBase64());
}
void MainWindow::restoreColumnState()
{
KConfigGroup cg = autoSaveConfigGroup();
QByteArray state;
if (cg.hasKey("MainHeaderState")) {
state = cg.readEntry("MainHeaderState", state);
m_editor->view()->header()->restoreState(QByteArray::fromBase64(state));
}
}
void MainWindow::showConfigDialog()
{
if (KConfigDialog::showDialog("settings")) {
return;
}
ConfigDialog *dialog = new ConfigDialog(this, "settings",
GlobalSettings::self());
connect(dialog, SIGNAL(settingsChanged(const QString&)),
this, SLOT(applySettings()));
dialog->show();
}
void MainWindow::applySettings()
{
Akonadi::Collection collection(GlobalSettings::collectionId());
if (!collection.isValid()) return;
Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(collection, Akonadi::CollectionFetchJob::Base);
job->exec();
GlobalModel::todoFlat()->setCollection(job->collections().first());
}
|
Make sure the collection is valid before trying a fetch.
|
Make sure the collection is valid before trying a fetch.
|
C++
|
lgpl-2.1
|
sandsmark/zanshin,kolab-groupware/zanshin,sandsmark/zanshin,kolab-groupware/zanshin,kolab-groupware/zanshin,sandsmark/zanshin
|
2bc5c81a5a0915731bba60495c8a404cb6a0a025
|
src/plugins/debugger/qml/qmljsscriptconsole.cpp
|
src/plugins/debugger/qml/qmljsscriptconsole.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "qmljsscriptconsole.h"
#include "interactiveinterpreter.h"
#include "qmladapter.h"
#include "debuggerstringutils.h"
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/coreconstants.h>
#include <utils/statuslabel.h>
#include <QtGui/QMenu>
#include <QtGui/QTextBlock>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QToolButton>
namespace Debugger {
namespace Internal {
class QmlJSScriptConsolePrivate
{
public:
QmlJSScriptConsolePrivate()
: prompt(_("> ")),
startOfEditableArea(-1),
lastKnownPosition(0),
inferiorStopped(false)
{
resetCache();
}
void resetCache();
void appendToHistory(const QString &script);
bool canEvaluateScript(const QString &script);
QWeakPointer<QmlAdapter> adapter;
QString prompt;
int startOfEditableArea;
int lastKnownPosition;
QStringList scriptHistory;
int scriptHistoryIndex;
InteractiveInterpreter interpreter;
bool inferiorStopped;
QList<QTextEdit::ExtraSelection> selections;
};
void QmlJSScriptConsolePrivate::resetCache()
{
scriptHistory.clear();
scriptHistory.append(QString());
scriptHistoryIndex = scriptHistory.count();
selections.clear();
}
void QmlJSScriptConsolePrivate::appendToHistory(const QString &script)
{
scriptHistoryIndex = scriptHistory.count();
scriptHistory.replace(scriptHistoryIndex - 1,script);
scriptHistory.append(QString());
scriptHistoryIndex = scriptHistory.count();
}
bool QmlJSScriptConsolePrivate::canEvaluateScript(const QString &script)
{
interpreter.clearText();
interpreter.appendText(script);
return interpreter.canEvaluate();
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsoleWidget
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsoleWidget::QmlJSScriptConsoleWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
vbox->setSpacing(0);
QWidget *statusbarContainer = new QWidget;
QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer);
hbox->setMargin(0);
hbox->setSpacing(0);
//Clear Button
QToolButton *clearButton = new QToolButton;
QAction *clearAction = new QAction(tr("Clear Console"), this);
clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE)));
clearButton->setDefaultAction(clearAction);
//Status Label
m_statusLabel = new Utils::StatusLabel;
hbox->addWidget(m_statusLabel, 20, Qt::AlignLeft);
hbox->addWidget(clearButton, 0, Qt::AlignRight);
m_console = new QmlJSScriptConsole;
connect(m_console, SIGNAL(evaluateExpression(QString)), this,
SIGNAL(evaluateExpression(QString)));
connect(m_console, SIGNAL(updateStatusMessage(const QString &, int)), m_statusLabel,
SLOT(showStatusMessage(const QString &, int)));
connect(clearAction, SIGNAL(triggered()), m_console, SLOT(clear()));
vbox->addWidget(statusbarContainer);
vbox->addWidget(m_console);
}
void QmlJSScriptConsoleWidget::setQmlAdapter(QmlAdapter *adapter)
{
m_console->setQmlAdapter(adapter);
}
void QmlJSScriptConsoleWidget::setInferiorStopped(bool inferiorStopped)
{
m_console->setInferiorStopped(inferiorStopped);
}
void QmlJSScriptConsoleWidget::appendResult(const QString &result)
{
m_console->appendResult(result);
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsole
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsole::QmlJSScriptConsole(QWidget *parent)
: QPlainTextEdit(parent),
d(new QmlJSScriptConsolePrivate())
{
connect(this, SIGNAL(cursorPositionChanged()), SLOT(onCursorPositionChanged()));
setFrameStyle(QFrame::NoFrame);
setUndoRedoEnabled(false);
setBackgroundVisible(false);
const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
setFont(fs.font());
displayPrompt();
}
QmlJSScriptConsole::~QmlJSScriptConsole()
{
delete d;
}
void QmlJSScriptConsole::setPrompt(const QString &prompt)
{
d->prompt = prompt;
}
QString QmlJSScriptConsole::prompt() const
{
return d->prompt;
}
void QmlJSScriptConsole::setInferiorStopped(bool inferiorStopped)
{
d->inferiorStopped = inferiorStopped;
onSelectionChanged();
}
void QmlJSScriptConsole::setQmlAdapter(QmlAdapter *adapter)
{
d->adapter = adapter;
if (adapter)
connect(adapter, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
clear();
}
void QmlJSScriptConsole::appendResult(const QString &result)
{
QString currentScript = getCurrentScript();
d->appendToHistory(currentScript);
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::End);
cur.insertText(_("\n"));
cur.insertText(result);
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(_("\n"));
setTextCursor(cur);
displayPrompt();
QTextEdit::ExtraSelection sel;
QTextCharFormat resultFormat;
resultFormat.setForeground(QBrush(QColor(Qt::darkGray)));
QTextCursor c(document()->findBlockByNumber(cur.blockNumber()-1));
c.movePosition(QTextCursor::StartOfBlock);
c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
sel.format = resultFormat;
sel.cursor = c;
d->selections.append(sel);
setExtraSelections(d->selections);
}
void QmlJSScriptConsole::clear()
{
d->resetCache();
QPlainTextEdit::clear();
displayPrompt();
}
void QmlJSScriptConsole::onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
QDeclarativeDebugExpressionQuery *query = qobject_cast<QDeclarativeDebugExpressionQuery *>(sender());
if (query && state != QDeclarativeDebugQuery::Error) {
QString result(query->result().toString());
if (result == _("<undefined>") && d->inferiorStopped) {
//don't give up. check if we can still evaluate using javascript engine
emit evaluateExpression(getCurrentScript());
} else {
appendResult(result);
}
} else {
QPlainTextEdit::appendPlainText(QString());
moveCursor(QTextCursor::EndOfLine);
}
delete query;
}
void QmlJSScriptConsole::onSelectionChanged()
{
if (!d->adapter.isNull()) {
QString status;
if (!d->inferiorStopped) {
status.append(tr("Current Selected Object: "));
status.append(d->adapter.data()->currentSelectedDisplayName());
}
emit updateStatusMessage(status, 0);
}
}
void QmlJSScriptConsole::keyPressEvent(QKeyEvent *e)
{
bool keyConsumed = false;
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
if (isEditableArea()) {
handleReturnKey();
keyConsumed = true;
}
break;
case Qt::Key_Backspace: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if ((hasSelection && selectionStart < d->startOfEditableArea)
|| (!hasSelection && selectionStart == d->startOfEditableArea)) {
keyConsumed = true;
}
break;
}
case Qt::Key_Delete:
if (textCursor().selectionStart() < d->startOfEditableArea) {
keyConsumed = true;
}
break;
case Qt::Key_Tab:
case Qt::Key_Backtab:
keyConsumed = true;
break;
case Qt::Key_Left:
if (textCursor().position() == d->startOfEditableArea) {
keyConsumed = true;
} else if (e->modifiers() & Qt::ControlModifier && isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_Up:
if (isEditableArea()) {
handleUpKey();
keyConsumed = true;
}
break;
case Qt::Key_Down:
if (isEditableArea()) {
handleDownKey();
keyConsumed = true;
}
break;
case Qt::Key_Home:
if (isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_C:
case Qt::Key_Insert: {
//Fair to assume that for any selection beyond startOfEditableArea
//only copy function is allowed.
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
if (!(e->modifiers() & Qt::ControlModifier))
keyConsumed = true;
}
break;
}
default: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
keyConsumed = true;
}
break;
}
}
if (!keyConsumed)
QPlainTextEdit::keyPressEvent(e);
}
void QmlJSScriptConsole::contextMenuEvent(QContextMenuEvent *event)
{
QTextCursor cursor = textCursor();
Qt::TextInteractionFlags flags = textInteractionFlags();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
bool canBeEdited = true;
if (hasSelection && selectionStart < d->startOfEditableArea) {
canBeEdited = false;
}
QMenu *menu = new QMenu();
QAction *a;
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Cut"), this, SLOT(cut()));
a->setEnabled(cursor.hasSelection());
}
a = menu->addAction(tr("Copy"), this, SLOT(copy()));
a->setEnabled(cursor.hasSelection());
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Paste"), this, SLOT(paste()));
a->setEnabled(canPaste());
}
menu->addSeparator();
a = menu->addAction(tr("Select All"), this, SLOT(selectAll()));
a->setEnabled(!document()->isEmpty());
menu->addSeparator();
menu->addAction(tr("Clear"), this, SLOT(clear()));
menu->exec(event->globalPos());
delete menu;
}
void QmlJSScriptConsole::mouseReleaseEvent(QMouseEvent *e)
{
QPlainTextEdit::mouseReleaseEvent(e);
QTextCursor cursor = textCursor();
if (e->button() == Qt::LeftButton && !cursor.hasSelection() && !isEditableArea()) {
cursor.setPosition(d->lastKnownPosition);
setTextCursor(cursor);
}
}
void QmlJSScriptConsole::onCursorPositionChanged()
{
if (!isEditableArea()) {
setTextInteractionFlags(Qt::TextSelectableByMouse);
} else {
d->lastKnownPosition = textCursor().position();
setTextInteractionFlags(Qt::TextEditorInteraction);
}
}
void QmlJSScriptConsole::displayPrompt()
{
d->startOfEditableArea = textCursor().position() + d->prompt.length();
QTextCursor cur = textCursor();
cur.insertText(d->prompt);
cur.movePosition(QTextCursor::EndOfWord);
setTextCursor(cur);
}
void QmlJSScriptConsole::handleReturnKey()
{
QString currentScript = getCurrentScript();
bool scriptEvaluated = false;
//Check if string is only white spaces
if (currentScript.trimmed().isEmpty()) {
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(_("\n"));
setTextCursor(cur);
displayPrompt();
scriptEvaluated = true;
}
if (!scriptEvaluated) {
//check if it can be evaluated
if (d->canEvaluateScript(currentScript)) {
//Select the engine for evaluation based on
//inferior state
if (!d->inferiorStopped) {
if (!d->adapter.isNull()) {
QDeclarativeEngineDebug *engineDebug = d->adapter.data()->engineDebugClient();
int id = d->adapter.data()->currentSelectedDebugId();
if (engineDebug && id != -1) {
QDeclarativeDebugExpressionQuery *query =
engineDebug->queryExpressionResult(id, currentScript, this);
connect(query, SIGNAL(stateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)),
this, SLOT(onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)));
scriptEvaluated = true;
}
}
}
if (!scriptEvaluated) {
emit evaluateExpression(currentScript);
scriptEvaluated = true;
}
}
}
if (!scriptEvaluated) {
QPlainTextEdit::appendPlainText(QString());
moveCursor(QTextCursor::EndOfLine);
}
}
void QmlJSScriptConsole::handleUpKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex > 1)
d->scriptHistoryIndex--;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleDownKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex < d->scriptHistory.count())
d->scriptHistoryIndex++;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleHomeKey()
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
setTextCursor(cursor);
}
QString QmlJSScriptConsole::getCurrentScript() const
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor)) ;
QString script = cursor.selectedText();
cursor.clearSelection();
//remove trailing white space
int end = script.size() - 1;
while (end > 0 && script[end].isSpace())
end--;
return script.left(end + 1);
}
void QmlJSScriptConsole::replaceCurrentScript(const QString &script)
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor)) ;
cursor.deleteChar();
cursor.insertText(script);
setTextCursor(cursor);
}
bool QmlJSScriptConsole::isEditableArea() const
{
return textCursor().position() >= d->startOfEditableArea;
}
} //Internal
} //Debugger
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "qmljsscriptconsole.h"
#include "interactiveinterpreter.h"
#include "qmladapter.h"
#include "debuggerstringutils.h"
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/coreconstants.h>
#include <utils/statuslabel.h>
#include <QtGui/QMenu>
#include <QtGui/QTextBlock>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QToolButton>
namespace Debugger {
namespace Internal {
class QmlJSScriptConsolePrivate
{
public:
QmlJSScriptConsolePrivate()
: prompt(_("> ")),
startOfEditableArea(-1),
lastKnownPosition(0),
inferiorStopped(false)
{
resetCache();
}
void resetCache();
void appendToHistory(const QString &script);
bool canEvaluateScript(const QString &script);
QWeakPointer<QmlAdapter> adapter;
QString prompt;
int startOfEditableArea;
int lastKnownPosition;
QStringList scriptHistory;
int scriptHistoryIndex;
InteractiveInterpreter interpreter;
bool inferiorStopped;
QList<QTextEdit::ExtraSelection> selections;
};
void QmlJSScriptConsolePrivate::resetCache()
{
scriptHistory.clear();
scriptHistory.append(QString());
scriptHistoryIndex = scriptHistory.count();
selections.clear();
}
void QmlJSScriptConsolePrivate::appendToHistory(const QString &script)
{
scriptHistoryIndex = scriptHistory.count();
scriptHistory.replace(scriptHistoryIndex - 1,script);
scriptHistory.append(QString());
scriptHistoryIndex = scriptHistory.count();
}
bool QmlJSScriptConsolePrivate::canEvaluateScript(const QString &script)
{
interpreter.clearText();
interpreter.appendText(script);
return interpreter.canEvaluate();
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsoleWidget
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsoleWidget::QmlJSScriptConsoleWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
vbox->setSpacing(0);
QWidget *statusbarContainer = new QWidget;
QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer);
hbox->setMargin(0);
hbox->setSpacing(0);
//Clear Button
QToolButton *clearButton = new QToolButton;
QAction *clearAction = new QAction(tr("Clear Console"), this);
clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE)));
clearButton->setDefaultAction(clearAction);
//Status Label
m_statusLabel = new Utils::StatusLabel;
hbox->addWidget(m_statusLabel, 20, Qt::AlignLeft);
hbox->addWidget(clearButton, 0, Qt::AlignRight);
m_console = new QmlJSScriptConsole;
connect(m_console, SIGNAL(evaluateExpression(QString)), this,
SIGNAL(evaluateExpression(QString)));
connect(m_console, SIGNAL(updateStatusMessage(const QString &, int)), m_statusLabel,
SLOT(showStatusMessage(const QString &, int)));
connect(clearAction, SIGNAL(triggered()), m_console, SLOT(clear()));
vbox->addWidget(statusbarContainer);
vbox->addWidget(m_console);
}
void QmlJSScriptConsoleWidget::setQmlAdapter(QmlAdapter *adapter)
{
m_console->setQmlAdapter(adapter);
}
void QmlJSScriptConsoleWidget::setInferiorStopped(bool inferiorStopped)
{
m_console->setInferiorStopped(inferiorStopped);
}
void QmlJSScriptConsoleWidget::appendResult(const QString &result)
{
m_console->appendResult(result);
}
///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsole
//
///////////////////////////////////////////////////////////////////////
QmlJSScriptConsole::QmlJSScriptConsole(QWidget *parent)
: QPlainTextEdit(parent),
d(new QmlJSScriptConsolePrivate())
{
connect(this, SIGNAL(cursorPositionChanged()), SLOT(onCursorPositionChanged()));
setFrameStyle(QFrame::NoFrame);
setUndoRedoEnabled(false);
setBackgroundVisible(false);
const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
setFont(fs.font());
displayPrompt();
}
QmlJSScriptConsole::~QmlJSScriptConsole()
{
delete d;
}
void QmlJSScriptConsole::setPrompt(const QString &prompt)
{
d->prompt = prompt;
}
QString QmlJSScriptConsole::prompt() const
{
return d->prompt;
}
void QmlJSScriptConsole::setInferiorStopped(bool inferiorStopped)
{
d->inferiorStopped = inferiorStopped;
onSelectionChanged();
}
void QmlJSScriptConsole::setQmlAdapter(QmlAdapter *adapter)
{
d->adapter = adapter;
if (adapter)
connect(adapter, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
clear();
}
void QmlJSScriptConsole::appendResult(const QString &result)
{
QString currentScript = getCurrentScript();
d->appendToHistory(currentScript);
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::End);
cur.insertText(_("\n"));
cur.insertText(result);
cur.insertText(_("\n"));
QTextEdit::ExtraSelection sel;
QTextCharFormat resultFormat;
resultFormat.setForeground(QBrush(QColor(Qt::darkGray)));
cur.movePosition(QTextCursor::PreviousBlock);
cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
sel.format = resultFormat;
sel.cursor = cur;
d->selections.append(sel);
setExtraSelections(d->selections);
displayPrompt();
}
void QmlJSScriptConsole::clear()
{
d->resetCache();
QPlainTextEdit::clear();
displayPrompt();
}
void QmlJSScriptConsole::onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
QDeclarativeDebugExpressionQuery *query = qobject_cast<QDeclarativeDebugExpressionQuery *>(sender());
if (query && state != QDeclarativeDebugQuery::Error) {
QString result(query->result().toString());
if (result == _("<undefined>") && d->inferiorStopped) {
//don't give up. check if we can still evaluate using javascript engine
emit evaluateExpression(getCurrentScript());
} else {
appendResult(result);
}
} else {
QPlainTextEdit::appendPlainText(QString());
moveCursor(QTextCursor::EndOfLine);
}
delete query;
}
void QmlJSScriptConsole::onSelectionChanged()
{
if (!d->adapter.isNull()) {
QString status;
if (!d->inferiorStopped) {
status.append(tr("Current Selected Object: "));
status.append(d->adapter.data()->currentSelectedDisplayName());
}
emit updateStatusMessage(status, 0);
}
}
void QmlJSScriptConsole::keyPressEvent(QKeyEvent *e)
{
bool keyConsumed = false;
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
if (isEditableArea()) {
handleReturnKey();
keyConsumed = true;
}
break;
case Qt::Key_Backspace: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if ((hasSelection && selectionStart < d->startOfEditableArea)
|| (!hasSelection && selectionStart == d->startOfEditableArea)) {
keyConsumed = true;
}
break;
}
case Qt::Key_Delete:
if (textCursor().selectionStart() < d->startOfEditableArea) {
keyConsumed = true;
}
break;
case Qt::Key_Tab:
case Qt::Key_Backtab:
keyConsumed = true;
break;
case Qt::Key_Left:
if (textCursor().position() == d->startOfEditableArea) {
keyConsumed = true;
} else if (e->modifiers() & Qt::ControlModifier && isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_Up:
if (isEditableArea()) {
handleUpKey();
keyConsumed = true;
}
break;
case Qt::Key_Down:
if (isEditableArea()) {
handleDownKey();
keyConsumed = true;
}
break;
case Qt::Key_Home:
if (isEditableArea()) {
handleHomeKey();
keyConsumed = true;
}
break;
case Qt::Key_C:
case Qt::Key_Insert: {
//Fair to assume that for any selection beyond startOfEditableArea
//only copy function is allowed.
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
if (!(e->modifiers() & Qt::ControlModifier))
keyConsumed = true;
}
break;
}
default: {
QTextCursor cursor = textCursor();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
if (hasSelection && selectionStart < d->startOfEditableArea) {
keyConsumed = true;
}
break;
}
}
if (!keyConsumed)
QPlainTextEdit::keyPressEvent(e);
}
void QmlJSScriptConsole::contextMenuEvent(QContextMenuEvent *event)
{
QTextCursor cursor = textCursor();
Qt::TextInteractionFlags flags = textInteractionFlags();
bool hasSelection = cursor.hasSelection();
int selectionStart = cursor.selectionStart();
bool canBeEdited = true;
if (hasSelection && selectionStart < d->startOfEditableArea) {
canBeEdited = false;
}
QMenu *menu = new QMenu();
QAction *a;
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Cut"), this, SLOT(cut()));
a->setEnabled(cursor.hasSelection());
}
a = menu->addAction(tr("Copy"), this, SLOT(copy()));
a->setEnabled(cursor.hasSelection());
if ((flags & Qt::TextEditable) && canBeEdited) {
a = menu->addAction(tr("Paste"), this, SLOT(paste()));
a->setEnabled(canPaste());
}
menu->addSeparator();
a = menu->addAction(tr("Select All"), this, SLOT(selectAll()));
a->setEnabled(!document()->isEmpty());
menu->addSeparator();
menu->addAction(tr("Clear"), this, SLOT(clear()));
menu->exec(event->globalPos());
delete menu;
}
void QmlJSScriptConsole::mouseReleaseEvent(QMouseEvent *e)
{
QPlainTextEdit::mouseReleaseEvent(e);
QTextCursor cursor = textCursor();
if (e->button() == Qt::LeftButton && !cursor.hasSelection() && !isEditableArea()) {
cursor.setPosition(d->lastKnownPosition);
setTextCursor(cursor);
}
}
void QmlJSScriptConsole::onCursorPositionChanged()
{
if (!isEditableArea()) {
setTextInteractionFlags(Qt::TextSelectableByMouse);
} else {
d->lastKnownPosition = textCursor().position();
setTextInteractionFlags(Qt::TextEditorInteraction);
}
}
void QmlJSScriptConsole::displayPrompt()
{
d->startOfEditableArea = textCursor().position() + d->prompt.length();
QTextCursor cur = textCursor();
cur.insertText(d->prompt);
cur.movePosition(QTextCursor::EndOfWord);
setTextCursor(cur);
}
void QmlJSScriptConsole::handleReturnKey()
{
QString currentScript = getCurrentScript();
bool scriptEvaluated = false;
//Check if string is only white spaces
if (currentScript.trimmed().isEmpty()) {
QTextCursor cur = textCursor();
cur.movePosition(QTextCursor::EndOfLine);
cur.insertText(_("\n"));
setTextCursor(cur);
displayPrompt();
scriptEvaluated = true;
}
if (!scriptEvaluated) {
//check if it can be evaluated
if (d->canEvaluateScript(currentScript)) {
//Select the engine for evaluation based on
//inferior state
if (!d->inferiorStopped) {
if (!d->adapter.isNull()) {
QDeclarativeEngineDebug *engineDebug = d->adapter.data()->engineDebugClient();
int id = d->adapter.data()->currentSelectedDebugId();
if (engineDebug && id != -1) {
QDeclarativeDebugExpressionQuery *query =
engineDebug->queryExpressionResult(id, currentScript, this);
connect(query, SIGNAL(stateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)),
this, SLOT(onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)));
scriptEvaluated = true;
}
}
}
if (!scriptEvaluated) {
emit evaluateExpression(currentScript);
scriptEvaluated = true;
}
}
}
if (!scriptEvaluated) {
QPlainTextEdit::appendPlainText(QString());
moveCursor(QTextCursor::EndOfLine);
}
}
void QmlJSScriptConsole::handleUpKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex > 1)
d->scriptHistoryIndex--;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleDownKey()
{
//get the current script and update in script history
QString currentScript = getCurrentScript();
d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);
if (d->scriptHistoryIndex < d->scriptHistory.count())
d->scriptHistoryIndex++;
replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}
void QmlJSScriptConsole::handleHomeKey()
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
setTextCursor(cursor);
}
QString QmlJSScriptConsole::getCurrentScript() const
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor)) ;
QString script = cursor.selectedText();
cursor.clearSelection();
//remove trailing white space
int end = script.size() - 1;
while (end > 0 && script[end].isSpace())
end--;
return script.left(end + 1);
}
void QmlJSScriptConsole::replaceCurrentScript(const QString &script)
{
QTextCursor cursor = textCursor();
cursor.setPosition(d->startOfEditableArea);
while (cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor)) ;
cursor.deleteChar();
cursor.insertText(script);
setTextCursor(cursor);
}
bool QmlJSScriptConsole::isEditableArea() const
{
return textCursor().position() >= d->startOfEditableArea;
}
} //Internal
} //Debugger
|
Refactor extra selections code
|
ScriptConsole: Refactor extra selections code
Change-Id: I251dc5646bfcf1da386939bb8309b8db6cd2eeaa
Reviewed-by: Kai Koehne <[email protected]>
|
C++
|
lgpl-2.1
|
amyvmiwei/qt-creator,colede/qtcreator,amyvmiwei/qt-creator,malikcjm/qtcreator,omniacreator/qtcreator,jonnor/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,jonnor/qt-creator,ostash/qt-creator-i18n-uk,AltarBeastiful/qt-creator,azat/qtcreator,danimo/qt-creator,maui-packages/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,KDAB/KDAB-Creator,farseerri/git_code,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,jonnor/qt-creator,martyone/sailfish-qtcreator,KDAB/KDAB-Creator,KDAB/KDAB-Creator,xianian/qt-creator,farseerri/git_code,farseerri/git_code,omniacreator/qtcreator,Distrotech/qtcreator,malikcjm/qtcreator,kuba1/qtcreator,KDE/android-qt-creator,xianian/qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,ostash/qt-creator-i18n-uk,hdweiss/qt-creator-visualizer,xianian/qt-creator,duythanhphan/qt-creator,hdweiss/qt-creator-visualizer,KDAB/KDAB-Creator,duythanhphan/qt-creator,malikcjm/qtcreator,xianian/qt-creator,ostash/qt-creator-i18n-uk,colede/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,danimo/qt-creator,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,syntheticpp/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,malikcjm/qtcreator,martyone/sailfish-qtcreator,colede/qtcreator,colede/qtcreator,Distrotech/qtcreator,colede/qtcreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,richardmg/qtcreator,maui-packages/qt-creator,farseerri/git_code,omniacreator/qtcreator,duythanhphan/qt-creator,danimo/qt-creator,richardmg/qtcreator,malikcjm/qtcreator,kuba1/qtcreator,jonnor/qt-creator,kuba1/qtcreator,KDE/android-qt-creator,maui-packages/qt-creator,hdweiss/qt-creator-visualizer,syntheticpp/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,duythanhphan/qt-creator,kuba1/qtcreator,kuba1/qtcreator,amyvmiwei/qt-creator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,colede/qtcreator,xianian/qt-creator,KDE/android-qt-creator,azat/qtcreator,richardmg/qtcreator,azat/qtcreator,KDE/android-qt-creator,danimo/qt-creator,syntheticpp/qt-creator,KDAB/KDAB-Creator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,xianian/qt-creator,jonnor/qt-creator,darksylinc/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,danimo/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,azat/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,azat/qtcreator,malikcjm/qtcreator,xianian/qt-creator,Distrotech/qtcreator,KDE/android-qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,Distrotech/qtcreator,danimo/qt-creator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,colede/qtcreator,maui-packages/qt-creator,maui-packages/qt-creator,omniacreator/qtcreator,maui-packages/qt-creator,duythanhphan/qt-creator,hdweiss/qt-creator-visualizer,KDAB/KDAB-Creator,kuba1/qtcreator,kuba1/qtcreator,richardmg/qtcreator,jonnor/qt-creator,richardmg/qtcreator,hdweiss/qt-creator-visualizer,martyone/sailfish-qtcreator,azat/qtcreator,darksylinc/qt-creator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,danimo/qt-creator,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator
|
1d102e916401e74f900ac8ef8a4479ee644823ab
|
libvast/test/time.cpp
|
libvast/test/time.cpp
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <date/date.h>
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/time.hpp"
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/time.hpp"
#define SUITE time
#include "vast/test/test.hpp"
using namespace vast;
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace date;
namespace {
template <class Input, class T>
void check_timespan(const Input& str, T x) {
timespan t;
CHECK(parsers::timespan(str, t));
CHECK_EQUAL(t, duration_cast<timespan>(x));
}
} // namespace <anonymous>
TEST(positive durations) {
MESSAGE("nanoseconds");
check_timespan("42 nsecs", 42ns);
check_timespan("42nsec", 42ns);
check_timespan("42ns", 42ns);
check_timespan("42ns", 42ns);
MESSAGE("microseconds");
check_timespan("42 usecs", 42us);
check_timespan("42usec", 42us);
check_timespan("42us", 42us);
MESSAGE("milliseconds");
check_timespan("42 msecs", 42ms);
check_timespan("42msec", 42ms);
check_timespan("42ms", 42ms);
MESSAGE("seconds");
check_timespan("42 secs", 42s);
check_timespan("42sec", 42s);
check_timespan("42s", 42s);
MESSAGE("minutes");
check_timespan("42 mins", 42min);
check_timespan("42min", 42min);
check_timespan("42m", 42min);
MESSAGE("hours");
check_timespan("42 hours", 42h);
check_timespan("42hour", 42h);
check_timespan("42h", 42h);
}
TEST(negative durations) {
check_timespan("-42ns", -42ns);
check_timespan("-42h", -42h);
}
TEST(fractional durations) {
check_timespan("3.54s", 3540ms);
check_timespan("-42.001ms", -42001us);
}
TEST(compound durations) {
check_timespan("3m42s10ms", 3min + 42s + 10ms);
check_timespan("-10m8ms1ns", -10min + 8ms + 1ns);
MESSAGE("no intermediate signs");
auto p = parsers::timespan >> parsers::eoi;
CHECK(!p("-10m-8ms1ns"));
}
TEST(ymdshms timestamp parser) {
timestamp ts;
MESSAGE("YYYY-MM-DD+HH:MM:SS.ssss");
CHECK(parsers::timestamp("2012-08-12+23:55:04.001234", ts));
auto sd = floor<days>(ts);
auto t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{55});
CHECK(t.seconds() == seconds{4});
CHECK(duration_cast<microseconds>(t.subseconds()) == microseconds{1234});
MESSAGE("YYYY-MM-DD+HH:MM:SS");
CHECK(parsers::timestamp("2012-08-12+23:55:04", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{55});
CHECK(t.seconds() == seconds{4});
MESSAGE("YYYY-MM-DD+HH:MM");
CHECK(parsers::timestamp("2012-08-12+23:55", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{55});
CHECK(t.seconds() == seconds{0});
MESSAGE("YYYY-MM-DD+HH");
CHECK(parsers::timestamp("2012-08-12+23", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{0});
CHECK(t.seconds() == seconds{0});
MESSAGE("YYYY-MM-DD");
CHECK(parsers::timestamp("2012-08-12", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{0});
CHECK(t.minutes() == minutes{0});
CHECK(t.seconds() == seconds{0});
MESSAGE("YYYY-MM");
CHECK(parsers::timestamp("2012-08", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/1);
CHECK(t.hours() == hours{0});
CHECK(t.minutes() == minutes{0});
CHECK(t.seconds() == seconds{0});
}
TEST(unix epoch timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("@1444040673", ts));
CHECK(ts.time_since_epoch() == 1444040673s);
CHECK(parsers::timestamp("@1398933902.686337", ts));
CHECK(ts.time_since_epoch() == double_seconds{1398933902.686337});
}
TEST(now timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("now", ts));
CHECK(ts > timestamp::clock::now() - minutes{1});
CHECK(ts < timestamp::clock::now() + minutes{1});
CHECK(parsers::timestamp("now - 1m", ts));
CHECK(ts < timestamp::clock::now());
CHECK(parsers::timestamp("now + 1m", ts));
CHECK(ts > timestamp::clock::now());
}
TEST(ago timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("10 days ago", ts));
CHECK(ts < timestamp::clock::now());
}
TEST(in timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("in 1 year", ts));
CHECK(ts > timestamp::clock::now());
}
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <date/date.h>
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/time.hpp"
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/time.hpp"
#define SUITE time
#include "vast/test/test.hpp"
using namespace vast;
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace date;
namespace {
template <class Input, class T>
void check_timespan(const Input& str, T x) {
timespan t;
CHECK(parsers::timespan(str, t));
CHECK_EQUAL(t, duration_cast<timespan>(x));
}
} // namespace <anonymous>
TEST(positive durations) {
MESSAGE("nanoseconds");
check_timespan("42 nsecs", 42ns);
check_timespan("42nsec", 42ns);
check_timespan("42ns", 42ns);
check_timespan("42ns", 42ns);
MESSAGE("microseconds");
check_timespan("42 usecs", 42us);
check_timespan("42usec", 42us);
check_timespan("42us", 42us);
MESSAGE("milliseconds");
check_timespan("42 msecs", 42ms);
check_timespan("42msec", 42ms);
check_timespan("42ms", 42ms);
MESSAGE("seconds");
check_timespan("42 secs", 42s);
check_timespan("42sec", 42s);
check_timespan("42s", 42s);
MESSAGE("minutes");
check_timespan("42 mins", 42min);
check_timespan("42min", 42min);
check_timespan("42m", 42min);
MESSAGE("hours");
check_timespan("42 hours", 42h);
check_timespan("42hour", 42h);
check_timespan("42h", 42h);
}
TEST(negative durations) {
check_timespan("-42ns", -42ns);
check_timespan("-42h", -42h);
}
TEST(fractional durations) {
check_timespan("3.54s", 3540ms);
check_timespan("-42.001ms", -42001us);
}
TEST(compound durations) {
check_timespan("3m42s10ms", 3min + 42s + 10ms);
check_timespan("3s42s10ms", 3s + 42s + 10ms);
check_timespan("42s3m10ms", 3min + 42s + 10ms);
check_timespan("-10m8ms1ns", -10min + 8ms + 1ns);
MESSAGE("no intermediate signs");
auto p = parsers::timespan >> parsers::eoi;
CHECK(!p("-10m-8ms1ns"));
}
TEST(ymdshms timestamp parser) {
timestamp ts;
MESSAGE("YYYY-MM-DD+HH:MM:SS.ssss");
CHECK(parsers::timestamp("2012-08-12+23:55:04.001234", ts));
auto sd = floor<days>(ts);
auto t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{55});
CHECK(t.seconds() == seconds{4});
CHECK(duration_cast<microseconds>(t.subseconds()) == microseconds{1234});
MESSAGE("YYYY-MM-DD+HH:MM:SS");
CHECK(parsers::timestamp("2012-08-12+23:55:04", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{55});
CHECK(t.seconds() == seconds{4});
MESSAGE("YYYY-MM-DD+HH:MM");
CHECK(parsers::timestamp("2012-08-12+23:55", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{55});
CHECK(t.seconds() == seconds{0});
MESSAGE("YYYY-MM-DD+HH");
CHECK(parsers::timestamp("2012-08-12+23", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{23});
CHECK(t.minutes() == minutes{0});
CHECK(t.seconds() == seconds{0});
MESSAGE("YYYY-MM-DD");
CHECK(parsers::timestamp("2012-08-12", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/12);
CHECK(t.hours() == hours{0});
CHECK(t.minutes() == minutes{0});
CHECK(t.seconds() == seconds{0});
MESSAGE("YYYY-MM");
CHECK(parsers::timestamp("2012-08", ts));
sd = floor<days>(ts);
t = make_time(ts - sd);
CHECK(sd == 2012_y/8/1);
CHECK(t.hours() == hours{0});
CHECK(t.minutes() == minutes{0});
CHECK(t.seconds() == seconds{0});
}
TEST(unix epoch timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("@1444040673", ts));
CHECK(ts.time_since_epoch() == 1444040673s);
CHECK(parsers::timestamp("@1398933902.686337", ts));
CHECK(ts.time_since_epoch() == double_seconds{1398933902.686337});
}
TEST(now timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("now", ts));
CHECK(ts > timestamp::clock::now() - minutes{1});
CHECK(ts < timestamp::clock::now() + minutes{1});
CHECK(parsers::timestamp("now - 1m", ts));
CHECK(ts < timestamp::clock::now());
CHECK(parsers::timestamp("now + 1m", ts));
CHECK(ts > timestamp::clock::now());
}
TEST(ago timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("10 days ago", ts));
CHECK(ts < timestamp::clock::now());
}
TEST(in timestamp parser) {
timestamp ts;
CHECK(parsers::timestamp("in 1 year", ts));
CHECK(ts > timestamp::clock::now());
}
|
Add unit tests for interesting corner cases
|
Add unit tests for interesting corner cases
Co-Authored-By: mavam <[email protected]>
|
C++
|
bsd-3-clause
|
mavam/vast,mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,vast-io/vast,vast-io/vast,mavam/vast,vast-io/vast
|
9cf0991cf5f4789c79f9180702753e296ebd609b
|
sources/runtime_extension.hpp
|
sources/runtime_extension.hpp
|
#pragma once
#include "./arglist.hpp"
static cov_basic::extension runtime_ext;
namespace runtime_cbs_ext {
using namespace cov_basic;
cov::any info(array&)
{
std::cout<<"Covariant Basic Parser\nVersion:2.1.1.1\nCopyright (C) 2017 Michael Lee"<<std::endl;
return number(0);
}
cov::any time(array&)
{
return number(cov::timer::time(cov::timer::time_unit::milli_sec));
}
cov::any delay(array& args)
{
arglist::check<number>(args);
cov::timer::delay(cov::timer::time_unit::milli_sec,cov::timer::timer_t(args.front().const_val<number>()));
return number(0);
}
cov::any rand(array& args)
{
arglist::check<number,number>(args);
return number(cov::rand<number>(args.at(0).const_val<number>(),args.at(1).const_val<number>()));
}
cov::any randint(array& args)
{
arglist::check<number,number>(args);
return number(cov::rand<long>(args.at(0).const_val<number>(),args.at(1).const_val<number>()));
}
cov::any error(array& args)
{
arglist::check<string>(args);
throw lang_error(args.front().const_val<string>());
return number(0);
}
cov::any load_extension(array& args)
{
arglist::check<string>(args);
return std::make_shared<extension_holder>(args.front().const_val<string>());
}
void init()
{
runtime_ext.add_var("info",native_interface(info));
runtime_ext.add_var("time",native_interface(time));
runtime_ext.add_var("delay",native_interface(delay));
runtime_ext.add_var("rand",native_interface(rand));
runtime_ext.add_var("randint",native_interface(randint));
runtime_ext.add_var("error",native_interface(error));
runtime_ext.add_var("load_extension",native_interface(load_extension));
}
}
|
#pragma once
#include "./arglist.hpp"
static cov_basic::extension runtime_ext;
namespace runtime_cbs_ext {
using namespace cov_basic;
cov::any info(array&)
{
std::cout<<"Covariant Basic Parser\nVersion:2.1.1.2\nCopyright (C) 2017 Michael Lee"<<std::endl;
return number(0);
}
cov::any time(array&)
{
return number(cov::timer::time(cov::timer::time_unit::milli_sec));
}
cov::any delay(array& args)
{
arglist::check<number>(args);
cov::timer::delay(cov::timer::time_unit::milli_sec,cov::timer::timer_t(args.front().const_val<number>()));
return number(0);
}
cov::any rand(array& args)
{
arglist::check<number,number>(args);
return number(cov::rand<number>(args.at(0).const_val<number>(),args.at(1).const_val<number>()));
}
cov::any randint(array& args)
{
arglist::check<number,number>(args);
return number(cov::rand<long>(args.at(0).const_val<number>(),args.at(1).const_val<number>()));
}
cov::any error(array& args)
{
arglist::check<string>(args);
throw lang_error(args.front().const_val<string>());
return number(0);
}
cov::any load_extension(array& args)
{
arglist::check<string>(args);
return std::make_shared<extension_holder>(args.front().const_val<string>());
}
void init()
{
runtime_ext.add_var("info",native_interface(info));
runtime_ext.add_var("time",native_interface(time));
runtime_ext.add_var("delay",native_interface(delay));
runtime_ext.add_var("rand",native_interface(rand));
runtime_ext.add_var("randint",native_interface(randint));
runtime_ext.add_var("error",native_interface(error));
runtime_ext.add_var("load_extension",native_interface(load_extension));
}
}
|
更新版本号(2.1.1.2)
|
更新版本号(2.1.1.2)
|
C++
|
apache-2.0
|
covscript/covscript,covscript/covscript,covscript/covscript
|
78523bf98fd3ab97a77c0e07f5c57ede82af8c3e
|
test/output/test_type_name.cpp
|
test/output/test_type_name.cpp
|
#include <mettle.hpp>
using namespace mettle;
struct my_type {};
namespace my_namespace {
struct another_type {};
}
suite<> test_type_name("type_name()", [](auto &_) {
_.test("primitives", []() {
expect(type_name<int>(), equal_to("int"));
expect(type_name<int &>(), equal_to("int &"));
expect(type_name<int &&>(), equal_to("int &&"));
expect(type_name<const int>(), equal_to("const int"));
expect(type_name<volatile int>(), equal_to("volatile int"));
expect(type_name<const volatile int>(), equal_to("const volatile int"));
});
_.test("custom types", []() {
expect(type_name<my_type>(), equal_to("my_type"));
expect(type_name<my_namespace::another_type>(),
equal_to("my_namespace::another_type"));
});
});
|
#include <mettle.hpp>
using namespace mettle;
struct my_type {};
namespace my_namespace {
struct another_type {};
}
suite<> test_type_name("type_name()", [](auto &_) {
_.test("primitives", []() {
expect(type_name<int>(), equal_to("int"));
expect(type_name<int &>(), regex_match("int\\s*&"));
expect(type_name<int &&>(), regex_match("int\\s*&&"));
expect(type_name<const int>(), equal_to("const int"));
expect(type_name<volatile int>(), equal_to("volatile int"));
expect(type_name<const volatile int>(), equal_to("const volatile int"));
});
_.test("custom types", []() {
expect(type_name<my_type>(), equal_to("my_type"));
expect(type_name<my_namespace::another_type>(),
equal_to("my_namespace::another_type"));
});
});
|
Use regex_match to be more flexible with checking type_name's result
|
Use regex_match to be more flexible with checking type_name's result
|
C++
|
bsd-3-clause
|
jimporter/mettle,jimporter/mettle
|
8cbb1853fece9aca3a85a88ef85616fd707956eb
|
test/resource_locator_test.cpp
|
test/resource_locator_test.cpp
|
#include <gmock/gmock.h>
#include <set>
#include "oddlib/stream.hpp"
#include <jsonxx/jsonxx.h>
#include "logger.hpp"
using namespace ::testing;
std::vector<Uint8> StringToVector(const std::string& str)
{
return std::vector<Uint8>(str.begin(), str.end());
}
class IFileSystem
{
public:
virtual ~IFileSystem() = default;
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) = 0;
//virtual std::string UserSettingsDirectory() = 0;
};
class FileSystem : public IFileSystem
{
public:
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override
{
std::ignore = fileName;
return nullptr;
}
};
class MockFileSystem : public IFileSystem
{
public:
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override
{
// Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call
return std::unique_ptr<Oddlib::IStream>(OpenProxy(fileName));
}
MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*));
};
// AOPC, AOPSX, FoosMod etc
class GameDefinition
{
public:
GameDefinition(IFileSystem& fileSystem, const char* gameDefinitionFile)
{
std::ignore = fileSystem;
std::ignore = gameDefinitionFile;
}
GameDefinition() = default;
std::string mName;
std::string mDescription;
std::string mAuthor;
// TODO: initial level, how maps connect, etc.
// Depends on DataSets
};
class ResourceMapper
{
public:
ResourceMapper(IFileSystem& fileSystem, const char* resourceMapFile)
{
auto stream = fileSystem.Open(resourceMapFile);
assert(stream != nullptr);
const auto jsonData = stream->LoadAllToString();
Parse(jsonData);
}
struct AnimMapping
{
std::string mFile;
Uint32 mId;
Uint32 mBlendingMode;
};
const AnimMapping* Find(const char* resourceName) const
{
auto it = mAnimMaps.find(resourceName);
if (it != std::end(mAnimMaps))
{
return &it->second;
}
return nullptr;
}
private:
std::map<std::string, AnimMapping> mAnimMaps;
void Parse(const std::string& json)
{
jsonxx::Object root;
root.parse(json);
if (root.has<jsonxx::Array>("anims"))
{
const jsonxx::Array& anims = root.get<jsonxx::Array>("anims");
const auto& file = root.get<jsonxx::String>("file");
const auto id = static_cast<Uint32>(root.get<jsonxx::Number>("id"));
for (size_t i = 0; i < anims.size(); i++)
{
AnimMapping mapping;
mapping.mFile = file;
mapping.mId = static_cast<Uint32>(id);
const jsonxx::Object& animRecord = anims.get<jsonxx::Object>(static_cast<Uint32>(i));
const auto& name = animRecord.get<jsonxx::String>("name");
const auto blendMode = animRecord.get<jsonxx::Number>("blend_mode");
mapping.mBlendingMode = static_cast<Uint32>(blendMode);
mAnimMaps[name] = mapping;
}
}
}
};
class ResourceBase
{
public:
};
// TODO: Should store the dataset somewhere too so explicly picking another data set
// still loads the resource
class ResourceCache
{
public:
void Add(ResourceBase* )
{
// TODO
}
void Remove(ResourceBase*)
{
// TODO
}
ResourceBase* Find(const char* resourceName)
{
auto it = mCache.find(resourceName);
if (it != std::end(mCache))
{
return it->second;
}
return nullptr;
}
private:
std::map<const char*, ResourceBase*> mCache;
};
template<class T>
class Resource : public ResourceBase
{
public:
Resource(const Resource& rhs)
: mCache(rhs.mCache)
{
*this = rhs;
}
Resource& operator = (const Resource& rhs)
{
if (this != &rhs)
{
// TODO
}
return *this;
}
Resource(ResourceCache& cache, std::unique_ptr<Oddlib::IStream>)
: mCache(cache)
{
mCache.Add(this);
}
~Resource()
{
mCache.Remove(this);
}
void Reload()
{
}
private:
ResourceCache& mCache;
};
class Animation
{
public:
};
using TAnimationResource = Resource < Animation >;
class ResourceLocator
{
public:
ResourceLocator(const ResourceLocator&) = delete;
ResourceLocator& operator =(const ResourceLocator&) = delete;
ResourceLocator(IFileSystem& fileSystem, GameDefinition& game, const char* resourceMapFile)
: mFs(fileSystem), mResMapper(fileSystem, resourceMapFile)
{
std::ignore = game;
}
void AddDataPath(const char* dataPath, Sint32 priority)
{
mDataPaths.insert({ dataPath, priority });
}
/*
void AddAnimationMapping(const char* resourceName, const char* dataSetName, int id, int animationIndex, int blendingMode)
{
std::ignore = resourceName;
std::ignore = dataSetName;
std::ignore = id;
std::ignore = animationIndex;
std::ignore = blendingMode;
}
*/
template<typename T>
Resource<T> Locate(const char* resourceName)
{
// Check if the resource is cached
ResourceBase* cachedRes = mResourceCache.Find(resourceName);
if (cachedRes)
{
return *static_cast<Resource<T>*>(cachedRes);
}
// For each data set attempt to find resourceName by mapping
// to a LVL/file/chunk. Or in the case of a mod dataset something else.
const ResourceMapper::AnimMapping* animMapping = mResMapper.Find(resourceName);
if (animMapping)
{
for (auto& path : mDataPaths)
{
const auto& lvlFileToFind = animMapping->mFile;
// TODO: We need to search in each LVL that the animMapping->mFile could be in
// within each path.mPath, however if the data path is a path to a mod then apply
// the override rules such as looking for PNGs instead.
auto stream = mFs.Open((path.mPath + "\\" + lvlFileToFind).c_str());
if (stream)
{
return Resource<T>(mResourceCache, std::move(stream));
}
}
}
// TODO
return Resource<T>(mResourceCache, nullptr);
}
template<typename T>
Resource<T> Locate(const char* resourceName, const char* dataSetName)
{
std::ignore = resourceName;
std::ignore = dataSetName;
// TODO
return Resource<T>(mResourceCache,nullptr);
}
private:
IFileSystem& mFs;
ResourceMapper mResMapper;
struct DataPath
{
std::string mPath;
Sint32 mPriority;
bool operator < (const DataPath& rhs) const
{
return mPriority < rhs.mPriority;
}
};
std::set<DataPath> mDataPaths;
ResourceCache mResourceCache;
};
TEST(ResourceLocator, ParseResourceMap)
{
// TODO
}
TEST(ResourceLocator, Locate)
{
GameDefinition aePc;
aePc.mAuthor = "Oddworld Inhabitants";
aePc.mDescription = "The original PC version of Oddworld Abe's Exoddus";
aePc.mName = "Oddworld Abe's Exoddus PC";
MockFileSystem fs;
const std::string resourceMapsJson = R"({"anims":[{"blend_mode":1,"name":"SLIGZ.BND_417_1"},{"blend_mode":1,"name":"SLIGZ.BND_417_2"}],"file":"SLIGZ.BND","id":417})";
EXPECT_CALL(fs, OpenProxy(StrEq("resource_maps.json"))).WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND"))).WillRepeatedly(Return(nullptr));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector("test"))))
.RetiresOnSaturation();
// TODO: Find a way to make gmock stop caching the argument causing us to double delete
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector("test"))))
.RetiresOnSaturation();
ResourceLocator locator(fs, aePc, "resource_maps.json");
locator.AddDataPath("C:\\dataset_location2", 2);
locator.AddDataPath("C:\\dataset_location1", 1);
// TODO: Test parsing the resource map on its own, use this to add the stuff we want to test
//locator.AddAnimationMapping("AbeWalkLeft", "ABEBSIC.BAN", 10, 1, 2);
TAnimationResource resMapped1 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped1.Reload();
TAnimationResource resMapped2 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped2.Reload();
// Can explicitly set the dataset to obtain it from a known location
TAnimationResource resDirect = locator.Locate<Animation>("SLIGZ.BND_417_1", "AEPCCD1");
resDirect.Reload();
}
|
#include <gmock/gmock.h>
#include <set>
#include "oddlib/stream.hpp"
#include <jsonxx/jsonxx.h>
#include "logger.hpp"
using namespace ::testing;
std::vector<Uint8> StringToVector(const std::string& str)
{
return std::vector<Uint8>(str.begin(), str.end());
}
class IFileSystem
{
public:
virtual ~IFileSystem() = default;
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) = 0;
//virtual std::string UserSettingsDirectory() = 0;
};
class FileSystem : public IFileSystem
{
public:
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override
{
std::ignore = fileName;
return nullptr;
}
};
class MockFileSystem : public IFileSystem
{
public:
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override
{
// Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call
return std::unique_ptr<Oddlib::IStream>(OpenProxy(fileName));
}
MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*));
};
// AOPC, AOPSX, FoosMod etc
class GameDefinition
{
public:
GameDefinition(IFileSystem& fileSystem, const char* gameDefinitionFile)
{
std::ignore = fileSystem;
std::ignore = gameDefinitionFile;
}
GameDefinition() = default;
std::string mName;
std::string mDescription;
std::string mAuthor;
// TODO: initial level, how maps connect, etc.
// Depends on DataSets
};
class ResourceMapper
{
public:
ResourceMapper(IFileSystem& fileSystem, const char* resourceMapFile)
{
auto stream = fileSystem.Open(resourceMapFile);
assert(stream != nullptr);
const auto jsonData = stream->LoadAllToString();
Parse(jsonData);
}
struct AnimMapping
{
std::string mFile;
Uint32 mId;
Uint32 mBlendingMode;
};
const AnimMapping* Find(const char* resourceName) const
{
auto it = mAnimMaps.find(resourceName);
if (it != std::end(mAnimMaps))
{
return &it->second;
}
return nullptr;
}
private:
std::map<std::string, AnimMapping> mAnimMaps;
void Parse(const std::string& json)
{
jsonxx::Object root;
root.parse(json);
if (root.has<jsonxx::Array>("anims"))
{
const jsonxx::Array& anims = root.get<jsonxx::Array>("anims");
const auto& file = root.get<jsonxx::String>("file");
const auto id = static_cast<Uint32>(root.get<jsonxx::Number>("id"));
for (size_t i = 0; i < anims.size(); i++)
{
AnimMapping mapping;
mapping.mFile = file;
mapping.mId = static_cast<Uint32>(id);
const jsonxx::Object& animRecord = anims.get<jsonxx::Object>(static_cast<Uint32>(i));
const auto& name = animRecord.get<jsonxx::String>("name");
const auto blendMode = animRecord.get<jsonxx::Number>("blend_mode");
mapping.mBlendingMode = static_cast<Uint32>(blendMode);
mAnimMaps[name] = mapping;
}
}
}
};
class ResourceBase
{
public:
};
// TODO: Should store the dataset somewhere too so explicly picking another data set
// still loads the resource
class ResourceCache
{
public:
void Add(ResourceBase* )
{
// TODO
}
void Remove(ResourceBase*)
{
// TODO
}
ResourceBase* Find(const char* resourceName)
{
auto it = mCache.find(resourceName);
if (it != std::end(mCache))
{
return it->second;
}
return nullptr;
}
private:
std::map<const char*, ResourceBase*> mCache;
};
template<class T>
class Resource : public ResourceBase
{
public:
Resource(const Resource& rhs)
: mCache(rhs.mCache)
{
*this = rhs;
}
Resource& operator = (const Resource& rhs)
{
if (this != &rhs)
{
// TODO
}
return *this;
}
Resource(ResourceCache& cache, std::unique_ptr<Oddlib::IStream>)
: mCache(cache)
{
mCache.Add(this);
}
~Resource()
{
mCache.Remove(this);
}
void Reload()
{
}
private:
ResourceCache& mCache;
};
class Animation
{
public:
};
using TAnimationResource = Resource < Animation >;
class ResourceLocator
{
public:
ResourceLocator(const ResourceLocator&) = delete;
ResourceLocator& operator =(const ResourceLocator&) = delete;
ResourceLocator(IFileSystem& fileSystem, GameDefinition& game, const char* resourceMapFile)
: mFs(fileSystem), mResMapper(fileSystem, resourceMapFile)
{
std::ignore = game;
}
void AddDataPath(const char* dataPath, Sint32 priority)
{
mDataPaths.insert({ dataPath, priority });
}
/*
void AddAnimationMapping(const char* resourceName, const char* dataSetName, int id, int animationIndex, int blendingMode)
{
std::ignore = resourceName;
std::ignore = dataSetName;
std::ignore = id;
std::ignore = animationIndex;
std::ignore = blendingMode;
}
*/
template<typename T>
Resource<T> Locate(const char* resourceName)
{
// Check if the resource is cached
ResourceBase* cachedRes = mResourceCache.Find(resourceName);
if (cachedRes)
{
return *static_cast<Resource<T>*>(cachedRes);
}
// For each data set attempt to find resourceName by mapping
// to a LVL/file/chunk. Or in the case of a mod dataset something else.
const ResourceMapper::AnimMapping* animMapping = mResMapper.Find(resourceName);
if (animMapping)
{
for (auto& path : mDataPaths)
{
const auto& lvlFileToFind = animMapping->mFile;
// TODO: We need to search in each LVL that the animMapping->mFile could be in
// within each path.mPath, however if the data path is a path to a mod then apply
// the override rules such as looking for PNGs instead.
auto stream = mFs.Open((path.mPath + "\\" + lvlFileToFind).c_str());
if (stream)
{
return Resource<T>(mResourceCache, std::move(stream));
}
}
}
// TODO
return Resource<T>(mResourceCache, nullptr);
}
template<typename T>
Resource<T> Locate(const char* resourceName, const char* dataSetName)
{
std::ignore = resourceName;
std::ignore = dataSetName;
// TODO
return Resource<T>(mResourceCache,nullptr);
}
private:
IFileSystem& mFs;
ResourceMapper mResMapper;
struct DataPath
{
std::string mPath;
Sint32 mPriority;
bool operator < (const DataPath& rhs) const
{
return mPriority < rhs.mPriority;
}
};
std::set<DataPath> mDataPaths;
ResourceCache mResourceCache;
};
TEST(ResourceLocator, ParseResourceMap)
{
// TODO
}
TEST(ResourceLocator, Locate)
{
GameDefinition aePc;
aePc.mAuthor = "Oddworld Inhabitants";
aePc.mDescription = "The original PC version of Oddworld Abe's Exoddus";
aePc.mName = "Oddworld Abe's Exoddus PC";
MockFileSystem fs;
const std::string resourceMapsJson = R"({"anims":[{"blend_mode":1,"name":"SLIGZ.BND_417_1"},{"blend_mode":1,"name":"SLIGZ.BND_417_2"}],"file":"SLIGZ.BND","id":417})";
EXPECT_CALL(fs, OpenProxy(StrEq("resource_maps.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND")))
.WillRepeatedly(Return(nullptr));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.Times(2)
.WillOnce(Return(new Oddlib::Stream(StringToVector("test")))) // For SLIGZ.BND_417_1
.WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); // For SLIGZ.BND_417_1
ResourceLocator locator(fs, aePc, "resource_maps.json");
locator.AddDataPath("C:\\dataset_location2", 2);
locator.AddDataPath("C:\\dataset_location1", 1);
// TODO: Test parsing the resource map on its own, use this to add the stuff we want to test
//locator.AddAnimationMapping("AbeWalkLeft", "ABEBSIC.BAN", 10, 1, 2);
TAnimationResource resMapped1 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped1.Reload();
TAnimationResource resMapped2 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped2.Reload();
// Can explicitly set the dataset to obtain it from a known location
TAnimationResource resDirect = locator.Locate<Animation>("SLIGZ.BND_417_1", "AEPCCD1");
resDirect.Reload();
}
|
fix test mock
|
fix test mock
|
C++
|
mit
|
paulsapps/alive,mlgthatsme/alive,mlgthatsme/alive,paulsapps/alive,paulsapps/alive,mlgthatsme/alive
|
17b169b3c8d97003334ebd214b92d46cb06ac9e2
|
concurrency_control/row_lock.cpp
|
concurrency_control/row_lock.cpp
|
#include "row.h"
#include "txn.h"
#include "row_lock.h"
#include "mem_alloc.h"
#include "manager.h"
void Row_lock::init(row_t * row) {
_row = row;
owners = NULL;
waiters_head = NULL;
waiters_tail = NULL;
owner_cnt = 0;
waiter_cnt = 0;
latch = new pthread_mutex_t;
pthread_mutex_init(latch, NULL);
lock_type = LOCK_NONE;
blatch = false;
}
RC Row_lock::lock_get(lock_t type, txn_man * txn) {
uint64_t *txnids = NULL;
int txncnt = 0;
return lock_get(type, txn, txnids, txncnt);
}
RC Row_lock::lock_get(lock_t type, txn_man * txn, uint64_t* &txnids, int &txncnt) {
assert (CC_ALG == DL_DETECT || CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE);
RC rc;
int part_id =_row->get_part_id();
if (g_central_man)
glob_manager->lock_row(_row);
else
pthread_mutex_lock( latch );
assert(owner_cnt <= g_thread_cnt);
assert(waiter_cnt < g_thread_cnt);
#if DEBUG_ASSERT
if (owners != NULL)
assert(lock_type == owners->type);
else
assert(lock_type == LOCK_NONE);
LockEntry * en = owners;
UInt32 cnt = 0;
while (en) {
assert(en->txn->get_thd_id() != txn->get_thd_id());
cnt ++;
en = en->next;
}
assert(cnt == owner_cnt);
en = waiters_head;
cnt = 0;
while (en) {
cnt ++;
en = en->next;
}
assert(cnt == waiter_cnt);
#endif
bool conflict = conflict_lock(lock_type, type);
if (CC_ALG == WAIT_DIE && !conflict) {
if (waiters_head && txn->get_ts() < waiters_head->txn->get_ts())
conflict = true;
}
// Some txns coming earlier is waiting. Should also wait.
if (CC_ALG == DL_DETECT && waiters_head != NULL)
conflict = true;
if (conflict) {
// Cannot be added to the owner list.
if (CC_ALG == NO_WAIT) {
rc = Abort;
goto final;
} else if (CC_ALG == DL_DETECT) {
LockEntry * entry = get_entry();
entry->txn = txn;
entry->type = type;
LIST_PUT_TAIL(waiters_head, waiters_tail, entry);
waiter_cnt ++;
txn->lock_ready = false;
rc = WAIT;
} else if (CC_ALG == WAIT_DIE) {
///////////////////////////////////////////////////////////
// - T is the txn currently running
// IF T.ts > ts of all owners
// T can wait
// ELSE
// T should abort
//////////////////////////////////////////////////////////
bool canwait = true;
LockEntry * en = owners;
while (en != NULL) {
if (en->txn->get_ts() < txn->get_ts()) {
canwait = false;
break;
}
en = en->next;
}
if (canwait) {
// insert txn to the right position
// the waiter list is always in timestamp order
LockEntry * entry = get_entry();
entry->txn = txn;
entry->type = type;
en = waiters_head;
while (en != NULL && txn->get_ts() < en->txn->get_ts())
en = en->next;
if (en) {
LIST_INSERT_BEFORE(en, entry);
if (en == waiters_head)
waiters_head = entry;
} else
LIST_PUT_TAIL(waiters_head, waiters_tail, entry);
waiter_cnt ++;
txn->lock_ready = false;
rc = WAIT;
}
else
rc = Abort;
}
} else {
LockEntry * entry = get_entry();
entry->type = type;
entry->txn = txn;
STACK_PUSH(owners, entry);
owner_cnt ++;
lock_type = type;
if (CC_ALG == DL_DETECT)
ASSERT(waiters_head == NULL);
rc = RCOK;
}
final:
if (rc == WAIT && CC_ALG == DL_DETECT) {
// Update the waits-for graph
ASSERT(waiters_tail->txn == txn);
txnids = (uint64_t *) mem_allocator.alloc(sizeof(uint64_t) * (owner_cnt + waiter_cnt), part_id);
txncnt = 0;
LockEntry * en = waiters_tail->prev;
while (en != NULL) {
if (conflict_lock(type, en->type))
txnids[txncnt++] = en->txn->get_txn_id();
en = en->prev;
}
en = owners;
if (conflict_lock(type, lock_type))
while (en != NULL) {
txnids[txncnt++] = en->txn->get_txn_id();
en = en->next;
}
ASSERT(txncnt > 0);
}
if (g_central_man)
glob_manager->release_row(_row);
else
pthread_mutex_unlock( latch );
return rc;
}
RC Row_lock::lock_release(txn_man * txn) {
if (g_central_man)
glob_manager->lock_row(_row);
else
pthread_mutex_lock( latch );
// Try to find the entry in the owners
LockEntry * en = owners;
LockEntry * prev = NULL;
while (en != NULL && en->txn != txn) {
prev = en;
en = en->next;
}
if (en) { // find the entry in the owner list
if (prev) prev->next = en->next;
else owners = en->next;
return_entry(en);
owner_cnt --;
if (owner_cnt == 0)
lock_type = LOCK_NONE;
} else {
// Not in owners list, try waiters list.
en = waiters_head;
while (en != NULL && en->txn != txn)
en = en->next;
ASSERT(en);
LIST_REMOVE(en);
if (en == waiters_head)
waiters_head = en->next;
if (en == waiters_tail)
waiters_tail = en->prev;
return_entry(en);
waiter_cnt --;
}
if (owner_cnt == 0)
ASSERT(lock_type == LOCK_NONE);
#if DEBUG_ASSERT && CC_ALG == WAIT_DIE
for (en = waiters_head; en != NULL && en->next != NULL; en = en->next)
assert(en->next->txn->get_ts() < en->txn->get_ts());
#endif
LockEntry * entry;
// If any waiter can join the owners, just do it!
while (waiters_head && !conflict_lock(lock_type, waiters_head->type)) {
LIST_GET_HEAD(waiters_head, waiters_tail, entry);
STACK_PUSH(owners, entry);
owner_cnt ++;
waiter_cnt --;
ASSERT(entry->txn->lock_ready == false);
entry->txn->lock_ready = true;
lock_type = entry->type;
}
ASSERT((owners == NULL) == (owner_cnt == 0));
if (g_central_man)
glob_manager->release_row(_row);
else
pthread_mutex_unlock( latch );
return RCOK;
}
bool Row_lock::conflict_lock(lock_t l1, lock_t l2) {
if (l1 == LOCK_NONE || l2 == LOCK_NONE)
return false;
else if (l1 == LOCK_EX || l2 == LOCK_EX)
return true;
else
return false;
}
LockEntry * Row_lock::get_entry() {
LockEntry * entry = (LockEntry *)
mem_allocator.alloc(sizeof(LockEntry), _row->get_part_id());
return entry;
}
void Row_lock::return_entry(LockEntry * entry) {
mem_allocator.free(entry, sizeof(LockEntry));
}
|
#include "row.h"
#include "txn.h"
#include "row_lock.h"
#include "mem_alloc.h"
#include "manager.h"
void Row_lock::init(row_t * row) {
_row = row;
owners = NULL;
waiters_head = NULL;
waiters_tail = NULL;
owner_cnt = 0;
waiter_cnt = 0;
latch = new pthread_mutex_t;
pthread_mutex_init(latch, NULL);
lock_type = LOCK_NONE;
blatch = false;
}
RC Row_lock::lock_get(lock_t type, txn_man * txn) {
uint64_t *txnids = NULL;
int txncnt = 0;
return lock_get(type, txn, txnids, txncnt);
}
RC Row_lock::lock_get(lock_t type, txn_man * txn, uint64_t* &txnids, int &txncnt) {
assert (CC_ALG == DL_DETECT || CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE);
RC rc;
int part_id =_row->get_part_id();
if (g_central_man)
glob_manager->lock_row(_row);
else
pthread_mutex_lock( latch );
assert(owner_cnt <= g_thread_cnt);
assert(waiter_cnt < g_thread_cnt);
#if DEBUG_ASSERT
if (owners != NULL)
assert(lock_type == owners->type);
else
assert(lock_type == LOCK_NONE);
LockEntry * en = owners;
UInt32 cnt = 0;
while (en) {
assert(en->txn->get_thd_id() != txn->get_thd_id());
cnt ++;
en = en->next;
}
assert(cnt == owner_cnt);
en = waiters_head;
cnt = 0;
while (en) {
cnt ++;
en = en->next;
}
assert(cnt == waiter_cnt);
#endif
bool conflict = conflict_lock(lock_type, type);
if (CC_ALG == WAIT_DIE && !conflict) {
if (waiters_head && txn->get_ts() < waiters_head->txn->get_ts())
conflict = true;
}
// Some txns coming earlier is waiting. Should also wait.
if (CC_ALG == DL_DETECT && waiters_head != NULL)
conflict = true;
if (conflict) {
// Cannot be added to the owner list.
if (CC_ALG == NO_WAIT) {
rc = Abort;
goto final;
} else if (CC_ALG == DL_DETECT) {
LockEntry * entry = get_entry();
entry->txn = txn;
entry->type = type;
LIST_PUT_TAIL(waiters_head, waiters_tail, entry);
waiter_cnt ++;
txn->lock_ready = false;
rc = WAIT;
} else if (CC_ALG == WAIT_DIE) {
///////////////////////////////////////////////////////////
// - T is the txn currently running
// IF T.ts < ts of all owners
// T can wait
// ELSE
// T should abort
//////////////////////////////////////////////////////////
bool canwait = true;
LockEntry * en = owners;
while (en != NULL) {
if (en->txn->get_ts() < txn->get_ts()) {
canwait = false;
break;
}
en = en->next;
}
if (canwait) {
// insert txn to the right position
// the waiter list is always in timestamp order
LockEntry * entry = get_entry();
entry->txn = txn;
entry->type = type;
en = waiters_head;
while (en != NULL && txn->get_ts() < en->txn->get_ts())
en = en->next;
if (en) {
LIST_INSERT_BEFORE(en, entry);
if (en == waiters_head)
waiters_head = entry;
} else
LIST_PUT_TAIL(waiters_head, waiters_tail, entry);
waiter_cnt ++;
txn->lock_ready = false;
rc = WAIT;
}
else
rc = Abort;
}
} else {
LockEntry * entry = get_entry();
entry->type = type;
entry->txn = txn;
STACK_PUSH(owners, entry);
owner_cnt ++;
lock_type = type;
if (CC_ALG == DL_DETECT)
ASSERT(waiters_head == NULL);
rc = RCOK;
}
final:
if (rc == WAIT && CC_ALG == DL_DETECT) {
// Update the waits-for graph
ASSERT(waiters_tail->txn == txn);
txnids = (uint64_t *) mem_allocator.alloc(sizeof(uint64_t) * (owner_cnt + waiter_cnt), part_id);
txncnt = 0;
LockEntry * en = waiters_tail->prev;
while (en != NULL) {
if (conflict_lock(type, en->type))
txnids[txncnt++] = en->txn->get_txn_id();
en = en->prev;
}
en = owners;
if (conflict_lock(type, lock_type))
while (en != NULL) {
txnids[txncnt++] = en->txn->get_txn_id();
en = en->next;
}
ASSERT(txncnt > 0);
}
if (g_central_man)
glob_manager->release_row(_row);
else
pthread_mutex_unlock( latch );
return rc;
}
RC Row_lock::lock_release(txn_man * txn) {
if (g_central_man)
glob_manager->lock_row(_row);
else
pthread_mutex_lock( latch );
// Try to find the entry in the owners
LockEntry * en = owners;
LockEntry * prev = NULL;
while (en != NULL && en->txn != txn) {
prev = en;
en = en->next;
}
if (en) { // find the entry in the owner list
if (prev) prev->next = en->next;
else owners = en->next;
return_entry(en);
owner_cnt --;
if (owner_cnt == 0)
lock_type = LOCK_NONE;
} else {
// Not in owners list, try waiters list.
en = waiters_head;
while (en != NULL && en->txn != txn)
en = en->next;
ASSERT(en);
LIST_REMOVE(en);
if (en == waiters_head)
waiters_head = en->next;
if (en == waiters_tail)
waiters_tail = en->prev;
return_entry(en);
waiter_cnt --;
}
if (owner_cnt == 0)
ASSERT(lock_type == LOCK_NONE);
#if DEBUG_ASSERT && CC_ALG == WAIT_DIE
for (en = waiters_head; en != NULL && en->next != NULL; en = en->next)
assert(en->next->txn->get_ts() < en->txn->get_ts());
#endif
LockEntry * entry;
// If any waiter can join the owners, just do it!
while (waiters_head && !conflict_lock(lock_type, waiters_head->type)) {
LIST_GET_HEAD(waiters_head, waiters_tail, entry);
STACK_PUSH(owners, entry);
owner_cnt ++;
waiter_cnt --;
ASSERT(entry->txn->lock_ready == false);
entry->txn->lock_ready = true;
lock_type = entry->type;
}
ASSERT((owners == NULL) == (owner_cnt == 0));
if (g_central_man)
glob_manager->release_row(_row);
else
pthread_mutex_unlock( latch );
return RCOK;
}
bool Row_lock::conflict_lock(lock_t l1, lock_t l2) {
if (l1 == LOCK_NONE || l2 == LOCK_NONE)
return false;
else if (l1 == LOCK_EX || l2 == LOCK_EX)
return true;
else
return false;
}
LockEntry * Row_lock::get_entry() {
LockEntry * entry = (LockEntry *)
mem_allocator.alloc(sizeof(LockEntry), _row->get_part_id());
return entry;
}
void Row_lock::return_entry(LockEntry * entry) {
mem_allocator.free(entry, sizeof(LockEntry));
}
|
Update row_lock.cpp
|
Update row_lock.cpp
Fixed a typo in comment
|
C++
|
isc
|
yxymit/DBx1000,yxymit/DBx1000,yxymit/DBx1000
|
102f7833c77e71af8f7471c304fce7df61286ffd
|
mesh/pmesh.hpp
|
mesh/pmesh.hpp
|
// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_PMESH
#define MFEM_PMESH
#include "../config/config.hpp"
#ifdef MFEM_USE_MPI
#include "../general/communication.hpp"
#include "../general/globals.hpp"
#include "mesh.hpp"
#include "pncmesh.hpp"
#include <iostream>
namespace mfem
{
#ifdef MFEM_USE_PUMI
class ParPumiMesh;
#endif
/// Class for parallel meshes
class ParMesh : public Mesh
{
#ifdef MFEM_USE_PUMI
friend class ParPumiMesh;
#endif
protected:
ParMesh() : MyComm(0), NRanks(0), MyRank(-1),
have_face_nbr_data(false), pncmesh(NULL) {}
MPI_Comm MyComm;
int NRanks, MyRank;
struct Vert3
{
int v[3];
Vert3() { }
Vert3(int v0, int v1, int v2) { v[0] = v0; v[1] = v1; v[2] = v2; }
void Set(int v0, int v1, int v2) { v[0] = v0; v[1] = v1; v[2] = v2; }
void Set(const int *w) { v[0] = w[0]; v[1] = w[1]; v[2] = w[2]; }
};
struct Vert4
{
int v[4];
Vert4() { }
Vert4(int v0, int v1, int v2, int v3)
{ v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; }
void Set(int v0, int v1, int v2, int v3)
{ v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; }
void Set(const int *w)
{ v[0] = w[0]; v[1] = w[1]; v[2] = w[2]; v[3] = w[3]; }
};
Array<Element *> shared_edges;
// shared face id 'i' is:
// * triangle id 'i', if i < shared_trias.Size()
// * quad id 'i-shared_trias.Size()', otherwise
Array<Vert3> shared_trias;
Array<Vert4> shared_quads;
/// Shared objects in each group.
Table group_svert;
Table group_sedge;
Table group_stria; // contains shared triangle indices
Table group_squad; // contains shared quadrilateral indices
/// Shared to local index mapping.
Array<int> svert_lvert;
Array<int> sedge_ledge;
// sface ids: all triangles first, then all quads
Array<int> sface_lface;
/// Create from a nonconforming mesh.
ParMesh(const ParNCMesh &pncmesh);
// Convert the local 'meshgen' to a global one.
void ReduceMeshGen();
// Determine sedge_ledge and sface_lface.
void FinalizeParTopo();
// Mark all tets to ensure consistency across MPI tasks; also mark the
// shared and boundary triangle faces using the consistently marked tets.
virtual void MarkTetMeshForRefinement(DSTable &v_to_v);
/// Return a number(0-1) identifying how the given edge has been split
int GetEdgeSplittings(Element *edge, const DSTable &v_to_v, int *middle);
/// Append codes identifying how the given face has been split to @a codes
void GetFaceSplittings(const int *fv, const HashTable<Hashed2> &v_to_v,
Array<unsigned> &codes);
bool DecodeFaceSplittings(HashTable<Hashed2> &v_to_v, const int *v,
const Array<unsigned> &codes, int &pos);
void GetFaceNbrElementTransformation(
int i, IsoparametricTransformation *ElTr);
ElementTransformation* GetGhostFaceTransformation(
FaceElementTransformations* FETr, Element::Type face_type,
Geometry::Type face_geom);
/// Update the groups after triangle refinement
void RefineGroups(const DSTable &v_to_v, int *middle);
/// Update the groups after tetrahedron refinement
void RefineGroups(int old_nv, const HashTable<Hashed2> &v_to_v);
void UniformRefineGroups2D(int old_nv);
// f2qf can be NULL if all faces are quads or there are no quad faces
void UniformRefineGroups3D(int old_nv, int old_nedges,
const DSTable &old_v_to_v,
const STable3D &old_faces,
Array<int> *f2qf);
/// Refine a mixed 2D mesh uniformly.
virtual void UniformRefinement2D();
/// Refine a mixed 3D mesh uniformly.
virtual void UniformRefinement3D();
virtual void NURBSUniformRefinement();
/// This function is not public anymore. Use GeneralRefinement instead.
virtual void LocalRefinement(const Array<int> &marked_el, int type = 3);
/// This function is not public anymore. Use GeneralRefinement instead.
virtual void NonconformingRefinement(const Array<Refinement> &refinements,
int nc_limit = 0);
virtual bool NonconformingDerefinement(Array<double> &elem_error,
double threshold, int nc_limit = 0,
int op = 1);
void DeleteFaceNbrData();
bool WantSkipSharedMaster(const NCMesh::Master &master) const;
public:
/** Copy constructor. Performs a deep copy of (almost) all data, so that the
source mesh can be modified (e.g. deleted, refined) without affecting the
new mesh. If 'copy_nodes' is false, use a shallow (pointer) copy for the
nodes, if present. */
explicit ParMesh(const ParMesh &pmesh, bool copy_nodes = true);
ParMesh(MPI_Comm comm, Mesh &mesh, int *partitioning_ = NULL,
int part_method = 1);
/// Read a parallel mesh, each MPI rank from its own file/stream.
/** The @a refine parameter is passed to the method Mesh::Finalize(). */
ParMesh(MPI_Comm comm, std::istream &input, bool refine = true);
/// Create a uniformly refined (by any factor) version of @a orig_mesh.
/** @param[in] orig_mesh The starting coarse mesh.
@param[in] ref_factor The refinement factor, an integer > 1.
@param[in] ref_type Specify the positions of the new vertices. The
options are BasisType::ClosedUniform or
BasisType::GaussLobatto.
The refinement data which can be accessed with GetRefinementTransforms()
is set to reflect the performed refinements.
@note The constructed ParMesh is linear, i.e. it does not have nodes. */
ParMesh(ParMesh *orig_mesh, int ref_factor, int ref_type);
virtual void Finalize(bool refine = false, bool fix_orientation = false);
MPI_Comm GetComm() const { return MyComm; }
int GetNRanks() const { return NRanks; }
int GetMyRank() const { return MyRank; }
GroupTopology gtopo;
// Face-neighbor elements and vertices
bool have_face_nbr_data;
Array<int> face_nbr_group;
Array<int> face_nbr_elements_offset;
Array<int> face_nbr_vertices_offset;
Array<Element *> face_nbr_elements;
Array<Vertex> face_nbr_vertices;
// Local face-neighbor elements and vertices ordered by face-neighbor
Table send_face_nbr_elements;
Table send_face_nbr_vertices;
ParNCMesh* pncmesh;
int GetNGroups() const { return gtopo.NGroups(); }
///@{ @name These methods require group > 0
int GroupNVertices(int group) { return group_svert.RowSize(group-1); }
int GroupNEdges(int group) { return group_sedge.RowSize(group-1); }
int GroupNTriangles(int group) { return group_stria.RowSize(group-1); }
int GroupNQuadrilaterals(int group) { return group_squad.RowSize(group-1); }
int GroupVertex(int group, int i)
{ return svert_lvert[group_svert.GetRow(group-1)[i]]; }
void GroupEdge(int group, int i, int &edge, int &o);
void GroupTriangle(int group, int i, int &face, int &o);
void GroupQuadrilateral(int group, int i, int &face, int &o);
///@}
void GenerateOffsets(int N, HYPRE_Int loc_sizes[],
Array<HYPRE_Int> *offsets[]) const;
void ExchangeFaceNbrData();
void ExchangeFaceNbrData(Table *gr_sface, int *s2l_face);
void ExchangeFaceNbrNodes();
int GetNFaceNeighbors() const { return face_nbr_group.Size(); }
int GetFaceNbrGroup(int fn) const { return face_nbr_group[fn]; }
int GetFaceNbrRank(int fn) const;
/** Similar to Mesh::GetFaceToElementTable with added face-neighbor elements
with indices offset by the local number of elements. */
Table *GetFaceToAllElementTable() const;
/** Get the FaceElementTransformations for the given shared face (edge 2D).
In the returned object, 1 and 2 refer to the local and the neighbor
elements, respectively. */
FaceElementTransformations *
GetSharedFaceTransformations(int sf, bool fill2 = true);
/// Return the number of shared faces (3D), edges (2D), vertices (1D)
int GetNSharedFaces() const;
/// Return the local face index for the given shared face.
int GetSharedFace(int sface) const;
/// See the remarks for the serial version in mesh.hpp
virtual void ReorientTetMesh();
/// Utility function: sum integers from all processors (Allreduce).
virtual long ReduceInt(int value) const;
/// Load balance the mesh. NC meshes only.
void Rebalance();
/** Print the part of the mesh in the calling processor adding the interface
as boundary (for visualization purposes) using the mfem v1.0 format. */
virtual void Print(std::ostream &out = mfem::out) const;
/** Print the part of the mesh in the calling processor adding the interface
as boundary (for visualization purposes) using Netgen/Truegrid format .*/
virtual void PrintXG(std::ostream &out = mfem::out) const;
/** Write the mesh to the stream 'out' on Process 0 in a form suitable for
visualization: the mesh is written as a disjoint mesh and the shared
boundary is added to the actual boundary; both the element and boundary
attributes are set to the processor number. */
void PrintAsOne(std::ostream &out = mfem::out);
/// Old mesh format (Netgen/Truegrid) version of 'PrintAsOne'
void PrintAsOneXG(std::ostream &out = mfem::out);
/// Returns the minimum and maximum corners of the mesh bounding box. For
/// high-order meshes, the geometry is refined first "ref" times.
void GetBoundingBox(Vector &p_min, Vector &p_max, int ref = 2);
void GetCharacteristics(double &h_min, double &h_max,
double &kappa_min, double &kappa_max);
/// Print various parallel mesh stats
virtual void PrintInfo(std::ostream &out = mfem::out);
/// Save the mesh in a parallel mesh format.
void ParPrint(std::ostream &out) const;
virtual int FindPoints(DenseMatrix& point_mat, Array<int>& elem_ids,
Array<IntegrationPoint>& ips, bool warn = true,
InverseElementTransformation *inv_trans = NULL);
virtual ~ParMesh();
};
}
#endif // MFEM_USE_MPI
#endif
|
// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_PMESH
#define MFEM_PMESH
#include "../config/config.hpp"
#ifdef MFEM_USE_MPI
#include "../general/communication.hpp"
#include "../general/globals.hpp"
#include "mesh.hpp"
#include "pncmesh.hpp"
#include <iostream>
namespace mfem
{
#ifdef MFEM_USE_PUMI
class ParPumiMesh;
#endif
/// Class for parallel meshes
class ParMesh : public Mesh
{
#ifdef MFEM_USE_PUMI
friend class ParPumiMesh;
#endif
protected:
ParMesh() : MyComm(0), NRanks(0), MyRank(-1),
have_face_nbr_data(false), pncmesh(NULL) {}
MPI_Comm MyComm;
int NRanks, MyRank;
struct Vert3
{
int v[3];
Vert3() { }
Vert3(int v0, int v1, int v2) { v[0] = v0; v[1] = v1; v[2] = v2; }
void Set(int v0, int v1, int v2) { v[0] = v0; v[1] = v1; v[2] = v2; }
void Set(const int *w) { v[0] = w[0]; v[1] = w[1]; v[2] = w[2]; }
};
struct Vert4
{
int v[4];
Vert4() { }
Vert4(int v0, int v1, int v2, int v3)
{ v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; }
void Set(int v0, int v1, int v2, int v3)
{ v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; }
void Set(const int *w)
{ v[0] = w[0]; v[1] = w[1]; v[2] = w[2]; v[3] = w[3]; }
};
Array<Element *> shared_edges;
// shared face id 'i' is:
// * triangle id 'i', if i < shared_trias.Size()
// * quad id 'i-shared_trias.Size()', otherwise
Array<Vert3> shared_trias;
Array<Vert4> shared_quads;
/// Shared objects in each group.
Table group_svert;
Table group_sedge;
Table group_stria; // contains shared triangle indices
Table group_squad; // contains shared quadrilateral indices
/// Shared to local index mapping.
Array<int> svert_lvert;
Array<int> sedge_ledge;
// sface ids: all triangles first, then all quads
Array<int> sface_lface;
/// Create from a nonconforming mesh.
ParMesh(const ParNCMesh &pncmesh);
// Convert the local 'meshgen' to a global one.
void ReduceMeshGen();
// Determine sedge_ledge and sface_lface.
void FinalizeParTopo();
// Mark all tets to ensure consistency across MPI tasks; also mark the
// shared and boundary triangle faces using the consistently marked tets.
virtual void MarkTetMeshForRefinement(DSTable &v_to_v);
/// Return a number(0-1) identifying how the given edge has been split
int GetEdgeSplittings(Element *edge, const DSTable &v_to_v, int *middle);
/// Append codes identifying how the given face has been split to @a codes
void GetFaceSplittings(const int *fv, const HashTable<Hashed2> &v_to_v,
Array<unsigned> &codes);
bool DecodeFaceSplittings(HashTable<Hashed2> &v_to_v, const int *v,
const Array<unsigned> &codes, int &pos);
void GetFaceNbrElementTransformation(
int i, IsoparametricTransformation *ElTr);
ElementTransformation* GetGhostFaceTransformation(
FaceElementTransformations* FETr, Element::Type face_type,
Geometry::Type face_geom);
/// Update the groups after triangle refinement
void RefineGroups(const DSTable &v_to_v, int *middle);
/// Update the groups after tetrahedron refinement
void RefineGroups(int old_nv, const HashTable<Hashed2> &v_to_v);
void UniformRefineGroups2D(int old_nv);
// f2qf can be NULL if all faces are quads or there are no quad faces
void UniformRefineGroups3D(int old_nv, int old_nedges,
const DSTable &old_v_to_v,
const STable3D &old_faces,
Array<int> *f2qf);
void ExchangeFaceNbrData(Table *gr_sface, int *s2l_face);
/// Refine a mixed 2D mesh uniformly.
virtual void UniformRefinement2D();
/// Refine a mixed 3D mesh uniformly.
virtual void UniformRefinement3D();
virtual void NURBSUniformRefinement();
/// This function is not public anymore. Use GeneralRefinement instead.
virtual void LocalRefinement(const Array<int> &marked_el, int type = 3);
/// This function is not public anymore. Use GeneralRefinement instead.
virtual void NonconformingRefinement(const Array<Refinement> &refinements,
int nc_limit = 0);
virtual bool NonconformingDerefinement(Array<double> &elem_error,
double threshold, int nc_limit = 0,
int op = 1);
void DeleteFaceNbrData();
bool WantSkipSharedMaster(const NCMesh::Master &master) const;
public:
/** Copy constructor. Performs a deep copy of (almost) all data, so that the
source mesh can be modified (e.g. deleted, refined) without affecting the
new mesh. If 'copy_nodes' is false, use a shallow (pointer) copy for the
nodes, if present. */
explicit ParMesh(const ParMesh &pmesh, bool copy_nodes = true);
ParMesh(MPI_Comm comm, Mesh &mesh, int *partitioning_ = NULL,
int part_method = 1);
/// Read a parallel mesh, each MPI rank from its own file/stream.
/** The @a refine parameter is passed to the method Mesh::Finalize(). */
ParMesh(MPI_Comm comm, std::istream &input, bool refine = true);
/// Create a uniformly refined (by any factor) version of @a orig_mesh.
/** @param[in] orig_mesh The starting coarse mesh.
@param[in] ref_factor The refinement factor, an integer > 1.
@param[in] ref_type Specify the positions of the new vertices. The
options are BasisType::ClosedUniform or
BasisType::GaussLobatto.
The refinement data which can be accessed with GetRefinementTransforms()
is set to reflect the performed refinements.
@note The constructed ParMesh is linear, i.e. it does not have nodes. */
ParMesh(ParMesh *orig_mesh, int ref_factor, int ref_type);
virtual void Finalize(bool refine = false, bool fix_orientation = false);
MPI_Comm GetComm() const { return MyComm; }
int GetNRanks() const { return NRanks; }
int GetMyRank() const { return MyRank; }
GroupTopology gtopo;
// Face-neighbor elements and vertices
bool have_face_nbr_data;
Array<int> face_nbr_group;
Array<int> face_nbr_elements_offset;
Array<int> face_nbr_vertices_offset;
Array<Element *> face_nbr_elements;
Array<Vertex> face_nbr_vertices;
// Local face-neighbor elements and vertices ordered by face-neighbor
Table send_face_nbr_elements;
Table send_face_nbr_vertices;
ParNCMesh* pncmesh;
int GetNGroups() const { return gtopo.NGroups(); }
///@{ @name These methods require group > 0
int GroupNVertices(int group) { return group_svert.RowSize(group-1); }
int GroupNEdges(int group) { return group_sedge.RowSize(group-1); }
int GroupNTriangles(int group) { return group_stria.RowSize(group-1); }
int GroupNQuadrilaterals(int group) { return group_squad.RowSize(group-1); }
int GroupVertex(int group, int i)
{ return svert_lvert[group_svert.GetRow(group-1)[i]]; }
void GroupEdge(int group, int i, int &edge, int &o);
void GroupTriangle(int group, int i, int &face, int &o);
void GroupQuadrilateral(int group, int i, int &face, int &o);
///@}
void GenerateOffsets(int N, HYPRE_Int loc_sizes[],
Array<HYPRE_Int> *offsets[]) const;
void ExchangeFaceNbrData();
void ExchangeFaceNbrNodes();
int GetNFaceNeighbors() const { return face_nbr_group.Size(); }
int GetFaceNbrGroup(int fn) const { return face_nbr_group[fn]; }
int GetFaceNbrRank(int fn) const;
/** Similar to Mesh::GetFaceToElementTable with added face-neighbor elements
with indices offset by the local number of elements. */
Table *GetFaceToAllElementTable() const;
/** Get the FaceElementTransformations for the given shared face (edge 2D).
In the returned object, 1 and 2 refer to the local and the neighbor
elements, respectively. */
FaceElementTransformations *
GetSharedFaceTransformations(int sf, bool fill2 = true);
/// Return the number of shared faces (3D), edges (2D), vertices (1D)
int GetNSharedFaces() const;
/// Return the local face index for the given shared face.
int GetSharedFace(int sface) const;
/// See the remarks for the serial version in mesh.hpp
virtual void ReorientTetMesh();
/// Utility function: sum integers from all processors (Allreduce).
virtual long ReduceInt(int value) const;
/// Load balance the mesh. NC meshes only.
void Rebalance();
/** Print the part of the mesh in the calling processor adding the interface
as boundary (for visualization purposes) using the mfem v1.0 format. */
virtual void Print(std::ostream &out = mfem::out) const;
/** Print the part of the mesh in the calling processor adding the interface
as boundary (for visualization purposes) using Netgen/Truegrid format .*/
virtual void PrintXG(std::ostream &out = mfem::out) const;
/** Write the mesh to the stream 'out' on Process 0 in a form suitable for
visualization: the mesh is written as a disjoint mesh and the shared
boundary is added to the actual boundary; both the element and boundary
attributes are set to the processor number. */
void PrintAsOne(std::ostream &out = mfem::out);
/// Old mesh format (Netgen/Truegrid) version of 'PrintAsOne'
void PrintAsOneXG(std::ostream &out = mfem::out);
/// Returns the minimum and maximum corners of the mesh bounding box. For
/// high-order meshes, the geometry is refined first "ref" times.
void GetBoundingBox(Vector &p_min, Vector &p_max, int ref = 2);
void GetCharacteristics(double &h_min, double &h_max,
double &kappa_min, double &kappa_max);
/// Print various parallel mesh stats
virtual void PrintInfo(std::ostream &out = mfem::out);
/// Save the mesh in a parallel mesh format.
void ParPrint(std::ostream &out) const;
virtual int FindPoints(DenseMatrix& point_mat, Array<int>& elem_ids,
Array<IntegrationPoint>& ips, bool warn = true,
InverseElementTransformation *inv_trans = NULL);
virtual ~ParMesh();
};
}
#endif // MFEM_USE_MPI
#endif
|
Make the method ParMesh::ExchangeFaceNbrData(Table*, int*) protected.
|
Make the method ParMesh::ExchangeFaceNbrData(Table*, int*) protected.
|
C++
|
bsd-3-clause
|
mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem
|
8955b2670d1330738d7499b80c2a4f25382e3132
|
uart.cpp
|
uart.cpp
|
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "horizonTracker.h"
#define START_BYTE 0x12
const int DOUBLE_SIZE = sizeof(double);
int uart0filestream = -1;
void UARTInit();
int writeStartByte();
int writeAngleData(double&);
int readAngleData(double&);
int readStartByte();
void reverse_array(unsigned char*, int);
void UARTInit()
{
uart0filestream = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if(uart0filestream == -1)
{
printf("Cant open UART\n");
}
struct termios options;
tcgetattr(uart0filestream, &options);
options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0filestream, TCIFLUSH);
tcsetattr(uart0filestream, TCSANOW, &options);
}
int writeStartByte()
{
if(mode == SERF)
{
printf("I'm not writing the start byte. I'm the SERF!");
}
char const data[] = { START_BYTE };
if(uart0filestream)
{
int count = write(uart0filestream, &data, 1);
if(count < 0)
{
printf("UART TX error\n");
return -1;
}
}
}
int writeAngleData(double & angle) {
if(mode == MASTER)
{
printf("I'm not writing angle data. I'm the MASTER!\n");
return -1;
}
unsigned char * const data = reinterpret_cast<unsigned char * const>(&angle);
if(uart0filestream)
{
int count = write(uart0filestream, &data, DOUBLE_SIZE);
if(count < 0)
{
printf("UART TX error\n");
return -1;
}
}
}
int readAngleData(double & angle)
{
if(mode == SERF)
{
printf("I'm not reading angle data. I'm the SERF!\n");
return -1;
}
if(uart0filestream != -1)
{
unsigned char rx_buffer[256];
int rx_length = read(uart0filestream, (void*)rx_buffer, 255);
if(rx_length <= 0)
{
// no data
return 0;
}
else if(rx_length >= DOUBLE_SIZE)
{
reverse_array(rx_buffer, DOUBLE_SIZE);
memcpy(&angle, rx_buffer, DOUBLE_SIZE);
return 0;
}
else
{
printf("Some uart error occurred. We received data, but not enough to make a double!!!\n");
return 0;
}
}
}
int readStartByte()
{
if(mode == MASTER)
{
printf("I'm not reading start byte data. I'm the MASTER!\n");
return -1;
}
if(uart0filestream != -1)
{
unsigned char rx_buffer[256];
int rx_length = read(uart0filestream, (void*)rx_buffer, 255);
printf("opened: %d\n", rx_length);
if(rx_length <= 0)
{
// no data
return 0;
}
else
{
if(rx_buffer[0] == START_BYTE)
{
return 1;
}
else
{
return 0;
}
}
}
}
void reverse_array( unsigned char array[], int arraylength )
{
for (int i = 0; i < (arraylength / 2); i++)
{
unsigned char temporary = array[i];
array[i] = array[(arraylength - 1) - i];
array[(arraylength - 1) - i] = temporary;
}
}
|
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "horizonTracker.h"
#define START_BYTE 0x12
const int DOUBLE_SIZE = sizeof(double);
int uart0filestream = -1;
void UARTInit();
int writeStartByte();
int writeAngleData(double&);
int readAngleData(double&);
int readStartByte();
void reverse_array(unsigned char*, int);
void shiftLeft(unsigned char*, int, int);
unsigned char rx_buffer[256] = { 0 };
int offset = 0;
void UARTInit()
{
uart0filestream = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if(uart0filestream == -1)
{
printf("Cant open UART\n");
}
struct termios options;
tcgetattr(uart0filestream, &options);
options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0filestream, TCIFLUSH);
tcsetattr(uart0filestream, TCSANOW, &options);
}
int writeStartByte()
{
if(mode == SERF)
{
printf("I'm not writing the start byte. I'm the SERF!");
}
char const data[] = { START_BYTE };
if(uart0filestream)
{
int count = write(uart0filestream, &data, 1);
if(count < 0)
{
printf("UART TX error\n");
return -1;
}
}
}
int writeAngleData(double & angle) {
if(mode == MASTER)
{
printf("I'm not writing angle data. I'm the MASTER!\n");
return -1;
}
unsigned char data[DOUBLE_SIZE+1] = { 0 };
memcpy((&data+1), &angle, DOUBLE_SIZE);
//unsigned char * const doubleData = reinterpret_cast<unsigned char * const>(&angle);
if(uart0filestream)
{
int count = write(uart0filestream, &data, DOUBLE_SIZE);
if(count < 0)
{
printf("UART TX error\n");
return -1;
}
}
}
int readAngleData(double & angle)
{
if(mode == SERF)
{
printf("I'm not reading angle data. I'm the SERF!\n");
return -1;
}
if(uart0filestream != -1)
{
int rx_length = read(uart0filestream, (void*)(rx_buffer+offset), 255-offset);
if(rx_length <= 0)
{
// no data
return 0;
}
else if(rx_length >= DOUBLE_SIZE)
{
//consume bytes;
while(rx_buffer[0] != 0) {
shiftLeft(rx_buffer, 256, 1);
}
reverse_array(rx_buffer, DOUBLE_SIZE);
memcpy(&angle, (&rx_buffer+1), DOUBLE_SIZE);
// pop off 9 bytes
shiftLeft(rx_buffer, 256, 9);
return 0;
}
else
{
printf("Some uart error occurred. We received data, but not enough to make a double!!!\n");
return 0;
}
}
}
int readStartByte()
{
if(mode == MASTER)
{
printf("I'm not reading start byte data. I'm the MASTER!\n");
return -1;
}
if(uart0filestream != -1)
{
unsigned char rx_buffer[256];
int rx_length = read(uart0filestream, (void*)rx_buffer, 255);
printf("opened: %d\n", rx_length);
if(rx_length <= 0)
{
// no data
return 0;
}
else
{
if(rx_buffer[0] == START_BYTE)
{
return 1;
}
else
{
return 0;
}
}
}
}
void shiftLeft(unsigned char * bytes, int length, int shift)
{
for(int j = 0; j < length-shift; j++) {
bytes[j]=bytes[j+shift];
}
for(int j = length-shift; j < length; j++) {
bytes[j]=bytes[0];
}
}
void reverse_array( unsigned char array[], int arraylength )
{
for (int i = 0; i < (arraylength / 2); i++)
{
unsigned char temporary = array[i];
array[i] = array[(arraylength - 1) - i];
array[(arraylength - 1) - i] = temporary;
}
}
|
align bytes to a null identifier
|
align bytes to a null identifier
|
C++
|
mit
|
LetsBuildRockets/Horizon-Tracker
|
88f8eb2cb5701a2c5ff239087845838a573feb33
|
src/servers/sapphire_zone/Zone/TerritoryMgr.cpp
|
src/servers/sapphire_zone/Zone/TerritoryMgr.cpp
|
#include "TerritoryMgr.h"
#include <common/Logging/Logger.h>
#include <common/Database/DatabaseDef.h>
#include <common/Exd/ExdDataGenerated.h>
#include "Actor/Player.h"
#include "Zone.h"
#include "ZonePosition.h"
#include "InstanceContent.h"
extern Core::Logger g_log;
extern Core::Data::ExdData g_exdData;
extern Core::Data::ExdDataGenerated g_exdDataGen;
Core::TerritoryMgr::TerritoryMgr() :
m_lastInstanceId( 10000 )
{
}
void Core::TerritoryMgr::loadTerritoryTypeDetailCache()
{
auto idList = g_exdDataGen.getTerritoryTypeIdList();
for( auto id : idList )
{
auto teri1 = g_exdDataGen.getTerritoryType( id );
if( !teri1->name.empty() )
m_territoryTypeDetailCacheMap[id] = teri1;
}
}
bool Core::TerritoryMgr::isValidTerritory( uint32_t territoryTypeId ) const
{
return !( m_territoryTypeDetailCacheMap.find( territoryTypeId ) == m_territoryTypeDetailCacheMap.end() );
}
bool Core::TerritoryMgr::init()
{
loadTerritoryTypeDetailCache();
loadTerritoryPositionMap();
createDefaultTerritories();
return true;
}
uint32_t Core::TerritoryMgr::getNextInstanceId()
{
return ++m_lastInstanceId;
}
Core::Data::TerritoryTypePtr Core::TerritoryMgr::getTerritoryDetail( uint32_t territoryTypeId ) const
{
auto tIt = m_territoryTypeDetailCacheMap.find( territoryTypeId );
if( tIt == m_territoryTypeDetailCacheMap.end() )
return nullptr;
return tIt->second;
}
bool Core::TerritoryMgr::isInstanceContentTerritory( uint32_t territoryTypeId ) const
{
auto pTeri = getTerritoryDetail( territoryTypeId );
if( !pTeri )
return false;
return pTeri->territoryIntendedUse == TerritoryIntendedUse::AllianceRaid ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::BeforeTrialDung ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Trial ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Dungeon ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::OpenWorldInstanceBattle ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::PalaceOfTheDead ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::RaidFights ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Raids ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::TreasureMapInstance;
}
bool Core::TerritoryMgr::isPrivateTerritory( uint32_t territoryTypeId ) const
{
auto pTeri = getTerritoryDetail( territoryTypeId );
if( !pTeri )
return false;
return pTeri->territoryIntendedUse == TerritoryIntendedUse::OpeningArea ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Inn ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::HousingPrivateArea ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::JailArea ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::MSQPrivateArea;
}
bool Core::TerritoryMgr::createDefaultTerritories()
{
// for each entry in territoryTypeExd, check if it is a normal and if so, add the zone object
for( const auto& territory : m_territoryTypeDetailCacheMap )
{
auto territoryId = territory.first;
auto territoryInfo = territory.second;
// if the zone has no name set
if( territoryInfo->name.empty() )
continue;
auto pPlaceName = g_exdDataGen.getPlaceName( territoryInfo->placeName );
if( !pPlaceName || pPlaceName->name.empty() || !isDefaultTerritory( territoryId ) )
continue;
uint32_t guid = getNextInstanceId();
g_log.Log( LoggingSeverity::info, std::to_string( territoryId ) +
"\t" + std::to_string( guid ) +
"\t" + std::to_string( territoryInfo->territoryIntendedUse ) +
"\t" + territoryInfo->name +
"\t" + pPlaceName->name );
ZonePtr pZone( new Zone( territoryId, guid, territoryInfo->name, pPlaceName->name ) );
pZone->init();
InstanceIdToZonePtrMap instanceMap;
instanceMap[guid] = pZone;
m_instanceIdToZonePtrMap[guid] = pZone;
m_territoryInstanceMap[territoryId] = instanceMap;
}
return true;
}
Core::ZonePtr Core::TerritoryMgr::createTerritoryInstance( uint32_t territoryTypeId )
{
if( !isValidTerritory( territoryTypeId ) )
return nullptr;
if( isInstanceContentTerritory( territoryTypeId ) )
return nullptr;
auto pTeri = getTerritoryDetail( territoryTypeId );
auto pPlaceName = g_exdDataGen.getPlaceName( pTeri->placeName );
if( !pTeri || !pPlaceName )
return nullptr;
g_log.debug( "Starting instance for territory: " + std::to_string( territoryTypeId ) + " (" + pPlaceName->name + ")" );
ZonePtr pZone = ZonePtr( new Zone( territoryTypeId, getNextInstanceId(), pTeri->name, pPlaceName->name ) );
pZone->init();
m_territoryInstanceMap[pZone->getTerritoryId()][pZone->getGuId()] = pZone;
m_instanceIdToZonePtrMap[pZone->getGuId()] = pZone;
return pZone;
}
Core::ZonePtr Core::TerritoryMgr::createInstanceContent( uint32_t instanceContentId )
{
auto pInstanceContent = g_exdDataGen.getInstanceContent( instanceContentId );
if( !pInstanceContent )
return nullptr;
if( !isInstanceContentTerritory( pInstanceContent->territoryType ) )
return nullptr;
auto pTeri = getTerritoryDetail( pInstanceContent->territoryType );
auto pPlaceName = g_exdDataGen.getPlaceName( pTeri->placeName );
if( !pTeri || !pPlaceName )
return nullptr;
g_log.debug( "Starting instance for InstanceContent id: " + std::to_string( instanceContentId ) + " (" + pPlaceName->name + ")" );
ZonePtr pZone = ZonePtr( new InstanceContent( pInstanceContent, getNextInstanceId(), pTeri->name, pPlaceName->name, instanceContentId ) );
pZone->init();
m_instanceContentToInstanceMap[instanceContentId][pZone->getGuId()] = pZone;
m_instanceIdToZonePtrMap[pZone->getGuId()] = pZone;
return pZone;
}
bool Core::TerritoryMgr::removeTerritoryInstance( uint32_t instanceId )
{
ZonePtr pZone;
if( ( pZone = getInstanceZonePtr( instanceId ) ) == nullptr )
return false;
m_instanceIdToZonePtrMap.erase( pZone->getGuId() );
if( isInstanceContentTerritory( pZone->getTerritoryId() ) )
{
auto instance = boost::dynamic_pointer_cast< InstanceContent >( pZone );
m_instanceContentToInstanceMap[instance->getInstanceContentId()].erase( pZone->getGuId() );
}
else
m_territoryInstanceMap[pZone->getTerritoryId()].erase( pZone->getGuId() );
return true;
}
Core::ZonePtr Core::TerritoryMgr::getInstanceZonePtr( uint32_t instanceId ) const
{
auto it = m_instanceIdToZonePtrMap.find( instanceId );
if( it == m_instanceIdToZonePtrMap.end() )
return nullptr;
return it->second;
}
void Core::TerritoryMgr::loadTerritoryPositionMap()
{
auto pQR = g_charaDb.query( "SELECT id, target_zone_id, pos_x, pos_y, pos_z, pos_o, radius FROM zonepositions;" );
while( pQR->next() )
{
uint32_t id = pQR->getUInt( 1 );
uint32_t targetZoneId = pQR->getUInt( 2 );
Common::FFXIVARR_POSITION3 pos{};
pos.x = pQR->getFloat( 3 );
pos.y = pQR->getFloat( 4 );
pos.z = pQR->getFloat( 5 );
float posO = pQR->getFloat( 6 );
uint32_t radius = pQR->getUInt( 7 );
m_territoryPositionMap[id] = ZonePositionPtr( new ZonePosition( id, targetZoneId, pos, radius, posO ) );
}
}
bool Core::TerritoryMgr::isDefaultTerritory( uint32_t territoryTypeId ) const
{
auto pTeri = getTerritoryDetail( territoryTypeId );
if( !pTeri )
return false;
return pTeri->territoryIntendedUse == TerritoryIntendedUse::Inn ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Town ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::OpenWorld ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::OpeningArea;
}
Core::ZonePositionPtr Core::TerritoryMgr::getTerritoryPosition( uint32_t territoryPositionId ) const
{
auto it = m_territoryPositionMap.find( territoryPositionId );
if( it != m_territoryPositionMap.end() )
return it->second;
return nullptr;
}
Core::ZonePtr Core::TerritoryMgr::getZoneByTerriId( uint32_t territoryId ) const
{
auto zoneMap = m_territoryInstanceMap.find( territoryId );
if( zoneMap == m_territoryInstanceMap.end() )
return nullptr;
// TODO: actually select the proper one
return zoneMap->second.begin()->second;
}
void Core::TerritoryMgr::updateTerritoryInstances( uint32_t currentTime )
{
for( auto zoneMap : m_territoryInstanceMap )
{
for( auto zone : zoneMap.second )
zone.second->runZoneLogic( currentTime );
}
for( auto zoneMap : m_instanceContentToInstanceMap )
{
for( auto zone: zoneMap.second )
zone.second->runZoneLogic( currentTime );
}
}
Core::TerritoryMgr::InstanceIdList Core::TerritoryMgr::getInstanceContentIdList( uint16_t instanceContentId ) const
{
std::vector< uint32_t > idList;
auto zoneMap = m_instanceContentToInstanceMap.find( instanceContentId );
if( zoneMap == m_instanceContentToInstanceMap.end() )
return idList;
for( auto& entry : zoneMap->second )
{
idList.push_back( entry.first );
}
return idList;
}
bool Core::TerritoryMgr::movePlayer( uint32_t territoryId, Core::Entity::PlayerPtr pPlayer )
{
auto pZone = getZoneByTerriId( territoryId );
if( !pZone )
{
g_log.error( "Zone " + std::to_string( territoryId ) + " not found on this server." );
return false;
}
pPlayer->setTerritoryId( territoryId );
// mark character as zoning in progress
pPlayer->setLoadingComplete( false );
if( pPlayer->getLastPing() != 0 )
pPlayer->getCurrentZone()->removeActor( pPlayer );
pPlayer->setCurrentZone( pZone );
pZone->pushActor( pPlayer );
return true;
}
bool Core::TerritoryMgr::movePlayer( ZonePtr pZone, Core::Entity::PlayerPtr pPlayer )
{
if( !pZone )
{
g_log.error( "Zone not found on this server." );
return false;
}
pPlayer->setTerritoryId( pZone->getTerritoryId() );
// mark character as zoning in progress
pPlayer->setLoadingComplete( false );
if( pPlayer->getLastPing() != 0 )
pPlayer->getCurrentZone()->removeActor( pPlayer );
pPlayer->setCurrentZone( pZone );
pZone->pushActor( pPlayer );
return true;
}
|
#include "TerritoryMgr.h"
#include <common/Logging/Logger.h>
#include <common/Database/DatabaseDef.h>
#include <common/Exd/ExdDataGenerated.h>
#include "Actor/Player.h"
#include "Zone.h"
#include "ZonePosition.h"
#include "InstanceContent.h"
extern Core::Logger g_log;
extern Core::Data::ExdData g_exdData;
extern Core::Data::ExdDataGenerated g_exdDataGen;
Core::TerritoryMgr::TerritoryMgr() :
m_lastInstanceId( 10000 )
{
}
void Core::TerritoryMgr::loadTerritoryTypeDetailCache()
{
auto idList = g_exdDataGen.getTerritoryTypeIdList();
for( auto id : idList )
{
auto teri1 = g_exdDataGen.getTerritoryType( id );
if( !teri1->name.empty() )
m_territoryTypeDetailCacheMap[id] = teri1;
}
}
bool Core::TerritoryMgr::isValidTerritory( uint32_t territoryTypeId ) const
{
return !( m_territoryTypeDetailCacheMap.find( territoryTypeId ) == m_territoryTypeDetailCacheMap.end() );
}
bool Core::TerritoryMgr::init()
{
loadTerritoryTypeDetailCache();
loadTerritoryPositionMap();
createDefaultTerritories();
return true;
}
uint32_t Core::TerritoryMgr::getNextInstanceId()
{
return ++m_lastInstanceId;
}
Core::Data::TerritoryTypePtr Core::TerritoryMgr::getTerritoryDetail( uint32_t territoryTypeId ) const
{
auto tIt = m_territoryTypeDetailCacheMap.find( territoryTypeId );
if( tIt == m_territoryTypeDetailCacheMap.end() )
return nullptr;
return tIt->second;
}
bool Core::TerritoryMgr::isInstanceContentTerritory( uint32_t territoryTypeId ) const
{
auto pTeri = getTerritoryDetail( territoryTypeId );
if( !pTeri )
return false;
return pTeri->territoryIntendedUse == TerritoryIntendedUse::AllianceRaid ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::BeforeTrialDung ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Trial ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Dungeon ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::OpenWorldInstanceBattle ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::PalaceOfTheDead ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::RaidFights ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Raids ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::TreasureMapInstance;
}
bool Core::TerritoryMgr::isPrivateTerritory( uint32_t territoryTypeId ) const
{
auto pTeri = getTerritoryDetail( territoryTypeId );
if( !pTeri )
return false;
return pTeri->territoryIntendedUse == TerritoryIntendedUse::OpeningArea ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Inn ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::HousingPrivateArea ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::JailArea ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::MSQPrivateArea;
}
bool Core::TerritoryMgr::createDefaultTerritories()
{
// for each entry in territoryTypeExd, check if it is a normal and if so, add the zone object
for( const auto& territory : m_territoryTypeDetailCacheMap )
{
auto territoryId = territory.first;
auto territoryInfo = territory.second;
// if the zone has no name set
if( territoryInfo->name.empty() )
continue;
auto pPlaceName = g_exdDataGen.getPlaceName( territoryInfo->placeName );
if( !pPlaceName || pPlaceName->name.empty() || !isDefaultTerritory( territoryId ) )
continue;
uint32_t guid = getNextInstanceId();
g_log.Log( LoggingSeverity::info, std::to_string( territoryId ) +
"\t" + std::to_string( guid ) +
"\t" + std::to_string( territoryInfo->territoryIntendedUse ) +
"\t" + territoryInfo->name +
"\t" + pPlaceName->name );
ZonePtr pZone( new Zone( territoryId, guid, territoryInfo->name, pPlaceName->name ) );
pZone->init();
InstanceIdToZonePtrMap instanceMap;
instanceMap[guid] = pZone;
m_instanceIdToZonePtrMap[guid] = pZone;
m_territoryInstanceMap[territoryId] = instanceMap;
}
return true;
}
Core::ZonePtr Core::TerritoryMgr::createTerritoryInstance( uint32_t territoryTypeId )
{
if( !isValidTerritory( territoryTypeId ) )
return nullptr;
if( isInstanceContentTerritory( territoryTypeId ) )
return nullptr;
auto pTeri = getTerritoryDetail( territoryTypeId );
auto pPlaceName = g_exdDataGen.getPlaceName( pTeri->placeName );
if( !pTeri || !pPlaceName )
return nullptr;
g_log.debug( "Starting instance for territory: " + std::to_string( territoryTypeId ) + " (" + pPlaceName->name + ")" );
ZonePtr pZone = ZonePtr( new Zone( territoryTypeId, getNextInstanceId(), pTeri->name, pPlaceName->name ) );
pZone->init();
m_territoryInstanceMap[pZone->getTerritoryId()][pZone->getGuId()] = pZone;
m_instanceIdToZonePtrMap[pZone->getGuId()] = pZone;
return pZone;
}
Core::ZonePtr Core::TerritoryMgr::createInstanceContent( uint32_t instanceContentId )
{
auto pInstanceContent = g_exdDataGen.getInstanceContent( instanceContentId );
if( !pInstanceContent )
return nullptr;
if( !isInstanceContentTerritory( pInstanceContent->territoryType ) )
return nullptr;
auto pTeri = getTerritoryDetail( pInstanceContent->territoryType );
if( !pTeri || pInstanceContent->name.empty() )
return nullptr;
g_log.debug( "Starting instance for InstanceContent id: " + std::to_string( instanceContentId ) +
" (" + pInstanceContent->name + ")" );
ZonePtr pZone = ZonePtr( new InstanceContent( pInstanceContent, getNextInstanceId(), pTeri->name,
pInstanceContent->name, instanceContentId ) );
pZone->init();
m_instanceContentToInstanceMap[instanceContentId][pZone->getGuId()] = pZone;
m_instanceIdToZonePtrMap[pZone->getGuId()] = pZone;
return pZone;
}
bool Core::TerritoryMgr::removeTerritoryInstance( uint32_t instanceId )
{
ZonePtr pZone;
if( ( pZone = getInstanceZonePtr( instanceId ) ) == nullptr )
return false;
m_instanceIdToZonePtrMap.erase( pZone->getGuId() );
if( isInstanceContentTerritory( pZone->getTerritoryId() ) )
{
auto instance = boost::dynamic_pointer_cast< InstanceContent >( pZone );
m_instanceContentToInstanceMap[instance->getInstanceContentId()].erase( pZone->getGuId() );
}
else
m_territoryInstanceMap[pZone->getTerritoryId()].erase( pZone->getGuId() );
return true;
}
Core::ZonePtr Core::TerritoryMgr::getInstanceZonePtr( uint32_t instanceId ) const
{
auto it = m_instanceIdToZonePtrMap.find( instanceId );
if( it == m_instanceIdToZonePtrMap.end() )
return nullptr;
return it->second;
}
void Core::TerritoryMgr::loadTerritoryPositionMap()
{
auto pQR = g_charaDb.query( "SELECT id, target_zone_id, pos_x, pos_y, pos_z, pos_o, radius FROM zonepositions;" );
while( pQR->next() )
{
uint32_t id = pQR->getUInt( 1 );
uint32_t targetZoneId = pQR->getUInt( 2 );
Common::FFXIVARR_POSITION3 pos{};
pos.x = pQR->getFloat( 3 );
pos.y = pQR->getFloat( 4 );
pos.z = pQR->getFloat( 5 );
float posO = pQR->getFloat( 6 );
uint32_t radius = pQR->getUInt( 7 );
m_territoryPositionMap[id] = ZonePositionPtr( new ZonePosition( id, targetZoneId, pos, radius, posO ) );
}
}
bool Core::TerritoryMgr::isDefaultTerritory( uint32_t territoryTypeId ) const
{
auto pTeri = getTerritoryDetail( territoryTypeId );
if( !pTeri )
return false;
return pTeri->territoryIntendedUse == TerritoryIntendedUse::Inn ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::Town ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::OpenWorld ||
pTeri->territoryIntendedUse == TerritoryIntendedUse::OpeningArea;
}
Core::ZonePositionPtr Core::TerritoryMgr::getTerritoryPosition( uint32_t territoryPositionId ) const
{
auto it = m_territoryPositionMap.find( territoryPositionId );
if( it != m_territoryPositionMap.end() )
return it->second;
return nullptr;
}
Core::ZonePtr Core::TerritoryMgr::getZoneByTerriId( uint32_t territoryId ) const
{
auto zoneMap = m_territoryInstanceMap.find( territoryId );
if( zoneMap == m_territoryInstanceMap.end() )
return nullptr;
// TODO: actually select the proper one
return zoneMap->second.begin()->second;
}
void Core::TerritoryMgr::updateTerritoryInstances( uint32_t currentTime )
{
for( auto zoneMap : m_territoryInstanceMap )
{
for( auto zone : zoneMap.second )
zone.second->runZoneLogic( currentTime );
}
for( auto zoneMap : m_instanceContentToInstanceMap )
{
for( auto zone: zoneMap.second )
zone.second->runZoneLogic( currentTime );
}
}
Core::TerritoryMgr::InstanceIdList Core::TerritoryMgr::getInstanceContentIdList( uint16_t instanceContentId ) const
{
std::vector< uint32_t > idList;
auto zoneMap = m_instanceContentToInstanceMap.find( instanceContentId );
if( zoneMap == m_instanceContentToInstanceMap.end() )
return idList;
for( auto& entry : zoneMap->second )
{
idList.push_back( entry.first );
}
return idList;
}
bool Core::TerritoryMgr::movePlayer( uint32_t territoryId, Core::Entity::PlayerPtr pPlayer )
{
auto pZone = getZoneByTerriId( territoryId );
if( !pZone )
{
g_log.error( "Zone " + std::to_string( territoryId ) + " not found on this server." );
return false;
}
pPlayer->setTerritoryId( territoryId );
// mark character as zoning in progress
pPlayer->setLoadingComplete( false );
if( pPlayer->getLastPing() != 0 )
pPlayer->getCurrentZone()->removeActor( pPlayer );
pPlayer->setCurrentZone( pZone );
pZone->pushActor( pPlayer );
return true;
}
bool Core::TerritoryMgr::movePlayer( ZonePtr pZone, Core::Entity::PlayerPtr pPlayer )
{
if( !pZone )
{
g_log.error( "Zone not found on this server." );
return false;
}
pPlayer->setTerritoryId( pZone->getTerritoryId() );
// mark character as zoning in progress
pPlayer->setLoadingComplete( false );
if( pPlayer->getLastPing() != 0 )
pPlayer->getCurrentZone()->removeActor( pPlayer );
pPlayer->setCurrentZone( pZone );
pZone->pushActor( pPlayer );
return true;
}
|
Use InstanceContent name instead of placeName for InstanceContent
|
Use InstanceContent name instead of placeName for InstanceContent
|
C++
|
agpl-3.0
|
SapphireMordred/Sapphire,SapphireMordred/Sapphire,SapphireMordred/Sapphire,SapphireMordred/Sapphire,SapphireMordred/Sapphire
|
0063ba960318c1f53025f3871422637cdc20fb12
|
source/PersistentStorageHelper/ConfigParamsPersistence.cpp
|
source/PersistentStorageHelper/ConfigParamsPersistence.cpp
|
/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "ConfigParamsPersistence.h"
#ifndef TARGET_NRF51822 /* Persistent storage supported on nrf51 platforms */
/**
* When not using an nRF51-based target then persistent storage is not available.
*/
#warning "EddystoneService is not configured to store configuration data in non-volatile memory"
bool loadEddystoneServiceConfigParams(EddystoneService::EddystoneParams_t *paramsP)
{
/* Avoid compiler warnings */
(void) paramsP;
/*
* Do nothing and let the main program set Eddystone params to
* defaults
*/
return false;
}
void saveEddystoneServiceConfigParams(const EddystoneService::EddystoneParams_t *paramsP)
{
/* Avoid compiler warnings */
(void) paramsP;
/* Do nothing... */
return;
}
#endif /* #ifdef TARGET_NRF51822 */
|
/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "ConfigParamsPersistence.h"
#if !defined(TARGET_NRF51822) && !defined(TARGET_NRF52832) /* Persistent storage supported on nrf51 platforms */
/**
* When not using an nRF51-based target then persistent storage is not available.
*/
#warning "EddystoneService is not configured to store configuration data in non-volatile memory"
bool loadEddystoneServiceConfigParams(EddystoneService::EddystoneParams_t *paramsP)
{
/* Avoid compiler warnings */
(void) paramsP;
/*
* Do nothing and let the main program set Eddystone params to
* defaults
*/
return false;
}
void saveEddystoneServiceConfigParams(const EddystoneService::EddystoneParams_t *paramsP)
{
/* Avoid compiler warnings */
(void) paramsP;
/* Do nothing... */
return;
}
#endif /* #ifdef TARGET_NRF51822 */
|
Add persistence support for NRF52
|
Add persistence support for NRF52
|
C++
|
apache-2.0
|
roywant/EddystoneBeacon,roywant/EddystoneBeacon
|
0adc6c7c9d2e976105ff2c60cebf2304accdae89
|
main.cpp
|
main.cpp
|
/* SpiCar mbed platform
* Copyright (c) 2017 Spiri Mobility Solutions
*
* 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 "mbed.h"
#include "ublox/spicar_gnss.h"
#include "ublox/spicar_mdm.h"
#include "imu/spicar_imu.h"
#include "benchmarks/benchmark_thread.h"
DigitalOut led1(LED1);
Serial pc(USBTX, USBRX);
Timer waitTimer;
int main() {
const int loopTime = 1000;
bool abort = false;
SpiCar_GNSS gnss(&pc);
Thread gnss_thread(osPriorityBelowNormal, 52*8);
SpiCar_MDM mdm(&pc);
Thread mdm_thread(osPriorityBelowNormal, 265*8);
SpiCar_IMU imu(SDA, SCL, LSM9DS1_PRIMARY_XG_ADDR, LSM9DS1_PRIMARY_M_ADDR, &pc);
Thread imu_thread(osPriorityBelowNormal, 96*8);
gnss_thread.start(&gnss, &SpiCar_GNSS::loop);
if (mdm.initialize()) {
mdm_thread.start(&mdm, &SpiCar_MDM::loop);
}
if (imu.initialize()) {
imu_thread.start(&imu, &SpiCar_IMU::loop);
}
waitTimer.start();
while(!abort) {
led1 = !led1;
time_t seconds = time(NULL);
pc.printf("Time: %s\r\n", ctime(&seconds));
// Benchmarks
//print_thread_data(&Thread, &pc);
print_thread_data(&gnss_thread, &pc);
print_thread_data(&mdm_thread, &pc);
print_thread_data(&imu_thread, &pc);
Thread::wait((loopTime - waitTimer.read_ms()));
waitTimer.reset();
}
}
|
/* SpiCar mbed platform
* Copyright (c) 2017 Spiri Mobility Solutions
*
* 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 "mbed.h"
#include "ublox/spicar_gnss.h"
#include "ublox/spicar_mdm.h"
#include "imu/spicar_imu.h"
#include "benchmarks/benchmark_thread.h"
DigitalOut led1(LED1);
Serial pc(USBTX, USBRX);
Timer waitTimer;
int main() {
const int loopTime = 1000;
bool abort = false;
SpiCar_GNSS gnss(&pc);
Thread gnss_thread(osPriorityBelowNormal, 112*8);
SpiCar_MDM mdm(&pc);
Thread mdm_thread(osPriorityBelowNormal, 270*8);
SpiCar_IMU imu(SDA, SCL, LSM9DS1_PRIMARY_XG_ADDR, LSM9DS1_PRIMARY_M_ADDR, &pc);
Thread imu_thread(osPriorityBelowNormal, 96*8);
gnss_thread.start(&gnss, &SpiCar_GNSS::loop);
if (mdm.initialize()) {
mdm_thread.start(&mdm, &SpiCar_MDM::loop);
}
if (imu.initialize()) {
imu_thread.start(&imu, &SpiCar_IMU::loop);
}
waitTimer.start();
while(!abort) {
led1 = !led1;
time_t seconds = time(NULL);
pc.printf("Time: %s\r\n", ctime(&seconds));
// Benchmarks
//print_thread_data(&Thread, &pc);
print_thread_data(&gnss_thread, &pc);
print_thread_data(&mdm_thread, &pc);
print_thread_data(&imu_thread, &pc);
Thread::wait((loopTime - waitTimer.read_ms()));
waitTimer.reset();
}
}
|
Increase stack sizes
|
Increase stack sizes
|
C++
|
apache-2.0
|
osterbye/spicar-mbed,osterbye/spicar-mbed
|
8f2facaacadcb766d62f8f91d091785b933bc280
|
main.cpp
|
main.cpp
|
#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include "httpserver.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//TODO: boost::program_args
QStringList args(a.arguments());
int pos = args.indexOf("--docroot");
QString docRoot = "/tmp";
if(-1 != pos){
docRoot = args[pos+1];
}
HTTPServer s(docRoot);
QTextStream out(stdout);
if(!s.listen(QHostAddress::LocalHost, 8080)){
out << "Cannot start the server: " << s.errorString() << endl;
}
else{
out << "Listening on " << s.serverAddress().toString() << ":"
<< s.serverPort() << endl;
out << "Documnet root is in: " << docRoot << endl;
}
return a.exec();
}
|
#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <QFileInfo>
#include "httpserver.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//TODO: boost::program_args
QStringList args(a.arguments());
int pos = args.indexOf("--docroot");
QString docRoot = "/tmp";
if(-1 != pos){
QFileInfo f(args[pos+1]);
if(f.isReadable()){
docRoot = f.absoluteFilePath();
}
}
HTTPServer s(docRoot);
QTextStream out(stdout);
if(!s.listen(QHostAddress::LocalHost, 8080)){
out << "Cannot start the server: " << s.errorString() << endl;
}
else{
out << "Listening on " << s.serverAddress().toString() << ":"
<< s.serverPort() << endl;
out << "Documnet root is in: " << docRoot << endl;
}
return a.exec();
}
|
check to ensure the docroot is readable
|
check to ensure the docroot is readable
|
C++
|
apache-2.0
|
paulbarbu/http-daemon,paulbarbu/http-daemon
|
0a1e697c2facc1ad0b0557ef0acda279c6604da9
|
tutorials/hist/rebin.C
|
tutorials/hist/rebin.C
|
//this tutorial illustrates how to:
// -create a variable binwidth histogram with a binning such
// that the population per bin is about the same.
// -rebin a variable binwidth histogram into another one.
//Author: Rene Brun
#include "TH1.h"
#include "TCanvas.h"
void rebin() {
//create a fix bin histogram
TH1F *h = new TH1F("h","test rebin",100,-3,3);
Int_t nentries = 1000;
h->FillRandom("gaus",nentries);
Double_t xbins[1000];
Int_t k=0;
TAxis *axis = h->GetXaxis();
for (Int_t i=1;i<=100;i++) {
Int_t y = (Int_t)h->GetBinContent(i);
if (y <=0) continue;
Double_t dx = axis->GetBinWidth(i)/y;
Double_t xmin = axis->GetBinLowEdge(i);
for (Int_t j=0;j<y;j++) {
xbins[k] = xmin +j*dx;
k++;
}
}
//create a variable binwidth histogram out of fix bin histogram
//new rebinned histogram should have about 10 entries per bin
TH1F *hnew = new TH1F("hnew","rebinned",k-1,xbins);
hnew->FillRandom("gaus",10*nentries);
//rebin hnew keeping only 50% of the bins
Double_t xbins2[501];
Int_t kk=0;
for (Int_t j=0;j<k;j+=2) {
xbins2[kk] = xbins[j];
kk++;
}
xbins2[kk] = xbins[k];
TH1F *hnew2 = (TH1F*)hnew->Rebin(kk-1,"hnew2",xbins2);
//draw the 3 histograms
TCanvas *c1 = new TCanvas("c1","c1",800,1000);
c1->Divide(1,3);
c1->cd(1);
h->Draw();
c1->cd(2);
hnew->Draw();
c1->cd(3);
hnew2->Draw();
}
|
//this tutorial illustrates how to:
// -create a variable binwidth histogram with a binning such
// that the population per bin is about the same.
// -rebin a variable binwidth histogram into another one.
//Author: Rene Brun
#include "TH1.h"
#include "TCanvas.h"
void rebin() {
//create a fix bin histogram
TH1F *h = new TH1F("h","test rebin",100,-3,3);
Int_t nentries = 1000;
h->FillRandom("gaus",nentries);
Double_t xbins[1001];
Int_t k=0;
TAxis *axis = h->GetXaxis();
for (Int_t i=1;i<=100;i++) {
Int_t y = (Int_t)h->GetBinContent(i);
if (y <=0) continue;
Double_t dx = axis->GetBinWidth(i)/y;
Double_t xmin = axis->GetBinLowEdge(i);
for (Int_t j=0;j<y;j++) {
xbins[k] = xmin +j*dx;
k++;
}
}
xbins[k] = axis->GetXmax();
//create a variable binwidth histogram out of fix bin histogram
//new rebinned histogram should have about 10 entries per bin
TH1F *hnew = new TH1F("hnew","rebinned",k,xbins);
hnew->FillRandom("gaus",10*nentries);
//rebin hnew keeping only 50% of the bins
Double_t xbins2[501];
Int_t kk=0;
for (Int_t j=0;j<k;j+=2) {
xbins2[kk] = xbins[j];
kk++;
}
xbins2[kk] = xbins[k];
TH1F *hnew2 = (TH1F*)hnew->Rebin(kk,"hnew2",xbins2);
//draw the 3 histograms
TCanvas *c1 = new TCanvas("c1","c1",800,1000);
c1->Divide(1,3);
c1->cd(1);
h->Draw();
c1->cd(2);
hnew->Draw();
c1->cd(3);
hnew2->Draw();
}
|
Fix for ROOT-5889
|
Fix for ROOT-5889
|
C++
|
lgpl-2.1
|
gganis/root,thomaskeck/root,gbitzes/root,gganis/root,karies/root,esakellari/root,beniz/root,perovic/root,pspe/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,olifre/root,agarciamontoro/root,evgeny-boger/root,agarciamontoro/root,zzxuanyuan/root,omazapa/root-old,zzxuanyuan/root,esakellari/root,vukasinmilosevic/root,0x0all/ROOT,vukasinmilosevic/root,0x0all/ROOT,thomaskeck/root,sbinet/cxx-root,simonpf/root,buuck/root,omazapa/root-old,simonpf/root,davidlt/root,omazapa/root-old,jrtomps/root,lgiommi/root,Y--/root,omazapa/root-old,sirinath/root,beniz/root,smarinac/root,veprbl/root,olifre/root,thomaskeck/root,omazapa/root-old,krafczyk/root,omazapa/root,nilqed/root,buuck/root,vukasinmilosevic/root,gganis/root,gbitzes/root,omazapa/root,satyarth934/root,0x0all/ROOT,georgtroska/root,zzxuanyuan/root-compressor-dummy,simonpf/root,lgiommi/root,perovic/root,beniz/root,perovic/root,buuck/root,georgtroska/root,esakellari/my_root_for_test,sawenzel/root,evgeny-boger/root,sbinet/cxx-root,lgiommi/root,pspe/root,lgiommi/root,BerserkerTroll/root,sawenzel/root,bbockelm/root,esakellari/root,gbitzes/root,agarciamontoro/root,omazapa/root,Y--/root,perovic/root,Duraznos/root,lgiommi/root,zzxuanyuan/root,gbitzes/root,zzxuanyuan/root,mkret2/root,bbockelm/root,esakellari/my_root_for_test,krafczyk/root,bbockelm/root,gganis/root,vukasinmilosevic/root,jrtomps/root,nilqed/root,gganis/root,perovic/root,lgiommi/root,buuck/root,zzxuanyuan/root-compressor-dummy,esakellari/root,sirinath/root,mkret2/root,karies/root,veprbl/root,mkret2/root,mhuwiler/rootauto,zzxuanyuan/root,Duraznos/root,agarciamontoro/root,simonpf/root,smarinac/root,smarinac/root,beniz/root,sawenzel/root,CristinaCristescu/root,krafczyk/root,karies/root,mhuwiler/rootauto,sirinath/root,perovic/root,davidlt/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,nilqed/root,Y--/root,olifre/root,root-mirror/root,mhuwiler/rootauto,zzxuanyuan/root,arch1tect0r/root,omazapa/root-old,omazapa/root-old,sbinet/cxx-root,gbitzes/root,omazapa/root,root-mirror/root,sawenzel/root,veprbl/root,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,bbockelm/root,mkret2/root,Duraznos/root,thomaskeck/root,esakellari/root,bbockelm/root,0x0all/ROOT,georgtroska/root,pspe/root,bbockelm/root,abhinavmoudgil95/root,pspe/root,Y--/root,simonpf/root,buuck/root,Y--/root,smarinac/root,satyarth934/root,jrtomps/root,arch1tect0r/root,smarinac/root,beniz/root,omazapa/root,sawenzel/root,sirinath/root,mattkretz/root,veprbl/root,dfunke/root,esakellari/root,evgeny-boger/root,jrtomps/root,abhinavmoudgil95/root,vukasinmilosevic/root,georgtroska/root,veprbl/root,vukasinmilosevic/root,pspe/root,bbockelm/root,mhuwiler/rootauto,CristinaCristescu/root,davidlt/root,esakellari/my_root_for_test,buuck/root,davidlt/root,root-mirror/root,BerserkerTroll/root,dfunke/root,CristinaCristescu/root,buuck/root,sbinet/cxx-root,veprbl/root,BerserkerTroll/root,arch1tect0r/root,mhuwiler/rootauto,gganis/root,mkret2/root,thomaskeck/root,root-mirror/root,evgeny-boger/root,evgeny-boger/root,Y--/root,simonpf/root,zzxuanyuan/root-compressor-dummy,mattkretz/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,dfunke/root,davidlt/root,smarinac/root,mkret2/root,dfunke/root,karies/root,pspe/root,satyarth934/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,gbitzes/root,omazapa/root-old,davidlt/root,krafczyk/root,georgtroska/root,beniz/root,karies/root,sbinet/cxx-root,BerserkerTroll/root,jrtomps/root,abhinavmoudgil95/root,agarciamontoro/root,gganis/root,thomaskeck/root,mkret2/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,dfunke/root,Duraznos/root,jrtomps/root,arch1tect0r/root,veprbl/root,veprbl/root,CristinaCristescu/root,satyarth934/root,BerserkerTroll/root,0x0all/ROOT,zzxuanyuan/root,BerserkerTroll/root,mhuwiler/rootauto,smarinac/root,bbockelm/root,BerserkerTroll/root,root-mirror/root,abhinavmoudgil95/root,pspe/root,gbitzes/root,agarciamontoro/root,veprbl/root,BerserkerTroll/root,davidlt/root,olifre/root,zzxuanyuan/root,karies/root,0x0all/ROOT,vukasinmilosevic/root,arch1tect0r/root,gganis/root,CristinaCristescu/root,Duraznos/root,BerserkerTroll/root,0x0all/ROOT,dfunke/root,karies/root,agarciamontoro/root,karies/root,krafczyk/root,gbitzes/root,esakellari/root,sbinet/cxx-root,arch1tect0r/root,thomaskeck/root,abhinavmoudgil95/root,root-mirror/root,nilqed/root,satyarth934/root,Duraznos/root,pspe/root,abhinavmoudgil95/root,abhinavmoudgil95/root,omazapa/root,lgiommi/root,Y--/root,krafczyk/root,omazapa/root,esakellari/root,BerserkerTroll/root,davidlt/root,karies/root,sawenzel/root,0x0all/ROOT,omazapa/root,satyarth934/root,root-mirror/root,sawenzel/root,olifre/root,arch1tect0r/root,georgtroska/root,buuck/root,olifre/root,sawenzel/root,gganis/root,agarciamontoro/root,satyarth934/root,simonpf/root,nilqed/root,mkret2/root,sirinath/root,evgeny-boger/root,perovic/root,lgiommi/root,krafczyk/root,nilqed/root,thomaskeck/root,olifre/root,Duraznos/root,root-mirror/root,mattkretz/root,georgtroska/root,simonpf/root,agarciamontoro/root,esakellari/my_root_for_test,smarinac/root,arch1tect0r/root,sirinath/root,lgiommi/root,CristinaCristescu/root,pspe/root,CristinaCristescu/root,karies/root,mattkretz/root,omazapa/root,dfunke/root,mhuwiler/rootauto,abhinavmoudgil95/root,omazapa/root-old,olifre/root,sirinath/root,esakellari/root,sawenzel/root,Duraznos/root,esakellari/root,lgiommi/root,gbitzes/root,zzxuanyuan/root,mattkretz/root,CristinaCristescu/root,arch1tect0r/root,simonpf/root,thomaskeck/root,mattkretz/root,vukasinmilosevic/root,abhinavmoudgil95/root,nilqed/root,esakellari/my_root_for_test,beniz/root,jrtomps/root,bbockelm/root,krafczyk/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,gganis/root,smarinac/root,thomaskeck/root,Y--/root,georgtroska/root,root-mirror/root,Duraznos/root,CristinaCristescu/root,arch1tect0r/root,satyarth934/root,dfunke/root,zzxuanyuan/root,perovic/root,vukasinmilosevic/root,beniz/root,smarinac/root,sawenzel/root,dfunke/root,dfunke/root,buuck/root,perovic/root,lgiommi/root,mkret2/root,zzxuanyuan/root,CristinaCristescu/root,esakellari/my_root_for_test,simonpf/root,davidlt/root,buuck/root,nilqed/root,pspe/root,esakellari/my_root_for_test,Y--/root,zzxuanyuan/root-compressor-dummy,pspe/root,gbitzes/root,sawenzel/root,CristinaCristescu/root,esakellari/root,jrtomps/root,georgtroska/root,beniz/root,gganis/root,zzxuanyuan/root,sirinath/root,mattkretz/root,simonpf/root,perovic/root,veprbl/root,krafczyk/root,olifre/root,sirinath/root,abhinavmoudgil95/root,mattkretz/root,Duraznos/root,omazapa/root-old,Y--/root,davidlt/root,Y--/root,abhinavmoudgil95/root,esakellari/my_root_for_test,sbinet/cxx-root,beniz/root,mkret2/root,sbinet/cxx-root,nilqed/root,nilqed/root,evgeny-boger/root,sbinet/cxx-root,georgtroska/root,mattkretz/root,buuck/root,jrtomps/root,vukasinmilosevic/root,arch1tect0r/root,evgeny-boger/root,agarciamontoro/root,olifre/root,root-mirror/root,esakellari/my_root_for_test,sbinet/cxx-root,dfunke/root,beniz/root,sirinath/root,krafczyk/root,olifre/root,jrtomps/root,nilqed/root,bbockelm/root,georgtroska/root,krafczyk/root,mkret2/root,evgeny-boger/root,agarciamontoro/root,root-mirror/root,sirinath/root,omazapa/root,satyarth934/root,vukasinmilosevic/root,karies/root,esakellari/my_root_for_test,Duraznos/root,omazapa/root,davidlt/root,evgeny-boger/root,veprbl/root,mhuwiler/rootauto,mhuwiler/rootauto,satyarth934/root,satyarth934/root,sbinet/cxx-root,mattkretz/root,BerserkerTroll/root,omazapa/root-old,perovic/root,mattkretz/root
|
ec06e40703ab6f11976019f8be804fa6923e2141
|
pcm_to_rgb.cc
|
pcm_to_rgb.cc
|
#include <periodic_thread.h>
#include <uart.h>
#include "fft.h"
#include "rgb_led_controller.h"
const int points = 2048;
static RGBLEDController led_ctrl = RGBLEDController();
static UART* uart = new UART();
short readInt16LE(UART* uart)
{
short a = uart->get(), b = uart->get();
return b << 8 | a;
}
int apply_fft()
{
while (true) {
double data[points * 2 + 1];
for (int i = 0; i < points * 2;) {
data[++i] = static_cast<double>(readInt16LE(uart));
data[++i] = 0;
}
fft::four1(data, points, 1);
int color;
// map complex to color
led_ctrl.writeColor(color);
Periodic_Thread::wait_next();
}
return 0;
}
int main()
{
UART uart;
RGBLEDController led_ctrl;
Periodic_Thread pt(fft, 44100 / points);
pt.join();
return 0;
}
|
#include <periodic_thread.h>
#include <uart.h>
#include "fft.h"
#include "rgb_led_controller.h"
const int points = 2048;
static RGBLEDController led_ctrl = RGBLEDController();
static UART* uart = new UART();
short readInt16LE(UART* uart)
{
short a = uart->get(), b = uart->get();
return b << 8 | a;
}
int apply_fft()
{
while (true) {
double data[points * 2 + 1];
for (int i = 0; i < points * 2;) {
data[++i] = static_cast<double>(readInt16LE(uart));
data[++i] = 0;
}
fft::four1(data, points, 1);
int color;
// map complex to color
led_ctrl.writeColor(color);
Periodic_Thread::wait_next();
}
return 0;
}
int main()
{
UART uart;
RGBLEDController led_ctrl;
Periodic_Thread pt(apply_fft, 44100 / points);
pt.join();
return 0;
}
|
Fix missing change
|
Fix missing change
|
C++
|
mit
|
ranisalt/epos-pcm-to-rgb,ranisalt/epos-pcm-to-rgb
|
d5198ab37c675bae9cf35234ab1165617149d1a0
|
main.cpp
|
main.cpp
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Christoph Brill
*
* 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 <iostream>
#include <unistd.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "tile.h"
#include "loader.h"
#include "input.h"
#include "global.h"
/**
* @brief poll for events
* @return false, if the program should end, otherwise true
*/
bool poll() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return false;
case SDL_KEYUP:
if (event.key.keysym.sym == SDLK_ESCAPE) {
return false;
}
break;
case SDL_MOUSEMOTION:
handle_mouse_motion(event.motion);
break;
case SDL_MOUSEBUTTONDOWN:
handle_mouse_button_down(event.button);
break;
case SDL_MOUSEBUTTONUP:
handle_mouse_button_up(event.button);
break;
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_RESIZED:
window_state.width = event.window.data1;
window_state.height = event.window.data2;
break;
}
break;
default:
break;
}
}
return true;
}
void render(int zoom, double latitude, double longitude) {
Tile* center_tile = TileFactory::instance()->get_tile(zoom, latitude, longitude);
// Clear with black
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-(window_state.width / 2), (window_state.width / 2), (window_state.height / 2), -(window_state.height / 2), -1000, 1000);
// Rotate and and tilt the world geometry
glRotated(viewport_state._angle2, 1.0, 0.0, 0.0);
glRotated(viewport_state._angle1, 0.0, 0.0, -1.0);
// Render the slippy map parts
glEnable(GL_TEXTURE_2D);
// Top left coordinate of the current tile
double tile_latitude = tiley2lat(center_tile->y, zoom);
double tile_longitude = tilex2long(center_tile->x, zoom);
// Offset of the current tile from the center of the screen
double lat_diff = (TILE_SIZE/2) + ((latitude - tile_latitude) * TILE_SIZE / TILE_SIZE_LAT_16);
double lon_diff = (TILE_SIZE/2) + ((tile_longitude - longitude) * TILE_SIZE / TILE_SIZE_LON_16);
glPushMatrix();
glTranslated(lon_diff, lat_diff, 0);
static const int top = -6;
static const int left = -6;
static const int bottom = 6;
static const int right = 6;
// Start 'left' and 'top' tiles from the center tile and render down to 'bottom' and
// 'right' tiles from the center tile
Tile* current = center_tile->get(left, top);
for (int y = top; y < bottom; y++) {
for (int x = left; x < right; x++) {
// If the texid is set to zero the download was finished successfully and
// the tile can be rendered now properly
if (current->texid == 0) {
Loader::instance()->open_image(*current);
}
// Render the tile itself at the correct position
glPushMatrix();
glTranslated(x*TILE_SIZE*2, y*TILE_SIZE*2, 0);
glBindTexture(GL_TEXTURE_2D, current->texid);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0); glVertex3f(-TILE_SIZE, TILE_SIZE, 0);
glTexCoord2f(1.0, 1.0); glVertex3f( TILE_SIZE, TILE_SIZE, 0);
glTexCoord2f(1.0, 0.0); glVertex3f( TILE_SIZE, -TILE_SIZE, 0);
glTexCoord2f(0.0, 0.0); glVertex3f(-TILE_SIZE, -TILE_SIZE, 0);
glEnd();
glPopMatrix();
current = current->get_west();
}
current = current->get(-(std::abs(left) + std::abs(right)), 1);
}
glPopMatrix();
glDisable(GL_TEXTURE_2D);
// Draw the players avatar at the center of the screen
glColor3d(1.0, 0.5, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f(-10, 15, 1);
glVertex3f( 10, 15, 1);
glVertex3f( 0, -10, 1);
glEnd();
glColor3d(1.0, 1.0, 1.0);
}
int main(int argc, char **argv) {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Could not initialize SDL video: " << SDL_GetError() << std::endl;
return 1;
}
// Create an OpenGL window
SDL_Window* window = SDL_CreateWindow("slippymap3d", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
std::cerr << "Could not create SDL window: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
SDL_GetWindowSize(window, &window_state.width, &window_state.height);
SDL_GLContext context = SDL_GL_CreateContext(window);
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
long base_time = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
int frames = 0;
while(true) {
if (!poll()) {
break;
}
frames++;
clock_gettime(CLOCK_REALTIME, &spec);
long time_in_mill = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
if ((time_in_mill - base_time) > 1000.0) {
std::cout << frames * 1000.0 / (time_in_mill - base_time) << " fps" << std::endl;
base_time = time_in_mill;
frames=0;
}
render(16, player_state.latitude, player_state.longitude);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Christoph Brill
*
* 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 <iostream>
#include <unistd.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "tile.h"
#include "loader.h"
#include "input.h"
#include "global.h"
/**
* @brief poll for events
* @return false, if the program should end, otherwise true
*/
bool poll() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return false;
case SDL_KEYUP:
if (event.key.keysym.sym == SDLK_ESCAPE) {
return false;
}
break;
case SDL_MOUSEMOTION:
handle_mouse_motion(event.motion);
break;
case SDL_MOUSEBUTTONDOWN:
handle_mouse_button_down(event.button);
break;
case SDL_MOUSEBUTTONUP:
handle_mouse_button_up(event.button);
break;
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_RESIZED:
window_state.width = event.window.data1;
window_state.height = event.window.data2;
glViewport(0, 0, window_state.width, window_state.height);
break;
}
break;
default:
break;
}
}
return true;
}
void render(int zoom, double latitude, double longitude) {
Tile* center_tile = TileFactory::instance()->get_tile(zoom, latitude, longitude);
// Clear with black
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-(window_state.width / 2), (window_state.width / 2), (window_state.height / 2), -(window_state.height / 2), -1000, 1000);
// Rotate and and tilt the world geometry
glRotated(viewport_state._angle2, 1.0, 0.0, 0.0);
glRotated(viewport_state._angle1, 0.0, 0.0, -1.0);
// Render the slippy map parts
glEnable(GL_TEXTURE_2D);
// Top left coordinate of the current tile
double tile_latitude = tiley2lat(center_tile->y, zoom);
double tile_longitude = tilex2long(center_tile->x, zoom);
// Offset of the current tile from the center of the screen
double lat_diff = (TILE_SIZE/2) + ((latitude - tile_latitude) * TILE_SIZE / TILE_SIZE_LAT_16);
double lon_diff = (TILE_SIZE/2) + ((tile_longitude - longitude) * TILE_SIZE / TILE_SIZE_LON_16);
glPushMatrix();
glTranslated(lon_diff, lat_diff, 0);
static const int top = -6;
static const int left = -6;
static const int bottom = 6;
static const int right = 6;
// Start 'left' and 'top' tiles from the center tile and render down to 'bottom' and
// 'right' tiles from the center tile
Tile* current = center_tile->get(left, top);
for (int y = top; y < bottom; y++) {
for (int x = left; x < right; x++) {
// If the texid is set to zero the download was finished successfully and
// the tile can be rendered now properly
if (current->texid == 0) {
Loader::instance()->open_image(*current);
}
// Render the tile itself at the correct position
glPushMatrix();
glTranslated(x*TILE_SIZE*2, y*TILE_SIZE*2, 0);
glBindTexture(GL_TEXTURE_2D, current->texid);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0); glVertex3f(-TILE_SIZE, TILE_SIZE, 0);
glTexCoord2f(1.0, 1.0); glVertex3f( TILE_SIZE, TILE_SIZE, 0);
glTexCoord2f(1.0, 0.0); glVertex3f( TILE_SIZE, -TILE_SIZE, 0);
glTexCoord2f(0.0, 0.0); glVertex3f(-TILE_SIZE, -TILE_SIZE, 0);
glEnd();
glPopMatrix();
current = current->get_west();
}
current = current->get(-(std::abs(left) + std::abs(right)), 1);
}
glPopMatrix();
glDisable(GL_TEXTURE_2D);
// Draw the players avatar at the center of the screen
glColor3d(1.0, 0.5, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f(-10, 15, 1);
glVertex3f( 10, 15, 1);
glVertex3f( 0, -10, 1);
glEnd();
glColor3d(1.0, 1.0, 1.0);
}
int main(int argc, char **argv) {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Could not initialize SDL video: " << SDL_GetError() << std::endl;
return 1;
}
// Create an OpenGL window
SDL_Window* window = SDL_CreateWindow("slippymap3d", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
std::cerr << "Could not create SDL window: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
SDL_GetWindowSize(window, &window_state.width, &window_state.height);
SDL_GLContext context = SDL_GL_CreateContext(window);
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
long base_time = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
int frames = 0;
while(true) {
if (!poll()) {
break;
}
frames++;
clock_gettime(CLOCK_REALTIME, &spec);
long time_in_mill = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
if ((time_in_mill - base_time) > 1000.0) {
std::cout << frames * 1000.0 / (time_in_mill - base_time) << " fps" << std::endl;
base_time = time_in_mill;
frames=0;
}
render(16, player_state.latitude, player_state.longitude);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
Update the GL viewport when resizing the window
|
Update the GL viewport when resizing the window
|
C++
|
mit
|
egore/slippymap3d,egore/slippymap3d
|
cd6f7f1fb510883f4fb4134629a49e53c5818634
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#define O_BINARY 0
const int RECORD_SIZE = 8 * 1024;
size_t get_file_size(const char *);
int main(int argc, char **argv)
{
// required for argument parsing
int fflag = 0;
int c;
const char * def_filename = "device-file";
char * filename;
extern char *optarg;
extern int optind;
static char usage[] = "usage: %s -f filename\n";
// permanent values
int num_records, file_size;
while ((c = getopt(argc, argv, "f:")) != -1)
{
switch (c)
{
case 'f':
filename = optarg;
fflag = 1;
break;
default:
// implement other options, such as help, etc.
break;
}
}
if (fflag == 0)
{
// need to implement default filename
}
file_size = (int) get_file_size(filename);
num_records = file_size / RECORD_SIZE;
std::cout << "File range is 0 to " << file_size << "." << std::endl;
std::cout << "Number of possible records: " << num_records << std::endl;
return 0;
}
// https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file
size_t get_file_size(const char * filename)
{
size_t file_size;
char *buffer;
struct stat stbuf;
int fd;
fd = open(filename, O_BINARY);
if (fd == -1)
{
/* Handle error */
}
if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode)))
{
/* Handle error */
}
file_size = stbuf.st_size;
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle error */
}
return file_size;
}
|
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#define O_BINARY 0
const int RECORD_SIZE = 8 * 1024;
size_t get_file_size(const char *);
int main(int argc, char **argv)
{
// required for argument parsing
int fflag = 0;
int c;
const char * def_filename = "device-file";
char * filename;
extern char *optarg;
extern int optind;
static char usage[] = "usage: %s -f filename\n";
// permanent values
int num_records, file_size;
while ((c = getopt(argc, argv, "f:")) != -1)
{
switch (c)
{
case 'f':
filename = optarg;
fflag = 1;
break;
default:
// implement other options, such as help, etc.
break;
}
}
if (fflag == 0)
{
// need to implement default filename
filename = strdup(def_filename);
}
file_size = (int) get_file_size(filename);
num_records = file_size / RECORD_SIZE;
std::cout << "File range is 0 to " << file_size << "." << std::endl;
std::cout << "Number of possible records: " << num_records << std::endl;
return 0;
}
// https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file
size_t get_file_size(const char * filename)
{
size_t file_size;
char *buffer;
struct stat stbuf;
int fd;
fd = open(filename, O_BINARY);
if (fd == -1)
{
/* Handle error */
}
if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode)))
{
/* Handle error */
}
file_size = stbuf.st_size;
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle error */
}
return file_size;
}
|
Implement default filename
|
Implement default filename
|
C++
|
bsd-3-clause
|
russellfolk/Pthread_Power_Fault_Tester,russellfolk/Pthread_Power_Fault_Tester,russellfolk/Pthread_Power_Fault_Tester
|
8b724a78e3e4c333fb4f9b8e01f918779e92bd08
|
main.cpp
|
main.cpp
|
/* main.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implement robot_class to provide functionality for robot.
*/
#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
//constructor - initialize drive
robot_class::robot_class() {
//do nothing
GetWatchdog().SetEnabled(false); //we don't want Watchdog
}
void robot_class::RobotInit() {
//Run-Time INIT
//set necessary inversions
drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse);
drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse);
drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse);
state_tracker global_state;
}
void robot_class::DisabledInit() {
//do nothing
}
void robot_class::AutonomousInit() {
//do nothing
}
void robot_class::TeleopInit() {
//do nothing
}
void robot_class::DisabledPeriodic() {
//do nothing
}
void robot_class::AutonomousPeriodic() {
update_sensors();
}
void robot_class::TeleopPeriodic() {
update_sensors();
}
void robot_class::DisabledContinuous() {
//do nothing
}
void robot_class::AutonomousContinuous() {
//do nothing
}
void robot_class::TeleopContinuous() {
if(global_state.get_state() == STATE_DRIVING) {
if (left_joystick.GetRawButton(1)) {
//arcade drive
drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
}
else {
//tank drive
float left = left_joystick.GetY();
float right = right_joystick.GetY();
//explicitly state drive power is based on Y axis of that side joy
drive.TankDrive(left, right);
}
if (left_joystick.GetRawButton(11)) {
right_servo_shift.Set(0.7);
left_servo_shift.Set(0.7);
// set servo to high gear
}
else if (left_joystick.GetRawButton(10)) {
right_servo_shift.Set(0.3);
left_servo_shift.Set(0.3);
//Sets servo to low gear
}
vector<double> target_degrees = vision_processing::get_degrees();
printf("Angle (degrees) of camera: %f", target_degrees[vision_processing::determine_aim_target_from_image(vision_processing::get_image())]);
}
Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
}
void robot_class::update_sensors() {
//run functions in update registry
registry.update();
}
//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
|
/* main.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implement robot_class to provide functionality for robot.
*/
#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
//constructor - initialize drive
robot_class::robot_class() {
//do nothing
GetWatchdog().SetEnabled(false); //we don't want Watchdog
}
void robot_class::RobotInit() {
//Run-Time INIT
//set necessary inversions
drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse);
drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse);
drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse);
state_tracker global_state;
}
void robot_class::DisabledInit() {
//do nothing
}
void robot_class::AutonomousInit() {
//do nothing
}
void robot_class::TeleopInit() {
//do nothing
}
void robot_class::DisabledPeriodic() {
//do nothing
}
void robot_class::AutonomousPeriodic() {
update_sensors();
}
void robot_class::TeleopPeriodic() {
update_sensors();
}
void robot_class::DisabledContinuous() {
//do nothing
}
void robot_class::AutonomousContinuous() {
//do nothing
}
void robot_class::TeleopContinuous() {
if(global_state.get_state() == STATE_DRIVING) {
if (left_joystick.GetRawButton(1)) {
//arcade drive
drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
}
else {
//tank drive
float left = left_joystick.GetY();
float right = right_joystick.GetY();
//explicitly state drive power is based on Y axis of that side joy
drive.TankDrive(left, right);
}
if (left_joystick.GetRawButton(11)) {
right_servo_shift.Set(0.7);
left_servo_shift.Set(0.7);
// set servo to high gear
}
else if (left_joystick.GetRawButton(10)) {
right_servo_shift.Set(0.3);
left_servo_shift.Set(0.3);
//Sets servo to low gear
}
vector<double> target_degrees = vision_processing::get_degrees();
printf("Angle (degrees) of camera: %f", target_degrees[vision_processing::determine_aim_target_from_image(vision_processing::get_image())]);
}
Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
}
void robot_class::update_sensors() {
//run functions in update registry
registry().update();
}
//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
|
Fix on a compile error
|
Fix on a compile error
|
C++
|
isc
|
rbmj/612-code,Chantilly612Code/612-2012,Chantilly612Code/612-2012,rbmj/612-code
|
42a560a66711981844e9670e2787ab0b3cd9a8f4
|
waypoints_navigation/src/waypoints_nav.cpp
|
waypoints_navigation/src/waypoints_nav.cpp
|
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <yaml-cpp/yaml.h>
#include <vector>
#include <fstream>
#include <string>
#include <visualization_msgs/MarkerArray.h>
class WaypointsNavigation{
public:
WaypointsNavigation() :
has_activate_(false),
move_base_action_("move_base", true),
rate_(10)
{
while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))
{
ROS_INFO("Waiting...");
}
ros::NodeHandle private_nh("~");
private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
private_nh.param("world_frame", world_frame_, std::string("/map"));
double max_update_rate;
private_nh.param("max_update_rate", max_update_rate, 10.0);
rate_ = ros::Rate(max_update_rate);
std::string filename = "";
private_nh.param("filename", filename, filename);
if(filename != ""){
ROS_INFO_STREAM("Read waypoints data from " << filename);
readFile(filename);
}
ros::NodeHandle nh;
syscommand_sub_ = nh.subscribe("syscommand", 1, &WaypointsNavigation::syscommandCallback, this);
marker_pub_ = nh.advertise<visualization_msgs::MarkerArray>("visualization_marker", 10);
}
void syscommandCallback(const std_msgs::String &msg){
if(msg.data == "start"){
has_activate_ = true;
}
}
bool readFile(const std::string &filename){
waypoints_.clear();
try{
std::ifstream ifs(filename.c_str(), std::ifstream::in);
if(ifs.good() == false){
return false;
}
YAML::Node node;
node = YAML::Load(ifs);
const YAML::Node &wp_node_tmp = node["waypoints"];
const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;
if(wp_node != NULL){
for(int i=0; i < wp_node->size(); i++){
geometry_msgs::PointStamped point;
point.point.x = (*wp_node)[i]["point"]["x"].as<double>();
point.point.y = (*wp_node)[i]["point"]["y"].as<double>();
point.point.z = (*wp_node)[i]["point"]["z"].as<double>();
waypoints_.push_back(point);
}
}else{
return false;
}
const YAML::Node &fp_node_tmp = node["finish_pose"];
const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;
if(fp_node != NULL){
finish_pose_.position.x = (*fp_node)["pose"]["position"]["x"].as<double>();
finish_pose_.position.y = (*fp_node)["pose"]["position"]["y"].as<double>();
finish_pose_.position.z = (*fp_node)["pose"]["position"]["z"].as<double>();
finish_pose_.orientation.x = (*fp_node)["pose"]["orientation"]["x"].as<double>();
finish_pose_.orientation.y = (*fp_node)["pose"]["orientation"]["y"].as<double>();
finish_pose_.orientation.z = (*fp_node)["pose"]["orientation"]["z"].as<double>();
finish_pose_.orientation.w = (*fp_node)["pose"]["orientation"]["w"].as<double>();
}else{
return false;
}
}catch(YAML::ParserException &e){
return false;
}catch(YAML::RepresentationException &e){
return false;
}
return true;
}
bool shouldSendGoal(){
bool ret = true;
actionlib::SimpleClientGoalState state = move_base_action_.getState();
if((state != actionlib::SimpleClientGoalState::ACTIVE) &&
(state != actionlib::SimpleClientGoalState::PENDING) &&
(state != actionlib::SimpleClientGoalState::RECALLED) &&
(state != actionlib::SimpleClientGoalState::PREEMPTED))
{
ret = false;
}
if(waypoints_.empty()){
ret = false;
}
return ret;
}
bool navigationFinished(){
return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;
}
bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){
tf::StampedTransform robot_gl;
try{
tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
}catch(tf::TransformException &e){
ROS_WARN_STREAM("tf::TransformException: " << e.what());
}
const double wx = dest.x;
const double wy = dest.y;
const double rx = robot_gl.getOrigin().x();
const double ry = robot_gl.getOrigin().y();
const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));
return dist < dist_err;
}
void sleep(){
rate_.sleep();
ros::spinOnce();
publishMarkers();
}
void startNavigationGL(const geometry_msgs::Point &dest){
geometry_msgs::Pose pose;
pose.position = dest;
pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
startNavigationGL(pose);
}
void startNavigationGL(const geometry_msgs::Pose &dest){
move_base_msgs::MoveBaseGoal move_base_goal;
move_base_goal.target_pose.header.stamp = ros::Time::now();
move_base_goal.target_pose.header.frame_id = world_frame_;
move_base_goal.target_pose.pose.position = dest.position;
move_base_goal.target_pose.pose.orientation = dest.orientation;
move_base_action_.sendGoal(move_base_goal);
}
void publishMarkers(){
visualization_msgs::MarkerArray markers_array;
for(int i=0; i < waypoints_.size(); i++){
visualization_msgs::Marker marker, label;
marker.header.frame_id = world_frame_;
marker.header.stamp = ros::Time::now();
marker.scale.x = 0.2;
marker.scale.y = 0.2;
marker.scale.z = 0.2;
marker.pose.position.z = marker.scale.z / 2.0;
marker.color.r = 0.8f;
marker.color.g = 0.2f;
marker.color.b = 0.2f;
std::stringstream name;
name << "waypoint " << i;
marker.ns = name.str();
marker.id = i;
marker.pose.position.x = waypoints_[i].point.x;
marker.pose.position.y = waypoints_[i].point.y;
marker.type = visualization_msgs::Marker::SPHERE;
marker.action = visualization_msgs::Marker::ADD;
marker.color.a = 1.0f;
markers_array.markers.push_back(marker);
ROS_INFO_STREAM("waypoints \n" << waypoints_[i]);
}
marker_pub_.publish(markers_array);
}
void run(){
while(ros::ok()){
if(has_activate_){
for(int i=0; i < waypoints_.size(); i++){
ROS_INFO_STREAM("waypoint = " << waypoints_[i]);
if(!ros::ok()) break;
startNavigationGL(waypoints_[i].point);
double start_nav_time = ros::Time::now().toSec();
while(!onNavigationPoint(waypoints_[i].point)){
if(ros::Time::now().toSec() - start_nav_time > 10.0){
ROS_INFO("Resend the navigation goal.");
startNavigationGL(waypoints_[i].point);
start_nav_time = ros::Time::now().toSec();
}
actionlib::SimpleClientGoalState state = move_base_action_.getState();
sleep();
}
ROS_INFO("waypoint goal");
}
ROS_INFO("waypoints clear");
waypoints_.clear();
startNavigationGL(finish_pose_);
while(!navigationFinished() && ros::ok()) sleep();
has_activate_ = false;
}
sleep();
}
}
private:
actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;
std::vector<geometry_msgs::PointStamped> waypoints_;
geometry_msgs::Pose finish_pose_;
bool has_activate_;
std::string robot_frame_, world_frame_;
tf::TransformListener tf_listener_;
ros::Rate rate_;
ros::Subscriber syscommand_sub_;
ros::Publisher marker_pub_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, ROS_PACKAGE_NAME);
WaypointsNavigation w_nav;
w_nav.run();
return 0;
}
|
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <yaml-cpp/yaml.h>
#include <vector>
#include <fstream>
#include <string>
#include <visualization_msgs/MarkerArray.h>
class WaypointsNavigation{
public:
WaypointsNavigation() :
has_activate_(false),
move_base_action_("move_base", true),
rate_(10)
{
while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))
{
ROS_INFO("Waiting...");
}
ros::NodeHandle private_nh("~");
private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
private_nh.param("world_frame", world_frame_, std::string("/map"));
double max_update_rate;
private_nh.param("max_update_rate", max_update_rate, 10.0);
rate_ = ros::Rate(max_update_rate);
std::string filename = "";
private_nh.param("filename", filename, filename);
if(filename != ""){
ROS_INFO_STREAM("Read waypoints data from " << filename);
readFile(filename);
}
ros::NodeHandle nh;
syscommand_sub_ = nh.subscribe("syscommand", 1, &WaypointsNavigation::syscommandCallback, this);
marker_pub_ = nh.advertise<visualization_msgs::MarkerArray>("visualization_marker", 10);
}
void syscommandCallback(const std_msgs::String &msg){
if(msg.data == "start"){
has_activate_ = true;
}
}
bool readFile(const std::string &filename){
waypoints_.clear();
try{
std::ifstream ifs(filename.c_str(), std::ifstream::in);
if(ifs.good() == false){
return false;
}
YAML::Node node;
node = YAML::Load(ifs);
const YAML::Node &wp_node_tmp = node["waypoints"];
const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;
if(wp_node != NULL){
for(int i=0; i < wp_node->size(); i++){
geometry_msgs::PointStamped point;
point.point.x = (*wp_node)[i]["point"]["x"].as<double>();
point.point.y = (*wp_node)[i]["point"]["y"].as<double>();
point.point.z = (*wp_node)[i]["point"]["z"].as<double>();
waypoints_.push_back(point);
}
}else{
return false;
}
const YAML::Node &fp_node_tmp = node["finish_pose"];
const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;
if(fp_node != NULL){
finish_pose_.position.x = (*fp_node)["pose"]["position"]["x"].as<double>();
finish_pose_.position.y = (*fp_node)["pose"]["position"]["y"].as<double>();
finish_pose_.position.z = (*fp_node)["pose"]["position"]["z"].as<double>();
finish_pose_.orientation.x = (*fp_node)["pose"]["orientation"]["x"].as<double>();
finish_pose_.orientation.y = (*fp_node)["pose"]["orientation"]["y"].as<double>();
finish_pose_.orientation.z = (*fp_node)["pose"]["orientation"]["z"].as<double>();
finish_pose_.orientation.w = (*fp_node)["pose"]["orientation"]["w"].as<double>();
}else{
return false;
}
}catch(YAML::ParserException &e){
return false;
}catch(YAML::RepresentationException &e){
return false;
}
return true;
}
bool shouldSendGoal(){
bool ret = true;
actionlib::SimpleClientGoalState state = move_base_action_.getState();
if((state != actionlib::SimpleClientGoalState::ACTIVE) &&
(state != actionlib::SimpleClientGoalState::PENDING) &&
(state != actionlib::SimpleClientGoalState::RECALLED) &&
(state != actionlib::SimpleClientGoalState::PREEMPTED))
{
ret = false;
}
if(waypoints_.empty()){
ret = false;
}
return ret;
}
bool navigationFinished(){
return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;
}
bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){
tf::StampedTransform robot_gl;
try{
tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
}catch(tf::TransformException &e){
ROS_WARN_STREAM("tf::TransformException: " << e.what());
}
const double wx = dest.x;
const double wy = dest.y;
const double rx = robot_gl.getOrigin().x();
const double ry = robot_gl.getOrigin().y();
const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));
return dist < dist_err;
}
void sleep(){
rate_.sleep();
ros::spinOnce();
publishMarkers();
}
void startNavigationGL(const geometry_msgs::Point &dest){
geometry_msgs::Pose pose;
pose.position = dest;
pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
startNavigationGL(pose);
}
void startNavigationGL(const geometry_msgs::Pose &dest){
move_base_msgs::MoveBaseGoal move_base_goal;
move_base_goal.target_pose.header.stamp = ros::Time::now();
move_base_goal.target_pose.header.frame_id = world_frame_;
move_base_goal.target_pose.pose.position = dest.position;
move_base_goal.target_pose.pose.orientation = dest.orientation;
move_base_action_.sendGoal(move_base_goal);
}
void publishMarkers(){
visualization_msgs::MarkerArray markers_array;
for(int i=0; i < waypoints_.size(); i++){
visualization_msgs::Marker marker, label;
marker.header.frame_id = world_frame_;
marker.header.stamp = ros::Time::now();
marker.scale.x = 0.2;
marker.scale.y = 0.2;
marker.scale.z = 0.2;
marker.pose.position.z = marker.scale.z / 2.0;
marker.color.r = 0.8f;
marker.color.g = 0.2f;
marker.color.b = 0.2f;
std::stringstream name;
name << "waypoint " << i;
marker.ns = name.str();
marker.id = i;
marker.pose.position.x = waypoints_[i].point.x;
marker.pose.position.y = waypoints_[i].point.y;
marker.type = visualization_msgs::Marker::SPHERE;
marker.action = visualization_msgs::Marker::ADD;
marker.color.a = 1.0f;
markers_array.markers.push_back(marker);
//ROS_INFO_STREAM("waypoints \n" << waypoints_[i]);
}
marker_pub_.publish(markers_array);
}
void run(){
while(ros::ok()){
if(has_activate_){
for(int i=0; i < waypoints_.size(); i++){
ROS_INFO_STREAM("waypoint = " << waypoints_[i]);
if(!ros::ok()) break;
startNavigationGL(waypoints_[i].point);
double start_nav_time = ros::Time::now().toSec();
while(!onNavigationPoint(waypoints_[i].point)){
if(ros::Time::now().toSec() - start_nav_time > 10.0){
ROS_INFO("Resend the navigation goal.");
startNavigationGL(waypoints_[i].point);
start_nav_time = ros::Time::now().toSec();
}
actionlib::SimpleClientGoalState state = move_base_action_.getState();
sleep();
}
ROS_INFO("waypoint goal");
}
ROS_INFO("waypoints clear");
waypoints_.clear();
startNavigationGL(finish_pose_);
while(!navigationFinished() && ros::ok()) sleep();
has_activate_ = false;
}
sleep();
}
}
private:
actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;
std::vector<geometry_msgs::PointStamped> waypoints_;
geometry_msgs::Pose finish_pose_;
bool has_activate_;
std::string robot_frame_, world_frame_;
tf::TransformListener tf_listener_;
ros::Rate rate_;
ros::Subscriber syscommand_sub_;
ros::Publisher marker_pub_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, ROS_PACKAGE_NAME);
WaypointsNavigation w_nav;
w_nav.run();
return 0;
}
|
Delete the unnecessary comment
|
Delete the unnecessary comment
|
C++
|
bsd-2-clause
|
open-rdc/icart,open-rdc/icart,open-rdc/icart_mini,open-rdc/icart_mini
|
a6511d096dc79a1c17a2c968b1a41743e665c324
|
main.cpp
|
main.cpp
|
#include <cstdio>
int max(int a, int b, int c) {
return c> (a>b ? a : b) ? c: (a>b ? a : b);
}
int main() {
int n, value, weight; // items, value, weight
float helper3; // readed item weight
int s1, s2; // sacks weight
float helper1, helper2; // readed sack weight
scanf("%f %f", &helper1, &helper2);
helper1*=10; // helps cast weight of first knapsack to int
helper2*=10; // helps cast weight of second knapsack to int
s1 = int(helper1+0.5); //http://www.cplusplus.com/forum/beginner/33018/
s2 = int(helper2+0.5);
int **knapsack = new int *[s1+1];
for (int a =0; a < s1+1; ++a) {
knapsack[a] = new int [s2+1];
for (int b = 0; b<s2+1; ++b) knapsack[a][b] = 0;
}
scanf("%d",&n);
// filing knapsack
for (int i = 0; i < n; i++) {
scanf("%f %d", &helper3, &value);
helper3*=10;
weight = int(helper3+0.5); // same as above
// need to fill up all the table cannot stop if one sack is full because item might fit in other
for (int weight1 = s1; weight1 >= 0; weight1--) { // weight of first knapsack
for (int weight2 = s2; weight2 >= 0; weight2--) { // weight of second knapsack
int value1 = 0;
int value2 = 0;
if(weight<=weight1) {
value1 = knapsack[weight1 - weight][weight2] + value;
}
if(weight<=weight2) {
value2 = knapsack[weight1][weight2 - weight] + value;
}
knapsack[weight1][weight2] = max(
knapsack[weight1][weight2] // we have best option
,value1 // put into sack one
,value2 // put into sack two
);
}
}
}
printf("%d\n", knapsack[s1][s2]);
return 0;
}
|
#include <cstdio>
int max(int a, int b, int c) {
return c > (a > b ? a : b) ? c : (a > b ? a : b);
}
int main() {
int n, value, weight; // items, value, weight
float helper3; // readed item weight
int s1, s2; // sacks weight
float helper1, helper2; // readed sack weight
scanf("%f %f", &helper1, &helper2);
helper1*=10; // helps cast weight of first knapsack to int
helper2*=10; // helps cast weight of second knapsack to int
s1 = int(helper1+0.5); //http://www.cplusplus.com/forum/beginner/33018/
s2 = int(helper2+0.5);
int **knapsack = new int *[s1 + 1];
for (int a = 0; a < s1 + 1; ++a) {
knapsack[a] = new int [s2 + 1];
for (int b = 0; b < s2 + 1; ++b) {
knapsack[a][b] = 0;
}
}
scanf("%d",&n);
// filing knapsack
for (int i = 0; i < n; i++) {
scanf("%f %d", &helper3, &value);
helper3*=10;
weight = int(helper3+0.5); // same as above
// need to fill up all the table cannot stop if one sack is full because item might fit in other
for (int weight1 = s1; weight1 >= 0; weight1--) { // weight of first knapsack
for (int weight2 = s2; weight2 >= 0; weight2--) { // weight of second knapsack
int value1 = 0;
int value2 = 0;
if (weight <= weight1) {
value1 = knapsack[weight1 - weight][weight2] + value;
}
if (weight <= weight2) {
value2 = knapsack[weight1][weight2 - weight] + value;
}
knapsack[weight1][weight2] = max(
knapsack[weight1][weight2] // we have best option
,value1 // put into sack one
,value2 // put into sack two
);
}
}
}
printf("%d\n", knapsack[s1][s2]);
return 0;
}
|
Update main.cpp
|
Update main.cpp
Coding style
|
C++
|
mit
|
Nubzor/Plecaki
|
cc66806887c9094e4f16f47ebdc833ccead1fb8f
|
tests/MergeInfillLinesTest.cpp
|
tests/MergeInfillLinesTest.cpp
|
//Copyright (c) 2019 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
#include "../src/Application.h" //To set up a scene and load settings that the layer plan and merger need.
#include "../src/FanSpeedLayerTime.h" //Required to construct a layer plan. Doesn't influence our tests.
#include "../src/pathPlanning/GCodePath.h" //The paths that we're going to be merging.
#include "../src/LayerPlan.h" //Constructing plans that the mergers can merge lines in.
#include "../src/MergeInfillLines.h" //The class under test.
#include "../src/RetractionConfig.h" //Required to construct a layer plan. Doesn't influence our tests.
#include "../src/Slice.h" //To set up a scene and load settings that the layer plan and merger need.
#include "../src/settings/types/LayerIndex.h" //Required to construct a layer plan. Doesn't influence our tests.
namespace cura
{
class MergeInfillLinesTest : public testing::Test
{
public:
//These settings don't matter for this test so they are all the same for every fixture.
const size_t extruder_nr = 0;
const LayerIndex layer_nr = 0;
const bool is_initial_layer = false;
const bool is_raft_layer = false;
const coord_t layer_thickness = 100;
const Point starting_position; //All plans start at 0,0.
/*
* A merger to test with.
*/
ExtruderPlan* extruder_plan;
MergeInfillLines* merger;
/*
* These fields are required for constructing layer plans and must be held
* constant for as long as the lifetime of the plans. Construct them once
* and store them in this fixture class.
*/
const FanSpeedLayerTimeSettings fan_speed_layer_time;
const RetractionConfig retraction_config;
const GCodePathConfig skin_config;
/*
* A path of skin lines without any points.
*/
GCodePath empty_skin;
/*
* A path of a single skin line.
*/
GCodePath single_skin;
/*
* A path of multiple skin lines that together form a straight line.
*
* This path should not get merged together to a single line.
*/
GCodePath lengthwise_skin;
MergeInfillLinesTest()
: starting_position(0, 0)
, fan_speed_layer_time()
, retraction_config()
, skin_config(PrintFeatureType::Skin, 400, layer_thickness, 1, GCodePathConfig::SpeedDerivatives{50, 1000, 10})
, empty_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::None, 1.0, false)
, single_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false)
, lengthwise_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false)
{
single_skin.points.emplace_back(1000, 0);
lengthwise_skin.points = {Point(1000, 0),
Point(2000, 0),
Point(3000, 0),
Point(4000, 0)};
}
void SetUp()
{
//Set up a scene so that we may request settings.
Application::getInstance().current_slice = new Slice(1);
Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr);
ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back();
train.settings.add("machine_nozzle_size", "0.4");
train.settings.add("meshfix_maximum_deviation", "0.1");
extruder_plan = new ExtruderPlan(extruder_nr, layer_nr, is_initial_layer, is_raft_layer, layer_thickness, fan_speed_layer_time, retraction_config);
merger = new MergeInfillLines(*extruder_plan);
}
void TearDown()
{
delete extruder_plan;
delete merger;
delete Application::getInstance().current_slice;
}
};
TEST_F(MergeInfillLinesTest, CalcPathLengthEmpty)
{
EXPECT_EQ(0, merger->calcPathLength(starting_position, empty_skin));
}
TEST_F(MergeInfillLinesTest, CalcPathLengthSingle)
{
EXPECT_EQ(1000, merger->calcPathLength(starting_position, single_skin));
}
TEST_F(MergeInfillLinesTest, CalcPathLengthMultiple)
{
EXPECT_EQ(4000, merger->calcPathLength(starting_position, lengthwise_skin));
}
/*
* Tries merging an empty set of paths together.
*
* This changes nothing in the paths, since there is nothing to change.
*/
TEST_F(MergeInfillLinesTest, MergeEmpty)
{
std::vector<GCodePath> paths; //Empty. No paths to merge.
const bool result = merger->mergeInfillLines(paths, starting_position);
EXPECT_FALSE(result) << "There are no lines to merge.";
EXPECT_EQ(paths.size(), 0) << "The number of paths should still be zero.";
}
/*
* Tries merging a single path of a single line.
*
* This changes nothing in the paths, since the line cannot be merged with
* anything else.
*/
TEST_F(MergeInfillLinesTest, MergeSingle)
{
std::vector<GCodePath> paths;
paths.push_back(single_skin);
const bool result = merger->mergeInfillLines(paths, starting_position);
EXPECT_FALSE(result) << "There is only one line, so it can't be merged with other lines.";
ASSERT_EQ(paths.size(), 1) << "The path should not get removed.";
EXPECT_EQ(paths[0].points.size(), 1) << "The path should not be modified.";
}
TEST_F(MergeInfillLinesTest, MergeLenthwise)
{
std::vector<GCodePath> paths;
paths.push_back(lengthwise_skin);
const bool result = merger->mergeInfillLines(paths, starting_position);
EXPECT_FALSE(result) << "Patterns like Gyroid infill with many (almost) lengthwise lines should not get merged, even if those lines are short.";
ASSERT_EQ(paths.size(), 1) << "The path should not get removed or split.";
EXPECT_EQ(paths[0].points.size(), 4) << "The path should not be modified.";
}
} //namespace cura
|
//Copyright (c) 2019 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
#include "../src/Application.h" //To set up a scene and load settings that the layer plan and merger need.
#include "../src/FanSpeedLayerTime.h" //Required to construct a layer plan. Doesn't influence our tests.
#include "../src/pathPlanning/GCodePath.h" //The paths that we're going to be merging.
#include "../src/LayerPlan.h" //Constructing plans that the mergers can merge lines in.
#include "../src/MergeInfillLines.h" //The class under test.
#include "../src/RetractionConfig.h" //Required to construct a layer plan. Doesn't influence our tests.
#include "../src/Slice.h" //To set up a scene and load settings that the layer plan and merger need.
#include "../src/settings/types/LayerIndex.h" //Required to construct a layer plan. Doesn't influence our tests.
namespace cura
{
class MergeInfillLinesTest : public testing::Test
{
public:
//These settings don't matter for this test so they are all the same for every fixture.
const size_t extruder_nr = 0;
const LayerIndex layer_nr = 0;
const bool is_initial_layer = false;
const bool is_raft_layer = false;
const coord_t layer_thickness = 100;
const Point starting_position; //All plans start at 0,0.
/*
* A merger to test with.
*/
ExtruderPlan* extruder_plan;
MergeInfillLines* merger;
/*
* These fields are required for constructing layer plans and must be held
* constant for as long as the lifetime of the plans. Construct them once
* and store them in this fixture class.
*/
const FanSpeedLayerTimeSettings fan_speed_layer_time;
const RetractionConfig retraction_config;
const GCodePathConfig skin_config;
/*
* A path of skin lines without any points.
*/
GCodePath empty_skin;
/*
* A path of a single skin line.
*/
GCodePath single_skin;
/*
* A path of multiple skin lines that together form a straight line.
*
* This path should not get merged together to a single line.
*/
GCodePath lengthwise_skin;
MergeInfillLinesTest()
: starting_position(0, 0)
, fan_speed_layer_time()
, retraction_config()
, skin_config(PrintFeatureType::Skin, 400, layer_thickness, 1, GCodePathConfig::SpeedDerivatives{50, 1000, 10})
, empty_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::None, 1.0, false)
, single_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false)
, lengthwise_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false)
{
single_skin.points.emplace_back(1000, 0);
lengthwise_skin.points = {Point(1000, 0),
Point(2000, 0),
Point(3000, 0),
Point(4000, 0)};
}
void SetUp()
{
//Set up a scene so that we may request settings.
Application::getInstance().current_slice = new Slice(1);
Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr);
ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back();
train.settings.add("machine_nozzle_size", "0.4");
train.settings.add("meshfix_maximum_deviation", "0.1");
extruder_plan = new ExtruderPlan(extruder_nr, layer_nr, is_initial_layer, is_raft_layer, layer_thickness, fan_speed_layer_time, retraction_config);
merger = new MergeInfillLines(*extruder_plan);
}
void TearDown()
{
delete extruder_plan;
delete merger;
delete Application::getInstance().current_slice;
}
};
TEST_F(MergeInfillLinesTest, CalcPathLengthEmpty)
{
EXPECT_EQ(0, merger->calcPathLength(starting_position, empty_skin));
}
TEST_F(MergeInfillLinesTest, CalcPathLengthSingle)
{
EXPECT_EQ(1000, merger->calcPathLength(starting_position, single_skin));
}
TEST_F(MergeInfillLinesTest, CalcPathLengthMultiple)
{
EXPECT_EQ(4000, merger->calcPathLength(starting_position, lengthwise_skin));
}
/*
* Tries merging an empty set of paths together.
*
* This changes nothing in the paths, since there is nothing to change.
*/
TEST_F(MergeInfillLinesTest, MergeEmpty)
{
std::vector<GCodePath> paths; //Empty. No paths to merge.
const bool result = merger->mergeInfillLines(paths, starting_position);
EXPECT_FALSE(result) << "There are no lines to merge.";
EXPECT_EQ(paths.size(), 0) << "The number of paths should still be zero.";
}
/*
* Tries merging a single path of a single line.
*
* This changes nothing in the paths, since the line cannot be merged with
* anything else.
*/
TEST_F(MergeInfillLinesTest, MergeSingle)
{
std::vector<GCodePath> paths;
paths.push_back(single_skin);
const bool result = merger->mergeInfillLines(paths, starting_position);
EXPECT_FALSE(result) << "There is only one line, so it can't be merged with other lines.";
ASSERT_EQ(paths.size(), 1) << "The path should not get removed.";
EXPECT_EQ(paths[0].points.size(), 1) << "The path should not be modified.";
}
/*
* Tries merging a single path that consists of multiple vertices in a straight
* line.
*
* This should not change anything in the paths, since the lines are in a single
* path without travel moves in between. It's just drawing a curve, and that
* curve should not get modified.
*
* This is basically the case that went wrong with the "Weird Fat Infill" bug
* (CURA-5776).
*/
TEST_F(MergeInfillLinesTest, MergeLenthwise)
{
std::vector<GCodePath> paths;
paths.push_back(lengthwise_skin);
const bool result = merger->mergeInfillLines(paths, starting_position);
EXPECT_FALSE(result) << "Patterns like Gyroid infill with many (almost) lengthwise lines should not get merged, even if those lines are short.";
ASSERT_EQ(paths.size(), 1) << "The path should not get removed or split.";
EXPECT_EQ(paths[0].points.size(), 4) << "The path should not be modified.";
}
} //namespace cura
|
Document new integration test for weird fat infill lines bug
|
Document new integration test for weird fat infill lines bug
|
C++
|
agpl-3.0
|
Ultimaker/CuraEngine,Ultimaker/CuraEngine
|
0e53520edba2e4f20c5865f520a7153b5ae03f0c
|
dune/gdt/playground/space/finitevolume.hh
|
dune/gdt/playground/space/finitevolume.hh
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACE_FINITEVOLUME_HH
#define DUNE_GDT_SPACE_FINITEVOLUME_HH
#include "../mapper/finitevolume.hh"
#include "../basefunctionset/finitevolume.hh"
#include "../../space/interface.hh"
namespace Dune {
namespace GDT {
namespace FiniteVolumeSpace {
// forward, to be used in the traits and to allow for specialization
template< class GridViewImp, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Default
{
static_assert(Dune::AlwaysFalse< GridViewImp >::value, "Untested for these dimensions!");
};
/**
* \brief Traits class for ContinuousLagrangeSpace::FemWrapper.
*/
template< class GridViewImp, class RangeFieldImp, int rangeDim, int rangeDimCols >
class DefaultTraits
{
public:
typedef Default< GridViewImp, RangeFieldImp, rangeDim, rangeDimCols > derived_type;
static const int polOrder = 0;
typedef double BackendType;
typedef GridViewImp GridViewType;
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = rangeDimCols;
typedef Mapper::FiniteVolume< GridViewType, dimRange, dimRangeCols > MapperType;
typedef BaseFunctionSet::FiniteVolume< typename GridViewType::template Codim< 0 >::Entity
, typename GridViewType::ctype, GridViewType::dimension
, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType;
static const bool needs_grid_view = true;
}; // class DefaultTraits
template< class GridViewImp, class RangeFieldImp, int rangeDim >
class Default< GridViewImp, RangeFieldImp, rangeDim, 1 >
: public SpaceInterface< DefaultTraits< GridViewImp, RangeFieldImp, rangeDim, 1 > >
{
typedef SpaceInterface< DefaultTraits< GridViewImp, RangeFieldImp, rangeDim, 1 > > BaseType;
typedef Default< GridViewImp, RangeFieldImp, rangeDim, 1 > ThisType;
public:
typedef DefaultTraits< GridViewImp, RangeFieldImp, rangeDim, 1 > Traits;
typedef typename Traits::GridViewType GridViewType;
static const int polOrder = Traits::polOrder;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef typename Traits::RangeFieldType RangeFieldType;
static const unsigned int dimRange = Traits::dimRange;
static const unsigned int dimRangeCols = Traits::dimRangeCols;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::MapperType MapperType;
typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
typedef typename Traits::EntityType EntityType;
typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;
Default(const std::shared_ptr< const GridViewType >& gv)
: grid_view_(gv)
, mapper_(std::make_shared< MapperType >(*grid_view_))
{}
Default(const ThisType& other)
: grid_view_(other.grid_view_)
, mapper_(other.mapper_)
{}
Default& operator=(const ThisType& other)
{
if (this != &other) {
grid_view_ = other.grid_view_;
mapper_ = other.mapper_;
}
return *this;
}
~Default() {}
const std::shared_ptr< const GridViewType >& grid_view() const
{
return grid_view_;
}
const BackendType& backend() const
{
return 1.0;
}
const MapperType& mapper() const
{
return *mapper_;
}
BaseFunctionSetType base_function_set(const EntityType& entity) const
{
return BaseFunctionSetType(entity);
}
private:
std::shared_ptr< const GridViewType > grid_view_;
std::shared_ptr< const MapperType > mapper_;
}; // class Default< ..., 1, 1 >
} // namespace FiniteVolumeSpace
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACE_FINITEVOLUME_HH
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACE_FINITEVOLUME_HH
#define DUNE_GDT_SPACE_FINITEVOLUME_HH
#include "../mapper/finitevolume.hh"
#include "../basefunctionset/finitevolume.hh"
#include "../../space/interface.hh"
namespace Dune {
namespace GDT {
namespace FiniteVolumeSpace {
// forward, to be used in the traits and to allow for specialization
template< class GridViewImp, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Default
{
static_assert(Dune::AlwaysFalse< GridViewImp >::value, "Untested for these dimensions!");
};
/**
* \brief Traits class for ContinuousLagrangeSpace::FemWrapper.
*/
template< class GridViewImp, class RangeFieldImp, int rangeDim, int rangeDimCols >
class DefaultTraits
{
public:
typedef Default< GridViewImp, RangeFieldImp, rangeDim, rangeDimCols > derived_type;
static const int polOrder = 0;
typedef double BackendType;
typedef GridViewImp GridViewType;
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = rangeDimCols;
typedef Mapper::FiniteVolume< GridViewType, dimRange, dimRangeCols > MapperType;
typedef BaseFunctionSet::FiniteVolume< typename GridViewType::template Codim< 0 >::Entity
, typename GridViewType::ctype, GridViewType::dimension
, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType;
static const bool needs_grid_view = true;
}; // class DefaultTraits
template< class GridViewImp, class RangeFieldImp, int rangeDim >
class Default< GridViewImp, RangeFieldImp, rangeDim, 1 >
: public SpaceInterface< DefaultTraits< GridViewImp, RangeFieldImp, rangeDim, 1 > >
{
typedef SpaceInterface< DefaultTraits< GridViewImp, RangeFieldImp, rangeDim, 1 > > BaseType;
typedef Default< GridViewImp, RangeFieldImp, rangeDim, 1 > ThisType;
public:
typedef DefaultTraits< GridViewImp, RangeFieldImp, rangeDim, 1 > Traits;
typedef typename Traits::GridViewType GridViewType;
static const int polOrder = Traits::polOrder;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef typename Traits::RangeFieldType RangeFieldType;
static const unsigned int dimRange = Traits::dimRange;
static const unsigned int dimRangeCols = Traits::dimRangeCols;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::MapperType MapperType;
typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
typedef typename Traits::EntityType EntityType;
typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;
Default(const std::shared_ptr< const GridViewType >& gv)
: grid_view_(gv)
, mapper_(std::make_shared< MapperType >(*grid_view_))
, backend_(1)
{}
Default(const ThisType& other)
: grid_view_(other.grid_view_)
, mapper_(other.mapper_)
{}
Default& operator=(const ThisType& other)
{
if (this != &other) {
grid_view_ = other.grid_view_;
mapper_ = other.mapper_;
}
return *this;
}
~Default() {}
const std::shared_ptr< const GridViewType >& grid_view() const
{
return grid_view_;
}
const BackendType& backend() const
{
return backend_;
}
const MapperType& mapper() const
{
return *mapper_;
}
BaseFunctionSetType base_function_set(const EntityType& entity) const
{
return BaseFunctionSetType(entity);
}
private:
std::shared_ptr< const GridViewType > grid_view_;
std::shared_ptr< const MapperType > mapper_;
const BackendType backend_;
}; // class Default< ..., 1, 1 >
} // namespace FiniteVolumeSpace
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACE_FINITEVOLUME_HH
|
fix 'backend' warnings
|
[space.fv] fix 'backend' warnings
|
C++
|
bsd-2-clause
|
ftalbrecht/dune-gdt,BarbaraV/dune-gdt
|
b3f9d2cc1f19b2fa90e2b721161d38a6b4777f07
|
dune/hdd/linearelliptic/testcases/base.hh
|
dune/hdd/linearelliptic/testcases/base.hh
|
// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#include <limits>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/io/file/dgfparser.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/grid/provider/default.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/exceptions.hh>
#if HAVE_DUNE_GRID_MULTISCALE
# include <dune/grid/multiscale/provider/cube.hh>
#endif
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/common/exceptions.hh>
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace TestCases {
namespace internal {
class ParametricBase
: public Pymor::Parametric
{
public:
typedef std::map< std::string, Pymor::ParameterType > ParameterTypesMapType;
typedef std::map< std::string, Pymor::Parameter > ParametersMapType;
static ParameterTypesMapType required_parameters()
{
return ParameterTypesMapType();
}
const ParametersMapType& parameters() const
{
return empty_parameters_map_;
}
protected:
static void check_parameters(const ParameterTypesMapType& required_types, const ParametersMapType& actual_parameters)
{
for (auto parameter_type : required_types) {
const auto search_result = actual_parameters.find(parameter_type.first);
if (search_result == actual_parameters.end())
DUNE_THROW(Stuff::Exceptions::wrong_input_given,
"Missing parameter '" << parameter_type.first << "' in given actual_parameters!");
if (search_result->second.type() != parameter_type.second)
DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,
"Given parameter '" << search_result->first << "' is a " << search_result->second.type()
<< " and should be a " << parameter_type.second << "!");
}
} // ... check_paramets(...)
private:
const ParametersMapType empty_parameters_map_;
}; // class ParametricBase
} // namespace internal
/**
* The purpose of this class is to behave like a Stuff::Grid::ConstProviderInterface and at the same time to provide a
* means to obtain the real grid level corresponding to a refinement level.
*/
template< class GridType >
class Base
: public Stuff::Grid::Providers::Default< GridType >
, public internal::ParametricBase
{
typedef Stuff::Grid::Providers::Default< GridType > BaseType;
public:
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
Base(std::shared_ptr< GridType > grd, size_t num_refinements)
: BaseType(grd)
{
levels_.push_back(this->grid().maxLevel());
static const int refine_steps_for_half = DGFGridInfo< GridType >::refineStepsForHalf();
for (size_t rr = 0; rr < num_refinements; ++rr) {
this->grid().globalRefine(refine_steps_for_half);
levels_.push_back(this->grid().maxLevel());
}
this->grid().globalRefine(refine_steps_for_half);
reference_level_ = this->grid().maxLevel();
} // Base(...)
size_t num_refinements() const
{
assert(levels_.size() > 0);
return levels_.size() - 1;
}
int level_of(const size_t refinement) const
{
assert(refinement <= num_refinements());
return levels_[refinement];
}
int reference_level() const
{
return reference_level_;
}
typename BaseType::LevelGridViewType reference_grid_view() const
{
return this->level_view(reference_level_);
}
private:
std::vector< int > levels_;
int reference_level_;
}; // class Base
#if HAVE_DUNE_GRID_MULTISCALE
template< class GridImp >
class MultiscaleCubeBase
: public internal::ParametricBase
{
public:
typedef GridImp GridType;
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
typedef FieldVector< DomainFieldType, dimDomain > DomainType;
typedef Stuff::Grid::Providers::Cube< GridType > GridProviderType;
typedef grid::Multiscale::Providers::Cube< GridType > MsGridProviderType;
MultiscaleCubeBase(const Stuff::Common::Configuration& grid_cfg,
const int initial_refinements,
const size_t num_refinements)
: partitions_(grid_cfg.get< std::string >("num_partitions"))
{
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING
std::cerr << Stuff::Common::Colors::red
<< "warning: running a multiscale testcase!\n"
<< " => the boundaryinfo is set to AllDirichlet and all boundary values are set to zero!\n"
<< " please manually check the testcase for compliance!\n"
<< Stuff::Common::StreamModifiers::normal << std::endl;
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING
const auto lower_left = grid_cfg.get< DomainType >("lower_left");
const auto upper_right = grid_cfg.get< DomainType >("upper_right");
const auto num_elements = grid_cfg.get< std::vector< unsigned int > >("num_elements", dimDomain);
const auto num_partitions = grid_cfg.get< std::vector< size_t > >("num_partitions", dimDomain);
const auto num_oversampling_layers = grid_cfg.get("oversampling_layers", size_t(0));
static const int refine_steps_for_half = DGFGridInfo< GridType >::refineStepsForHalf();
for (size_t rr = 0; rr <= num_refinements; ++rr) {
auto grid_ptr = GridProviderType(lower_left, upper_right, num_elements).grid_ptr();
grid_ptr->globalRefine(boost::numeric_cast< int >(initial_refinements + rr*refine_steps_for_half));
level_providers_.emplace_back(new MsGridProviderType(grid_ptr,
lower_left,
upper_right,
num_partitions,
num_oversampling_layers));
}
auto grid_ptr = GridProviderType(lower_left, upper_right, num_elements).grid_ptr();
grid_ptr->globalRefine(boost::numeric_cast< int >(initial_refinements + (num_refinements + 1)*refine_steps_for_half));
reference_provider_ = Stuff::Common::make_unique< MsGridProviderType >(grid_ptr,
lower_left,
upper_right,
num_partitions,
num_oversampling_layers);
} // MultiscaleCubeBase(...)
std::string partitioning() const
{
return partitions_;
}
size_t num_refinements() const
{
assert(level_providers_.size() > 0);
return level_providers_.size() - 1;
}
const std::unique_ptr< MsGridProviderType >& level_provider(const size_t level) const
{
assert(level < level_providers_.size());
return level_providers_[level];
}
const std::unique_ptr< MsGridProviderType >& reference_provider() const
{
return reference_provider_;
}
private:
const std::string partitions_;
std::vector< std::unique_ptr< MsGridProviderType > > level_providers_;
std::unique_ptr< MsGridProviderType > reference_provider_;
}; // class MultiscaleCubeBase
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace TestCases
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
|
// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#include <limits>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/io/file/dgfparser.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/grid/provider/default.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/exceptions.hh>
#if HAVE_DUNE_GRID_MULTISCALE
# include <dune/grid/multiscale/provider/cube.hh>
#endif
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/common/exceptions.hh>
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace TestCases {
namespace internal {
class ParametricBase
: public Pymor::Parametric
{
public:
typedef std::map< std::string, Pymor::ParameterType > ParameterTypesMapType;
typedef std::map< std::string, Pymor::Parameter > ParametersMapType;
static ParameterTypesMapType required_parameters()
{
return ParameterTypesMapType();
}
const ParametersMapType& parameters() const
{
return empty_parameters_map_;
}
protected:
static void check_parameters(const ParameterTypesMapType& required_types, const ParametersMapType& actual_parameters)
{
for (auto parameter_type : required_types) {
const auto search_result = actual_parameters.find(parameter_type.first);
if (search_result == actual_parameters.end())
DUNE_THROW(Stuff::Exceptions::wrong_input_given,
"Missing parameter '" << parameter_type.first << "' in given actual_parameters!");
if (search_result->second.type() != parameter_type.second)
DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,
"Given parameter '" << search_result->first << "' is a " << search_result->second.type()
<< " and should be a " << parameter_type.second << "!");
}
} // ... check_paramets(...)
private:
const ParametersMapType empty_parameters_map_;
}; // class ParametricBase
} // namespace internal
/**
* The purpose of this class is to behave like a Stuff::Grid::ConstProviderInterface and at the same time to provide a
* means to obtain the real grid level corresponding to a refinement level.
*/
template< class GridType >
class Base
: public Stuff::Grid::Providers::Default< GridType >
, public internal::ParametricBase
{
typedef Stuff::Grid::Providers::Default< GridType > BaseType;
public:
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
Base(std::shared_ptr< GridType > grd, size_t num_refinements)
: BaseType(grd)
{
levels_.push_back(this->grid().maxLevel());
static const int refine_steps_for_half = DGFGridInfo< GridType >::refineStepsForHalf();
for (size_t rr = 0; rr < num_refinements; ++rr) {
this->grid().globalRefine(refine_steps_for_half);
levels_.push_back(this->grid().maxLevel());
}
this->grid().globalRefine(refine_steps_for_half);
reference_level_ = this->grid().maxLevel();
} // Base(...)
size_t num_refinements() const
{
assert(levels_.size() > 0);
return levels_.size() - 1;
}
int level_of(const size_t refinement) const
{
assert(refinement <= num_refinements());
return levels_[refinement];
}
int reference_level() const
{
return reference_level_;
}
typename BaseType::LevelGridViewType reference_grid_view() const
{
return this->level_view(reference_level_);
}
private:
std::vector< int > levels_;
int reference_level_;
}; // class Base
#if HAVE_DUNE_GRID_MULTISCALE
template< class GridImp >
class MultiscaleCubeBase
: public internal::ParametricBase
{
public:
typedef GridImp GridType;
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
typedef FieldVector< DomainFieldType, dimDomain > DomainType;
typedef Stuff::Grid::Providers::Cube< GridType > GridProviderType;
typedef grid::Multiscale::Providers::Cube< GridType > MsGridProviderType;
MultiscaleCubeBase(const Stuff::Common::Configuration& grid_cfg,
const int initial_refinements,
const size_t num_refinements,
const bool H_with_h = false)
: partitions_(H_with_h
? grid_cfg.get< std::string >("num_partitions") + "_H_with_h"
: grid_cfg.get< std::string >("num_partitions"))
{
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING
std::cerr << Stuff::Common::Colors::red
<< "warning: running a multiscale testcase!\n"
<< " => the boundaryinfo is set to AllDirichlet and all boundary values are set to zero!\n"
<< " please manually check the testcase for compliance!\n"
<< Stuff::Common::StreamModifiers::normal << std::endl;
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING
const auto lower_left = grid_cfg.get< DomainType >("lower_left");
const auto upper_right = grid_cfg.get< DomainType >("upper_right");
const auto num_elements = grid_cfg.get< std::vector< unsigned int > >("num_elements", dimDomain);
const auto num_partitions = grid_cfg.get< std::vector< size_t > >("num_partitions", dimDomain);
const auto num_oversampling_layers = grid_cfg.get("oversampling_layers", size_t(0));
static const int refine_steps_for_half = DGFGridInfo< GridType >::refineStepsForHalf();
for (size_t rr = 0; rr <= num_refinements; ++rr) {
auto grid_ptr = GridProviderType(lower_left, upper_right, num_elements).grid_ptr();
grid_ptr->globalRefine(boost::numeric_cast< int >(initial_refinements + rr*refine_steps_for_half));
std::vector< size_t > actual_partitions = num_partitions;
if (H_with_h)
for (auto& element : actual_partitions)
element *= std::pow(2, rr);
level_providers_.emplace_back(new MsGridProviderType(grid_ptr,
lower_left,
upper_right,
actual_partitions,
num_oversampling_layers));
}
auto grid_ptr = GridProviderType(lower_left, upper_right, num_elements).grid_ptr();
grid_ptr->globalRefine(boost::numeric_cast< int >(initial_refinements + (num_refinements + 1)*refine_steps_for_half));
reference_provider_ = Stuff::Common::make_unique< MsGridProviderType >(grid_ptr,
lower_left,
upper_right,
num_partitions,
num_oversampling_layers);
} // MultiscaleCubeBase(...)
std::string partitioning() const
{
return partitions_;
}
size_t num_refinements() const
{
assert(level_providers_.size() > 0);
return level_providers_.size() - 1;
}
const std::unique_ptr< MsGridProviderType >& level_provider(const size_t level) const
{
assert(level < level_providers_.size());
return level_providers_[level];
}
const std::unique_ptr< MsGridProviderType >& reference_provider() const
{
return reference_provider_;
}
private:
const std::string partitions_;
std::vector< std::unique_ptr< MsGridProviderType > > level_providers_;
std::unique_ptr< MsGridProviderType > reference_provider_;
}; // class MultiscaleCubeBase
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace TestCases
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
|
add H_with_h (default to false)
|
[linearelliptic.testcases...] add H_with_h (default to false)
This allows to run a multiscale test case where coarse and fine grid are
refined, such that H/h is constant.
|
C++
|
bsd-2-clause
|
pymor/dune-hdd,pymor/dune-hdd
|
7bb4fd979bdfb0a524c5964f9f6e9ba8351a81c6
|
main.cpp
|
main.cpp
|
4d16dd45-ad5a-11e7-949d-ac87a332f658
|
4da362fa-ad5a-11e7-a6cb-ac87a332f658
|
update testing
|
update testing
|
C++
|
mit
|
justinhyou/GestureRecognition-CNN,justinhyou/GestureRecognition-CNN
|
67bcea6ce73f87bc1aefd65c2eb42b58a9ecbeda
|
main.cpp
|
main.cpp
|
7909cfc5-4b02-11e5-a305-28cfe9171a43
|
791e5f28-4b02-11e5-b551-28cfe9171a43
|
Fix that bug where things didn't work but now they should
|
Fix that bug where things didn't work but now they should
|
C++
|
apache-2.0
|
haosdent/jcgroup,haosdent/jcgroup
|
9ce223ca43e5c3377820617522cc21375f5c9615
|
main.cpp
|
main.cpp
|
5485dff3-ad58-11e7-a4a1-ac87a332f658
|
54f06c0a-ad58-11e7-a238-ac87a332f658
|
Deal with it
|
Deal with it
|
C++
|
mit
|
justinhyou/GestureRecognition-CNN,justinhyou/GestureRecognition-CNN
|
080fac34c403d4a115dbc203f44ae26f6069d09e
|
main.cpp
|
main.cpp
|
/*
* main.cpp
* openc2e
*
* Created by Alyssa Milburn on Wed 02 Jun 2004.
* Copyright (c) 2004-2008 Alyssa Milburn. All rights reserved.
* Copyright (c) 2005-2008 Bryan Donlan. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "openc2e.h"
#include <iostream>
#include "Engine.h"
#include "SDLBackend.h"
#ifdef OPENAL_SUPPORT
#include "OpenALBackend.h"
#endif
#ifdef QT_SUPPORT
#include "qtgui/qtopenc2e.h"
#include "qtgui/QtBackend.h"
#endif
#ifdef _WIN32
#include <windows.h>
#undef main
#endif
extern "C" int main(int argc, char *argv[]) {
try {
std::cout << "openc2e (development build), built " __DATE__ " " __TIME__ "\nCopyright (c) 2004-2008 Alyssa Milburn and others\n\n";
engine.addPossibleBackend("sdl", shared_ptr<Backend>(new SDLBackend()));
#ifdef QT_SUPPORT
boost::shared_ptr<QtBackend> qtbackend = boost::shared_ptr<QtBackend>(new QtBackend());
boost::shared_ptr<Backend> qtbackend_generic = boost::dynamic_pointer_cast<class Backend, class QtBackend>(qtbackend);
engine.addPossibleBackend("qt", qtbackend_generic); // last-added backend is default
#endif
#ifdef OPENAL_SUPPORT
engine.addPossibleAudioBackend("openal", shared_ptr<AudioBackend>(new OpenALBackend()));
#endif
// pass command-line flags to the engine, but do no other setup
if (!engine.parseCommandLine(argc, argv)) return 1;
// get the engine to do all the startup (read catalogue, loading world, etc)
if (!engine.initialSetup()) return 0;
int ret = engine.backend->run(argc, argv);
// we're done, be sure to shut stuff down
engine.shutdown();
return ret;
} catch (std::exception &e) {
#ifdef _WIN32
MessageBox(NULL, e.what(), "openc2e - Fatal exception encountered:", MB_ICONERROR);
#else
std::cerr << "Fatal exception encountered: " << e.what() << "\n";
#endif
return 1;
}
}
/* vim: set noet: */
|
/*
* main.cpp
* openc2e
*
* Created by Alyssa Milburn on Wed 02 Jun 2004.
* Copyright (c) 2004-2008 Alyssa Milburn. All rights reserved.
* Copyright (c) 2005-2008 Bryan Donlan. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "openc2e.h"
#include <iostream>
#include "Engine.h"
#include "SDLBackend.h"
#ifdef OPENAL_SUPPORT
#include "OpenALBackend.h"
#endif
#ifdef QT_SUPPORT
#include "qtgui/QtBackend.h"
#endif
#ifdef _WIN32
#include <windows.h>
#undef main
#endif
extern "C" int main(int argc, char *argv[]) {
try {
std::cout << "openc2e (development build), built " __DATE__ " " __TIME__ "\nCopyright (c) 2004-2008 Alyssa Milburn and others\n\n";
engine.addPossibleBackend("sdl", shared_ptr<Backend>(new SDLBackend()));
#ifdef QT_SUPPORT
boost::shared_ptr<QtBackend> qtbackend = boost::shared_ptr<QtBackend>(new QtBackend());
boost::shared_ptr<Backend> qtbackend_generic = boost::dynamic_pointer_cast<class Backend, class QtBackend>(qtbackend);
engine.addPossibleBackend("qt", qtbackend_generic); // last-added backend is default
#endif
#ifdef OPENAL_SUPPORT
engine.addPossibleAudioBackend("openal", shared_ptr<AudioBackend>(new OpenALBackend()));
#endif
// pass command-line flags to the engine, but do no other setup
if (!engine.parseCommandLine(argc, argv)) return 1;
// get the engine to do all the startup (read catalogue, loading world, etc)
if (!engine.initialSetup()) return 0;
int ret = engine.backend->run(argc, argv);
// we're done, be sure to shut stuff down
engine.shutdown();
return ret;
} catch (std::exception &e) {
#ifdef _WIN32
MessageBox(NULL, e.what(), "openc2e - Fatal exception encountered:", MB_ICONERROR);
#else
std::cerr << "Fatal exception encountered: " << e.what() << "\n";
#endif
return 1;
}
}
/* vim: set noet: */
|
remove unnecessary qtopenc2e.h include from main.cpp
|
remove unnecessary qtopenc2e.h include from main.cpp
|
C++
|
lgpl-2.1
|
ccdevnet/openc2e,crystalline/openc2e,bdonlan/openc2e,ccdevnet/openc2e,crystalline/openc2e,bdonlan/openc2e,ccdevnet/openc2e,bdonlan/openc2e,ccdevnet/openc2e,ccdevnet/openc2e,crystalline/openc2e,ccdevnet/openc2e,bdonlan/openc2e,crystalline/openc2e,crystalline/openc2e
|
4b3977ec689fc918215ec47fd67d6fd4360250f8
|
main.cpp
|
main.cpp
|
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"
/**
* @todo: Config file in ~/.config/qmldmenu/
* @todo: SHIFT(ENTER) for sudo
* @todo: TAB For command (term /bin/*) / app (.desktop) mode
*/
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<Process>("Process", 1, 0, "Process");
qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
|
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"
/**
* @todo: Config file in ~/.config/qmldmenu/
* @todo: SHIFT(ENTER) for sudo
* @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
*/
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<Process>("Process", 1, 0, "Process");
qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
|
Fix warning in todo
|
Fix warning in todo
|
C++
|
mit
|
bayi/qdmenu,bayi/qdmenu,bayi/qdmenu
|
b87a8b3f25b2f74b860fe820fa594576babf64ff
|
src/Nazara/Audio/Sound.cpp
|
src/Nazara/Audio/Sound.cpp
|
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Audio module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/OpenAL.hpp>
#include <Nazara/Core/Error.hpp>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <Nazara/Audio/Debug.hpp>
namespace Nz
{
Sound::Sound(const SoundBuffer* soundBuffer)
{
SetBuffer(soundBuffer);
}
Sound::Sound(const Sound& sound) :
SoundEmitter(sound)
{
SetBuffer(sound.m_buffer);
}
Sound::~Sound()
{
Stop();
}
void Sound::EnableLooping(bool loop)
{
alSourcei(m_source, AL_LOOPING, loop);
}
const SoundBuffer* Sound::GetBuffer() const
{
return m_buffer;
}
UInt32 Sound::GetDuration() const
{
#if NAZARA_AUDIO_SAFE
if (!m_buffer)
{
NazaraError("Invalid sound buffer");
return 0;
}
#endif
return m_buffer->GetDuration();
}
UInt32 Sound::GetPlayingOffset() const
{
ALfloat seconds = -1.f;
alGetSourcef(m_source, AL_SEC_OFFSET, &seconds);
return static_cast<UInt32>(seconds*1000);
}
SoundStatus Sound::GetStatus() const
{
return GetInternalStatus();
}
bool Sound::IsLooping() const
{
ALint loop;
alGetSourcei(m_source, AL_LOOPING, &loop);
return loop != AL_FALSE;
}
bool Sound::IsPlayable() const
{
return m_buffer != nullptr;
}
bool Sound::IsPlaying() const
{
return GetStatus() == SoundStatus_Playing;
}
bool Sound::LoadFromFile(const String& filePath, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::New();
if (!buffer->LoadFromFile(filePath, params))
{
NazaraError("Failed to load buffer from file (" + filePath + ')');
return false;
}
SetBuffer(buffer);
return true;
}
bool Sound::LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::New();
if (!buffer->LoadFromMemory(data, size, params))
{
NazaraError("Failed to load buffer from memory (" + String::Pointer(data) + ')');
return false;
}
SetBuffer(buffer);
return true;
}
bool Sound::LoadFromStream(Stream& stream, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::New();
if (!buffer->LoadFromStream(stream, params))
{
NazaraError("Failed to load buffer from stream");
return false;
}
SetBuffer(buffer);
return true;
}
void Sound::Pause()
{
alSourcePause(m_source);
}
void Sound::Play()
{
#if NAZARA_AUDIO_SAFE
if (!m_buffer)
{
NazaraError("Invalid sound buffer");
return;
}
#endif
alSourcePlay(m_source);
}
void Sound::SetBuffer(const SoundBuffer* buffer)
{
#if NAZARA_AUDIO_SAFE
if (buffer && !buffer->IsValid())
{
NazaraError("Invalid sound buffer");
return;
}
#endif
if (m_buffer == buffer)
return;
Stop();
m_buffer = buffer;
if (m_buffer)
alSourcei(m_source, AL_BUFFER, m_buffer->GetOpenALBuffer());
else
alSourcei(m_source, AL_BUFFER, AL_NONE);
}
void Sound::SetPlayingOffset(UInt32 offset)
{
alSourcef(m_source, AL_SEC_OFFSET, offset/1000.f);
}
void Sound::Stop()
{
alSourceStop(m_source);
}
}
|
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Audio module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/OpenAL.hpp>
#include <Nazara/Core/Error.hpp>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <Nazara/Audio/Debug.hpp>
namespace Nz
{
Sound::Sound(const SoundBuffer* soundBuffer)
{
SetBuffer(soundBuffer);
}
Sound::Sound(const Sound& sound) :
SoundEmitter(sound)
{
SetBuffer(sound.m_buffer);
}
Sound::~Sound()
{
Stop();
}
void Sound::EnableLooping(bool loop)
{
alSourcei(m_source, AL_LOOPING, loop);
}
const SoundBuffer* Sound::GetBuffer() const
{
return m_buffer;
}
UInt32 Sound::GetDuration() const
{
NazaraAssert(m_buffer, "Invalid sound buffer");
return m_buffer->GetDuration();
}
UInt32 Sound::GetPlayingOffset() const
{
ALfloat seconds = -1.f;
alGetSourcef(m_source, AL_SEC_OFFSET, &seconds);
return static_cast<UInt32>(seconds*1000);
}
SoundStatus Sound::GetStatus() const
{
return GetInternalStatus();
}
bool Sound::IsLooping() const
{
ALint loop;
alGetSourcei(m_source, AL_LOOPING, &loop);
return loop != AL_FALSE;
}
bool Sound::IsPlayable() const
{
return m_buffer != nullptr;
}
bool Sound::IsPlaying() const
{
return GetStatus() == SoundStatus_Playing;
}
bool Sound::LoadFromFile(const String& filePath, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::New();
if (!buffer->LoadFromFile(filePath, params))
{
NazaraError("Failed to load buffer from file (" + filePath + ')');
return false;
}
SetBuffer(buffer);
return true;
}
bool Sound::LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::New();
if (!buffer->LoadFromMemory(data, size, params))
{
NazaraError("Failed to load buffer from memory (" + String::Pointer(data) + ')');
return false;
}
SetBuffer(buffer);
return true;
}
bool Sound::LoadFromStream(Stream& stream, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::New();
if (!buffer->LoadFromStream(stream, params))
{
NazaraError("Failed to load buffer from stream");
return false;
}
SetBuffer(buffer);
return true;
}
void Sound::Pause()
{
alSourcePause(m_source);
}
void Sound::Play()
{
#if NAZARA_AUDIO_SAFE
if (!m_buffer)
{
NazaraError("Invalid sound buffer");
return;
}
#endif
alSourcePlay(m_source);
}
void Sound::SetBuffer(const SoundBuffer* buffer)
{
#if NAZARA_AUDIO_SAFE
if (buffer && !buffer->IsValid())
{
NazaraError("Invalid sound buffer");
return;
}
#endif
if (m_buffer == buffer)
return;
Stop();
m_buffer = buffer;
if (m_buffer)
alSourcei(m_source, AL_BUFFER, m_buffer->GetOpenALBuffer());
else
alSourcei(m_source, AL_BUFFER, AL_NONE);
}
void Sound::SetPlayingOffset(UInt32 offset)
{
alSourcef(m_source, AL_SEC_OFFSET, offset/1000.f);
}
void Sound::Stop()
{
alSourceStop(m_source);
}
}
|
Replace error check by assert
|
Audio/Sound: Replace error check by assert
Former-commit-id: 76192feaa3a29342b5456a97f660719714be3fe6
|
C++
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
f563a2d0efee66e5976bc0f3492f6545c521b06d
|
utils.cc
|
utils.cc
|
#include "utils.h"
ustring to_unicode(const std::string &s)
{
ustring out;
for (size_t i = 0; i < s.size(); ++i) {
unsigned char c = s[i];
if (c < 128) {
out += c;
} else {
out += '?';
}
}
return out;
}
|
#include "utils.h"
ustring to_unicode(const std::string &in)
{
ustring out(in.size(), 0);
for (size_t i = 0; i < in.size(); ++i) {
unsigned char c = in[i];
if (c >= 128) {
c = '?';
}
out[i] = c;
}
return out;
}
|
Optimize to_unicode() [PERFECTIVE]
|
utils: Optimize to_unicode() [PERFECTIVE]
|
C++
|
lgpl-2.1
|
japeq/jamail,japeq/jamail
|
c86317e370f53a4c3f34d23dd1f79da7510cbf8d
|
main.cpp
|
main.cpp
|
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#if defined(Q_OS_MACX)
QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath() + "/../PlugIns");
#endif
QQmlApplicationEngine engine;
if (argc < 2) {
printf("Usage: OwaViewer [directory]\n");
printf(" or: OwaViewer [File]\n");
printf(" or: OwaViewer --demo\n");
return 1;
}
QString qmlPath;
if (QString(argv[1]) == "--demo") {
qmlPath = QString("qrc:/tests/test.qml");
} else {
QDir dirPath(argv[1]);
// It's a directory
if (QFileInfo(dirPath.path()).isDir()) {
// Trying to read QML file in the directory
qmlPath = dirPath.filePath("app.qml");
if (!QFile(qmlPath).exists()) {
qmlPath = dirPath.filePath("App.qml");
if (!QFile(qmlPath).exists()) {
printf("Cannot find application in the directory.\n");
return 1;
}
}
} else {
// Whether does the QML file exists or not?
qmlPath = dirPath.path();
if (!QFile(qmlPath).exists()) {
printf("OwaNEXT Application doesn't exist.\n");
return -1;
}
}
}
// Run it
engine.load(QUrl(qmlPath));
return app.exec();
}
|
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setApplicationName("OwaViewer");
app.setOrganizationName("HanGee OwaNEXT");
app.setOrganizationDOmain("han-gee.com");
#if defined(Q_OS_MACX)
QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath() + "/../PlugIns");
#endif
QQmlApplicationEngine engine;
if (argc < 2) {
printf("Usage: OwaViewer [directory]\n");
printf(" or: OwaViewer [File]\n");
printf(" or: OwaViewer --demo\n");
return 1;
}
QString qmlPath;
if (QString(argv[1]) == "--demo") {
qmlPath = QString("qrc:/tests/test.qml");
} else {
QDir dirPath(argv[1]);
// It's a directory
if (QFileInfo(dirPath.path()).isDir()) {
// Trying to read QML file in the directory
qmlPath = dirPath.filePath("app.qml");
if (!QFile(qmlPath).exists()) {
qmlPath = dirPath.filePath("App.qml");
if (!QFile(qmlPath).exists()) {
printf("Cannot find application in the directory.\n");
return 1;
}
}
} else {
// Whether does the QML file exists or not?
qmlPath = dirPath.path();
if (!QFile(qmlPath).exists()) {
printf("OwaNEXT Application doesn't exist.\n");
return -1;
}
}
}
// Run it
engine.load(QUrl(qmlPath));
return app.exec();
}
|
set application and orgnization information
|
set application and orgnization information
|
C++
|
mit
|
HanGee/OwaViewer,HanGee/OwaViewer
|
936ae2574f044c142a90ffc167b3162076761849
|
main.cpp
|
main.cpp
|
#include <fstream>
bool file_exists(std::string& path) {
std::ifstream file(path);
return file.good();
}
void allocate_file(std::string& path, unsigned int size = 0) {
std::ofstream file(path);
if (size > 0) {
file.seekp(size - 1);
file << '\0';
}
}
bool check_length(std::fstream& fs, unsigned int length) {
fs.seekg(0, fs.end);
bool length_matches = fs.tellg() == length;
fs.seekg(0, fs.beg);
return length_matches;
}
template <typename T>
class BINMatrix {
public:
BINMatrix(std::string, unsigned int, unsigned int);
T read(unsigned int, unsigned int);
void write(unsigned int, unsigned int, T);
private:
unsigned int n;
unsigned int p;
unsigned int length;
std::fstream fs;
unsigned int reduce_indexes(unsigned int, unsigned int);
};
template <typename T>
BINMatrix<T>::BINMatrix(std::string path, unsigned int n_, unsigned int p_) : n(n_), p(p_), length(n * p * sizeof(T)) {
if (!file_exists(path)) {
allocate_file(path, length);
}
fs.open(path, std::ios::in | std::ios::out | std::ios::binary);
if (!check_length(fs, length)) {
throw std::length_error("dimensions do not match file length");
}
};
template <typename T>
T BINMatrix<T>::read(unsigned int i, unsigned int j) {
unsigned int index(reduce_indexes(i, j));
fs.seekg(index);
T buffer;
fs.read(reinterpret_cast<char*>(&buffer), sizeof(T));
return buffer;
};
template <typename T>
void BINMatrix<T>::write(unsigned int i, unsigned int j, T value) {
unsigned int index(reduce_indexes(i, j));
fs.seekp(index);
fs.write(reinterpret_cast<char*>(&value), sizeof(T));
fs.flush();
};
template <typename T>
unsigned int BINMatrix<T>::reduce_indexes(unsigned int i, unsigned int j) {
// Convert to zero-based index
--i; --j;
// Convert two-dimensional to one-dimensional index
return ((i * n) + j) * sizeof(T);
};
int main() {
try {
// char
//BINMatrix<char> m_char("test", 6, 6);
//m_char.write(1, 1, 'a');
//m_char.write(1, 6, 'b');
//m_char.write(2, 1, 'c');
//m_char.write(6, 6, 'z');
//std::cout << m_char.read(1, 1) << std::endl;
//std::cout << m_char.read(1, 6) << std::endl;
//std::cout << m_char.read(2, 1) << std::endl;
//std::cout << m_char.read(6, 6) << std::endl;
// int
//BINMatrix<int> m_int("test", 6, 6);
//m_int.write(1, 1, 1);
//m_int.write(1, 6, 2);
//m_int.write(2, 1, 3);
//m_int.write(6, 6, 99);
//std::cout << m_int.read(1, 1) << std::endl;
//std::cout << m_int.read(1, 6) << std::endl;
//std::cout << m_int.read(2, 1) << std::endl;
//std::cout << m_int.read(6, 6) << std::endl;
//double
BINMatrix<double> m_double("test", 6, 6);
m_double.write(1, 1, 1.1);
m_double.write(1, 6, 2.2);
m_double.write(2, 1, 3.3);
m_double.write(6, 6, 99.99);
std::cout << m_double.read(1, 1) << std::endl;
std::cout << m_double.read(1, 6) << std::endl;
std::cout << m_double.read(2, 1) << std::endl;
std::cout << m_double.read(6, 6) << std::endl;
} catch (std::length_error& ex) {
std::cerr << ex.what() << std::endl;
}
}
|
#include <fstream>
bool file_exists(std::string& path) {
std::ifstream file(path);
return file.good();
}
void allocate_file(std::string& path, unsigned long long int size = 0) {
std::ofstream file(path);
if (size > 0) {
file.seekp(size - 1);
file << '\0';
}
}
bool check_length(std::fstream& fs, unsigned long long int length) {
fs.seekg(0, fs.end);
bool length_matches = fs.tellg() == length;
fs.seekg(0, fs.beg);
return length_matches;
}
template <typename T>
class BINMatrix {
public:
BINMatrix(std::string, unsigned int, unsigned int);
T read(unsigned long long int);
T read(unsigned int, unsigned int);
void write(unsigned long long int, T);
void write(unsigned int, unsigned int, T);
private:
unsigned int n;
unsigned int p;
unsigned long long int length;
std::fstream fs;
unsigned long long int reduce_indexes(unsigned int, unsigned int);
};
template <typename T>
BINMatrix<T>::BINMatrix(std::string path, unsigned int n_, unsigned int p_) : n(n_), p(p_), length(n * p * sizeof(T)) {
if (!file_exists(path)) {
allocate_file(path, length);
}
fs.open(path, std::ios::in | std::ios::out | std::ios::binary);
if (!check_length(fs, length)) {
throw std::length_error("dimensions do not match file length");
}
};
template <typename T>
T BINMatrix<T>::read(unsigned long long int index) {
index *= sizeof(T);
fs.seekg(index);
T buffer;
fs.read(reinterpret_cast<char*>(&buffer), sizeof(T));
return buffer;
};
template <typename T>
T BINMatrix<T>::read(unsigned int i, unsigned int j) {
return read(reduce_indexes(i, j));
};
template <typename T>
void BINMatrix<T>::write(unsigned long long index, T value) {
index *= sizeof(T);
fs.seekp(index);
fs.write(reinterpret_cast<char*>(&value), sizeof(T));
fs.flush();
};
template <typename T>
void BINMatrix<T>::write(unsigned int i, unsigned int j, T value) {
write(reduce_indexes(i, j), value);
};
template <typename T>
unsigned long long int BINMatrix<T>::reduce_indexes(unsigned int i, unsigned int j) {
// Convert to zero-based index
--i; --j;
// Convert two-dimensional to one-dimensional index
return ((i * n) + j);
};
int main() {
try {
// char
//BINMatrix<char> m_char("test", 6, 6);
//m_char.write(1, 1, 'a');
//m_char.write(1, 6, 'b');
//m_char.write(2, 1, 'c');
//m_char.write(6, 6, 'z');
//std::cout << m_char.read(1, 1) << std::endl;
//std::cout << m_char.read(1, 6) << std::endl;
//std::cout << m_char.read(2, 1) << std::endl;
//std::cout << m_char.read(6, 6) << std::endl;
// int
//BINMatrix<int> m_int("test", 6, 6);
//m_int.write(1, 1, 1);
//m_int.write(1, 6, 2);
//m_int.write(2, 1, 3);
//m_int.write(6, 6, 99);
//std::cout << m_int.read(1, 1) << std::endl;
//std::cout << m_int.read(1, 6) << std::endl;
//std::cout << m_int.read(2, 1) << std::endl;
//std::cout << m_int.read(6, 6) << std::endl;
//double
BINMatrix<double> m_double("test", 6, 6);
m_double.write(1, 1, 1.1);
m_double.write(1, 6, 2.2);
m_double.write(2, 1, 3.3);
m_double.write(6, 6, 99.99);
std::cout << m_double.read(1, 1) << std::endl;
std::cout << m_double.read(1, 6) << std::endl;
std::cout << m_double.read(2, 1) << std::endl;
std::cout << m_double.read(6, 6) << std::endl;
} catch (std::length_error& ex) {
std::cerr << ex.what() << std::endl;
}
}
|
Add single index methods.
|
Add single index methods.
|
C++
|
mit
|
QuantGen/BINMatrix,QuantGen/BINMatrix
|
45e02b4a18b54293b60d42e2daf684c49472c05a
|
main.cpp
|
main.cpp
|
/*
* Copyright (c) 2015 Isode Limited.
* All rights reserved.
* See the LICENSE file for more information.
*/
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <restpp/JSONRESTHandler.h>
#include <restpp/MemoryFileHandler.h>
#include <restpp/RESTServer.h>
#include <restpp/SessionCollection.h>
#include <restpp/SessionRestHandler.h>
#include <restpp/WebSocket.h>
#include <restpp/WebSocketHinter.h>
#include "config.h"
using namespace librestpp;
using namespace restsocket;
class DemoSession {
public:
DemoSession(WebSocket::ref webSocket) : webSocket_(webSocket) {}
WebSocket::ref webSocket_;
};
class DemoSessionCollection : public SessionCollection<boost::shared_ptr<DemoSession>> {
public:
DemoSessionCollection() {}
virtual ~DemoSessionCollection() {}
std::string addSession(boost::shared_ptr<DemoSession> session) {
std::string key = boost::lexical_cast<std::string>(uuidGenerator_());
sessions_[key] = session;
webSocketSessions_[session->webSocket_] = std::pair<boost::shared_ptr<DemoSession>, std::string>(session, key);
return key;
}
void removeSession(WebSocket::ref webSocket) {
boost::shared_ptr<DemoSession> session = webSocketSessions_[webSocket].first;
std::string key = webSocketSessions_[webSocket].second;
if (!session) return;
sessions_.erase(key);
webSocketSessions_.erase(session->webSocket_);
}
bool hasSession(WebSocket::ref webSocket) {
return webSocketSessions_.count(webSocket) > 0;
}
private:
std::map<WebSocket::ref, std::pair<boost::shared_ptr<DemoSession>, std::string>> webSocketSessions_;
boost::uuids::random_generator uuidGenerator_;
};
boost::shared_ptr<JSONObject> configToJSON(Config* config) {
boost::shared_ptr<JSONObject> json = boost::make_shared<JSONObject>();
json->set("name", boost::make_shared<JSONString>(config->name_));
return json;
}
void handleConfigGetRequest(boost::shared_ptr<RESTRequest> request, Config* config) {
request->setReplyHeader(RESTRequest::HTTP_OK);
request->addReplyContent(configToJSON(config));
request->sendReply();
}
class WebSockets {
public:
WebSockets(boost::shared_ptr<DemoSessionCollection> sessions) : sessions_(sessions) {}
void handleNewWebSocket(WebSocket::ref webSocket) {
std::cout << "Received new websocket connection" << std::endl;
webSocket->onMessage.connect(boost::bind(&WebSockets::handleMessage, this, webSocket, _1));
}
void sendModelHint(const std::string& uri) {
for (size_t i = 0; i < hinters_.size(); i++) {
hinters_[i]->sendModelHint(uri);
}
}
private:
void handleMessage(WebSocket::ref webSocket, boost::shared_ptr<JSONObject> message) {
std::cout << "Receiving websocket message " << message->serialize() << std::endl;
if (sessions_->hasSession(webSocket)) {
// Unexpected message, but just ignore for this demo and reprocess it
}
boost::shared_ptr<JSONString> type = boost::dynamic_pointer_cast<JSONString>(message->getValues()["type"]);
if (!type || type->getValue() != "login") {
std::cout << "Not a login" << std::endl;
return;
} // Bad format
boost::shared_ptr<JSONString> user = boost::dynamic_pointer_cast<JSONString>(message->getValues()["user"]);
boost::shared_ptr<JSONString> password = boost::dynamic_pointer_cast<JSONString>(message->getValues()["password"]);
if (!user || !password || user->getValue() != "demo" || password->getValue() != "secret!") {
std::cout << "Login invalid" << std::endl;
// Do real error handling in a real application
return;
}
std::cout << "Login successful" << std::endl;
boost::shared_ptr<DemoSession> session = boost::make_shared<DemoSession>(webSocket);
std::string key = sessions_->addSession(session);
WebSocketHinter::ref hinter = boost::make_shared<WebSocketHinter>(webSocket);
hinters_.push_back(hinter);
webSocket->onClosed.connect(boost::bind(&WebSockets::handleWebSocketClosed, this, hinter));
boost::shared_ptr<JSONObject> reply = boost::make_shared<JSONObject>();
reply->set("type", boost::make_shared<JSONString>("login-success"));
reply->set("cookie", boost::make_shared<JSONString>("librestpp_session=" + key));
std::cout << "Sending reply:" << reply->serialize() << std::endl;
hinter->send(reply);
}
void handleWebSocketClosed(WebSocketHinter::ref hinter) {
std::cout << "Websocket closed" << std::endl;
sessions_->removeSession(hinter->getWebSocket());
hinters_.erase(std::remove(hinters_.begin(), hinters_.end(), hinter), hinters_.end());
}
private:
std::vector<WebSocketHinter::ref> hinters_;
boost::shared_ptr<DemoSessionCollection> sessions_;
};
void handleConfigPostRequest(boost::shared_ptr<RESTRequest> request, Config* config, WebSockets* webSockets) {
boost::shared_ptr<JSONObject> json = request->getJSON();
boost::shared_ptr<JSONString> str;
if (!!json) {
auto values = json->getValues();
auto nameJSON = values["name"];
str = boost::dynamic_pointer_cast<JSONString>(nameJSON);
}
if (str) {
config->name_ = str->getValue();
request->setReplyHeader(RESTRequest::HTTP_OK);
request->addReplyContent(configToJSON(config));
}
else {
request->setReplyHeader(RESTRequest::HTTP_OK);
request->addReplyContent("Invalid JSON sent");
}
request->sendReply();
webSockets->sendModelHint("/api/config");
}
int main(int argc, const char* argv[])
{
librestpp::RESTServer server(1080);
Config config;
config.name_ = "Demo";
boost::shared_ptr<DemoSessionCollection> sessions = boost::make_shared<DemoSessionCollection>();
WebSockets webSockets(sessions);
typedef SessionRESTHandler<boost::shared_ptr<DemoSession>> DemoSessionRestHandler;
boost::shared_ptr<DemoSessionRestHandler> configGetHandler = boost::make_shared<DemoSessionRestHandler>(sessions, [&config](boost::shared_ptr<DemoSession>, boost::shared_ptr<RESTRequest> request) {handleConfigGetRequest(request, &config);});
server.addJSONEndpoint(PathVerb("/api/config", PathVerb::GET), configGetHandler);
boost::shared_ptr<DemoSessionRestHandler> configPostHandler = boost::make_shared<DemoSessionRestHandler>(sessions, [&config, &webSockets](boost::shared_ptr<DemoSession>, boost::shared_ptr<RESTRequest> request) {handleConfigPostRequest(request, &config, &webSockets);});
server.addJSONEndpoint(PathVerb("/api/config", PathVerb::POST), configPostHandler);
boost::shared_ptr<JSONRESTHandler> cssHandler = boost::make_shared<MemoryFileHandler>("client/_build/styles.nonCached.css");
server.addJSONEndpoint(PathVerb("/styles.nonCached.css", PathVerb::GET), cssHandler);
boost::shared_ptr<JSONRESTHandler> jsHandler = boost::make_shared<MemoryFileHandler>("client/_build/app.nonCached.js");
server.addJSONEndpoint(PathVerb("/app.nonCached.js", PathVerb::GET), jsHandler);
boost::shared_ptr<JSONRESTHandler> htmlHandler = boost::make_shared<MemoryFileHandler>("client/_build/index.html");
server.addDefaultGetEndpoint(htmlHandler);
server.onWebSocketConnection.connect(boost::bind(&WebSockets::handleNewWebSocket, &webSockets, _1));
server.run();
}
|
/*
* Copyright (c) 2015 Isode Limited.
* All rights reserved.
* See the LICENSE file for more information.
*/
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <restpp/JSONRESTHandler.h>
#include <restpp/MemoryFileHandler.h>
#include <restpp/RESTServer.h>
#include <restpp/SessionCollection.h>
#include <restpp/SessionRESTHandler.h>
#include <restpp/WebSocket.h>
#include <restpp/WebSocketHinter.h>
#include "config.h"
using namespace librestpp;
using namespace restsocket;
class DemoSession {
public:
DemoSession(WebSocket::ref webSocket) : webSocket_(webSocket) {}
WebSocket::ref webSocket_;
};
class DemoSessionCollection : public SessionCollection<boost::shared_ptr<DemoSession>> {
public:
DemoSessionCollection() {}
virtual ~DemoSessionCollection() {}
std::string addSession(boost::shared_ptr<DemoSession> session) {
std::string key = boost::lexical_cast<std::string>(uuidGenerator_());
sessions_[key] = session;
webSocketSessions_[session->webSocket_] = std::pair<boost::shared_ptr<DemoSession>, std::string>(session, key);
return key;
}
void removeSession(WebSocket::ref webSocket) {
boost::shared_ptr<DemoSession> session = webSocketSessions_[webSocket].first;
std::string key = webSocketSessions_[webSocket].second;
if (!session) return;
sessions_.erase(key);
webSocketSessions_.erase(session->webSocket_);
}
bool hasSession(WebSocket::ref webSocket) {
return webSocketSessions_.count(webSocket) > 0;
}
private:
std::map<WebSocket::ref, std::pair<boost::shared_ptr<DemoSession>, std::string>> webSocketSessions_;
boost::uuids::random_generator uuidGenerator_;
};
boost::shared_ptr<JSONObject> configToJSON(Config* config) {
boost::shared_ptr<JSONObject> json = boost::make_shared<JSONObject>();
json->set("name", boost::make_shared<JSONString>(config->name_));
return json;
}
void handleConfigGetRequest(boost::shared_ptr<RESTRequest> request, Config* config) {
request->setReplyHeader(RESTRequest::HTTP_OK);
request->addReplyContent(configToJSON(config));
request->sendReply();
}
class WebSockets {
public:
WebSockets(boost::shared_ptr<DemoSessionCollection> sessions) : sessions_(sessions) {}
void handleNewWebSocket(WebSocket::ref webSocket) {
std::cout << "Received new websocket connection" << std::endl;
webSocket->onMessage.connect(boost::bind(&WebSockets::handleMessage, this, webSocket, _1));
}
void sendModelHint(const std::string& uri) {
for (size_t i = 0; i < hinters_.size(); i++) {
hinters_[i]->sendModelHint(uri);
}
}
private:
void handleMessage(WebSocket::ref webSocket, boost::shared_ptr<JSONObject> message) {
std::cout << "Receiving websocket message " << message->serialize() << std::endl;
if (sessions_->hasSession(webSocket)) {
// Unexpected message, but just ignore for this demo and reprocess it
}
boost::shared_ptr<JSONString> type = boost::dynamic_pointer_cast<JSONString>(message->getValues()["type"]);
if (!type || type->getValue() != "login") {
std::cout << "Not a login" << std::endl;
return;
} // Bad format
boost::shared_ptr<JSONString> user = boost::dynamic_pointer_cast<JSONString>(message->getValues()["user"]);
boost::shared_ptr<JSONString> password = boost::dynamic_pointer_cast<JSONString>(message->getValues()["password"]);
if (!user || !password || user->getValue() != "demo" || password->getValue() != "secret!") {
std::cout << "Login invalid" << std::endl;
// Do real error handling in a real application
return;
}
std::cout << "Login successful" << std::endl;
boost::shared_ptr<DemoSession> session = boost::make_shared<DemoSession>(webSocket);
std::string key = sessions_->addSession(session);
WebSocketHinter::ref hinter = boost::make_shared<WebSocketHinter>(webSocket);
hinters_.push_back(hinter);
webSocket->onClosed.connect(boost::bind(&WebSockets::handleWebSocketClosed, this, hinter));
boost::shared_ptr<JSONObject> reply = boost::make_shared<JSONObject>();
reply->set("type", boost::make_shared<JSONString>("login-success"));
reply->set("cookie", boost::make_shared<JSONString>("librestpp_session=" + key));
std::cout << "Sending reply:" << reply->serialize() << std::endl;
hinter->send(reply);
}
void handleWebSocketClosed(WebSocketHinter::ref hinter) {
std::cout << "Websocket closed" << std::endl;
sessions_->removeSession(hinter->getWebSocket());
hinters_.erase(std::remove(hinters_.begin(), hinters_.end(), hinter), hinters_.end());
}
private:
std::vector<WebSocketHinter::ref> hinters_;
boost::shared_ptr<DemoSessionCollection> sessions_;
};
void handleConfigPostRequest(boost::shared_ptr<RESTRequest> request, Config* config, WebSockets* webSockets) {
boost::shared_ptr<JSONObject> json = request->getJSON();
boost::shared_ptr<JSONString> str;
if (!!json) {
auto values = json->getValues();
auto nameJSON = values["name"];
str = boost::dynamic_pointer_cast<JSONString>(nameJSON);
}
if (str) {
config->name_ = str->getValue();
request->setReplyHeader(RESTRequest::HTTP_OK);
request->addReplyContent(configToJSON(config));
}
else {
request->setReplyHeader(RESTRequest::HTTP_OK);
request->addReplyContent("Invalid JSON sent");
}
request->sendReply();
webSockets->sendModelHint("/api/config");
}
int main(int argc, const char* argv[])
{
librestpp::RESTServer server(1080);
Config config;
config.name_ = "Demo";
boost::shared_ptr<DemoSessionCollection> sessions = boost::make_shared<DemoSessionCollection>();
WebSockets webSockets(sessions);
typedef SessionRESTHandler<boost::shared_ptr<DemoSession>> DemoSessionRestHandler;
boost::shared_ptr<DemoSessionRestHandler> configGetHandler = boost::make_shared<DemoSessionRestHandler>(sessions, [&config](boost::shared_ptr<DemoSession>, boost::shared_ptr<RESTRequest> request) {handleConfigGetRequest(request, &config);});
server.addJSONEndpoint(PathVerb("/api/config", PathVerb::GET), configGetHandler);
boost::shared_ptr<DemoSessionRestHandler> configPostHandler = boost::make_shared<DemoSessionRestHandler>(sessions, [&config, &webSockets](boost::shared_ptr<DemoSession>, boost::shared_ptr<RESTRequest> request) {handleConfigPostRequest(request, &config, &webSockets);});
server.addJSONEndpoint(PathVerb("/api/config", PathVerb::POST), configPostHandler);
boost::shared_ptr<JSONRESTHandler> cssHandler = boost::make_shared<MemoryFileHandler>("client/_build/styles.nonCached.css");
server.addJSONEndpoint(PathVerb("/styles.nonCached.css", PathVerb::GET), cssHandler);
boost::shared_ptr<JSONRESTHandler> jsHandler = boost::make_shared<MemoryFileHandler>("client/_build/app.nonCached.js");
server.addJSONEndpoint(PathVerb("/app.nonCached.js", PathVerb::GET), jsHandler);
boost::shared_ptr<JSONRESTHandler> htmlHandler = boost::make_shared<MemoryFileHandler>("client/_build/index.html");
server.addDefaultGetEndpoint(htmlHandler);
server.onWebSocketConnection.connect(boost::bind(&WebSockets::handleNewWebSocket, &webSockets, _1));
server.run();
}
|
Fix caps in main.cpp
|
Fix caps in main.cpp
|
C++
|
mit
|
Kev/restsocket,Kev/restsocket,Kev/restsocket,Kev/restsocket
|
f67956108c3dc53a0386c975eb25032ca77514ab
|
main.cpp
|
main.cpp
|
#define FUSE_USE_VERSION 30
#include <fuse.h>
// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>
#include <time.h>
#include <limits.h> // PATH_MAX
// STL
#include <system_error>
#include <map>
#include <set>
#include <string>
#include <cstdint>
#include <cassert>
#include <cstring>
#include <iostream>
namespace posix
{
static const int success_response = 0;
static const int error_response = -1;
static int success(void) { errno = 0; return success_response; }
static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; }
}
namespace circlefs
{
enum class Epath
{
root,
directory,
file,
};
struct file_entry_t
{
bool operator < (const file_entry_t& other) const // for locating files by name
{ return name < other.name; }
std::string name;
pid_t pid;
struct stat stat;
};
std::map<uid_t, std::set<file_entry_t>> files;
void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename)
{
const char* dir_pos = std::strchr(path, '/') + 1;
const char* file_pos = std::strchr(dir_pos, '/');
std::string dir;
if(path[1] == '\0')
{
type = Epath::root;
pw_ent = nullptr;
filename.clear();
}
else
{
if(file_pos == nullptr)
{
dir = dir_pos;
filename.clear();
type = Epath::directory;
}
else
{
dir = std::string(dir_pos, file_pos - dir_pos);
filename = file_pos + 1;
type = Epath::file;
}
pw_ent = ::getpwnam(dir.c_str());
}
}
void clean_set(std::set<file_entry_t>& dir_set)
{
char path[PATH_MAX + 1];
struct stat info;
auto pos = dir_set.begin();
while(pos != dir_set.end())
{
// Linux only
sprintf(path, "/proc/%d", pos->pid);
if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) // if process
pos = dir_set.erase(pos);
else
++pos;
}
}
struct timespec get_oldest(std::set<file_entry_t>& dir_set)
{
struct timespec oldest = dir_set.begin()->stat.st_atim;
auto pos = dir_set.begin();
while(pos != dir_set.end())
{
if(pos->stat.st_atim.tv_sec < oldest.tv_sec)
oldest.tv_sec = pos->stat.st_atim.tv_sec;
}
return oldest;
}
int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo)
{
(void)fileInfo;
filler(buf, "." , nullptr, 0);
filler(buf, "..", nullptr, 0);
Epath type;
passwd* pw_ent;
std::string filename;
deconstruct_path(path, type, pw_ent, filename);
switch(type)
{
case Epath::root: // root directory (fill with usernames in use)
{
auto pos = files.begin();
while(pos != files.end())
{
clean_set(pos->second);
if(pos->second.empty())
pos = files.erase(pos);
else
{
filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset);
++pos;
}
}
break;
}
case Epath::directory: // list files in directory (based on username)
{
auto pos = files.find(pw_ent->pw_uid);
if(pos == files.end()) // username has no files
{
posix::error(std::errc::no_such_file_or_directory);
return 0 - errno;
}
clean_set(pos->second);
for(const file_entry_t& entry : pos->second)
filler(buf, entry.name.c_str(), &entry.stat, offset);
break;
}
case Epath::file: // there must have been a parsing error (impossible situation)
assert(false);
}
return posix::success();
}
int mknod(const char* path, mode_t mode, dev_t rdev)
{
(void)rdev;
if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
return posix::error(std::errc::permission_denied);
Epath type;
passwd* pw_ent = nullptr;
std::string filename;
struct stat stat = {};
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
deconstruct_path(path, type, pw_ent, filename);
switch(type)
{
case Epath::root: // root directory - cannot make root!
case Epath::directory: // directory (based on username) - cannot make directory!
return posix::error(std::errc::permission_denied);
case Epath::file: // create a node file!
fuse_context* ctx = fuse_get_context();
auto& dir = files[pw_ent->pw_uid];
auto entry = dir.find({ filename, 0, stat });
if(entry != dir.end())
dir.erase(entry);
stat.st_uid = pw_ent->pw_uid;
stat.st_gid = pw_ent->pw_gid;
stat.st_mode = mode;
stat.st_ctim =
stat.st_mtim =
stat.st_atim = time;
dir.insert({ filename, ctx->pid, stat });
break;
}
return posix::success();
}
int getattr(const char* path, struct stat* statbuf)
{
Epath type;
passwd* pw_ent = nullptr;
std::string filename;
deconstruct_path(path, type, pw_ent, filename);
switch(type)
{
case Epath::root: // root directory (always exists)
statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
posix::success();
break;
case Epath::directory: // username (exists if username exists)
statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
if(pw_ent == nullptr)
posix::error(std::errc::no_such_file_or_directory);
else
posix::success();
break;
case Epath::file:
auto pos = files.find(pw_ent->pw_uid);
if(pos == files.end()) // username not registered
{
posix::error(std::errc::no_such_file_or_directory);
break;
}
clean_set(pos->second);
for(const file_entry_t& entry : pos->second) // check every file
{
if(entry.name == filename)
{
*statbuf = entry.stat;
posix::success();
return 0 - errno;
}
}
posix::error(std::errc::no_such_file_or_directory); // no file matched
break;
}
return 0 - errno;
}
}
int main(int argc, char *argv[])
{
static struct fuse_operations ops;
ops.readdir = circlefs::readdir;
ops.mknod = circlefs::mknod;
ops.getattr = circlefs::getattr;
return fuse_main(argc, argv, &ops, nullptr);
}
|
#define FUSE_USE_VERSION 30
#include <fuse.h>
// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>
#include <time.h>
#include <limits.h> // PATH_MAX
// STL
#include <system_error>
#include <map>
#include <set>
#include <string>
#include <cstdint>
#include <cassert>
#include <cstring>
#include <iostream>
namespace posix
{
static const int success_response = 0;
static const int error_response = -1;
static int success(void) { errno = 0; return success_response; }
static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; }
}
namespace circlefs
{
enum class Epath
{
root,
directory,
file,
};
struct file_entry_t
{
bool operator < (const file_entry_t& other) const // for locating files by name
{ return name < other.name; }
std::string name;
pid_t pid;
struct stat stat;
};
std::map<uid_t, std::set<file_entry_t>> files;
void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename)
{
const char* dir_pos = std::strchr(path, '/') + 1;
const char* file_pos = std::strchr(dir_pos, '/');
std::string dir;
if(path[1] == '\0')
{
type = Epath::root;
pw_ent = nullptr;
filename.clear();
}
else
{
if(file_pos == nullptr)
{
dir = dir_pos;
filename.clear();
type = Epath::directory;
}
else
{
dir = std::string(dir_pos, file_pos - dir_pos);
filename = file_pos + 1;
type = Epath::file;
}
pw_ent = ::getpwnam(dir.c_str());
}
}
void clean_set(std::set<file_entry_t>& dir_set)
{
char path[PATH_MAX + 1];
struct stat info;
auto pos = dir_set.begin();
while(pos != dir_set.end())
{
// Linux only
sprintf(path, "/proc/%d", pos->pid);
if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) // if process
pos = dir_set.erase(pos);
else
++pos;
}
}
/*
struct timespec get_oldest(std::set<file_entry_t>& dir_set)
{
struct timespec oldest = dir_set.begin()->stat.st_atim;
auto pos = dir_set.begin();
while(pos != dir_set.end())
{
if(pos->stat.st_atim.tv_sec < oldest.tv_sec)
oldest.tv_sec = pos->stat.st_atim.tv_sec;
}
return oldest;
}
*/
int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo)
{
(void)fileInfo;
filler(buf, "." , nullptr, 0);
filler(buf, "..", nullptr, 0);
Epath type;
passwd* pw_ent;
std::string filename;
deconstruct_path(path, type, pw_ent, filename);
switch(type)
{
case Epath::root: // root directory (fill with usernames in use)
{
auto pos = files.begin();
while(pos != files.end())
{
clean_set(pos->second);
if(pos->second.empty())
pos = files.erase(pos);
else
{
filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset);
++pos;
}
}
break;
}
case Epath::directory: // list files in directory (based on username)
{
auto pos = files.find(pw_ent->pw_uid);
if(pos == files.end()) // username has no files
{
posix::error(std::errc::no_such_file_or_directory);
return 0 - errno;
}
clean_set(pos->second);
for(const file_entry_t& entry : pos->second)
filler(buf, entry.name.c_str(), &entry.stat, offset);
break;
}
case Epath::file: // there must have been a parsing error (impossible situation)
assert(false);
}
return posix::success();
}
int mknod(const char* path, mode_t mode, dev_t rdev)
{
(void)rdev;
if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
return posix::error(std::errc::permission_denied);
Epath type;
passwd* pw_ent = nullptr;
std::string filename;
struct stat stat = {};
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
deconstruct_path(path, type, pw_ent, filename);
switch(type)
{
case Epath::root: // root directory - cannot make root!
case Epath::directory: // directory (based on username) - cannot make directory!
return posix::error(std::errc::permission_denied);
case Epath::file: // create a node file!
fuse_context* ctx = fuse_get_context();
auto& dir = files[pw_ent->pw_uid];
auto entry = dir.find({ filename, 0, stat });
if(entry != dir.end())
dir.erase(entry);
stat.st_uid = pw_ent->pw_uid;
stat.st_gid = pw_ent->pw_gid;
stat.st_mode = mode;
stat.st_ctim =
stat.st_mtim =
stat.st_atim = time;
dir.insert({ filename, ctx->pid, stat });
break;
}
return posix::success();
}
int getattr(const char* path, struct stat* statbuf)
{
Epath type;
passwd* pw_ent = nullptr;
std::string filename;
deconstruct_path(path, type, pw_ent, filename);
switch(type)
{
case Epath::root: // root directory (always exists)
statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
posix::success();
break;
case Epath::directory: // username (exists if username exists)
statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
if(pw_ent == nullptr)
posix::error(std::errc::no_such_file_or_directory);
else
posix::success();
break;
case Epath::file:
auto pos = files.find(pw_ent->pw_uid);
if(pos == files.end()) // username not registered
{
posix::error(std::errc::no_such_file_or_directory);
break;
}
clean_set(pos->second);
for(const file_entry_t& entry : pos->second) // check every file
{
if(entry.name == filename)
{
*statbuf = entry.stat;
posix::success();
return 0 - errno;
}
}
posix::error(std::errc::no_such_file_or_directory); // no file matched
break;
}
return 0 - errno;
}
}
int main(int argc, char *argv[])
{
static struct fuse_operations ops;
ops.readdir = circlefs::readdir;
ops.mknod = circlefs::mknod;
ops.getattr = circlefs::getattr;
return fuse_main(argc, argv, &ops, nullptr);
}
|
comment out unused code
|
comment out unused code
|
C++
|
unlicense
|
GravisZro/circlefs
|
a1f66c9d12955e3b994ae2e5903155a75b27cd49
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <sched.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string>
int run(void* arg)
{
char **argv = (char**) arg;
const std::string name = "funny-name";
struct utsname uts;
sethostname((const char *) name.c_str(), name.size());
std::cout << "This is child" << std::endl;
uname(&uts);
std::cout << "This is a child's nodename: " << uts.nodename << std::endl;
pid_t pid = fork();
if (pid == 0)
{
std::cout << "About to spin a new task" << std::endl;
std::cout << argv[1] << std::endl;
execvp(argv[1], &argv[1]);
}
else if (pid > 0)
{
// parent process
waitpid(pid, NULL, 0);
}
else
{
std::cout << "Forking failed" << std::endl;
return 1;
}
return 0;
}
int main(int argc, char *argv[])
{
struct utsname uts;
char *stack = (char*) malloc(1024*1024);
std::cout << "This is parent" << std::endl;
pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv);
if (pid == -1)
{
std::cout << "Creating new namespace failed. Error number: " << errno;
}
sleep(1);
uname(&uts);
std::cout << "This is a parent's nodename: " << uts.nodename << std::endl;
waitpid(pid, NULL, 0);
}
|
#include <iostream>
#include <sched.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string>
int run(void* arg)
{
char **argv = (char**) arg;
const std::string name = "funny-name";
struct utsname uts;
sethostname((const char *) name.c_str(), name.size());
std::cout << "This is child" << std::endl;
uname(&uts);
std::cout << "This is a child's nodename: " << uts.nodename << std::endl;
pid_t pid = fork();
if (pid == 0)
{
std::cout << "About to spin a new task" << std::endl;
std::cout << argv[1] << std::endl;
execvp(argv[1], &argv[1]);
}
else if (pid > 0)
{
// parent process
waitpid(pid, NULL, 0);
}
else
{
std::cout << "Forking failed" << std::endl;
return 1;
}
return 0;
}
int main(int argc, char *argv[])
{
struct utsname uts;
char *stack = (char*) malloc(1024*1024);
std::cout << "This is parent" << std::endl;
pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv);
if (pid == -1)
{
std::cout << "Creating new namespace failed. Error number: " << errno;
}
sleep(1);
uname(&uts);
std::cout << "This is a parent's nodename: " << uts.nodename << std::endl;
waitpid(pid, NULL, 0);
}
|
Convert indentation
|
Convert indentation
|
C++
|
mit
|
chmeldax/boxie
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.